30.07.2015 Views

Actas JP2011 - Universidad de La Laguna

Actas JP2011 - Universidad de La Laguna

Actas JP2011 - Universidad de La Laguna

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-ii


<strong>Actas</strong> <strong>de</strong> las XXII Jornadas <strong>de</strong> Paralelismo<strong>La</strong> <strong>La</strong>guna, Tenerife, EspañaEditoresFrancisco AlmeidaVicente BlancoCoromoto LeónCasiano RodríguezFrancisco <strong>de</strong> San<strong>de</strong>7–9 Septiembre 2011


<strong>Actas</strong> <strong>de</strong> las XXII Jornadas <strong>de</strong> Paralelismo <strong>JP2011</strong>Editores: Francisco Almeida, Vicente Blanco, Coromoto León,Casiano Rodríguez y Francisco <strong>de</strong> San<strong>de</strong>ISBN: 978-84-694-1791-1Servicio <strong>de</strong> Publicaciones. <strong>Universidad</strong> <strong>de</strong> <strong>La</strong> <strong>La</strong>guna, Tenerife, 2011Edición: 1 aImpresión: 1 aN o <strong>de</strong> páginas: 744Formato: 17 x 24Materia CDU: 004 Ciencia y tecnología <strong>de</strong> los or<strong>de</strong>nadores. InformáticaReservados los <strong>de</strong>rechos para todos los países <strong>de</strong> lengua española. De conformidad con lo dispuesto en elartículo 270 y siguientes <strong>de</strong>l código penal vigente, podrán ser castigados con penas <strong>de</strong> multa y privaci6n <strong>de</strong>libertad quienes reprodujeren o plagiaren, en todo o en parte, una obra literaria, artística o científica fijadaen cualquier tipo <strong>de</strong> soporte sin la preceptiva autorización. Ninguna parte <strong>de</strong> esta publicación, incluido eldiseño <strong>de</strong> la cubierta, pue<strong>de</strong> ser reproducida, almacenada o trasmitida <strong>de</strong> ninguna forma, ni por ningún medio,sea éste electrónico, químico, mecánico, e1ectro–óptico, i grabación, fotocopia o cualquier otro, sin la previaautorización escrita por parte <strong>de</strong> la editorial.Diríjase a CEDRO (Centro Español <strong>de</strong> Derechos Reprográficos), www.cedro.org, si necesita fotocopiaro escanear algún fragmento <strong>de</strong> esta obra.COPYRIGHT c○2011 UNIVERSIDAD DE LA LAGUNA.svpubl@ull.es<strong>Actas</strong> <strong>de</strong> las XXII Jornadas <strong>de</strong> ParalelismoDerechos reservados c○2011 respecto a la primera edición en español, por LOS AUTORESDerechos reservados c○2011 respecto a la primera edición en español, por UNIVERSIDAD DE LALAGUNA1 a Edición, 1 a ImpresiónISBN: 978-84-694-1791-1Depósito Legal: TF-723-2011http://jp2011.pcg.ull.esCréditos:Diseño <strong>de</strong> Portada: Jose A. <strong>de</strong> Luis jobues@yahoo.esMaquetación LATEX: LOS EDITOREScon la clase LATEX‘confproc’ (por V. Verfaille)Impreso en <strong>La</strong> <strong>La</strong>guna — Septiembre 2011


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011ComitésCoordinaciónRamón Beivi<strong>de</strong> Palacios (UC)Jesús Carretero Pérez (UCIIIM)José Duato Marín (UPV)Inmaculada García Fernán<strong>de</strong>z (UAL)Antonio Garrido Del Solo (UCLM)Emilio López Zapata (UMA)Emilio Luque Fadón (UAB)Pedro <strong>de</strong> Miguel Anasagasti (UPM)Alberto Prieto Espinosa (UGR)Francisco José Quiles Flor (UCLM)Ana Ripoll Aracil (UAB)Francisco Tirado Fernán<strong>de</strong>z (UCM)Mateo Valero Cortés (UPC)Victor Viñals Yúferas (UZ)Comité Organizador (ULL)Alejandro Acosta DíazFrancisco Almeida RodríguezJésica <strong>de</strong> Armas AdriánVicente Blanco PérezJuan Carlos Castillo CanoLuis Cerrudo ConcepciónAntonio Javier Dorta LorenzoJuan José Fumero AlfonsoCarlos González VilaCoromoto León Hernán<strong>de</strong>zIván López RodríguezGara Miranda ValladaresCarlos Alberto Morales DíazRuymán Reyes CastroCasiano Rodríguez LeónElena Sánchez NielsenFrancisco <strong>de</strong> San<strong>de</strong> GonzálezAdrián Santos MarreroEduardo Segredo GonzálezCarlos Segura González<strong>JP2011</strong>-iii


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-iv


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011PresentaciónEs un placer para nosotros y un verda<strong>de</strong>ro honor darles la bienvenida a la vigésimo segunda edición<strong>de</strong> las Jornadas <strong>de</strong> Paralelismo que se celebran por primera vez en Canarias los días 7, 8 y 9 <strong>de</strong>septiembre <strong>de</strong> 2011 en <strong>La</strong> <strong>La</strong>guna. Este evento, con más <strong>de</strong> dos décadas <strong>de</strong> tradición, supone elencuentro <strong>de</strong> numerosos investigadores para intercambiar experiencias que reflejan su trabajo enel ámbito <strong>de</strong> la computación <strong>de</strong> altas prestaciones. Por primera vez las Jornadas <strong>de</strong> Paralelismo secelebran <strong>de</strong> forma conjunta con las Jornadas <strong>de</strong> Computación Reconfigurable y Aplicaciones, JCRA.El creciente interés <strong>de</strong> la comunidad investigadora por todo lo relacionado con el paralelismo y lacomputación <strong>de</strong> altas prestaciones se ve claramente reflejado en la variedad, calidad y número <strong>de</strong> trabajospresentes en esta edición <strong>de</strong> las Jornadas. Este año se han recibido un total <strong>de</strong> 117 trabajos cuyapresentación se ha organizado en un programa que incluye 24 sesiones <strong>de</strong> ponencias. Por otra parte,el número <strong>de</strong> inscritos en las Jornadas ascien<strong>de</strong> a 158 participantes, lo que muestra una vez más, tantoel elevado grado <strong>de</strong> aceptación <strong>de</strong>l evento como el nivel <strong>de</strong> consolidación <strong>de</strong>l mismo. Es <strong>de</strong> <strong>de</strong>stacarque el abanico <strong>de</strong> tópicos tratado en las jornadas ha ido creciendo con los años y se ha adaptado a lainvestigación que se realiza en nuestro país. El programa cubre una amplia variedad <strong>de</strong> tópicos queincluyen la supercomputación; las arquitecturas <strong>de</strong>l procesador, multiprocesadores y chips multinúcleo;las re<strong>de</strong>s y sistemas <strong>de</strong> comunicaciones; los algoritmos y técnicas <strong>de</strong> programación paralelas;las Tecnologías grid, cluster, cloud computing y plataformas distribuidas; la arquitecturas <strong>de</strong>l subsistema<strong>de</strong> memoria y almacenamiento secundario; la evaluación <strong>de</strong> prestaciones; la compilación parasistemas <strong>de</strong> altas prestaciones; las aplicaciones <strong>de</strong> la computación <strong>de</strong> altas prestaciones y la docenciaen arquitectura, tecnología <strong>de</strong> computadores y programación paralela.Contamos en esta edición con dos conferencias que abordarán temas <strong>de</strong> investigación <strong>de</strong> gran actualidady que esperamos que sean <strong>de</strong> su interés. Por una parte, el profesor <strong>de</strong> la Universitat Politècnica<strong>de</strong> Catalunya, D. Antonio González, director <strong>de</strong>l centro Intel-UPC impartirá la conferencia tituladaLess energy is more performance. Asimismo, el profesor D. Marco Danelutto <strong>de</strong> la Università diPisa, director <strong>de</strong> Institute of Programming Mo<strong>de</strong>ls <strong>de</strong> esta universidad y miembro <strong>de</strong> la red Core-GRID impartirá la charla The multi/many core challenge: a pattern based programming perspective.El programa <strong>de</strong> las Jornadas incluye también dos mesas redondas con ponentes <strong>de</strong> gran relevancia.En la primera mesa redonda se <strong>de</strong>batirá sobre <strong>La</strong> ley <strong>de</strong> la ciencia y en la segunda sobre <strong>La</strong> ProgramaciónParalela en los títulos <strong>de</strong> Grado y Máster temas ambos que esperamos resulten <strong>de</strong>l máximointerés para los participantes en las Jornadas. Tendremos asimismo oportunidad <strong>de</strong> asistir en elmarco <strong>de</strong> las Jornadas a la asamblea <strong>de</strong> la Sociedad <strong>de</strong> Arquitectura y Tecnología <strong>de</strong> Computadores(SARTECO).No queremos acabar esta presentación sin mostrar nuestro agra<strong>de</strong>cimiento a todos los organimos yentida<strong>de</strong>s, públicos y privados, que han colaborado en el <strong>de</strong>sarrollo <strong>de</strong> estas Jornadas, en concreto,a la <strong>Universidad</strong> <strong>de</strong> <strong>La</strong> <strong>La</strong>guna, al Ayuntamiento <strong>de</strong> San Cristobal <strong>de</strong> <strong>La</strong> <strong>La</strong>guna, al Cabildo <strong>de</strong>Tenerife, a la Agencia Canaria <strong>de</strong> Investigación, Innovación y Sociedad <strong>de</strong> la Información, al Departamento<strong>de</strong> EIO y Computación, a la Escuela Técnica Superior <strong>de</strong> Ingeniería Informática <strong>de</strong> la ULL,a la Facultad <strong>de</strong> Matemáticas <strong>de</strong> la ULL, a las empresas Bull e IBM, y por último a los miembros<strong>de</strong> los grupos <strong>de</strong> Computación <strong>de</strong> Altas Prestaciones y Algoritmos y Lenguajes Paralelos <strong>de</strong> la ULL,que han prestado su apoyo para la organización <strong>de</strong> este congreso.Bienvenidos a <strong>La</strong> <strong>La</strong>guna y muchas gracias por su interés y participación en estas XXII Jornadas <strong>de</strong>Paralelismo, que esperamos cumplan con sus expectativas.Comité Organizador <strong>de</strong> las XXII Jornadas <strong>de</strong> Paralelismo<strong>La</strong> <strong>La</strong>guna, 7-9 <strong>de</strong> septiembre <strong>de</strong> 2011<strong>JP2011</strong>-v


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-vi


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Índice <strong>de</strong> las <strong>Actas</strong> <strong>JP2011</strong>Algoritmos y técnicas <strong>de</strong> programación paralelas3 Una Versión Paralela <strong>de</strong> la Evolución Diferencial para Pre<strong>de</strong>cir Motifs en Ca<strong>de</strong>nas <strong>de</strong> ADNDavid L. González-Álvarez, Miguel A. Vega-Rodríguez, Juan A. Gómez-Pulido, Juan M. Sánchez-Pérez9 Comparación <strong>de</strong> Algoritmos Evolutivos Paralelos y Secuenciales para el Alineamiento Múltiple <strong>de</strong> SecuenciasFernando José Mateus Silva, Juan Manuel Sánchez-Pérez, Juan A. Gómez-Pulido, Miguel A. Vega-Rodríguez15 Evolución Diferencial OpenMP+MPI en Re<strong>de</strong>s Ópticas WDMÁlvaro Rubio-<strong>La</strong>rgo, Miguel A. Vega-Rodríguez, Juan A. Gómez-Pulido, Juan M. Sánchez-Pérez21 Paralelización <strong>de</strong>l algoritmo <strong>de</strong> bi-mezclaJ.F.R. Herrera, L.G. Casado, I. García, Eligius M.T. Hendrix27 Optimización <strong>de</strong>l Método BST para la Reducción <strong>de</strong> Mo<strong>de</strong>los en Arquitecturas MultinúcleoPablo Ezzatti, Enrique S. Quintana-Ortí, Alfredo Remón33 Genetic Algorithm to Predict Wavelet Coefficients SignRicardo García, Otoniel López, Pablo Piñol, Miguel Martínez, Manuel P. Malumbres, Antonio Martí39 Resolución <strong>de</strong>l Empaquetado 2D Multiobjetivizado con un Algoritmo Memético ParaleloCoromoto León, Carlos Segura, Eduardo Segredo45 Diseño <strong>de</strong> Filtros con Técnicas Evolutivas para la Clasificación <strong>de</strong> Señales <strong>de</strong> EncefalogramaCoromoto León, Yanira González, Carlos Segura51 Ranking <strong>de</strong> listas enlazadas en procesadores multicoreHugo Vegas, Thierry Gautier, Carlos García, Manuel Prieto57 Parallelizing Biblio-MetReS, a data mining toolOussama Ab<strong>de</strong>lli, Anabel Usié, Hiren Karathia, Jordi Vilaplana, Francesc Solsona, Rui Alves63 Paralelización <strong>de</strong> una Plataforma para la Resolución <strong>de</strong> Problemas NP-completos Mediante Algoritmos EvolutivosJosé M. <strong>La</strong>nza-Gutiérrez, Juan A. Gómez-Pulido, Miguel A. Vega-Rodríguez, Juan M. Sánchez-Pérez69 Comparando Mo<strong>de</strong>los Paralelos Basados en Islas para el Problema <strong>de</strong>l Posicionamiento <strong>de</strong> Antenas MultiobjetivizadoCoromoto León, Eduardo Segredo, Carlos Segura75 Exhaustive Program’s Robustness Analysis against Transient FaultsJoao Gramacho, Dolores Rexachs, Emilio Luque81 Biblioteca <strong>de</strong> Altas Prestaciones para la Resolución <strong>de</strong> Problemas Matriciales EstructuradosPedro Alonso-Jordá, Pablo Martínez-Naredo, F.J. Martínez-Zaldívar, José Ranilla, Antonio M. Vidal87 A translator framework for Dynamic Programming problemsAlejandro Acosta, Francisco Almeida, Ignacio PeláezAplicaciones <strong>de</strong> la computación <strong>de</strong> altas prestaciones95 Resolviendo el Diseño <strong>de</strong> Re<strong>de</strong>s para Mo<strong>de</strong>los <strong>de</strong> Tráfico Reales <strong>de</strong> Internet Mediante Optimización Multiobjetivoen MultiprocesadoresJosé M. <strong>La</strong>nza-Gutiérrez, Juan A. Gómez-Pulido, Miguel A. Vega-Rodríguez, Juan M. Sánchez-Pérez101 A New Tool for Classification of Satellite Images Available from Google Maps: Efficient Implementation inGraphics Processing UnitsS. Bernabé, A. Plaza107 Visibility Map Computation at all Points of a TerrainS. Tabik, L.F. Romero, E.L. Zapata113 Un método <strong>de</strong> acceso aproximado para alta dimensionalidad y su paralalelizaciónF. Artigas119 Perceptually enhanced INTRA vi<strong>de</strong>o enco<strong>de</strong>r for high <strong>de</strong>finition/quality servicesM. Martínez-Rach, O. López, Pablo Piñol, Manuel P. Malumbres, J. Oliver125 Equipo paralelo <strong>de</strong> metaheurísticas para la resolución <strong>de</strong> un problema real <strong>de</strong> telecomunicacionesJosé M. Chaves-González, Miguel A. Vega-Rodríguez, Juan A. Gómez-Pulido, Juan M. Sánchez-Pérez<strong>JP2011</strong>-vii


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011131 Determination of traffic control tables by HPCEligius M.T. Hendrix, Siham Tabik, Rene Haijema135 Evaluación <strong>de</strong>l método <strong>de</strong>l Gradiente Biconjugado para matrices dispersas en GPUsG. Ortega, E. M. Garzón, F. Vázquez, I. García141 Paralelización <strong>de</strong>l cálculo <strong>de</strong> coeficientes <strong>de</strong>l Método <strong>de</strong> Elementos <strong>de</strong> Contorno en la resolución <strong>de</strong> problemas<strong>de</strong> contacto termoelástico 3DRaquel González, Lidia Sánchez, José Vallepuga147 Iterative procedure to solve thermoelastic contact problems between 3D solids using BEM and OOPA. Suárez, Raquel González, Lidia Sánchez, José Vallepuga153 Evaluación <strong>de</strong> la Paralelización <strong>de</strong> un Mo<strong>de</strong>lo Hidrodinámico 3DMario C. Acosta, Mancia Anguita, Francisco J. Rueda, F. Javier Fernán<strong>de</strong>z-Baldomero159 Paralelización <strong>de</strong>l Análisis <strong>de</strong> Imágenes con Tensor <strong>de</strong> Difusión en Resonancia Magnética usando GPUsMoisés Hernán<strong>de</strong>z, Ginés D. Guerrero, José M. Cecilia, José M. García, Alberto Inuggi165 Agent-Based Simulation to Optimize Healthcare Emergency DepartmentsEduardo Cabrera, Manel Taboada, Emilio Luque171 Reducción <strong>de</strong> ruido impulsivo Fijo y Uniforme en imágenes digitales usando las GPUs.M. Guadalupe Sánchez, Vicente Vidal, Jordi Bataller, Alejandro Rivera177 Estrategias <strong>de</strong> Paralelización <strong>de</strong> Algoritmos <strong>de</strong> Razonamiento para Ontologías BiomédicasEduardo J. Cepas, Ginés D. Guerrero, José M. Cecilia, José M. García, Jesualdo Fernán<strong>de</strong>zArquitecturas <strong>de</strong>l procesador, multiprocesadores y chips multinúcleo185 Real-Time Task Migration with Dynamic Partitioning to Reduce Power ConsumptionJosé Luis March, Julio Sahuquillo, Salvador Petit, Houcine Hassan, José Duato191 Unified Locality-sensitive Signatures for Transactional MemoryR. Quislant, E. Gutiérrez, O. Plata, E.L. Zapata197 Overriding the Coherence Protocol to Improve Directory CachesB. Cuesta, A. Ros, M.E. Gómez, A. Robles, José Duato203 Overcoming the Scalability Constraints of Coherence Protocols of Commodity SystemsA. Ros, B. Cuesta, Ricardo Fernán<strong>de</strong>z-Pascual, M.E. Gómez, Manuel E. Acacio, A. Robles, J. M. García, JoséDuato209 Efficient hardware support for lock synchronization in Many-core CMPsJosé L. Abellán, Juan Fernán<strong>de</strong>z, Manuel E. Acacio215 A Cooperative and Scalable Built-In Self-Test Architecture for NoCsC. Gómez, A. Strano, D. Ludovici, M. Favalli, M.E. Gómez, D. Bertozzi, P. López, José Duato221 Modular Distributed Switch: Spreading the Switch along the LinkA. Roca, C. Hernán<strong>de</strong>z, José Flich, F. Silla, J. Duato227 Reducing the Energy Consumption of Hardware Prefetching in Many-Core CMPs using Reply PartitioningA. Flores, Manuel E. Acacio, Juan L. Aragón233 Mo<strong>de</strong>lling Permanent Fault Impact on Cache PerformanceDaniel Sánchez, Yiannakis Sazei<strong>de</strong>s, Juan L. Aragón, José M. García239 Coherencia <strong>de</strong> Caché Mediante Árbol Basado en Proximidad y PredicciónAntonio García-Guirado, Ricardo Fernán<strong>de</strong>z-Pascual, José M. García245 Explotación <strong>de</strong> Técnicas <strong>de</strong> Especialización <strong>de</strong> Cores para Planificación Eficiente en Procesadores MulticoreAsimétricosJ.C. Sáez, Manuel Prieto, A. Pousa, A. Fedorova251 Optimización MapReduce para uso <strong>de</strong> los recursos en las arquitecturas multi-core.Tharso Ferreira, Aprigio Bezerra, Antonio Espinosa, Porfídio Hernán<strong>de</strong>z, Juan Carlos Moure255 Análisis <strong>de</strong> los datos privados/compartidos en aplicaciones paralelas sobre CMPsAlfonso Ramos, Antonio García-Guirado, José M. García261 Reconfiguración <strong>de</strong> la NoC en la Virtualización <strong>de</strong> CMPsF. Triviño, Francisco J. Alfaro, José L. Sánchez, José Flich, S. González<strong>JP2011</strong>-viii


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011267 Beneficios <strong>de</strong>l uso <strong>de</strong> la Red <strong>de</strong> Interconexión en la Aceleración <strong>de</strong> la CoherenciaL.G. Menezo, A. Colaso, P. Prieto, P. Abad, V. Puente, J.A. Gregorio273 Conversion between DPD and RBCD for on-line arithmetic computationSonia González, Carlos García, Julio Villalba277 Multiples Puertos <strong>de</strong> Inyección en una Red en ChipJ. Camacho, José Flich, José Duato283 A Flexible Hybrid Transactional Memory Multicore on FPGAOriol Arcas, Nehir Sonmez, Osman S. Unsal, Adrián Cristal, Mateo Valero291 An Adaptive Controller to Save Dynamic Energy in LP-NUCAD. Suárez Gracia, T. Monreal Arnal, V. Viñals Yúfera297 Acelerando las simulaciones <strong>de</strong> sistema completo usando Simics en sistemas multiprocesadorSantos González, Francisco Triviño, Francisco J. Andujar, José L. Sánchez, Francisco J. AlfaroArquitecturas, algoritmos y aplicaciones sobre aceleradores hardware305 Parallelization of the Generalized Hough Transform on GPUJuan Gómez-Luna, José María González-Linares, José Ignacio Benavi<strong>de</strong>s, E.L. Zapata, Nicolás Guil311 rCUDA: Uso Concurrente <strong>de</strong> Dispositivos Compatibles con CUDA <strong>de</strong> Forma Remota. Adaptación a CUDA 4C. Reaño, A. J. Peña, F. Silla, R. Mayo, Enrique S. Quintana-Ortí, José Duato317 Un nuevo entorno para el uso <strong>de</strong> GPUsP. Valero, F. L. Pelayo323 Pre-procesamiento <strong>de</strong> Flujo Óptico Robusto en Hardware GráficoF. Ayuso, G. Botella, C. García, Manuel Prieto, F. Tirado329 Experiencias con Python y CUDA en Computación <strong>de</strong> Altas PrestacionesSergio Armas, Lionel Mena, Alejandro Samarín, Vicente Blanco, A. Morales, Francisco Almeida335 A Scalable Visualization System for Crowd SimulationsGuillermo Vigueras, Juan M. Orduña, Miguel Lozano, Víctor Fernán<strong>de</strong>z-Bauset341 A New Approach to rCUDAJosé Duato, A. J. Peña, F. Silla, J. C. Fernán<strong>de</strong>z, R. Mayo, Enrique S. Quintana-Ortí347 Métodos no lineales basados en el gradiente conjugado para GPUsH. Migallón, V. Migallón, J. Penadés353 Búsquedas por Similitud en Espacios Métricos sobre Plataformas Basadas en GPUsRoberto Uribe-Pare<strong>de</strong>s, Pedro Valero-<strong>La</strong>ra, Enrique Arias, José Luis Sánchez, Diego Cazorla359 Query Processing in Metric Spaces using GPUsR.J. Barrientos, J.I. Gómez, C. Tenllado, Manuel PrietoRe<strong>de</strong>s y comunicaciones367 Desarrollo <strong>de</strong> un Prototipo para la Notificación Automática <strong>de</strong> Acci<strong>de</strong>ntes <strong>de</strong> Tráfico usando Re<strong>de</strong>s VehicularesManuel Fogue, Piedad Garrido, Francisco J. Martinez, Carlos T. Calafate, Juan Carlos Cano, Pietro Manzoni373 Hierarchical Analysis of Resilience Benchmarking Results Using LSP: Ad Hoc Networks As a Case StudyJesús Friginal, Juan-Carlos Ruiz, David <strong>de</strong> Andrés, Pedro Gil379 Protocolo para entrega fiable <strong>de</strong> contenidos en re<strong>de</strong>s inalámbricas basado en codificación RaptorMiguel Báguena, Carlos T. Calafate, Juan Carlos Cano, Pietro Manzoni385 Evaluating vi<strong>de</strong>o streaming performance in MANETs using a testbedTim Bohrloch, Carlos T. Calafate, Alvaro Torres, Juan Carlos Cano, Pietro Manzoni391 Statistical Mo<strong>de</strong>ling of Transmission Path Loss in Un<strong>de</strong>rwater Acoustic NetworksJ. Llor, Manuel P. Malumbres397 Predictive and Distributed Routing Balancing for High Speed Interconnection NetworksC. Núñez Castillo, D. Lugones, D. Franco, Emilio Luque403 Evaluación <strong>de</strong> una alternativa para aumentar el número <strong>de</strong> puertos <strong>de</strong> los conmutadoresJuan Antonio Villar, Francisco J. Andújar, José L. Sánchez, Francisco J. Alfaro, José Duato<strong>JP2011</strong>-ix


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011409 Combinando diferentes enfoques para el control <strong>de</strong> congestión en re<strong>de</strong>s <strong>de</strong> interconexión <strong>de</strong> altas prestacionesJesús Escu<strong>de</strong>ro-Sahuquillo, E. G. Gran, Pedro Javier García, José Flich, T. Skeie, O. Lysne, F. J. Quiles, JoséDuato415 Un acercamiento a la eficacia <strong>de</strong> las técnicas <strong>de</strong> control <strong>de</strong> congestión en re<strong>de</strong>s <strong>de</strong> interconexión con topologíasdirectasDaniel Gómez-García, Pedro Javier García, Francisco José Quiles, Jesús Escu<strong>de</strong>ro-Sahuquillo, Juan AntonioVillar, José Flich, José Duato421 Peripheral twists for torus topologies with arbitrary aspect ratioEnrique Vallejo, Miquel Moretó, Carmen Martínez, Ramón Beivi<strong>de</strong>427 Performance analysis of an IEEE 802.21 based Vertical Handover protocol using ns-2Johann Márquez-Barja, Carlos T. Calafate, Juan Carlos Cano, Pietro Manzoni433 Mecanismos <strong>de</strong> Comunicación Eficientes en Re<strong>de</strong>s <strong>de</strong> Altas Prestaciones para Bibliotecas <strong>de</strong> Paso <strong>de</strong> Mensajesen JavaRoberto R. Expósito, Guillermo L. Taboada, Juan Touriño, Ramón Doallo439 Comunicaciones Escalables en Memoria Compartida para Paso <strong>de</strong> Mensajes en JavaSabela Ramos, Guillermo L. Taboada, Juan Touriño, Ramón Doallo445 Aproximación distribuida <strong>de</strong> incendios forestales con WSN usando la envolvente convexaM. Ángeles Serna, Aurelio Bermú<strong>de</strong>z, Rafael Casado, Pawel Kulakowski451 A First Approach to King Topologies for On-Chip NetworksE. Stafford, J.L. Bosque, C. Martinez, F. Vallejo, Ramón Beivi<strong>de</strong>, C. CamareroSistemas Web e Internet459 Incorporación <strong>de</strong>l dinamismo <strong>de</strong>l usuario en un benchmark <strong>de</strong> comercio electrónicoRaúl Peña-Ortiz, José Antonio Gil, Julio Sahuquillo, Ana Pont467 Servicios Web Semánticos. Una aproximación <strong>de</strong>s<strong>de</strong> las OntologíasE. González, I. López, E. NielsenTecnología grid, cluster, cloud computing y plataformas distribuidas475 Planificación <strong>de</strong> DAGS en entornos oportunísticosMaria <strong>de</strong>l Mar López, Elisa Heymann, Miquel Àngel Senar483 QoS en Entornos Grid mediante un Sistema <strong>de</strong> Meta-planificación por A<strong>de</strong>lantado basado en SLAsJ. Conejero, L. Tomás, C. Carrión, B. Caminero489 RSA@Cloud: Sistema <strong>de</strong> Criptoanálisis sobre Infraestructuras CloudAlberto Megía Negrillo, Antonio Molinera <strong>La</strong>mas, José Antonio Rueda Sánchez, José Luis Vázquez-Poletti495 Descripción <strong>de</strong> la Plataforma Formiga CloudFernando Gomez-Folgar, Javier López Cacheiro, C. Fernán<strong>de</strong>z Sánchez, Antonio García-Loureiro, R. Valin,Víctor Fernán<strong>de</strong>z-Albor501 Planificación <strong>de</strong> trabajos MapReduce en clusters Hadoop no-<strong>de</strong>dicadosAprigio Bezerra, Tharso Ferreira, Antonio Espinosa, Juan Carlos Moure, Porfídio Hernán<strong>de</strong>z507 Procesamiento <strong>de</strong> vi<strong>de</strong>os usando la nubeA. Morales, Francisco Almeida513 R en la nubeA. Santos, Francisco Almeida, Vicente Blanco, J.C. Castillo519 Comparativa y estudio <strong>de</strong> distribución <strong>de</strong> software <strong>de</strong> cálculo científico en entornos cloud con CVMFSVíctor Fernán<strong>de</strong>z-Albor, Ricardo Graciani, Javier López Cacheiro, Fernando Gomez-Folgar, Antonio García-Loureiro, Juan José Saborido525 Multi-Cluster Performance Impact on the Multiple-Job Co-Allocation SchedulingH. Blanco, F. Guirado, J. L. Lérida531 Mr-Cirrus: Implementación <strong>de</strong> Map-Reduce bajo MPI para la ejecución paralela <strong>de</strong> programas secuencialesD. Ramet, J. <strong>La</strong>go, J. Falgueras, O. Trelles537 AbFS: Sistema <strong>de</strong> Ficheros AbiertoAntonio F. Díaz, Mancia Anguita, Hugo E. Camacho, Erik Nieto, Julio Ortega<strong>JP2011</strong>-x


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011543 Comparación <strong>de</strong>l rendimiento entre los hipervisores XEN y KVM usando virtualización por hardwareIsaac Zablah, R. Valin, Antonio García-Loureiro, Javier López Cacheiro, Fernando Gomez-FolgarArquitecturas <strong>de</strong>l subsistema <strong>de</strong> memoria y almacenamiento secundario551 A Novel Approach for a Metadata ClusterA. Avilés-Gonález, J. Piernas, P. González-Férez557 Algoritmo <strong>de</strong> reemplazo para cache <strong>de</strong> último nivel basado en periodos MRUAlejandro Valero, Julio Sahuquillo, Salvador Petit, Pedro López, José Duato563 A Comparison of Cache Hierarchies for SMT ProcessorsD. Suárez Gracia, T. Monreal Arnal, V. Viñals Yúfera569 Metodología para Analizar y Evaluar los Sistemas <strong>de</strong> Entrada/Salida ParalelosSandra Mén<strong>de</strong>z, Dolores Rexachs, Emilio Luque575 Memory Hierarchy and Network Co-<strong>de</strong>sign through Trace-Driven SimulationMario Lod<strong>de</strong>, José FlichDocencia en arquitectura, tecnología <strong>de</strong> computadores y programación paralela583 E-Assessment of Matlab Assignments in Moodle: Application to an Introductory Programming Course for EngineersJulián Ramos, María A. Trenas, Sergio Romero, Eladio Gutiérrez589 Sobre la integración <strong>de</strong>l Curriculum Initiative on Parallel and Distributed Computing en los planes <strong>de</strong> estudio <strong>de</strong>lGrado en Ingeniería InformáticaFrancisco Almeida, Domingo Giménez, José Miguel Mantas, Antonio M. Vidal595 Experiencias en Docencia <strong>de</strong> Diseño y Evaluación <strong>de</strong> ConfiguracionesA.M. Mora, P. García-Sánchez, P.A. Castillo, M.G. Arenas, J.J. Merelo, J. Ortega599 Diseño <strong>de</strong> un cluster <strong>de</strong> computadores como actividad para Arquitectura <strong>de</strong> ComputadoresF. Javier Fernán<strong>de</strong>z-Baldomero, Mancia AnguitaEvaluación <strong>de</strong> prestaciones607 Achieving interactive multiagent simulations over Jason through Java tuningVíctor Fernán<strong>de</strong>z Bauset, Francisco Grimaldo Moreno, Miguel Lozano Ibáñez, Juan Manuel Orduña Huertas613 Dynamically Tuning Master/Worker Applications with MATEA. Martínez, A. Morajko619 Análisis <strong>de</strong> un sistema Android como plataforma para juegos <strong>de</strong> realidad aumentadaA.L. Sarmiento, M. Amor, C.V. Regueiro, E.J. Padrón625 Un mo<strong>de</strong>lo analítico mejorado para la arquitectura CUDAM. Viñas, B.B. Fraguela, M. Amor, Ramón Doallo631 Análisis <strong>de</strong> Escalabilidad en Aplicaciones Paralelas con Carga <strong>de</strong> Trabajo No EquilibradaJ.L. Bosque, OD. Robles, P. Toharía, L. Pastor637 Mejorando las aplicaciones <strong>de</strong> red en arquitecturas multinúcleo heterogéneasA. Ortiz, J. Ortega, Antonio F. Díaz, A. Prieto643 Estimación <strong>de</strong>l efecto <strong>de</strong> los fallos cache en el rendimiento <strong>de</strong> aplicaciones paralelasD.R. Martínez, Vicente Blanco, J.C. Cabaleiro, T.F. Pena, Francisco F. Rivera649 Metodología para la sintonización <strong>de</strong> aplicaciones OpenMP en sistemas multicoreC. Allan<strong>de</strong>, J. Jorba, E. César, A. Morajko655 Herramientas para la monitorización <strong>de</strong> los accesos a memoria <strong>de</strong> códigos paralelos mediante contadores hardwareOscar G. Lorenzo, Juan A. Lorenzo, Dora B. Heras, Juan C. Pichel, Francisco F. Rivera661 Evaluación <strong>de</strong>l Benchmark Rodinia en los sistemas <strong>de</strong>l SAIIL. Cerrudo, A. J. Dorta, J. J. Fumero, C. González, L. Grillo, I. López, F. <strong>de</strong> San<strong>de</strong><strong>JP2011</strong>-xi


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Computación <strong>de</strong> altas prestaciones sobre arquitecturas paralelas heterogéneas669 Algoritmos eficientes para la transformada wavelet discreta en multicores y GPUsV. Galiano, O. López, Manuel P. Malumbres, H. Migallón675 Tableless Distributed Routing in Heterogeneous MPSoC SystemsJosé Cano, José Flich, José Duato, Marcello Coppola, Riccardo Locatelli681 Uso <strong>de</strong>l conocimiento <strong>de</strong> la arquitectura Fermi para mejorar el rendimiento en aplicaciones CUDAYuri Torres, Arturo González-Escribano, Diego R. Llanos687 Estrategias <strong>de</strong> optimización en diferentes arquitecturas CUDA usando llCoMPR. Reyes, J. J. Fumero, I. López, F. <strong>de</strong> San<strong>de</strong>693 Sistema modular <strong>de</strong>sarrollado en FPGA, para el cálculo <strong>de</strong> mapas <strong>de</strong> disparidad <strong>de</strong> imagenes estereoscópicasS. Ibarra, José Ignacio Benavi<strong>de</strong>s, M.H. Calviño699 Estrategias <strong>de</strong> optimización en GPU y CPU multi-core <strong>de</strong> mo<strong>de</strong>los SPHJ. M. Domínguez, A. J. C. Crespo, A. Barreiro, M. Gómez-Gesteira705 Implementación <strong>de</strong>l algoritmo <strong>de</strong> registro no lineal DARTEL sobre una plataforma heterogéneaP. Valero, José Luis Sánchez, Enrique Arias, D. CazorlaCompilación para sistemas <strong>de</strong> altas prestaciones713 Checkpoint Size Reduction in Application-level Fault Tolerant SolutionsI. Cores, G. Rodríguez, M. Martín, P. González719 Source-to-Source Transformations for Efficient SIMD Co<strong>de</strong> GenerationAlejandro Berna, Marta Jiménez, Jose M. Llabería.727 Índice <strong>de</strong> Autores<strong>JP2011</strong>-xii


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Algoritmos y técnicas <strong>de</strong> programación paralelas<strong>JP2011</strong>-1


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-2


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Una Versión Paralela <strong>de</strong> la EvoluciónDiferencial para Pre<strong>de</strong>cir Motifs en Ca<strong>de</strong>nas <strong>de</strong>ADNDavid L. González-Álvarez1 Miguel A. Vega-Rodríguez 2 Juan A. Gómez-Pulido 3Juan M. Sánchez-Pérez 4Resumen—<strong>La</strong> utilidad y la eficiencia <strong>de</strong> un algoritmo pararesolver un <strong>de</strong>terminado problema <strong>de</strong> optimizaciónno viene dado solo por la calidad <strong>de</strong> las solucionesobtenidas, es también importante el tiempo computacionaly los recursos requeridos para su obtención.En este artículo presentamos una implementaciónparalela <strong>de</strong> la Evolución Diferencial (DE) para resolverel Problema <strong>de</strong>l Descubrimiento <strong>de</strong> Motifs(PDM). El PDM es un problema <strong>de</strong> gran importanciabiológica que pue<strong>de</strong> requerir una gran cargacomputacional si analizamos gran<strong>de</strong>s cantida<strong>de</strong>s <strong>de</strong>información genética, por ello, la utilización <strong>de</strong> paralelismoen maquinas <strong>de</strong> memoria compartida pue<strong>de</strong>ayudarnos a obtener resultados más rápidamente.Para asegurarnos <strong>de</strong> que nuestra heurística obtieneresultados relevantes, hemos comparado los resultadosobtenidos con los obtenidos por un algoritmoestándar en la computación evolutiva como es el algoritmoNSGA-II, a<strong>de</strong>más <strong>de</strong> con otros catorce métodosmuy conocidos <strong>de</strong>ntro <strong>de</strong>l campo <strong>de</strong> la biología. Comoveremos, la estructura <strong>de</strong>l algoritmo lo hace apropiadopara la paralelización, logrando buenos resultadosy eficiencias <strong>de</strong> hasta un 95%.Palabras clave—Evolución Diferencial, computación paralela, multinúcleo,optimización multiobjetivo, <strong>de</strong>scubrimiento<strong>de</strong> motifs.I. IntroducciónEn los últimos años hemos visto una granevolución en las interfaces <strong>de</strong> memoria compartida.Actualmente prácticamente todos los compiladoresincluyen las librerías necesarias para <strong>de</strong>sarrollarfácilmente programas paralelos. Entre todasestas interfaces estándares <strong>de</strong> programación paralela<strong>de</strong>stacan MPI y OpenMP. MPI es una interfaz <strong>de</strong>dicadaa la programación <strong>de</strong> clusters, mientras queOpenMP es el estándar <strong>de</strong> programación más empleadoen la programación <strong>de</strong> multiprocesadores conmemoria compartida. En este trabajo aplicamos esteúltimo tipo <strong>de</strong> paralelismo para resolver un importanteproblema <strong>de</strong>ntro <strong>de</strong> la bioinformatica, el Problema<strong>de</strong>l Descubrimiento <strong>de</strong> Motifs (PDM). Pre<strong>de</strong>cirmotifs es uno <strong>de</strong> los problemas más importantes<strong>de</strong>ntro <strong>de</strong>l análisis <strong>de</strong> secuencias, y aun nadie ha1 Dpto. Tecnología <strong>de</strong> Computadores y Comunicaciones,Grupo <strong>de</strong> Investigación ARCO, <strong>Universidad</strong> <strong>de</strong> Extremadura,e-mail: dlga@unex.es2 Dpto. Tecnología <strong>de</strong> Computadores y Comunicaciones,Grupo <strong>de</strong> Investigación ARCO, <strong>Universidad</strong> <strong>de</strong> Extremadura,e-mail: mavega@unex.es3 Dpto. Tecnología <strong>de</strong> Computadores y Comunicaciones,Grupo <strong>de</strong> Investigación ARCO, <strong>Universidad</strong> <strong>de</strong> Extremadura,e-mail: jangomez@unex.es4 Dpto. Tecnología <strong>de</strong> Computadores y Comunicaciones,Grupo <strong>de</strong> Investigación ARCO, <strong>Universidad</strong> <strong>de</strong> Extremadura,e-mail: sanperez@unex.esconseguido resolverlo <strong>de</strong> una manera eficiente. Estosmotifs son pequeños patrones <strong>de</strong> ADN, ARNo proteínas que normalmente ejercen la función <strong>de</strong>Puntos <strong>de</strong> Unión <strong>de</strong> Factores <strong>de</strong> Transcripción endistintos genes (TFBS). Normalmente no son muylargos (alre<strong>de</strong>dor <strong>de</strong> 30 nucleótidos) y sin espacios,por lo que <strong>de</strong>scubrirlos entre una gran cantidad <strong>de</strong>información biológica en las secuencias <strong>de</strong> ADN no esuna tarea nada fácil. Para encontrarlos, hemos utilizadouna heurística basada en la Evolución Diferencial(DE) que hemos paralelizado utilizando el interfazOpenMP. A<strong>de</strong>más, hemos implementado tambiénuna versión paralela <strong>de</strong>l algoritmo NSGA-II para asídisponer <strong>de</strong> un punto <strong>de</strong> referencia con el que compararlos resultados obtenidos por nuestra propuesta.En este trabajo no solo hemos analizado las eficienciaslogradas por las versiones paralelas <strong>de</strong> estos dosalgoritmos, sino que también hemos analizado la calidad<strong>de</strong> los motifs predichos por los algoritmos. Parahacer esto, hemos aplicado diferentes indicadorescomo el Hipervolumen o la Relación <strong>de</strong> Cobertura, yestadísticas como la Sensibilidad, el Valor <strong>de</strong> PrediccionesPositivas, el Coeficiente <strong>de</strong> Rendimiento o elCoeficiente <strong>de</strong> Correlación. Como veremos, nuestroalgoritmo logra buenos resultados paralelos, a<strong>de</strong>más<strong>de</strong> resultados biológicamente relevantes.Este documento se organiza <strong>de</strong> la siguiente forma.En la siguiente sección explicamos brevemente elPDM. En la Sección III <strong>de</strong>scribimos los algoritmospresentados en este trabajo y <strong>de</strong>tallamos comolos hemos paralelizado. <strong>La</strong> Sección IV muestralos resultados obtenidos por nuestras propuestas,comparándolas con varios algoritmos y métodosbiológicos. Finalmente, la Sección V incluye variasconclusiones obtenidas tras la elaboración <strong>de</strong> estetrabajo.II. Problema <strong>de</strong>l Descubrimiento <strong>de</strong> MotifsEl Problema <strong>de</strong>l Descubrimiento <strong>de</strong> Motifs (PDM)trata <strong>de</strong> resolver <strong>de</strong> forma óptima el problema quesupone pre<strong>de</strong>cir motifs, aplicado a la tarea específica<strong>de</strong> <strong>de</strong>scubrir nuevos Puntos <strong>de</strong> Unión <strong>de</strong> Factores <strong>de</strong>Transcripción (TFBS) en secuencias <strong>de</strong> ADN [1]. LosTFBSs y otros elementos genéticos con una estructuray función específica son conocidos con el nombre<strong>de</strong> motifs. Para <strong>de</strong>scubrir motifs <strong>de</strong> una ciertarelevancia biológica <strong>de</strong>bemos satisfacer unos objetivosconcretos a la vez que cumplir ciertas restricciones.Nosotros hemos afrontado el PDM <strong>de</strong>finiendotres objetivos: el tamaño, el soporte y la simila-<strong>JP2011</strong>-3


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA IUn problema <strong>de</strong> <strong>de</strong>scubrimiento <strong>de</strong> motifs artificial. Muestra en (a) las secuencias, (b) indica las posicionesiniciales <strong>de</strong> los motifs candidatos, (c) los motifs candidatos, (d) la tasa <strong>de</strong> concordancia existente entre cadamotif candidato y el motif consenso ‘TCTTGGAA’ (umbral <strong>de</strong>l soporte en 50%) y (e) las MRP y MFP.(a) (b) (c) (d) (e)1 GAC TCTTGGAC TAATCCTTC -1214 TCTTGGAC 7/8 √ A: 2 0 0 0 0 1 10 52 A GCTTGGAA TTGACTAGTGG -1137 GCTTGGAA 7/8 √ C: 1 10 0 0 0 0 0 33 CAGGGCTCT TCTGTAAA AAA -1266 TCTGTAAA 5/8 √ G: 1 0 1 2 8 9 0 04 TTTA ACTTGGAA AGCACTCA -0434 ACTTGGAA 7/8 √ T: 6 0 9 8 2 0 0 25 ACAATATGAC ACTTGGAC CA -0607 ACTTGGAC 6/8 √ A: 20% 0% 0% 0% 0% 10% 100% 50%6 A CCTTGGAA GTCAACAAAAA -0676 CCTTGGAA 7/8 √ C: 10% 100% 0% 0% 0% 0% 0% 30%7 GCAATTCGTGT TCTTTGAT G -1089 TCTTTGAT 6/8 √ G: 10% 0% 10% 20% 80% 90% 0% 0%8 GGATAT TCTTGGAT TCCTAG -0186 TCTTGGAT 6/8 √ T: 60% 0% 90% 80% 20% 0% 0% 20%9 AGGT TCTGGGAC TTTCCAGA -0887 TCTGGGAC 6/8 √10 AAC TCGTGGAA CGGCACATG -1067 TCGTGGAA 7/8 √ Soporte: 10, Tamaño: 8, Similaridad: 81%ridad <strong>de</strong>l motif. Dado un conjunto <strong>de</strong> secuenciasS = {S i |i = 1, 2, ..., D} <strong>de</strong> nucleótidos <strong>de</strong>finidos en elalfabeto B = {A, C, G, T }. S i = {S j i |j = 1, 2, ..., w i}es una secuencia <strong>de</strong> nucleótidos, don<strong>de</strong> w i es la longitud<strong>de</strong> la secuencia. El conjunto <strong>de</strong> todas las subsecuenciascontenidas en S es {s jii |i = 1, 2, ..., D, j i =1, 2, ..., w i − l + 1}, don<strong>de</strong> j i es el punto <strong>de</strong> unión<strong>de</strong> un posible motif candidato s j i en la secuencia S i,y l es el tamaño <strong>de</strong>l motif, el primer objetivo a sermaximizado. Para obtener los valores <strong>de</strong> los otrosdos objetivos tenemos que construir la Matriz <strong>de</strong> Indicadores<strong>de</strong> Posición (MIP) A = {A i |i = 1, 2, ..., D}<strong>de</strong>l motif, don<strong>de</strong> A i = {A j i |j = 1, 2, ..., w i} es el vectorindicador con respecto a la secuencia S i . A j ies 1 si la posición j en S i es el punto <strong>de</strong> unióny 0 en caso contrario. Nos referimos al número<strong>de</strong> motifs candidatos como |A| = ∑ D ∑ wii=1 j=1 Aj i .También necesitamos encontrar el motif consenso, elcual se extrae <strong>de</strong> los motifs candidatos. En este trabajoconsi<strong>de</strong>ramos un solo motif candidato por secuenciay, solo aquellas secuencias que logren motifscandidatos <strong>de</strong> cierta calidad (con respecto almotif consenso) se tendrán en cuanta a la hora <strong>de</strong>formar el motif final. Esto se indica a través <strong>de</strong>lsegundo objetivo, el soporte. A<strong>de</strong>más, S(A) ={S(A) 1 , S(A) 2 , ..., S(A) |A| } es el conjunto <strong>de</strong> |A| motifscandidatos, don<strong>de</strong> S(A) i = S(A) 1 i S(A)2 i ...S(A)l ies el i-esimo motif candidato <strong>de</strong> |A|. S(A) pue<strong>de</strong>también expandirse con (S(A) 1 , S(A) 2 , ..., S(A) l ),don<strong>de</strong> S(A) j = S(A) j 1 S(A)j 2 ...S(A)j |A|es la lista <strong>de</strong>nucleótidos <strong>de</strong> la j-esima posición <strong>de</strong>l motif candidato.A continuación <strong>de</strong>bemos construir la Matriz <strong>de</strong>Repeticiones por Posición (MRP) N(A) teniendo encuenta el número <strong>de</strong> nucleótidos <strong>de</strong> cada tipo que hayen cada posición <strong>de</strong> cada motif candidato (A) quehaya superado el valor umbral en el segundo objetivo,el soporte. N(A) = {N(A) 1 , N(A) 2 , ..., N(A) l }y N(A) j = {N(A) j b |b ∈ B}, don<strong>de</strong> N(A)j b=|{S(A) j i |S(A)j i = b}|. El número <strong>de</strong> repeticiones <strong>de</strong>lnucleótido dominante en cada posición se normalizaobteniendo la Matriz <strong>de</strong> Frecuencia por Posición(MFP) ̂N = N(A)|A|. Finalmente, para hallar el valor<strong>de</strong>l último objetivo, la similaridad, <strong>de</strong>bemos calcularel valor medio <strong>de</strong> las repeticiones <strong>de</strong> los nucleótidosdominantes en cada columna <strong>de</strong> la MFP, tal y comose indica en la siguiente expresión:∑ li=1Similaridad(Motif) =max b{f(b, i)}l(1)don<strong>de</strong> f(b, i) es la puntuación obtenida por el nucleótidob en la columna i <strong>de</strong> la MFP y max b {f(b, i)}es el número <strong>de</strong> repeticiones normalizado obtenidopor el nucleótido dominante en la columna i.Para orientar la búsqueda <strong>de</strong> patrones hacia solucionescon cierta relevancia biológica, hemos incorporadovarias restricciones que <strong>de</strong>ben satisfacer todaslas soluciones obtenidas por nuestros algoritmos.<strong>La</strong> primera <strong>de</strong> ellas limita el tamaño <strong>de</strong> los motifsal rango [7,64], don<strong>de</strong> 7 es el tamaño mínimo y 64el máximo. En el segundo objetivo hemos establecidoun valor mínimo en el soporte <strong>de</strong> 2 para losmotifs <strong>de</strong>scubiertos en instancias compuestas por 4o menos secuencias, y <strong>de</strong> 3 en las <strong>de</strong>más (más <strong>de</strong>4 secuencias). Finalmente, hemos aplicado el concepto<strong>de</strong> complejidad [2]. <strong>La</strong> complejidad <strong>de</strong> un motif<strong>de</strong>be consi<strong>de</strong>rarse para <strong>de</strong>scartar las solucionesmenos complejas y, por lo tanto, menos relevantesbiológicamente hablando. Para ello aplicaremos lasiguiente expresión:Complejidad = log Nl!∏ (ni )!(2)don<strong>de</strong> N = 4 para secuencias <strong>de</strong> ADN, l es el tamaño<strong>de</strong>l motif, y n i es el número <strong>de</strong> nucleótidos <strong>de</strong>l tipoi ∈ {A, C, G, T }.<strong>La</strong> Tabla I muestra un PDM artificial con motifs <strong>de</strong>tamaño = 8. En este ejemplo, utilizando los motifscandidatos mostrados en las Tablas Ia y Ic obtenemosel motif consenso TCTTGGAA. Con este motifpo<strong>de</strong>mos calcular el valor <strong>de</strong>l segundo objetivo, elsoporte (ver Tabla Id). <strong>La</strong>s secuencias cuyos motifscandidatos superen o igualen el valor umbral <strong>de</strong> concordanciaestablecido en 50% (4/8), se tendrán encuenta en este objetivo. En este ejemplo obtenemosun soporte = 10. El último paso es construir la MRP<strong>JP2011</strong>-4


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 1.Esquema <strong>de</strong> la versión paralela <strong>de</strong> la Evolución Diferencial.y la MFP utilizando los nucleótidos <strong>de</strong> los motifs candidatosque hayan superado el filtro anterior (umbral<strong>de</strong>l soporte). Hecho esto, po<strong>de</strong>mos obtener el valorfinal <strong>de</strong> similaridad aplicando la ecuación (1). Eneste ejemplo obtenemos una similaridad = 0, 8125.III. Descripción <strong>de</strong> los AlgoritmosParalelosEn este trabajo presentamos una versión paralela<strong>de</strong> la Evolución Diferencial (DE). Esta nueva versión<strong>de</strong>l algoritmo la comparamos con otra versión paralela<strong>de</strong>l algoritmo NSGA-II. El algoritmo DE es unalgoritmo basado en población [3] que optimiza unproblema manteniendo una serie <strong>de</strong> individuos que secruzan para generar otros nuevos. Todo este procesose realiza aplicando una formulación <strong>de</strong> cruce y mutaciónmuy sencilla. Para adaptar el funcionamiento<strong>de</strong> este algoritmo al PDM multiobjetivo hemos incorporadoel concepto <strong>de</strong> Torneos <strong>de</strong> Pareto, obteniendoun nuevo algoritmo llamado Evolución Diferencialcon Torneos <strong>de</strong> Pareto (DEPT), <strong>de</strong>scrito en [4]. El interfaz<strong>de</strong> programación OpenMP es el escogido para<strong>de</strong>sarrollar las versiones paralelas <strong>de</strong> nuestros algoritmos.Si analizamos el funcionamiento <strong>de</strong>l DEPT ([3]y [4]) po<strong>de</strong>mos comprobar cómo no existe ninguna<strong>de</strong>pen<strong>de</strong>ncia <strong>de</strong> datos en el bucle principal, por loque se pue<strong>de</strong> paralelizar en su totalidad. Para ello,hemos incrustado la directiva OpenMP ‘#pragmaomp parallel for’ antes <strong>de</strong>l bucle principal <strong>de</strong>l algoritmo,especificando apropiadamente las variablespúblicas y privadas necesarias. En cada iteración <strong>de</strong>lbucle el algoritmo aplica el esquema <strong>de</strong> selección especificadoa todos los individuos <strong>de</strong> la población (individuosobjetivo). Suponiendo una población <strong>de</strong> 8individuos en una maquina <strong>de</strong> 8 núcleos, cada núcleoprocesaría solo un individuo objetivo, generando elcorrespondiente individuo <strong>de</strong> prueba y ejecutando eltorneo <strong>de</strong> Pareto que enfrentará al individuo objetivocon el individuo <strong>de</strong> prueba. Nuestra Evolución Diferencialparalela divi<strong>de</strong> cada iteración <strong>de</strong>l bucle principalen diferentes hilos. Si lo explicásemos <strong>de</strong> formamatemática, diríamos que disponiendo <strong>de</strong> un sisteman-núcleos y un tamaño <strong>de</strong> población P S, cada hiloejecuta P S/n iteraciones <strong>de</strong>l bucle principal. En laFigura 1 mostramos una representación grafica <strong>de</strong>lproceso seguido por el algoritmo paralelo suponiendouna población <strong>de</strong> 32 individuos en un sistema con 8núcleos. En este ejemplo <strong>de</strong>splegamos 8 hilos, don<strong>de</strong>cada uno <strong>de</strong> ellos procesa 4 individuos objetivo encada generación. Es importante saber que hasta quetodos los hilos no hayan terminado su ejecución, lasiguiente generación no comenzará.El segundo algoritmo que hemos paralelizado esel Algoritmo Genético <strong>de</strong> Or<strong>de</strong>nación Nodominada(NSGA-II). Este algoritmo es una extensión <strong>de</strong>lAlgoritmo Genético (GA) diseñado para optimizarmúltiples objetivos. En [5] po<strong>de</strong>mos encontraruna <strong>de</strong>scripción <strong>de</strong>tallada <strong>de</strong>l algoritmo. Para paralelizarlohemos seguido la misma metodología queen el algoritmo DEPT, utilizando el interfaz <strong>de</strong> programaciónOpenMP. En la versión paralela <strong>de</strong>l algoritmoNSGA-II hemos paralelizado la función quegenera la población padre, la función que se encarga<strong>de</strong> generar la población hija utilizando individuos <strong>de</strong>la población padre, la or<strong>de</strong>nación nodominada y elcálculo <strong>de</strong> la distancia <strong>de</strong> crowding. Para ello hemosvuelto a hacer uso <strong>de</strong> la directiva ‘#pragma ompparallel for’, <strong>de</strong>finiendo los parámetros necesariospara no sobrescribir ninguna variable. Empleando lamisma formulación matemática que en el algoritmoanterior, en las funciones que generan las poblacionespadre e hija, cada hilo genera P S/n individuos, lograndouna mejora temporal consi<strong>de</strong>rable. En lasotras dos funciones (la or<strong>de</strong>nación nodominada y elcálculo <strong>de</strong> la distancia <strong>de</strong> crowding) cada hilo calculael numero <strong>de</strong> soluciones dominadas o que dominan acada individuo en cada uno <strong>de</strong> ellos (para <strong>de</strong>spuéspo<strong>de</strong>r or<strong>de</strong>narlos según esos datos) y obtener así elcorrespondiente valor <strong>de</strong> distancia <strong>de</strong> crowding.Con los dos algoritmos paralelizados po<strong>de</strong>moscomenzar a hacer comparativas para saber cuál <strong>de</strong> losdos algoritmos es más apropiado paralelizar. En lasiguiente sección se muestra los resultados (speedupsy eficiencias) obtenidos por cada algoritmo y se analizael comportamiento <strong>de</strong> ambos en diferentes sistemasmulti-núcleo. Como veremos los primerosresultados indican que el algoritmo DEPT es másapropiado para la paralelización que el algoritmoNSGA-II, logrando eficiencias <strong>de</strong> hasta un 95%.IV. Evaluación Experimental yComparativasAntes <strong>de</strong> paralelizar los algoritmos, <strong>de</strong>bemos encontrarlas configuraciones que mejores resultadosobtienen. En esta sección <strong>de</strong>scribimos las instanciasutilizadas en nuestros experimentos y mostramos losresultados obtenidos. <strong>La</strong> metodología seguida y larepresentación <strong>de</strong> los individuos es la misma que laque utilizada en [4], estableciendo como condición<strong>de</strong> terminación 3000 generaciones en ambos algorit-<strong>JP2011</strong>-5


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA IICaracterísticas <strong>de</strong> las instancias utilizadas.TABLA IIIMejores configuraciones encontradas.Nombre #Sec. Tamaño Nombre #Sec. Tamañodm01g 4 1500 mus02r 9 1000dm04g 4 2000 mus03g 5 500dm05g 3 2500 mus07g 4 1500hm03r 10 1500 yst03m 8 500hm04m 13 2000 yst04r 7 1000hm16g 7 3000 yst08r 11 1000DEPT Tamaño <strong>de</strong> la Población 200Probabilidad <strong>de</strong> Cruce 25%Factor <strong>de</strong> Mutación 3%Esquema <strong>de</strong> Selección Aleatorio/1/BinomialNSGA-II Tamaño <strong>de</strong> la Población 200Probabilidad <strong>de</strong> Cruce 60%Factor <strong>de</strong> Mutación 50%Elección <strong>de</strong> los Padres Torneo BinarioTABLA IVHipervolúmenes obtenidos por los algoritmos.DEPTNSGAIIPeor Media Mejor Peor Media Mejordm01g 76,69% 79,68% 82,41% 80,62% 81,56% 82,27%dm04g 77,26% 79,74% 81,70% 80,22% 81,06% 81,90%dm05g 79,59% 81,95% 84,46% 83,53% 84,41% 85,86%hm03r 61,80% 65,33% 71,91% 42,70% 47,40% 53,38%hm04m 56,87% 61,25% 65,40% 39,30% 43,32% 45,93%hm16g 74,78% 79,72% 85,41% 65,92% 68,12% 70,47%mus02r 67,71% 69,96% 74,69% 57,09% 59,24% 61,72%mus03g 73,73% 77,49% 79,62% 76,38% 77,18% 77,55%mus07g 76,49% 80,58% 87,19% 86,16% 87,01% 88,30%yst03m 71,85% 73,22% 74,98% 63,50% 65,52% 68,10%yst04r 70,66% 74,32% 78,97% 74,29% 74,80% 75,80%yst08r 63,39% 68,03% 75,78% 62,23% 64,87% 67,09%Media 70,90% 74,27% 78,54% 67,66% 69,54% 71,53%TABLA VRelación <strong>de</strong> cobertura (A ≽ B).A B dm01g dm04g dm05g hm03r hm04m hm16g mus02r mus03g mus07g yst03m yst04r yst08r MediaDEPT NSGAII 44,12% 65,85% 55,17% 97,62% 97,26% 90,00% 94,52% 83,93% 60,87% 93,06% 89,83% 95,24% 80,62%NSGAII DEPT 51,79% 39,29% 48,39% 0,00% 0,00% 0,00% 0,00% 23,75% 42,11% 0,78% 0,00% 0,00% 17,17%mos. Para comparar los resultados obtenidos por losalgoritmos que hemos implementado, a<strong>de</strong>más <strong>de</strong>l indicadorHipervolumen, hemos utilizado la Relación<strong>de</strong> Cobertura [6], la cual permite analizar que algoritmoobtiene los mejores frentes <strong>de</strong> Pareto. En nuestraexperimentación hemos utilizado doce instanciasreales seleccionadas <strong>de</strong> la base <strong>de</strong> datos TRANS-FAC [7]. Estos conjuntos <strong>de</strong> datos tienen diferentespropieda<strong>de</strong>s para asegurar que nuestros algoritmosfuncionan bien con todo tipo <strong>de</strong> instancias (ver TablaII).Los parámetros configurados y los mejores valoresencontrados para cada uno <strong>de</strong> ellos se muestran enla Tabla III. El or<strong>de</strong>n en el que estos han sido ajustadoses el mismo que aparece en la Tabla III. Para<strong>de</strong>mostrar que los resultados obtenidos por ambosalgoritmos son relevantes hemos realizado comparativasutilizando diferentes indicadores. <strong>La</strong> primeracomparativa analiza los resultados obtenidos por ambosalgoritmos utilizando el indicador Hipervolumen.Este indicador mi<strong>de</strong> la región cubierta por las solucionespredichas por cada algoritmo en cada instancia.En la Tabla IV mostramos los Hipervolúmenesobtenidos. Po<strong>de</strong>mos apreciar como en los conjuntos<strong>de</strong> datos con 4 o menos secuencias (instanciasdm y mus07g) el algoritmo NSGA-II logra mejoresresultados que el DEPT. Vemos también como enlos conjuntos <strong>de</strong> datos con entre 5 y 7 secuencias(mus03g, yst04r y hm16g) ambos algoritmos obtienenHipervolúmenes similares. Sin embargo, elalgoritmo DEPT obtiene mejores resultados en lasinstancias con 7 o más secuencias. Esto <strong>de</strong>muestraque el algoritmo DEPT es un algoritmo muy regular,mientras que el algoritmo NSGA-II solo funcionabien en instancias sencillas con pocas secuencias.En la Tabla V aplicamos el segundo indicador,la Relación <strong>de</strong> Cobertura. Este indicador permitecomparar los resultados individuales obtenidos porambos algoritmos [6], ya que se aplica sobre las solucionesnodominadas <strong>de</strong>scubiertas por los algoritmos.En la Tabla V vemos como las soluciones nodominadas<strong>de</strong>l algoritmo DEPT cubren el 80.62% <strong>de</strong>las soluciones nodominadas <strong>de</strong>l algoritmos NSGA-II,mientras que el algoritmo NSGA-II solo logra cubrir<strong>JP2011</strong>-6


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA VIComparativas <strong>de</strong> Sensibilidad (nSn) y Valor <strong>de</strong> Predicciones Positivas (nP P V ) <strong>de</strong> las soluciones <strong>de</strong>l DEPT.nSnnPPVInstancia Mejor Valor (método) DEPT Incremento Mejor Valor (método) DEPT Incrementodm01g 0,344000 (SeSiMCMC) 0,440000 0,096000 0,344000 (SeSiMCMC) 1,000000 0,656000dm04g 0,022222 (MotifSampler) 0,370370 0,348148 0,032967 (MotifSampler) 0,888889 0,855922dm05g 0,037500 (MEME) 0,293750 0,256250 0,026666 (MEME) 1,000000 0,973333hm03r 0,063725 (MEME) 0,250000 0,186275 0,108333 (MEME) 0,564103 0,455770hm04m 0,005952 (AlignACE) 0,273810 0,267858 0,006060 (AlignACE) 0,333333 0,327272hm16g 0,000000 (-) 0,384146 0,384146 0,000000 (-) 0,666667 0,666667mus02r 0,094827 (MEME) 0,306034 0,211206 0,142857 (MEME) 0,750000 0,607143mus03g 0,281690 (AlignACE) 0,528169 0,246479 0,256410 (AlignACE) 1,000000 0,743590mus07g 0,040000 (ANN Spec) 0,510000 0,470000 0,020942 (ANN Spec) 1,000000 0,979058yst03m 0,340136 (Improbizer) 0,251701 -0,088435 0,700000 (YMF) 0,904762 0,204762yst04r 0,335877 (Consensus) 0,448598 0,112720 0,357142 (MITRA) 0,590909 0,233766yst08r 0,387096 (AlignACE) 0,390681 0,003584 0,786407 (MotifSampler) 0,559524 -0,226884TABLA VIIComparativas <strong>de</strong> Rendimiento (nP C) y Coeficiente <strong>de</strong> Correlación (nCC) <strong>de</strong> las soluciones <strong>de</strong>l DEPT.nPCnCCInstancia Mejor Valor (método) DEPT Incremento Mejor Valor (método) DEPT Incrementodm01g 0,207729 (SeSiMCMC) 0,404762 0,197033 0,330042 (SeSiMCMC) 0,628460 0,298417dm04g 0,013452 (MotifSampler) 0,247525 0,234072 0,013401 (MotifSampler) 0,388252 0,374851dm05g 0,015831 (MEME) 0,211429 0,195598 0,006491 (MEME) 0,399132 0,392641hm03r 0,041800 (MEME) 0,195402 0,153601 0,063601 (MEME) 0,330695 0,267094hm04m 0,003012 (AlignACE) 0,136364 0,133352 -0,000399 (AlignACE) 0,237391 0,237791hm16g 0,000000 (-) 0,274882 0,274882 -0,005203 (MEME) 0,438551 0,443755mus02r 0,060439 (MEME) 0,201258 0,140818 0,097480 (MEME) 0,347446 0,249966mus03g 0,155038 (AlignACE) 0,401070 0,246031 0,222479 (AlignACE) 0,551272 0,328792mus07g 0,013937 (ANN Spec) 0,382114 0,368177 0,006056 (ANN Spec) 0,555691 0,549635yst03m 0,261904 (oligodyad) 0,203488 -0,058417 0,437304 (oligodyad) 0,369000 -0,068304yst04r 0,202765 (Consensus) 0,265152 0,062387 0,322430 (Consensus) 0,430516 0,108086yst08r 0,269103 (MotifSampler) 0,250000 -0,019103 0,470595 (MotifSampler) 0,384898 -0,085698TABLA VIIIRendimiento <strong>de</strong>l DEPT y el NSGA-II utilizando diferentes sistemas multi-núcleo. X es el tiempo medio (ensegundos), S p es el speed-up y E p la eficiencia, para p núcleos.Secuencial 2-Núcleos 4-Núcleos 8-NúcleosDEPT NSGA-II DEPT NSGA-II DEPT NSGA-II DEPT NSGA-IIInstancias X X S 2 E 2 S 2 E 2 S 4 E 4 S 4 E 4 S 8 E 8 S 8 E 8dm01g 139,0 176,6 1,90 95,1% 1,80 90,0% 3,63 90,7% 3,13 78,4% 6,51 81,3% 4,58 57,3%dm04g 139,1 168,6 1,90 94,9% 1,90 95,1% 3,62 90,6% 3,16 79,0% 6,50 81,2% 4,89 61,2%dm05g 107,2 43,2 1,89 94,3% 1,68 84,0% 3,57 89,2% 2,38 59,6% 6,21 77,6% 2,80 35,0%hm03r 150,7 115,6 1,87 93,7% 1,74 86,9% 3,48 87,0% 2,78 69,4% 5,42 67,8% 3,63 45,3%hm04m 130,5 132,3 1,81 90,4% 1,73 86,4% 3,33 83,3% 2,85 71,2% 4,33 54,1% 3,75 46,8%hm16g 156,8 170,6 1,88 94,0% 1,77 88,6% 3,59 89,8% 3,08 77,1% 6,31 78,8% 4,56 56,9%mus02r 177,6 141,7 1,88 93,9% 1,76 88,2% 3,60 90,0% 2,92 73,0% 6,26 78,3% 4,15 51,9%mus03g 131,7 180,8 1,91 95,3% 1,75 87,7% 3,60 90,1% 3,30 82,4% 6,41 80,1% 4,83 60,4%mus07g 173,1 142,3 1,85 92,5% 1,82 90,8% 3,51 87,7% 3,06 76,4% 5,73 71,6% 4,06 50,7%yst03m 175,9 190,1 1,88 94,1% 1,83 91,7% 3,61 90,1% 3,20 80,0% 6,52 81,5% 4,84 60,5%yst04r 172,9 218,2 1,90 94,8% 1,82 91,0% 3,63 90,7% 3,19 79,9% 6,50 81,3% 4,87 60,9%yst08r 200,1 160,6 1,89 94,7% 1,78 89,1% 3,61 90,1% 3,09 77,1% 6,26 78,2% 4,30 53,7%Media 154,6 153,4 1,88 94,0% 1,78 89,1% 3,56 89,1% 3,01 75,3% 6,08 76,0% 4,27 53,4%<strong>JP2011</strong>-7


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011el 17.17% <strong>de</strong> las soluciones <strong>de</strong>l DEPT.Po<strong>de</strong>mos observar también como en casi todaslas instancias don<strong>de</strong> el algoritmo NSGA-II logramejores Hipervolúmenes que el DEPT, este últimologra mayores tasas <strong>de</strong> cobertura. Esto es <strong>de</strong>bidoal hecho <strong>de</strong> que el algoritmo NSGA-II logra puntosmás dispersos en sus frentes <strong>de</strong> Pareto (favoreciendoel Hipervolumen). Sin embargo, las soluciones <strong>de</strong>scubiertaspor el DEPT tienen mejores valores ensus objetivos. <strong>La</strong> última comparativa preten<strong>de</strong> <strong>de</strong>mostrarla relevancia biológica <strong>de</strong> los motifs predichospor nuestro principal algoritmo, el DEPT. Parahacer esto, hemos comparado estas soluciones conlas predichas por otros catorce métodos bien conocidosen el campo biológico, <strong>de</strong>scritos con <strong>de</strong>talle en[8]. En esta comparativa analizamos la Sensibilidad(nSn), el Valor <strong>de</strong> Predicciones Positivas (nP P V ), elRendimiento (nP C) y el Coeficiente <strong>de</strong> Correlación(nCC) <strong>de</strong> los mejores motifs <strong>de</strong>scubiertos por el algoritmoDEPT, en cada uno <strong>de</strong> los conjuntos <strong>de</strong> datos.Comparándolos con el mejor resultado obtenido porel mejor método <strong>de</strong> entre los catorce anteriormentemencionados. Véase como en las Tablas VI y VIIen casi todas las instancias, los resultados obtenidospor nuestros motifs logran mejores resultados que losobtenidos por el mejor, <strong>de</strong>mostrando así que los resultados<strong>de</strong>scubiertos por nuestra heurística tienenuna gran relevancia biológica.Finalmente, en esta sección presentamos los resultados<strong>de</strong> la paralelización aplicada sobre los algoritmosDEPT y NSGA-II, utilizando el interfaz<strong>de</strong> programación OpenMP. Es importante <strong>de</strong>stacarque los resultados obtenidos por las versiones paralelasy secuenciales <strong>de</strong> los algoritmos son los mismos,solo que se obtienen más rápidamente. En laTabla VIII mostramos los tiempos <strong>de</strong> ejecución, losspeedups y las eficiencias logradas por ambos algoritmos(DEPT y NSGA-II), en distintos sistemas multinúcleo(con 1, 2, 4 y 8 núcleos). En cada experimentohemos calculado el valor medio <strong>de</strong> speedup yeficiencia <strong>de</strong> entre 30 ejecuciones in<strong>de</strong>pendientes, utilizandouna maquina multi-núcleo que dispone <strong>de</strong> 8núcleos (2,8Ghz y Scientific Linux 5,3). En la TablaVIII vemos como el algoritmo DEPT consigue casiel speedup i<strong>de</strong>al utilizando los sistemas con 2 y 4núcleos. Vemos también como el algoritmo NSGA-II,aunque consigue eficiencias muy prometedoras (porencima <strong>de</strong>l 75%), obtiene resultados un poco peoresque los logrados por el DEPT. Finalmente, enlas pruebas realizadas con el sistema <strong>de</strong> 8 núcleos,el algoritmo DEPT mantiene eficiencias mayores <strong>de</strong>l75%, mientras que el algoritmo NSGA-II cae hasta el53,4%. Con estos datos concluimos que el algoritmoDEPT es capaz <strong>de</strong> obtener soluciones hasta 6 vecesmás rápido (speedup <strong>de</strong> 6,08) en un sistema con 8núcleos. Por contra, el algoritmo NSGA-II solo escapaz <strong>de</strong> obtener los resultados 4 veces más rápido(speedup <strong>de</strong> 4,27). <strong>La</strong>s diferencias entre ambos algoritmosson consi<strong>de</strong>rables siendo el algoritmo DEPTun algoritmo muy a<strong>de</strong>cuado para paralelizar.V. Conclusiones y Líneas FuturasEn este trabajo hemos propuesto una versión paralela<strong>de</strong> la Evolución Diferencial para resolver elProblemas <strong>de</strong>l Descubrimiento <strong>de</strong> Motifs (PDM)utilizando la interfaz OpenMP. Los experimentosrealizados con distintos sistemas multi-núcleo <strong>de</strong>muestranque este algoritmo es apropiado para laparalelización, obteniendo eficiencias <strong>de</strong> hasta un95%. También hemos <strong>de</strong>sarrollado la correspondienteversión paralela <strong>de</strong>l algoritmo NSGA-II un algoritmoestándar en computación evolutiva. Analizandotodos los resultados po<strong>de</strong>mos concluir quenuestra propuesta paralela obtiene mejores eficienciasy mejores predicciones que el algoritmo NSGA-II. Como trabajo futuro implementaremos y paralelizaremosnuevos algoritmos evolutivos multiobjetivopara resolver el PDM, comparando los resultadosobtenidos con los obtenidos por los algoritmosincluidos en este trabajo.Agra<strong>de</strong>cimientosGracias a la Fundación Valhondo Calaff por elapoyo económico ofrecido a David L. González-Álvarez para realizar este trabajo. Este trabajo estáparcialmente financiado por el Ministerio <strong>de</strong> Cienciae Innovación y el FEDER (Fondo Europeo <strong>de</strong> DesarrolloRegional), bajo el proyecto TIN2008-06491-C04-04 (proyecto M*).Referencias[1] P. D’haeseleer, What are DNA sequence motifs?, NatureBiotechnology, vol. 24, no. 4, pp. 423-425, 2006.[2] G.B. Fogel et al., Evolutionary computation for discoveryof composite transcription factor binding sites, NucleicAcids Reseach, vol. 36, no. 21, pp. e142, 2008.[3] K. Price, R. Storn, Differential Evolution - A Simple EvolutionStrategy for Fast Optimization, Dr. Dobb’s Journal,vol. 22, no. 4, pp. 18-24 and 78, 1997.[4] D.L. González-Álvarez, M.A. Vega-Rodríguez, J.A.Gómez-Pulido, J.M. Sánchez-Pérez, Solving the MotifDiscovery Problem by Using Differential Evolution withPareto Tournaments, CEC’10, IEEE Computer Society,Barcelona, Spain, pp. 4140-4147, 2010.[5] K. Deb, A. Pratap, S. Agarwal, T. Meyarivan, A fast an<strong>de</strong>litist multi-objective genetic algorithm: NSGA II, IEEETransactions on Evolutionary Computation, vol. 6, 182-197, 2002.[6] E. Zitzler, K. Deb, L. Thiele, Comparison of multiobjectiveevolutionary algorithms: empirical results, IEEE Transactionson Evolutionary Computation, vol. 8, no. 2, pp.173-195, 2000.[7] E. Wingen<strong>de</strong>r, P. Dietze, H. Karas, R. Knüppel, TRANS-FAC: a database on transcription factors and their DNAbinding sites, Nucleic Acids Research, vol. 24, no. 1, pp.238-241, 1996.[8] M. Tompa, et al, Assessing computational tools for thediscovery of transcription factor binding sites, NatureBiotechnology, vol. 23, no. 1, pp. 137-144, 2005.<strong>JP2011</strong>-8


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Comparación <strong>de</strong> Algoritmos Evolutivos Paralelos y Secuencialespara el Alineamiento Múltiple <strong>de</strong> SecuenciasFernando José Mateus Silva 1 Juan Manuel Sánchez-Pérez 2 , Juan Antonio Gómez-Pulido 2 and MiguelA. Vega-Rodríguez 2 -TISCTGNIGAG-NHVKWYQQLPGResumen—El alineamiento múltiple <strong>de</strong> secuencias es una <strong>de</strong>las tareas más comunes en Bioinformática. Es un método quepermite organizar un conjunto <strong>de</strong> secuencias moleculares con elfin <strong>de</strong> mostrar sus similitu<strong>de</strong>s y sus diferencias. El uso <strong>de</strong>métodos exactos, para abordar este problema, está limitado porla gran cantidad <strong>de</strong> recursos <strong>de</strong> computación necesarios paraexplorar espacios <strong>de</strong> soluciones gran<strong>de</strong>s y complejos. AlineaGAes un algoritmo evolutivo <strong>de</strong>sarrollado para realizaralineamiento múltiple <strong>de</strong> secuencias y constituye, a<strong>de</strong>más, unaalternativa para mejorar la exploración y explotación <strong>de</strong> labúsqueda <strong>de</strong> soluciones con el fin <strong>de</strong> encontrar el mejoralineamiento. Este algoritmo se ha <strong>de</strong>sarrollado tanto en formasecuencial como paralela. <strong>La</strong> versión paralela utiliza elprotocolo MPI y, no sólo aumenta la calidad <strong>de</strong> las solucionesencontradas sino que las encuentra en menos tiempo. En estetrabajo se comparan las versiones secuencial y paralela <strong>de</strong>AlineaGA, realizando a<strong>de</strong>más una comparación <strong>de</strong> la calidad<strong>de</strong> las soluciones obtenidas con las que se encuentran con una<strong>de</strong> las herramientas mas usadas en el alineamiento múltiple <strong>de</strong>secuencias - ClustalW2. Los resultados <strong>de</strong> esta comparaciónpermiten sacar conclusiones sobre la eficacia y aplicabilidad <strong>de</strong>los algoritmos <strong>de</strong>sarrollados.Palabras clave—Alineamiento múltiple <strong>de</strong> secuencias,algoritmos genéticos, algoritmos genéticos paralelos, MPI,MPI.NET.UI. INTRODUCCIÓNNA <strong>de</strong> las tareas más comunes en Bioinformática es elalineamiento <strong>de</strong> secuencias moleculares. Diversosmétodos <strong>de</strong> mo<strong>de</strong>lización biológica <strong>de</strong>pen<strong>de</strong>n <strong>de</strong> unalineamiento preciso <strong>de</strong> las secuencias. Entre estos métodosse encuentran la reconstrucción filogenética, los perfiles y lapredicción <strong>de</strong> estructuras; y se aplican a diversas áreas comogenómica funcional, estudios evolutivos, mo<strong>de</strong>lado <strong>de</strong>estructuras, experimentos <strong>de</strong> mutagénesis y diseño <strong>de</strong>fármacos [1]. El alineamiento múltiple <strong>de</strong> secuencias pue<strong>de</strong>ayudar a comparar la relación <strong>de</strong> estructuras entre lassecuencias estableciendo conexiones entre sus elementos[2]. Un alineamiento organiza las secuencias <strong>de</strong> manera queindica don<strong>de</strong> las secuencias son similares, y don<strong>de</strong> sondiferentes. En las secuencias se pue<strong>de</strong>n introducir espaciospara encontrar regiones <strong>de</strong> similitud entre ellas. Estos1School of Technology and Management, Computer Science andCommunication Research Centre, of the Polytechnic Institute of Leiria,Portugal (e-mail: fernando.silva@estg.ipleiria.pt).2Dept. Tecnologías Computadores y Comunicaciones, EscuelaPolitécnica, <strong>Universidad</strong> <strong>de</strong> Extremadura, Cáceres, Spain (e-mail:{sanperez, jangomez, mavega}@unex.es).espacios se <strong>de</strong>nominan “gaps” y se representan por el signo“-”. Un alineamiento óptimo es el que exhibe el mayornúmero <strong>de</strong> correspon<strong>de</strong>ncias y el menor número <strong>de</strong>diferencias, pero este alineamiento pue<strong>de</strong> o no pue<strong>de</strong> serbiológicamente significativo [3]. <strong>La</strong> Fig. 1 muestra unejemplo <strong>de</strong> un alineamiento múltiple <strong>de</strong> secuencias.-RLSCSSIFSS--YAMYWVRQAPGL-LTCTVSFDD--YYSTWVRQPPGPEVTCVVSHEDPQVKFNWYVQ-PGFig. 1. Ejemplo <strong>de</strong> un alineamiento múltiple <strong>de</strong> secuencias.Actualmente, hay dos métodos importantes para realizarel alineamiento múltiple <strong>de</strong> secuencias: el métodoprogresivo y el método iterativo. Sin embargo, elalineamiento múltiple <strong>de</strong> secuencias se pue<strong>de</strong> realizartambién con algoritmos exactos, que intentan encontrar unaalineación óptima o cuasi-óptima <strong>de</strong>ntro <strong>de</strong> límites bien<strong>de</strong>finidos. Sin embargo, este procedimiento está muylimitado por la cantidad <strong>de</strong> recursos informáticos necesariospara alinear un gran número <strong>de</strong> secuencias [4].Aunque el enfoque progresivo es el adoptado por lamayoría <strong>de</strong> las herramientas <strong>de</strong> alineamiento múltiple <strong>de</strong>secuencias [5], tiene algunas limitaciones. En este método,el alineamiento se construye alineando progresivamentepares <strong>de</strong> secuencias según su similitud. Si el cálculo <strong>de</strong> lasimilitud es incorrecto, tendrá consecuencias en el resultadofinal, que se agravarán gradualmente mientras mássecuencias se añadan al alineamiento [6]. Uno <strong>de</strong> losejemplos más visibles basados en este método es ClustalW2.0 [7], que es probablemente el programa <strong>de</strong> alineamientomúltiple <strong>de</strong> secuencias más utilizado [8].Por el contrario, los métodos iterativos producen unalineamiento y luego lo refinan durante una serie <strong>de</strong>iteraciones hasta que no pue<strong>de</strong>n hacerse más mejoras. Estosmétodos intentan optimizar una función <strong>de</strong> puntuación querefleje eventos biológicos <strong>de</strong> tal modo que optimizando lapuntuación se llegue a un alineamiento correcto [9]. LosAlgoritmos Evolutivos (AE), como p.e los AlgoritmosGenéticos (AGs), tanto secuenciales como paralelos, sonejemplos <strong>de</strong> métodos iterativos.AlineaGA [10, 11] es un AE que realiza el alineamientomúltiple <strong>de</strong> secuencias utilizando un AG que incorpora aalgunos <strong>de</strong> sus operadores genéticos un sencillo método <strong>de</strong>optimización <strong>de</strong> búsqueda local. Está disponible en dosversiones: la secuencial y la paralela. <strong>La</strong> paralela “Parallel<strong>JP2011</strong>-9


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011AlineaGA” [12] utiliza la implementación MPI.NET [13]<strong>de</strong>l protocolo <strong>de</strong> comunicaciones MPI (Message PassingInterface) [14]. A continuación presentamos unacomparación <strong>de</strong> ambas versiones <strong>de</strong>l algoritmo con el fin <strong>de</strong>sacar conclusiones sobre su eficacia. Aunque en este estudiono se tienen en cuenta los costes <strong>de</strong> comunicación, ya que secentra en la calidad <strong>de</strong> las soluciones obtenidas, se presentatambién una comparación entre los tiempos <strong>de</strong> ejecución <strong>de</strong>las diferentes versiones <strong>de</strong>l algoritmo. Con el fin <strong>de</strong>compren<strong>de</strong>r mejor la contribución <strong>de</strong> AlineaGA en laobtención <strong>de</strong> alineamientos múltiples <strong>de</strong> secuencias, tambiéncomparamos la calidad <strong>de</strong> las soluciones encontradas porambas versiones con las encontradas por ClustalW 2.0 [7] en8 conjuntos <strong>de</strong> datos o configuraciones <strong>de</strong> test <strong>de</strong> BAliBASE[15].II. ANTECEDENTESEn esta sección se introduce la terminología <strong>de</strong> losconceptos más relevantes relacionados con nuestrapropuesta para resolver el problema <strong>de</strong>l alineamientomúltiple <strong>de</strong> secuencias.A. Algoritmos GenéticosLos AEs son métodos <strong>de</strong> búsqueda inspirados en laselección natural y la supervivencia <strong>de</strong>l más apto en elmundo biológico. Se diferencian <strong>de</strong> las técnicas mástradicionales <strong>de</strong> optimización porque realizan la búsqueda <strong>de</strong>una población <strong>de</strong> soluciones, y no <strong>de</strong> una única solución.Los AGs son una categoría <strong>de</strong> métodos evolutivos <strong>de</strong>búsqueda que se centran en la optimización <strong>de</strong> problemascombinatorios. Son procesos <strong>de</strong> búsqueda robustos yadaptativos, inspirados en eventos naturales, como laherencia genética y la lucha Darwiniana por la supervivencia[16].En los AGs, una población <strong>de</strong> tamaño fijo <strong>de</strong> solucionesevoluciona mediante una serie <strong>de</strong> iteraciones con operadoresgenéticos, como el cruce y la mutación. El cruce combina lascaracterísticas <strong>de</strong> la población intercambiando segmentoscorrespondientes <strong>de</strong> dos individuos escogidosaleatoriamente (los padres), y forma dos nuevos individuossimilares (hijos). <strong>La</strong> mutación por lo general aplica uncambio aleatorio en una solución. Ambos operadores seutilizan con una tasa <strong>de</strong> probabilidad <strong>de</strong>finida <strong>de</strong> antemano[17]. Para po<strong>de</strong>r realizar esta evolución, cada solución tieneasociado un valor o “fitness” que refleja su aptitud y que sepue<strong>de</strong> utilizar para <strong>de</strong>terminar qué soluciones se pue<strong>de</strong>nutilizar para producir nuevos individuos.B. Algoritmos Genéticos ParalelosAunque la paralelización se utiliza para acelerar laejecución <strong>de</strong> los algoritmos, en el caso <strong>de</strong> los AGs tambiénse traduce en una mejora <strong>de</strong> la eficiencia y eficacia comoconsecuencia <strong>de</strong> su población estructurada [18]. AGs <strong>de</strong>múltiples poblaciones o múltiples-<strong>de</strong>mes, hacen uso <strong>de</strong>diferentes subpoblaciones in<strong>de</strong>pendientes que intercambiansoluciones <strong>de</strong> vez en cuando. Este intercambio <strong>de</strong> solucionesse <strong>de</strong>nomina migración y está limitado por diversosparámetros, tales como tasa <strong>de</strong> migración, que es el número<strong>de</strong> individuos que se intercambian entre las subpoblaciones,intervalo <strong>de</strong> la migración, que indica cuando se realiza lamigración, y topología, que establece como se realiza laconexión entre las subpoblaciones [19].Esta clase <strong>de</strong> algoritmos, también <strong>de</strong>nominados AGsdistribuidos [18], AGs <strong>de</strong> grano grueso [19], o AGsparalelos basados en islas (IPGA) [17, 19], son fáciles <strong>de</strong>implementar, ya que ejecutan varios AGs in<strong>de</strong>pendientessimultáneamente, añadiendo subrutinas que se encarguen <strong>de</strong>la migración. Estos algoritmos paralelos se pue<strong>de</strong>n ejecutaren sistemas multiprocesadores e incluso en sistemasmonoprocesador utilizando tecnologías MPI [14].III. ALGORITMOS ALINEAGAEsta sección explica brevemente las características yoperaciones que realizan los algoritmos <strong>de</strong>sarrollados. Elapartado A) introduce la versión secuencial <strong>de</strong>l AlgoritmoAlineaGA, explicando a<strong>de</strong>más características comunes aambas versiones, secuencial y paralela. En el apartado B) seexplican las particularida<strong>de</strong>s <strong>de</strong> la versión paralela, haciendoénfasis en las cuestiones <strong>de</strong> migración.A. AlineaGA – Un AE para Alineamiento Múltiple <strong>de</strong>SecuenciasAlineaGA utiliza una población <strong>de</strong> soluciones candidatasque evoluciona a lo largo <strong>de</strong> un <strong>de</strong>terminado número <strong>de</strong>generaciones. Los individuos <strong>de</strong> esta población sonalineamientos múltiples <strong>de</strong> secuencias, como el representadoen la Fig. 1, don<strong>de</strong> pue<strong>de</strong> observarse que utiliza una versiónno codificada <strong>de</strong> los cromosomas. Cada solución se generamediante la colocación <strong>de</strong> cada secuencia en una línea <strong>de</strong>larray e insertando a continuación “gaps” <strong>de</strong> forma aleatoriahasta conseguir que todas las secuencias tengan la mismalongitud. Los pasos que se realizan posteriormente consistenen seleccionar, combinar y mutar las soluciones durante unnúmero <strong>de</strong>finido <strong>de</strong> generaciones para producir nuevosindividuos (soluciones).En cada generación, todos los individuos <strong>de</strong> cadasubpoblación se evalúan para <strong>de</strong>terminar su aptitud o“fitness”. Para ello, se utiliza la función suma <strong>de</strong> pares [20]que se ilustra en (1). También se utiliza una matriz <strong>de</strong>puntuación (PAM 350) [21] para <strong>de</strong>terminar el costo <strong>de</strong>lalineamiento <strong>de</strong> cada pareja <strong>de</strong> aminoácidos. Se emplea, unapenalización <strong>de</strong> -10 [11] cuando un aminoácido se alineacon un “gap”.n 1 n∑∑−i= 1 j=i+1Sum − of − Pairs = ScoringMatrix(l i, lj) (1)<strong>La</strong> selección <strong>de</strong> los padres se realiza según su aptitud, locual significa que los padres más aptos tienen másprobabilida<strong>de</strong>s <strong>de</strong> reproducirse por medio <strong>de</strong> una operación<strong>de</strong> cruce. Se ha adoptado una aproximación elitista, según la<strong>JP2011</strong>-10


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011cual se mantiene el 40% <strong>de</strong> las mejores soluciones <strong>de</strong> cadageneración. <strong>La</strong> selección <strong>de</strong> los restantes individuos serealiza utilizando “torneos” <strong>de</strong> tamaño 2. Según estemétodo, se cogen aleatoriamente dos individuos <strong>de</strong> lapoblación y el que tiene mayor aptitud (“fitness”), i.e.puntuación, se selecciona para el cruce. Si ambos candidatostienen la misma aptitud se selecciona el que presente elmayor número <strong>de</strong> columnas totalmente idénticas.<strong>La</strong> recombinación <strong>de</strong> los individuos se realiza utilizandotres operadores <strong>de</strong> cruce, que se eligen aleatoriamente con lamisma probabilidad <strong>de</strong> selección. En [11] se da una<strong>de</strong>scripción <strong>de</strong>tallada <strong>de</strong> estos operadores.<strong>La</strong>s mutaciones se producen, introduciendo nuevascaracterísticas en la población, aumentando así la diversidad.Con el fin <strong>de</strong> no modificar las secuencias y, por tantoinvalidar el alineamiento, los cambios sólo se pue<strong>de</strong>n hacercon los “gaps” y no con los aminoácidos. Por lo tanto,insertar o <strong>de</strong>splazar “gaps” son las formas más efectivas <strong>de</strong>introducir nuevos patrones en la población. Tanto AlineaGAcomo Parallel AlineaGA hacen uso <strong>de</strong> seis operadores <strong>de</strong>mutación [22]. Cada operador <strong>de</strong> mutación se selecciona alazar y se aplica a un individuo <strong>de</strong> acuerdo con laprobabilidad <strong>de</strong> mutación <strong>de</strong>finida. Si la solución mutada espeor que la original, se pue<strong>de</strong> aplicar una nueva mutación alindividuo mutado. Este proceso pue<strong>de</strong> repetirse hasta quemejore la aptitud, o durante un cierto número <strong>de</strong> intentospreviamente <strong>de</strong>finidos por el usuario. En nuestros tests, sepermiten un máximo <strong>de</strong> 2 intentos, lo cual representa unbuen compromiso entre velocidad y robustez, sintransformar completamente los individuos <strong>de</strong> una solageneración.Se utilizan dos tipos diferentes <strong>de</strong> operadores <strong>de</strong>mutación: los estocásticos y los avariciosos, que hemos<strong>de</strong>nominado operadores inteligentes (“Smart”). Losoperadores estocásticos se basan en versiones <strong>de</strong> estosoperadores ya <strong>de</strong>scritas en la literatura: [23-25].Los operadores inteligentes mejoran las versionesestocásticas hibridándolas con una sencilla estrategia <strong>de</strong>búsqueda local. <strong>La</strong>s mutaciones inteligentes sólo producenla mutación si el alineamiento mutado presenta una aptitud opuntuación mejor que la <strong>de</strong>l el original. Estos operadoresutilizan una probabilidad <strong>de</strong> dirección que <strong>de</strong>termina lainserción/<strong>de</strong>splazamiento <strong>de</strong> los “gaps” al principio o al final<strong>de</strong>l alineamiento. Esta probabilidad se establece inicialmentepara el centro <strong>de</strong>l alineamiento y se actualiza <strong>de</strong> acuerdo alos resultados, aumentando la probabilidad <strong>de</strong>insertar/<strong>de</strong>splazar los “gaps” a la izquierda o la <strong>de</strong>recha <strong>de</strong>lalineamiento. Cada operador intenta mejorar el alineamientoun máximo <strong>de</strong> 3 veces. En [22] se da una <strong>de</strong>scripción mas<strong>de</strong>tallada <strong>de</strong> estos operadores.B. Parallel AlineaGAParallel AlineaGA es un IPGA, en el que cadasubpoblación <strong>de</strong> un número fijo <strong>de</strong> soluciones evoluciona <strong>de</strong>forma in<strong>de</strong>pendiente, intercambiando periódicamenteindividuos entre sí mediante <strong>de</strong> un proceso <strong>de</strong>nominadomigración. <strong>La</strong> representación <strong>de</strong> soluciones, los mecanismos<strong>de</strong> selección, la forma <strong>de</strong> evaluación, así como lasoperaciones <strong>de</strong> cruce y mutación son iguales que losutilizados por AlineaGA. Sin embargo, la diferencia radicaen su proceso <strong>de</strong> migración.Cada subpoblación se asigna a un proceso diferente quepue<strong>de</strong> ser ejecutado en procesadores distintos. Se utiliza unatopología en estrella para conectar los procesos. En estatopología, en cada intervalo <strong>de</strong> migración <strong>de</strong>finido, cadaproceso esclavo envía su mejor individuo al procesoprincipal o maestro y el proceso maestro envía su mejorindividuo a cada proceso esclavo. Estos intercambiossustituyen los peores individuos <strong>de</strong> cada subpoblación,manteniendo su tamaño sin cambios. Este proceso se realiza<strong>de</strong> forma asíncrona, para evitar los cuellos <strong>de</strong> botellaoriginados por los procesos más lentos. El procedimiento serepite durante un número fijo <strong>de</strong> generaciones para encontrarla mejor solución posible entre todas las subpoblaciones.Para llevar a cabo la comunicación entre lassubpoblaciones, se ha utilizado MPI.NET [13] la aplicación<strong>de</strong>l protocolo MPI [14]. Esta elección está relacionada con laespecificidad <strong>de</strong> la plataforma .NET utilizada para ejecutarel algoritmo.IV. TESTS Y RESULTADOSEn esta sección se realiza una breve comparación <strong>de</strong> losresultados obtenidos con AlineaGA y Parallel AlineaGA.Hemos realizado tests para comprobar la eficiencia <strong>de</strong>AlineaGA y Parallel AlineaGA con ocho configuraciones <strong>de</strong>test “Reference 1” <strong>de</strong> BAliBASE [15]. Cuatro <strong>de</strong> lasconfiguraciones utilizadas (1aho, 1fmb, 1plc, 1dox)presentan más <strong>de</strong>l 35% <strong>de</strong> coinci<strong>de</strong>ncias entre sussecuencias y las otras cuatro (1fjlA, 1hpi, 1pfc, 1ycc)presentan entre un 20% y un 40% <strong>de</strong> coinci<strong>de</strong>ncias. Paraevaluar el rendimiento <strong>de</strong> AlineaGA y Parallel AlineaGAhemos <strong>de</strong>terminado el valor <strong>de</strong> la función <strong>de</strong> aptitud (suma<strong>de</strong>-pares)para cada una <strong>de</strong> las configuraciones <strong>de</strong> testmencionadas.Debido a la naturaleza estocástica <strong>de</strong>l algoritmo, lascomparaciones se han realizado teniendo en cuenta la media<strong>de</strong> los resultados obtenidos en 30 ejecucionesin<strong>de</strong>pendientes <strong>de</strong> cada versión <strong>de</strong> AlineaGA con cadaconfiguración <strong>de</strong> test. A<strong>de</strong>más, en el caso <strong>de</strong> ParallelAlineaGA y con la finalidad <strong>de</strong> enten<strong>de</strong>r mejor el efecto <strong>de</strong>lnúmero <strong>de</strong> islas en los resultados finales, cada configuración<strong>de</strong> test se ha ejecutado con mo<strong>de</strong>los <strong>de</strong> 4 y 8 islasrespectivamente.En esta sección también se hace una comparación entrelos resultados obtenidos con AlineaGA, Parallel AlineaGA,ClustalW2 [7] (http://www.ebi.ac.uk/Tools/clustalw2), conlas configuraciones <strong>de</strong> test <strong>de</strong> BAliBASE [15].<strong>La</strong>s dos versiones <strong>de</strong>l algoritmo, secuencial y paralela, sehan escrito en C#, usando .NET Framework 4. <strong>La</strong>s versionesparalelas usan MPI.NET [13] para la comunicación entre los<strong>JP2011</strong>-11


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011diferentes procesos. Todas los tests se hicieron en un 2.4GHz CPU Core2 Quad Q6600, con 2 GB <strong>de</strong> memoria,Windows XP Professional, Service Pack 3.A. Configuraciones <strong>de</strong> TestA continuación, se comparan los resultados <strong>de</strong> lasdiferentes versiones utilizadas para resolver el problema <strong>de</strong>lalineamiento múltiple <strong>de</strong> secuencias utilizando técnicas <strong>de</strong>Computación Evolutiva.Los parámetros utilizados para las diferentes versiones <strong>de</strong>lalgoritmo son similares y se eligieron en base a los trabajosrealizados con AlineaGA [11] y Parallel AlineaGA [12].Todos los operadores <strong>de</strong> cruce y mutación se escogieronaleatoriamente con la misma probabilidad <strong>de</strong> selección encada generación. Sin embargo, el número <strong>de</strong> generacionesnecesarias para obtener las soluciones es diferente para cadaversión <strong>de</strong>l algoritmo como se indica en la Tabla I.TABLA ICONFIGURACIONES DE TESTParámetros AlineaGA Parallel AlineaGATamaño <strong>de</strong> Población 100 -Tamaño Subpoblación - 100Intervalo <strong>de</strong> Migración - 100 generacionesMatriz <strong>de</strong> Puntuación PAM350 PAM350Método <strong>de</strong> selección Torneo (Tamaño 2) Torneo (Tamaño 2)Probabilidad <strong>de</strong> Cruce 0.8 0.8Probab. <strong>de</strong> Mutación 0.4 0.4Generaciones 2000 1000B. ResultadosA continuación se presentan los resultados <strong>de</strong> los testsrealizados, teniendo en cuenta el rendimiento global y laevolución <strong>de</strong> la población.1) Rendimiento: <strong>La</strong> Tabla II que resume los resultadosobtenidos con AlineaGA y Parallel AlineaGA, permitecomparar la calidad <strong>de</strong> las soluciones obtenidas con lacalidad <strong>de</strong> las configuraciones <strong>de</strong> test <strong>de</strong> BAliBASE [15] ycon la <strong>de</strong> las soluciones obtenidas con ClustalW2 [7] para lasmismas configuraciones <strong>de</strong> test. <strong>La</strong> columna “Suma <strong>de</strong> Pares<strong>de</strong> BAliBASE” presenta la suma <strong>de</strong> pares <strong>de</strong> lasconfiguraciones <strong>de</strong> test <strong>de</strong> referencia. <strong>La</strong> columna “Suma <strong>de</strong>Pares <strong>de</strong> ClustalW2” muestra el valor <strong>de</strong> la suma <strong>de</strong> pares <strong>de</strong>los resultados obtenidos con ClustalW2 [7]. Estos valores seobtuvieron usando la matriz PAM 350 y una penalización <strong>de</strong>apertura <strong>de</strong> “gaps” <strong>de</strong> -10. <strong>La</strong>s columnas “Suma <strong>de</strong> Pares <strong>de</strong>AlineaGA” y “Suma <strong>de</strong> Pares <strong>de</strong> Parallel AlineaGA”presentan el promedio <strong>de</strong> todos los resultados obtenidos enlas 30 ejecuciones <strong>de</strong> las dos versiones <strong>de</strong> AlineaGA.Al comparar los alineamientos <strong>de</strong> BAliBASE con lassoluciones encontradas con ClustalW2, se observa queClustalW2 presenta mejores soluciones para lasconfiguraciones <strong>de</strong> test: 1fmb, 1fjlA y 1pfc. Para lasconfiguraciones restantes ClustalW2 no alcanza los valores<strong>de</strong> las configuraciones <strong>de</strong> referencia. Con respecto a lassoluciones obtenidas con AlineaGA, sólo lasconfiguraciones 1dox, 1fjlA y 1hpi no superan el valor <strong>de</strong> lasuma <strong>de</strong> pares conseguido por BAliBASE. Para las <strong>de</strong>másconfiguraciones <strong>de</strong> test AlineaGA se comporta mejor.Con respecto a ClustalW2, AlineaGA presenta mejoresvalores <strong>de</strong> la suma <strong>de</strong> pares para las configuraciones: 1fmb,1dox y 1fjlA. Sin embargo al comparar los resultados <strong>de</strong>ClustalW2 con los obtenidos por Parallel AlineaGA seobserva que el mo<strong>de</strong>lo <strong>de</strong> 4 islas se comporta mejor paratodas las configuraciones excepto para: 1dox y 1fjlA, y queel mo<strong>de</strong>lo <strong>de</strong> 8 islas tiene un mejor comportamiento en todaslas configuraciones excepto en: 1fjlA. El mo<strong>de</strong>lo <strong>de</strong> 8 islas<strong>de</strong> Parallel AlineaGA no supera los valores <strong>de</strong> lasconfiguraciones <strong>de</strong> test 1dox, 1fjlA y 1hpi <strong>de</strong> BAliBASE.Al comparar los resultados <strong>de</strong> AlineaGA con los <strong>de</strong>Parallel AlineaGA resulta obvio que con las versionesparalelas se obtienen soluciones <strong>de</strong> mayor calidad. Esto se<strong>de</strong>be principalmente a que cuando se utilizan variaspoblaciones, se tiene más capacidad para explorar un mayorárea <strong>de</strong>l espacio <strong>de</strong> búsqueda, a<strong>de</strong>más se aprovechan mejorlos resultados <strong>de</strong> la búsqueda gracias la migración. Elmo<strong>de</strong>lo <strong>de</strong> 4 islas presenta mejores resultados que la versiónsecuencial para todas las configuraciones <strong>de</strong> test.Consi<strong>de</strong>rando globalmente la versión paralela <strong>de</strong> AlineaGAse pue<strong>de</strong> constatar que la configuración <strong>de</strong> 8 islas logramejores resultados que la configuración <strong>de</strong> 4 islas. Sinembargo, aunque en los tests realizados no se han tenido encuenta los gastos <strong>de</strong> comunicación, se observa que laconfiguración <strong>de</strong> 8 islas tiene el inconveniente <strong>de</strong> mayorestiempos <strong>de</strong> ejecución como pue<strong>de</strong> observarse en la Fig. 2.TABLA IIRESULTADOS DE LOS TESTSSuma <strong>de</strong> Pares <strong>de</strong>Configuraciones Suma <strong>de</strong> Pares Suma <strong>de</strong> Pares Suma <strong>de</strong> ParesParallel AlineaGA<strong>de</strong> Test <strong>de</strong> BAliBASE ClustalW2 <strong>de</strong> AlineaGA4 Islas 8 Islas1aho 2015 1644 2016.89 2145.67 2207.771fmb 1706 1780 1769.63 1859.80 1876.231plc 2403 2387 2404.83 2537.53 2590.571dox 1234 1020 833.57 974.40 1162.031fjlA 1740 1770 1366.33 1558.17 1710.031hpi 1208 1087 1142.10 1190.37 1199.431pfc 2216 2231 2422.50 2501.80 2533.331ycc 963 798 971.23 1099.33 1152.20“Suma <strong>de</strong> Pares <strong>de</strong> AlineaGA” y “Suma <strong>de</strong> Pares <strong>de</strong> Parallel AlineaGA” se obtuvieron por promedio <strong>de</strong> la suma-<strong>de</strong>-pares obtenida en 30 ejecuciones <strong>de</strong>AlineaGA y Parallel AlineaGA, respectivamente.<strong>JP2011</strong>-12


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Al observar el valor medio <strong>de</strong> la suma <strong>de</strong> pares <strong>de</strong> lapoblación, se pue<strong>de</strong> comprobar que cada isla realiza unabúsqueda diferente, pero su comportamiento es similarcuando las mejores soluciones en todas las subpoblacionescomienzan a ser semejantes.Fig. 2. Comparación <strong>de</strong> los tiempos <strong>de</strong> ejecución <strong>de</strong> AlineaGA y ParallelAlineaGA (en milisegundos).Al comparar los tiempos <strong>de</strong> ejecución <strong>de</strong> las diferentesversiones <strong>de</strong> AlineaGA se observa que cuando se consi<strong>de</strong>rael mo<strong>de</strong>lo paralelo <strong>de</strong> 8 islas los tiempos <strong>de</strong> ejecución sonsimilares a los <strong>de</strong> su versión secuencial; sin embargo, elmo<strong>de</strong>lo <strong>de</strong> 4 islas presenta mejores tiempos <strong>de</strong> ejecución quela versión secuencial para todas las configuraciones <strong>de</strong> test.No obstante, la obtención <strong>de</strong> resultados <strong>de</strong> más calidadconseguidos con el mo<strong>de</strong>lo <strong>de</strong> 8 islas justifica el tiempoextra que necesita para encontrar las soluciones. <strong>La</strong>sversiones paralelas <strong>de</strong> AlineaGA suponen una mejora tantoen la calidad <strong>de</strong> las soluciones como en los tiempos <strong>de</strong>ejecución (especialmente el mo<strong>de</strong>lo <strong>de</strong> 4 islas) con respectoa su versión secuencial.2) Evolución <strong>de</strong> la Población: Para ilustrar las diferencias<strong>de</strong> comportamiento <strong>de</strong> las versiones paralelas <strong>de</strong> AlineaGAcon respecto a la versión secuencial, analizaremos laevolución <strong>de</strong> la población con una <strong>de</strong> las configuraciones <strong>de</strong>test.<strong>La</strong>s Figuras 3, 4 y 5 comparan la evolución <strong>de</strong> la aptitud<strong>de</strong>l mejor individuo y la aptitud media <strong>de</strong> toda la poblaciónpara la configuración <strong>de</strong> test 1aho en AlineaGA y en lasconfiguraciones <strong>de</strong> 4 y 8 islas <strong>de</strong> Parallel AlineaGA. <strong>La</strong>sleyendas “Best” se refieren la evolución <strong>de</strong> la mejor soluciónencontrada. <strong>La</strong>s leyendas “Pop” se refieren al valor medio<strong>de</strong> todos los individuos <strong>de</strong> la población.Al comparar el comportamiento <strong>de</strong> la población entre lasversiones paralelas y la versión secuencial, está claro que ladiversidad que existe en la población <strong>de</strong> AlineaGA no escomparable con la <strong>de</strong> las distintas islas <strong>de</strong> las versionesparalelas <strong>de</strong> AlineaGA. Esta diversidad permite quesoluciones similares a las alcanzadas por AlineaGA al final<strong>de</strong> la última generación, se puedan conseguir en torno a lageneración 500 en la versión <strong>de</strong> 4 islas <strong>de</strong> AlineaGA y entorno a la generación 400 en la versión <strong>de</strong> 8 islas <strong>de</strong>AlineaGA. <strong>La</strong> reducción <strong>de</strong>l número <strong>de</strong> generacionescontribuye a la reducción <strong>de</strong> los tiempos <strong>de</strong> ejecución.Si consi<strong>de</strong>ramos sólo la evolución <strong>de</strong> la población en lasversiones paralelas <strong>de</strong>l algoritmo, se pue<strong>de</strong> observar que,<strong>de</strong>bido a la migración <strong>de</strong> las mejores soluciones entre lasdiferentes islas, las series que representan la mejor solucióntienen un comportamiento análogo, acabando porsuperponerse tan pronto como en una <strong>de</strong> las islas se generensoluciones <strong>de</strong> alta calidad.Fig. 3. Mejor solución <strong>de</strong> AlineaGA y evolución <strong>de</strong> la población con laconfiguración <strong>de</strong> test 1aho.Fig. 4. Mejor solución <strong>de</strong> Parallel AlineaGA con 4 islas y la evolución <strong>de</strong> lapoblación con la configuración <strong>de</strong> test 1aho.Fig. 5. Mejor solución <strong>de</strong> Parallel AlineaGA con 8 islas y la evolución <strong>de</strong> lapoblación con la configuración <strong>de</strong> test 1aho.V. CONCLUSIONESAlineaGA pue<strong>de</strong> encontrar alineamientos múltiples <strong>de</strong>secuencias <strong>de</strong> calidad. Sin embargo, su rendimiento losupera Parallel AlineaGA, tanto en calidad <strong>de</strong> las solucionesencontradas, para los mo<strong>de</strong>los <strong>de</strong> 4 y 8 islas, como entiempos <strong>de</strong> ejecución, para el mo<strong>de</strong>lo <strong>de</strong> 4 islas. Sinembargo, ambas versiones pue<strong>de</strong>n encontrar solucionesinteresantes que en la mayoría <strong>de</strong> los casos testeados, sonmejores que las que se encuentran con ClustalW2 [7].<strong>JP2011</strong>-13


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011El número <strong>de</strong> islas en el mo<strong>de</strong>lo paralelo es también<strong>de</strong>cisivo para aumentar la robustez <strong>de</strong> los resultados.Mientras más islas tenga el mo<strong>de</strong>lo se alcanzaran mejoressoluciones que serán más consistentes. Sin embargo esplausible que los costos <strong>de</strong> comunicación crezcan con elnúmero <strong>de</strong> islas <strong>de</strong> los mo<strong>de</strong>los, por lo que este número no<strong>de</strong>be <strong>de</strong>scuidarse.AGRADECIMIENTOSEste trabajo ha sido parcialmente soportado por elInstituto Politécnico <strong>de</strong> Leiria (Portugal) y por el proyectoMSTAR <strong>de</strong> referencia TIN 2008-06491-C04-04/TIN(MICINN España).REFERENCIAS[1] J. D. Thompson and O. Poch, "Multiple sequence alignment as aworkbench for molecular systems biology," Current Bioinformatics,vol. 1, pp. 95-104, 2006.[2] J. Horng, L. Wu, C. Lin, and B. Yang, "A genetic algorithm for multiplesequence alignment," Soft Computing, vol. 9, pp. 407-420, June 2005.[3] S. K. Pal, S. Bandyopadhyay, and S. S. Ray, "Evolutionary computationin bioinformatics: A review," IEEE Transactions on Systems Man andCybernetics Part C-Appl and Rev, vol. 36, pp. 601-615, September2006.[4] O. Lecompte, J. D. Thompson, F. Plewniak, J.-C. Thierry, and O. Poch,"Multiple alignment of complete sequences (MACS) in the postgenomicera," Gene, pp. 17-30, March 2001.[5] C. Notredame, "Recent evolutions of multiple sequence alignmentalgorithms," PLoS Comput. Biol, vol. 3, p. e123, 2007.[6] C. Notredame, D. G. Higgins, and J. Heringa, "T-Coffee: A novelmethod for fast and accurate multiple sequence alignment," Journal ofMolecular Biology, vol. 302, pp. 205-17, 2000.[7] M. A. <strong>La</strong>rkin, G. Blackshields, N. P. Brown, R. Chenna, P. A.McGettigan, H. McWilliam, F. Valentin, I. M. Wallace, A. Wilm, andR. Lopez, "Clustal W and Clustal X version 2.0," Bioinformatics, vol.23, p. 2947, 2007.[8] R. C. Edgar and S. Batzoglou, "Multiple sequence alignment," CurrentOpinion in Structural Biology, vol. 16, pp. 368-373, 2006.[9] T. <strong>La</strong>ssmann and E. L. L. Sonnhammer, "Quality assessment ofmultiple alignment programs," FEBS Letters, vol. 529, pp. 126-130,2002.[10] F. J. M. Silva, J. M. Sánchez Pérez, J. A. Gómez Pulido, and M. Á.Vega Rodríguez, "AlineaGA - A Genetic Algorithm with Local SearchOptimization for Multiple Sequence Alignment," Applied Intelligence,pp. 1-9, 2009.[11] F. J. M. Silva, J. M. Sánchez Pérez, J. A. Gómez Pulido, and M. Á.Vega Rodríguez, "An Evolutionary Approach for Performing MultipleSequence Alignment," in WCCI 2010 IEEE World Congress onComputational Intelligence Barcelona, Spain, 2010, pp. 992-998.[12] F. J. M. Silva, J. M. Sánchez Pérez, J. A. Gómez Pulido, and M. Á.Vega Rodríguez, "Parallel AlineaGA: An Island Parallel EvolutionaryAlgorithm for Multiple Sequence Alignment," in SoCPaR 2010 -International Conference on Soft Computing and Pattern Recognition,Cergy Pontoise, Paris, France, 2010, pp. 279-284.[13] D. Gregor and A. Lumsdaine, "Design and implementation of a highperformanceMPI for C# and the common language infrastructure," inProceedings of the 13th ACM SIGPLAN Symposium on Principles andpractice of parallel programming, Salt <strong>La</strong>ke City, USA, 2008, pp. 133-142.[14] W. Gropp, E. Lusk, and A. Skjellum, "Using MPI: portable parallelprogramming with the message passing interface," 1999.[15] J. D. Thompson, F. Plewniak, and O. Poch, "BAliBASE: a benchmarkalignment database for the evaluation of multiple alignment programs,"Bioinformatics, vol. 15, pp. 87-88, 1999.[16] Z. Michalewicz, Genetic algorithms + data structures = evolutionprograms - Third, Revised and Exten<strong>de</strong>d Edition, 3 ed.: Springer, 1996.[17] L. A. Anbarasu, P. Narayanasamy, and V. Sundararajan, "Multiplemolecular sequence alignment by island parallel genetic algorithm,"Current Science, vol. 78, pp. 858-863, April 2000.[18] E. Alba and J. M. Troya, "A survey of parallel distributed geneticalgorithms," Complexity, vol. 4, pp. 31-52, 1999.[19] E. Cantú-Paz, "A survey of parallel genetic algorithms," CalculateursParalleles, Reseaux et Systems Repartis, vol. 10, pp. 141-171, 1998.[20] M. Murata, J. S. Richardson, and J. L. Sussman, "Simultaneouscomparison of three protein sequences," Proceedings of the NationalAca<strong>de</strong>my of Sciences of the United States of America, vol. 82, p. 3073,1985.[21] M. O. Dayhoff, R. M. Schwartz, and B. C. Orcutt, "A Mo<strong>de</strong>l ofEvolutionary Change in Proteins," in Atlas of Protein Sequence andStructure. vol. 5: National Biomedical Research Foundation, 1978, pp.345-352.[22] F. J. M. Silva, J. M. Sánchez Pérez, J. A. Gómez Pulido, and M. Á.Vega Rodríguez, "Optimizing Multiple Sequence Alignment byImproving Mutation Operators of a Genetic Algorithm," in ISDA '09Ninth International Conference on Intelligent Systems Design andApplications, 2009, pp. 1257-1262.[23] J.-T. Horng, C.-M. Lin, B.-J. Liu, and C.-Y. Kao, "Using GeneticAlgorithms to Solve Multiple Sequence Alignments," in Proceedings ofthe Genetic and Evolutionary Computation Conference (GECCO-2000), <strong>La</strong>s Vegas, Nevada, USA, 2000, pp. 883-890.[24] C. Notredame, E. A. O'Brien, and D. G. Higgins, "RAGA: RNAsequence alignment by genetic algorithm," Nucleic Acids Research, vol.25, pp. 4570-4580, 1997.[25] C. Wang and E. J. Lefkowitz, "Genomic multiple sequence alignments:refinement using a genetic algorithm," BMC Bioinformatics, vol. 6,August 2005.<strong>JP2011</strong>-14


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Evolución Diferencial OpenMP+MPI en Re<strong>de</strong>sÓpticas WDMÁlvaro Rubio-<strong>La</strong>rgo 1 , Miguel A. Vega-Rodríguez 1 , Juan A. Gómez-Pulido 1 yJuan M. Sánchez-Pérez 1Resumen—Hoy en día, la multiplexación por división <strong>de</strong> longitud<strong>de</strong> onda (Wavelength Division Multiplexing oWDM) es la tecnología más utilizada para explotarel enorme ancho <strong>de</strong> banda presente en las re<strong>de</strong>sópticas. Sin embargo, cuando es necesario estableceruna conexión entre un nodo origen y un nodo <strong>de</strong>stino,el problema <strong>de</strong> enrutamiento y asignación <strong>de</strong>longitud <strong>de</strong> onda (Routing and Wavelength Assignmento RWA) aparece. En este trabajo se proponeuna versión híbrida OpenMP+MPI <strong>de</strong> la EvoluciónDiferencial con Torneos <strong>de</strong> Pareto (DEPT) para resolverel problema RWA. Hemos estudiado el comportamiento<strong>de</strong> esta versión híbrida <strong>de</strong> la EvoluciónDiferencial multiobjetivo, con una versión <strong>de</strong>l algoritmoDEPT que únicamente utiliza MPI. En este estudiohemos utilizado la topología real Nippon Telegraphand Telephone (NTT, Japón) y un clúster homogéneocompuesto por 16 nodos multi-núcleo, cadanodo con 8 núcleos (un total <strong>de</strong> 128 núcleos). Trasrealizar distintos experimentos con 2, 4, 8, 16, 32,64 y 128 núcleos, po<strong>de</strong>mos concluir que la versiónOpenMP+MPI <strong>de</strong>l algoritmo DEPT es altamenteparalelizable, obteniendo una eficiencia media superioral 95%.Palabras clave— Híbrido OpenMP+MPI, EvoluciónDiferencial, Optimización Multiobjetivo, ProblemaRWA, Re<strong>de</strong>s Ópticas.I. IntroducciónEl número <strong>de</strong> usuarios que utilizan las re<strong>de</strong>s<strong>de</strong> datos ha crecido <strong>de</strong> manera exponencial enlos últimos años. Debido a que el ancho <strong>de</strong>banda <strong>de</strong> nuestras re<strong>de</strong>s actuales no es suficientepara satisfacer este crecimento exponencial, surge lanecesidad <strong>de</strong> utilizar fibra óptica.<strong>La</strong> clave para explotar el enorme ancho <strong>de</strong> banda<strong>de</strong> este tipo <strong>de</strong> re<strong>de</strong>s es introducir concurrencia enlas transmisiones <strong>de</strong> datos. Este es precisamenteel objetivo <strong>de</strong> la tecnología <strong>de</strong> Multiplexación porDivisión <strong>de</strong> Longitud <strong>de</strong> Onda (en inglés, WavelengthDivision Multiplexing o WDM), dividir un enlace<strong>de</strong> fibra óptica en diferentes canales o longitu<strong>de</strong>s <strong>de</strong>onda [1]. Cuando surge la necesidad <strong>de</strong> estableceruna conexión entre un nodo origen y un nodo<strong>de</strong>stino, aparece un problema <strong>de</strong> enrutamiento yasignación <strong>de</strong> longitud <strong>de</strong> onda. Éste, es conocidoen la literatura como Routing and WavelengthAssignment (RWA) problem.Dado que el problema RWA es un problema <strong>de</strong>Optimización Multiobjetivo (MOOP) [2], en estetrabajo <strong>de</strong>cidimos utilizar un algoritmo evolutivomultiobjetivo para resolver el problema RWA. Elalgoritmo elegido es la Evolución Diferencial con1 Dpto. Tecnología <strong>de</strong> Computadores y Comunicaciones,Grupo <strong>de</strong> Investigación ARCO, <strong>Universidad</strong> <strong>de</strong> Extremadura,e-mail: {arl, mavega, jangomez,sanperez}@unex.esTorneos <strong>de</strong> Pareto [3]. En este trabajo presentamosuna versión paralela <strong>de</strong> grano fino <strong>de</strong>l algoritmoDEPT y el uso <strong>de</strong> un clúster multi-núcleo parareducir el tiempo que emplea el algoritmo DEPTen obtener soluciones <strong>de</strong> calidad. Para conseguireste objetivo, hemos diseñado una versión híbridaOpenMP+MPI <strong>de</strong> la Evolución Diferencial.Hemos estudiado el comportamiento <strong>de</strong> estaversión híbrida OpenMP+MPI <strong>de</strong>l algoritmo DEPT,con una versión <strong>de</strong>l mismo que únicamente utilizaMPI, con el fin <strong>de</strong> <strong>de</strong>mostrar el alto rendimiento <strong>de</strong>nuestra propuesta. En este estudio hemos utilizadola topología real Nippon Telegraph and Telephone(NTT, Japón) y un clúster homogéneo compuestopor 16 nodos multi-núcleo, cada nodo con 8 núcleos(un total <strong>de</strong> 128 núcleos). Tras numerosos experimentoscon distinto número <strong>de</strong> núcleos (2, 4, 8,16, 32, 64 y 128), po<strong>de</strong>mos concluir que la versiónOpenMP+MPI <strong>de</strong>l algoritmo DEPT obtiene unaalta eficiencia media (superior al 95%).El resto <strong>de</strong>l artículo se organiza como sigue. Una<strong>de</strong>finición formal <strong>de</strong>l problema RWA se presentaen la Sección 2. En la Sección 3 se <strong>de</strong>cribe<strong>de</strong>talladamente la versión Híbrida OpenMP+MPI <strong>de</strong>la Evolución Diferencial con Torneos <strong>de</strong> Pareto. Unestudio experimental exhaustivo <strong>de</strong> la metaheurísticaparalela se muestra en la Sección 4. Por último,las conclusiones y líneas futuras se muestran en laSección 5.II. Definición Formal <strong>de</strong>l Problema RWAEn este trabajo, una red óptica se representa comoun grafo dirigido G = (V, E, C), don<strong>de</strong> V es elconjunto <strong>de</strong> nodos, E es el conjunto <strong>de</strong> enlaces entrenodos y C es el conjunto <strong>de</strong> longitu<strong>de</strong>s <strong>de</strong> ondadisponibles en cada enlace óptico <strong>de</strong> E.• (i, j) ∈ E : Enlace óptico <strong>de</strong>s<strong>de</strong> el nodo i al nodoj; i, j ∈ V .• c ij ∈ C : Número <strong>de</strong> longitu<strong>de</strong>s <strong>de</strong> onda distintaspor enlace (i, j).• u = (s, d) : Demanda unicast u con nodo origens y nodo <strong>de</strong>stino d, don<strong>de</strong> s, d ∈ V .• U : Conjunto <strong>de</strong> <strong>de</strong>mandas unicast.: Longitud <strong>de</strong> Onda λ asignada a u en (i, j).• u λ i,j• l u : Conjunto <strong>de</strong> enlaces entre un nodo origen s uy un nodo <strong>de</strong>stino d u ; con la correspondiente λasignada en cada enlace (i, j).• L u : Solución al problema RWA consi<strong>de</strong>rando elconjunto <strong>de</strong> <strong>de</strong>mandas U.<strong>JP2011</strong>-15


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 1.Ejemplo ilustrativo <strong>de</strong>l problema RWADebemos tener en cuenta que L u = {l u — l u esel conjunto <strong>de</strong> enlaces con su correspondiente λ asignada}. Utilizando la <strong>de</strong>finición anterior, el problemaRWA pue<strong>de</strong> ser tratado como un Problema <strong>de</strong> OptimizaciónMultiobjetivo (Multiobjective OptimizationProblem, MOOP) [2], el cual trata <strong>de</strong> encontrarla mejor solución L u que minimice simultáneamentelas siguientes funciones objetivo:1. Número <strong>de</strong> Saltos:y 1 = ∑ ∑u∈U (i,j)∈l uΦ j{ } (1)Φj = 1 si (i, j) ∈ ldon<strong>de</strong>uΦ j = 0 si en otro caso2. Número <strong>de</strong> Conmutaciones <strong>de</strong> Longitu<strong>de</strong>s <strong>de</strong>Onda (λ):y 2 = ∑ ∑u∈U i∈V ϕ j{ } (2)ϕj = 1 si i ∈ V conmuta λdon<strong>de</strong>ϕ j = 0 si en otro casoA<strong>de</strong>más, <strong>de</strong>bemos cumplir la restricción <strong>de</strong> conflicto<strong>de</strong> longitu<strong>de</strong>s <strong>de</strong> onda [4]: Dos transmisionesunicast diferentes <strong>de</strong>ben tener diferente longitud <strong>de</strong>onda si se encuentran en el mismo enlace óptico (i, j).Un ejemplo ayudará a enten<strong>de</strong>r la formulación ylas funciones objetivo <strong>de</strong>l problema RWA. Dada latopología <strong>de</strong> red óptica que aparece en Figura 1,suponer el conjunto <strong>de</strong> <strong>de</strong>mandas {(0,2), (1,4), (4,0),y (2,3)}; y dos longitu<strong>de</strong>s <strong>de</strong> onda disponibles en cadaenlace (c ij = 2). Como po<strong>de</strong>mos ver en Figura 1, las<strong>de</strong>mandas (0,2), (1,4) y (4,0) no presentan ningunaconversión <strong>de</strong> longitud <strong>de</strong> onda; sin embargo, la<strong>de</strong>manda (2,3) presenta una conversión <strong>de</strong> longitud<strong>de</strong> onda en el nodo 4. A<strong>de</strong>más, en Figura 1, sepresentan los cálculos necesarios para obtener elvalor <strong>de</strong> las funciones objetivo: número <strong>de</strong> saltos(Y 1 ) y número <strong>de</strong> conmutaciones <strong>de</strong> longitud <strong>de</strong> onda(y 2 ). Aclaramos que la solución presentada (y 1 = 8,y 2 = 1) pue<strong>de</strong> no ser la solución idónea, sin embargo,el objetivo <strong>de</strong> este ejemplo es ayudar a compren<strong>de</strong>rla formulación <strong>de</strong>l problema y las funciones objetivo<strong>de</strong>l problema RWA.III. Versión Híbrida OpenMP+MPI <strong>de</strong> laEvolución Diferencial<strong>La</strong> Evolución Diferencial (DE) es un algoritmobasado en población, creado por Rainer Storny Ken Price [5]. Este algorítmo optimiza unproblema manteniendo una población <strong>de</strong> individuosy generando nuevos individuos mediante un simplemecanismo <strong>de</strong> cruce y mutación.Algoritmo 1 Pseudocódigo algoritmo DEPT1. P ← GenerarPoblaciónAleatoria(TamañoPoblación)2. EvaluarPoblación(P )3. para g = 0 to MAX-GENERACIONES hacer4. para i = 0 to TamañoPoblación hacer5. x target ← P [i]6. x target ← GenerarIndividuoTrial(x target , S)7. EvaluarIndividuo(x trial )8. /* TORNEO DE PARETO */9. si x trial ≠ x target entonces10. si x target .MOfitness > x trial .MOfitness entonces11. P [i] ← x trial12. sino si x target .MOfitness = x trial .MOfitness entonces13. P ′ ← x target ∪ x trial ∪ SolucionesNoDominadas(P, x trial )14. x target .cd ← DistanciaCrowding(P ′ , x target )15. x trial .cd ← DistanciaCrowding(P ′ , x trial )16. si x target .cd < x trial .cd entonces17. P [i] ← x trial18. fin si19. fin si20. fin si21. fin para22. fin paraEn [3], se presenta una versión multiobjetivo<strong>de</strong>l algoritmo DE. En esta versión se incorpora el<strong>JP2011</strong>-16


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011(a) Versión paralela MPI <strong>de</strong>l algoritmo DEPT(b) Versión paralela OpenMP+MPI <strong>de</strong>l algoritmo DEPTFig. 2.Versiones paralelas <strong>de</strong> la Evolución Diferencial con Torneos <strong>de</strong> Pareto (DEPT)concepto <strong>de</strong> Torneos <strong>de</strong> Pareto, con el objetivo<strong>de</strong> adaptar la Evolución Diferencial para resolverproblemas multiobjetivo, tales como el problemaRWA. En Algoritmo 1, se muestra el pseudocódigo<strong>de</strong>l algoritmo DEPT. Para una <strong>de</strong>scripción más<strong>de</strong>talla <strong>de</strong> la Evolución Diferencial con Torneos <strong>de</strong>Pareto (DEPT), consultar [3].Dado que el problema RWA es un problema NPcompletoen el que se emplea <strong>de</strong>masiado tiempoen obtener soluciones <strong>de</strong> calidad, en este trabajose propone una versión paralela <strong>de</strong> grano fino <strong>de</strong>lalgoritmo DEPT y el uso <strong>de</strong> un clúster multinúcleo(el más común hoy en día) para reducir eltiempo <strong>de</strong> ejecución empleado en este problema <strong>de</strong>comunicaciones.Por un lado, el Interfaz <strong>de</strong> Paso <strong>de</strong> Mensajes<strong>JP2011</strong>-17


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011(Message Passing Interface o MPI) tiene la principal<strong>de</strong>sventaja <strong>de</strong>l excesivo tiempo mal empleado enla comunicación entre los núcleos que disponen <strong>de</strong>memoria compartida en un clúster multi-núcleo.Por otra parte, la interfaz <strong>de</strong> programación <strong>de</strong>aplicaciones para memoria compartida OpenMP nosrestringe ha utilizar los núcleos que compartenmemoria (normalmente no es superior a 8 núcleos,lo cuál no es suficiente [6]).Utilizando ambas tecnologías <strong>de</strong> forma conjunta(OpenMP+MPI), en este trabajo se propone unaversión híbrida OpenMP+MPI <strong>de</strong> la EvoluciónDiferencial con Torneos <strong>de</strong> Pareto, la cuál aprovechalas ventajas <strong>de</strong> ambas técnicas, obteniendo soluciones<strong>de</strong> idéntica calidad a las mostradas en [3], pero en untiempo razonable.En Figura 2, presentamos una <strong>de</strong>scripciónilustrativa <strong>de</strong> cada versión paralela (MPI yOpenMP+MPI). En estos ejemplos, hemos supuestoun clúster homogéneo con 4 nodos (cada nodo con 2núcleos) y un tamaño <strong>de</strong> población <strong>de</strong> 16 individuos.Si nos centramos en la versión MPI, ver Figura2(a), para explotar el clúster multi-núcleo es necesariolanzar ocho procesos MPI, uno por cada núcleo.Despúés <strong>de</strong> esto, el proceso maestro emite a cadaproceso <strong>de</strong> forma simultánea un mensaje MPI. Estemensaje contiene una copia <strong>de</strong> la población entiempo t (P t ), ya que es necesaria para generar losnuevos individuos x trial . Cada proceso será capaz <strong>de</strong>conocer cuantos individuos tendrá que procesar yaque conoce cuantos procesos se encuentran activos(suponemos una distribución homogénea <strong>de</strong> los individuos<strong>de</strong> la población entre los procesos). A<strong>de</strong>más,utilizando su propio i<strong>de</strong>ntificador <strong>de</strong> proceso, cadaproceso i<strong>de</strong>ntificará la posición <strong>de</strong> comienzo. Porejemplo, en Figura 2(a), el proceso con i<strong>de</strong>ntificador2 comenzará a procesar individuos <strong>de</strong>s<strong>de</strong> la cuartaposición. Cuando un proceso termina <strong>de</strong> procesar,éste envía al proceso maestro únicamente los individuosque ha procesado. Finalmente, el proceso maestrocrea la nueva población (P t+1 ) para la siguientegeneración.Por otro lado, la versión OpenMP+MPI, verFigura 2(b), sólo necesita lanzar un proceso MPI porcada nodo <strong>de</strong>l clúster multi-núcleo (cuatro procesosen nuestro ejemplo). <strong>La</strong> metodología utilizada es lamisma que la explicada anteriormente, sin embargo,una vez que un proceso obtiene su propia copia <strong>de</strong> lapoblación P t , éste divi<strong>de</strong> la carga <strong>de</strong> trabajo entre losnúcleos utilizando directivas OpenMP, explotando <strong>de</strong>esta forma cada nodo <strong>de</strong>l clúster.Como po<strong>de</strong>mos ver, existe una diferencia <strong>de</strong>stacableentre ambas versiones paralelas: la versión MPInecesita el doble <strong>de</strong> mensajes para explotar el clústermulti-núcleo que la versión OpenMP+MPI, lo quese traduce en el doble <strong>de</strong> tiempo empleado en comunicacionesentre núcleos, lo que supone una pérdidaconsi<strong>de</strong>rable <strong>de</strong> rendimiento en este tipo <strong>de</strong> sistemas.TABLA IMejor configuración encontrada para el algoritmoDEPTDEPTK-caminos-más-cortos (k) 10Tamaño <strong>de</strong> Población (N) 256Probabilidad <strong>de</strong> Cruce (CR) 20%Factor <strong>de</strong> Mutación (F ) 50%Esquema <strong>de</strong> Selección (S) Best/1/BinIV. Resultados ExperimentalesEn esta sección presentamos varios experimentoscomparando las versiones OpenMP+MPI y MPI <strong>de</strong>la Evolución Diferencial en un clúster homogéneocompuesto por 16 nodos multi-núcleo, cada nodocuenta con 8 núcleos (un total <strong>de</strong> 128 núcleos).En este trabajo se ha utilizado una topología<strong>de</strong> fibra óptica real, la conocida Nippon Telegraphand Telephone (NTT, Japón), y seis conjuntos <strong>de</strong><strong>de</strong>mandas; para más información acerca <strong>de</strong> lasinstancias, consultar [7].<strong>La</strong>s versiones paralelas fueron compiladas utilizandoel compilador gcc 4.1.2 (sin opciones <strong>de</strong> optimizacióny directivas OpenMP) y MPICH2 v1.0.8.En cada experimento, se han realizado 30 ejecucionesin<strong>de</strong>pendientes <strong>de</strong> 100 generaciones, con el objetivo<strong>de</strong> asegurar cierta relevancia estadística. Losparámetros <strong>de</strong> configuración <strong>de</strong>l algoritmo DEPT semuestran en Tabla I.En primer lugar, en Tabla II presentamos eltiempo <strong>de</strong> ejecución <strong>de</strong>l algoritmo DEPT en secuencialpara cada conjunto <strong>de</strong> datos. Como po<strong>de</strong>mosobservar, la instancia NTT c ij =10, |U|=40 necesitael tiempo más alto, 1229,81 segundos.TABLA IITiempo <strong>de</strong> Ejecución <strong>de</strong>l algoritmo DEPT (secuencial)en segundosTopología NTTc ij =10, |U|=10 582,05c ij =10, |U|=20 858,98c ij =10, |U|=40 1229,81c ij =8, |U|=10 591,34c ij =8, |U|=20 814,8c ij =8, |U|=30 955,32Con el objetivo <strong>de</strong> realizar una comparativa justaentre ambas versiones paralelas (OpenMP+MPI yMPI), se han realizado varios experimentos utilizandodiferente número <strong>de</strong> núcleos: 2, 4, 8, 16, 32,64 y 128. A<strong>de</strong>más, se ha medido por separado eltiempo <strong>de</strong> comunicación entre procesos y el tiempo<strong>de</strong> computación invertido por cada versión.En Figura 3 se muestran los resultados obtenidospor las heurísticas paralelas para cada conjunto<strong>de</strong> datos. Como po<strong>de</strong>mos ver, la versión MPIobtiene mayor tiempo <strong>de</strong> ejecución que la versiónOpenMP+MPI, i<strong>de</strong>pendientemente <strong>de</strong>l número <strong>de</strong>núcleos utilizado. Po<strong>de</strong>mos comprobar que esto<strong>JP2011</strong>-18


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 3.Tiempos <strong>de</strong> Ejecución <strong>de</strong> las versiones paralelas <strong>de</strong>l algoritmo DEPT (OpenMP+MPI y MPI)es <strong>de</strong>bido a que la versión MPI invierte muchomás tiempo en comunicaciones entre procesos quela versión híbrida. A<strong>de</strong>más, po<strong>de</strong>mos observar enFigura 3 que la versión OpenMP+MPI no presentatiempo <strong>de</strong> comunicaciones en los experimentos con2, 4 y 8 núcleos, <strong>de</strong>bido a que esto no es necesarioya que comparten memoria. Con el fin <strong>de</strong> facilitar lalectura <strong>de</strong> los gráficos <strong>de</strong> barra presentados en Figura3, se ha ampliado la zona <strong>de</strong>l gráfico correspondientea los experimentos con 16, 32, 64 y 128 núcleos.Po<strong>de</strong>mos ver que la versión OpenMP+MPI obtieneresultados muy prometedores en todas las instancias.Por ejemplo, en el conjunto <strong>de</strong> datos NTTc ij =10, |U|=40, con 128 núcleos, la versión híbridaDEPT es capaz <strong>de</strong> ejecutar 100 generaciones en 11,32segundos, en lugar <strong>de</strong> 1229,81 segundos en la versiónsecuencial. Esto significa que utilizando la versiónOpenMP+MPI <strong>de</strong> la Evolución Diferencial con Torneos<strong>de</strong> Pareto, po<strong>de</strong>mos obtener soluciones <strong>de</strong> igualcalidad a las presentadas en [3], pero por encima <strong>de</strong>cien veces más rápido.Finalmente, en Figura 4(a) y Figura 4(b) semuestran el valor medio <strong>de</strong> aceleración y eficienciaobtenido por cada una <strong>de</strong> las versiones paralelas<strong>JP2011</strong>-19


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011implementadas en este trabajo.Como po<strong>de</strong>mos ver en Figura 4(a), ambas versionespresentan un comportamiento similar con 2,4 y 8 núcleos, sin embargo, cuando el número <strong>de</strong>núcleos es incrementado, las diferencias entre ambasheurísticas crecen exponencialmente. De Figura 4(b)po<strong>de</strong>mos extraer las mismas conclusiones: a medidaque aumenta el número <strong>de</strong> núcleos, la eficiencia <strong>de</strong>la versión MPI <strong>de</strong>crece <strong>de</strong> manera exponencial.Po<strong>de</strong>mos concluir diciendo que el algoritmo DEPTes a<strong>de</strong>cuado para ser paralelizado. A<strong>de</strong>más, teniendoen cuenta que la versión OpenMP+MPI únicamenteacelera la ejecución <strong>de</strong>l algoritmo (obteniendo soluciones<strong>de</strong> idéntica calidad), es capaz <strong>de</strong> superar losresultados obtenidos por otras heurísticas publicadasen la literatura ([8] and [9]), como indicamos en [3].<strong>de</strong> Enrutamiento y Asignación <strong>de</strong> Longitu<strong>de</strong>s <strong>de</strong>Onda (RWA). Tras realizar una comparativa entrenuestra versión híbrida y una versión MPI, condistinto número <strong>de</strong> núcleos: 2, 4, 8, 16, 32, 64 y128, po<strong>de</strong>mos concluir que la versión OpenMP+MPIobtiene resultados muy prometedores (una eficienciamedia <strong>de</strong> 95%), mientras que en la versión MPI laeficiencia <strong>de</strong>crece <strong>de</strong> manera exponencial a medidaque el número <strong>de</strong> núcleos se incrementa. Deesta forma, utilizando OpenMP y MPI <strong>de</strong> maneraconjunta para paralelizar el algoritmo multiobjetivoDEPT po<strong>de</strong>mos solucionar el problema RWA en untiempo razonable.Como trabajo futuro, tenemos la intención <strong>de</strong>aplicar esta versión OpenMP+MPI <strong>de</strong> la EvoluciónDiferencial a otros problemas <strong>de</strong> telecomunicaciones,tales como Traffic Grooming. A<strong>de</strong>más, no se<strong>de</strong>scarta diseñar otros algoritmos evolutivos multiobjetivocon el fin <strong>de</strong> realizar comparativas <strong>de</strong>rendimiento.Agra<strong>de</strong>cimentosEl presente trabajo ha sido parcialmente financiadopor el Ministerio <strong>de</strong> Ciencia e Innovación yel FEDER (Fondo Europeo <strong>de</strong> Desarrollo Regional),bajo el proyecto TIN2008- 06491-C04-04 (proyectoM*). Álvaro Rubio-<strong>La</strong>rgo es becario <strong>de</strong> investigación(PRE09010) <strong>de</strong> la Junta <strong>de</strong> Extremadura (Consejería<strong>de</strong> Economía, Comercio e Innovación).(a) Aceleración Media(b) Eficiencia MediaFig. 4. Aceleración y Eficiencia media obtenida por lasversiones paralelas <strong>de</strong>l algoritmo DEPTV. Conclusiones y Trabajo FuturoEn este artículo presentamos una versión HíbridaOpenMP+MPI <strong>de</strong> la Evolución Diferencial conTorneos <strong>de</strong> Pareto (DEPT) para resolver el problemaReferencias[1] A. M. Hamad y A. E. Kamal, “A survey of multicastingprotocols for broadcast-and-select single-hop networks,”IEEE Network, vol. 16, pp. 36–48, 2002.[2] K. Deb, Multi-Objective Optimization Using EvolutionaryAlgorithms. New York, NY, USA: John Wiley & Sons,Inc., 2001.[3] A. Rubio-<strong>La</strong>rgo, M. A. Vega-Rodríguez, J. A. Gómez-Pulido, y J. M. Sánchez-Pérez, “A Differential Evolutionwith Pareto Tournaments for solving the Routing andWavelength Assignment Problem in WDM Networks,”Proceedings of the 2010 IEEE Congress on EvolutionaryComputation (CEC 2010), pp. 129–136, 2010.[4] M. Gagnaire, M. Koubaa, y N. Puech, “Network Dimensioningun<strong>de</strong>r Scheduled and Random Lightpath Demandsin All-Optical WDM Networks,” IEEE Journal on SelectedAreas in Communications, vol. 25, no. S-9, pp. 58–67, 2007.[5] R. Storn y K. Price, “Differential Evolution - A SimpleEvolution Strategy for Fast Optimization,” Dr. Dobb,vol. 22, no. 4, pp. 18–24, 1997.[6] A. Rubio-<strong>La</strong>rgo, M. A. Vega-Rodríguez, J. A. Gómez-Pulido, y J. M. Sánchez-Pérez, “Improving optical wdmnetworks by using a multi-core version of differential evolutionwith pareto tournaments,” Distributed Computingand Artificial Intelligence, Springer Berlin / Hei<strong>de</strong>lberg,vol. 79, pp. 629–636, 2010.[7] M. Schaerer y B. Barán, “A Multiobjective Ant ColonySystem for Vehicle Routing Problem with Time Windows,”IASTED International Conference on Applied Informatics,pp. 97–102, 2003.[8] C. Insfrán, D. Pinto, y B. Barán, “Diseño <strong>de</strong> TopologíasVirtuales en Re<strong>de</strong>s Ópticas. Un enfoque basado en Colonia<strong>de</strong> Hormigas,” XXXII <strong>La</strong>tin-American Conference onInformatics 2006 - CLEI2006, vol. 8, pp. 173–195, 2006.[9] A. Arteta, B. Barán, y D. Pinto, “Routing and WavelengthAssignment over WDM Optical Networks: a comparisonbetween MOACOs and classical approaches,” in LANC’07: Proceedings of the 4th international IFIP/ACM<strong>La</strong>tin American conference on Networking. New York,NY, USA: ACM, 2007, pp. 53–63.<strong>JP2011</strong>-20


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Paralelización <strong>de</strong>l algoritmo <strong>de</strong> bi-mezclaJuan F. R. Herrera 1 , Leocadio G. Casado 2 , Inmaculada García 3 y Eligius M. T. Hendrix 4Resumen— Los algoritmos <strong>de</strong> diseño <strong>de</strong> mezclas tienencomo objetivo <strong>de</strong>terminar las mezclas <strong>de</strong> ingredientesque se ajustan a las restricciones <strong>de</strong> diseñoimpuestas para el producto en cuestión. Estas restriccionespue<strong>de</strong>n ser lineales y/o cuadráticas. <strong>La</strong>s mezclas<strong>de</strong>ben ser óptimas, tanto el coste como el número<strong>de</strong> ingredientes empleado tiene que ser mínimo. Losfabricantes elaboran una serie <strong>de</strong> productos a partir<strong>de</strong> un conjunto dado <strong>de</strong> materias primas. <strong>La</strong> escasezen la disponibilidad <strong>de</strong> estas materias primas introducerestricciones <strong>de</strong> disponibilidad que alteran la soluciónPareto-óptima. Los autores han <strong>de</strong>sarrolladoalgoritmos <strong>de</strong> Ramificación y Acotación para resolverproblemas <strong>de</strong> mezcla en don<strong>de</strong> la complejidad computacionalse incrementa con la dimensión <strong>de</strong>l producto.Debido a esta complejidad, se abordará el problema<strong>de</strong> mezcla para la obtención <strong>de</strong> sólo dos productos.El diseño <strong>de</strong> mezclas para dos productos es másdifícil que para un único producto porque a<strong>de</strong>más <strong>de</strong>que el diseño <strong>de</strong> cada producto está sometido a unasrestricciones, el frente <strong>de</strong> Pareto así como la disponibilidad<strong>de</strong> materias primas pasa a ser común a ambosproductos. Se <strong>de</strong>be realizar una combinación finalentre todas las soluciones <strong>de</strong>l primer y el segundoproducto para eliminar las combinaciones <strong>de</strong> mezclasque no satisfacen los criterios impuestos. El conjuntoresultante pue<strong>de</strong> ser usado como dato <strong>de</strong> entrada<strong>de</strong>l mismo algoritmo cuando se requieran resultadosmás precisos. El coste computacional <strong>de</strong> la fase <strong>de</strong>combinación <strong>de</strong>pen<strong>de</strong>rá <strong>de</strong>l número <strong>de</strong> elementos <strong>de</strong>lconjunto final <strong>de</strong> cada producto.Aquí, estudiaremos el coste computacional <strong>de</strong> lasdiferentes fases <strong>de</strong>l algoritmo <strong>de</strong> mezcla para dos productosy proporcionaremos versiones hebradas paralas fases más costosas. Los experimentos se han realizadoen una máquina <strong>de</strong> ocho núcleos con memoriacompartida, usando un problema <strong>de</strong> tamaño mediopara evitar largos tiempos <strong>de</strong> ejecución. Los experimentosmuestran que la computación paralela es unaherramienta necesaria para hacer una búsqueda exhaustivaen problemas <strong>de</strong> gran<strong>de</strong>s dimensiones y <strong>de</strong>más <strong>de</strong> un producto.Palabras clave— Memoria compartida, Procesamientoparalelo , Multihebrado, Ramificación y acotación,Optimización global.I. IntroducciónENCONTRAR un diseño robusto y barato paraun producto que satisfaga una serie <strong>de</strong> restriccionescuadráticas es un problema arduo. Se pue<strong>de</strong>nencontrar <strong>de</strong>scripciones <strong>de</strong> casos prácticos en [1] y[2], entre otros. En la industria, las compañías pue<strong>de</strong>nutilizar las mismas materias primas para producirvarios productos. Esto complica el proceso <strong>de</strong>búsqueda <strong>de</strong> soluciones factibles y robustas si se preten<strong>de</strong>garantizar la optimalidad y robustez <strong>de</strong> la soluciónfinal.1 Dpto. <strong>de</strong> Arquitectura <strong>de</strong> Computadores y Electrónica,Univ. Almería, e-mail: juanfrh@ual.es.2 Dpto. <strong>de</strong> Arquitectura <strong>de</strong> Computadores y Electrónica,Univ. Almería, e-mail: leo@ual.es.3 Dpto. <strong>de</strong> Arquitectura <strong>de</strong> Computadores, Univ. Málaga,e-mail: igarciaf@uma.es.4 Dpto. <strong>de</strong> Arquitectura <strong>de</strong> Computadores, Univ. Málaga,e-mail: eligius.hendrix@wur.nl.Los algoritmos <strong>de</strong> búsqueda exhaustiva para unproblema <strong>de</strong> diseño <strong>de</strong> un solo producto son <strong>de</strong>scritosen [3], [4] y [5], mientras que el enfoque para laobtención <strong>de</strong> dos productos aparece en [6].<strong>La</strong> Sección I-A <strong>de</strong>scribe el problema <strong>de</strong> mezcla paraun producto y la Sección I-B para dos productos(bi-mezcla). <strong>La</strong> Sección II <strong>de</strong>scribe la versión secuencial<strong>de</strong>l algoritmo <strong>de</strong> bi-mezcla y la Sección III <strong>de</strong>scribesu mo<strong>de</strong>lo paralelo. <strong>La</strong> Sección IV muestra losresultados computacionales y la Sección V resumelas conclusiones y el trabajo futuro.A. El problema <strong>de</strong> diseño <strong>de</strong> un productoEl problema <strong>de</strong> diseño que nosotros investigamos(Semi-continuous Quadratic Mixture Design Problem,SQMDP) está <strong>de</strong>scrito en [4], don<strong>de</strong> aparecenrestricciones cuadráticas y semicontinuas. Aquí resumiremoslas principales características <strong>de</strong>l mismo.<strong>La</strong>s variables x i representan la fracción <strong>de</strong> la materiaprima i en la mezcla x. El conjunto <strong>de</strong> posiblesmezclas está matemáticamente <strong>de</strong>finido por elsímplex unitario{}n∑S = x ∈ R n : x i = 1,0; x i ≥ 0 , (1)i=1don<strong>de</strong> n <strong>de</strong>nota el número <strong>de</strong> materias primas.El objetivo es encontrar una mezcla x que minimiceel coste <strong>de</strong>l producto, f(x) = c T x, don<strong>de</strong> el vectorc representa el coste <strong>de</strong> las materias primas. No sóloel coste <strong>de</strong>l producto <strong>de</strong>be ser minimizado, sino tambiénel número <strong>de</strong> materias primas involucradas enla mezcla x dado por ∑ ni=1 δ i(x), don<strong>de</strong>{1 si xi > 0,δ i (x) =0 si x i = 0.<strong>La</strong> semicontinuidad <strong>de</strong> las variables está relacionadacon la dosis mínima aceptable md (minimaldose) <strong>de</strong> cada materia prima i, <strong>de</strong> forma que x i = 0ó x i ≥ md. El número <strong>de</strong> subsímplices resultantes(caras) esn∑( n= 2t)n − 1,t=1don<strong>de</strong> t <strong>de</strong>nota el número <strong>de</strong> materias primas en cadasubsímplex. Todos los puntos x en un símplex inicialP u , u = 1, . . . , 2 n − 1, son mezclas <strong>de</strong>l mismo grupo<strong>de</strong> materias primas. El índice u representa el grupo<strong>de</strong> materias primas correspondiente a un símplexinicial P u :n∑u = 2 i−1 δ i (x), ∀x ∈ P u .i=1Los productos <strong>de</strong>ben satisfacer ciertos requisitos.Para problemas <strong>de</strong> mezcla relativamente sencillos, los<strong>JP2011</strong>-21


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011x 21,01,0 Una materia primamd0,0mdDos materias primasx 1x 1x2x 3Fig. 1Símplices 2D y 3D sin la región <strong>de</strong> dosis mínimalímites o restricciones lineales (véase [1], [2] y [7])<strong>de</strong>finen el espacio <strong>de</strong> búsqueda X ⊂ S.Sin embargo, en la práctica aparecen restriccionescuadráticas [3], [4]. Se <strong>de</strong>fine Q como el espacio don<strong>de</strong>se satisfacen tales restricciones cuadráticas.A<strong>de</strong>más, el resultado <strong>de</strong>be satisfacer las restriccionescuadráticas cuando aparecen pequeñas variacionesen los porcentajes <strong>de</strong> la mezcla <strong>de</strong>bido al proceso<strong>de</strong> producción. Dada una mezcla x, se <strong>de</strong>fine la robustez<strong>de</strong> x como R(x) y ésta <strong>de</strong>be ser mayor o iguala un umbral ε, véase [4].Teniendo en cuenta las consi<strong>de</strong>raciones anteriores,se <strong>de</strong>fine SQMDP como:míns.a.f(x), ∑ ni=1 δ i(x)x ∈ X ∩ QR(x) ≥ εEn [3] se <strong>de</strong>scriben tests basados en las llamadas✭✭esferas <strong>de</strong> no factibilidad✮✮, que i<strong>de</strong>ntifican áreasdon<strong>de</strong> no se pue<strong>de</strong> encontrar una mezcla factible. En[4] se <strong>de</strong>scribe un algoritmo <strong>de</strong> Ramificación y Acotaciónpara resolver SQMDP usando tests <strong>de</strong> rechazobasados en restricciones lineales, cuadráticas y <strong>de</strong> robustez.El problema <strong>de</strong> encontrar la mejor solución robustase convierte en un problema <strong>de</strong> Optimización Global,don<strong>de</strong> resulta complejo garantizar que la solución obtenidaes la global, ya que pue<strong>de</strong>n existir múltiplesóptimos locales y el área factible pue<strong>de</strong> no ser convexao incluso estar dividida en varios compartimentos.En [8] se presentó una versión multihebrada <strong>de</strong>l algoritmopara resolver SQMDP mediante un esquemaAsynchronous Multiple Pool [9], don<strong>de</strong> se siguió unaestrategia similar a la utilizada en el algoritmo paralelo<strong>de</strong> Optimización Global basado en Aritmética<strong>de</strong> Intervalos (Local-PAMIGO), publicado en [10].B. El problema <strong>de</strong> diseño <strong>de</strong> dos productosEn este artículo, nuestro objetivo es paralelizar elalgoritmo que encuentre las mejores mezclas cuandose preten<strong>de</strong> diseñar dos productos que compartenmaterias primas. En algunas ocasiones, la industriase enfrenta al problema <strong>de</strong> la escasez <strong>de</strong> materiasprimas para los productos que <strong>de</strong>sea elaborar. Esteinconveniente pue<strong>de</strong> ser resuelto mediante el uso <strong>de</strong>una dosis mayor <strong>de</strong> otro ingrediente, aunque esto hagaque la solución óptima para cada producto no seasiempre la solución <strong>de</strong>l problema completo.Tal y como se <strong>de</strong>scribe en [6], cada producto tienesu propia <strong>de</strong>manda y sus propias especificaciones<strong>de</strong> diseño en forma <strong>de</strong> restricciones lineales y/ocuadráticas. Una manera común <strong>de</strong> <strong>de</strong>scribir el problemaes i<strong>de</strong>ntificar un índice j para cada producto,que tiene una cierta <strong>de</strong>manda D j . <strong>La</strong> cantidad <strong>de</strong>materia prima i disponible viene dado por B i . Ahora,la variable <strong>de</strong> <strong>de</strong>cisión principal x i,j es la fracción<strong>de</strong> la materia prima i presente en el producto j.En principio, todos los productos x ∗,j , j = 1, 2,pue<strong>de</strong>n hacer uso <strong>de</strong> todas las n materias primas;x ∗,j ∈ R n , j = 1, 2. Esto significa que x i,1 y x i,2hacen referencia a fracciones <strong>de</strong>l mismo ingredientepara los productos 1 y 2. <strong>La</strong>s reservas <strong>de</strong> materiasprimas se <strong>de</strong>scriben a través <strong>de</strong> las restricciones <strong>de</strong>disponibilidad, que vienen dadas por2∑D j x i,j ≤ B i ; i = 1, . . . , n.j=1Por lo tanto, se establece la función <strong>de</strong> coste <strong>de</strong>este problema como:f bi (x ∗,1 , x ∗,2 ) =2∑D j f(x ∗,j ).j=1El otro criterio a minimizar es el número <strong>de</strong> distintasmaterias primas utilizado en el diseño <strong>de</strong> losdos productos:ω(x ∗,1 , x ∗,2 ) =n∑δ i (x ∗,1 ) ∨ δ i (x ∗,2 ),i=1don<strong>de</strong> ∨ <strong>de</strong>nota la operación or bit a bit.Por lo tanto, se <strong>de</strong>fine el problema <strong>de</strong> bi-mezclacomo:mín f bi (x ∗,1 , x ∗,2 ), ω(x ∗,1 , x ∗,2 )s.a. x ∗,1 ∈ X 1 ∩ Q 1 , x ∗,2 ∈ X 2 ∩ Q 2R(x ∗,j ) ≥ ε, j = 1, 2∑ 2j=1 D jx i,j ≤ B i ; i = 1, . . . , nII. Algoritmo para resolver el problema<strong>de</strong> bi-mezclaResolver el problema <strong>de</strong> bi-mezcla <strong>de</strong> una maneraexhaustiva (el método obtiene todas las soluciones<strong>JP2011</strong>-22


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Algoritmo 1 B&B1: Inicializar ns := 2 × (2 n − 1)2: Inicializar la lista Λ 1 := {C 1 , . . . , C 2n −1}3: Inicializar la lista Λ 2 := {C 2 n, . . . , C ns }4: Inicializar las listas Q 1 := {} y Q 2 := {}5: while Λ 1 , Λ 2 ≠ {} do6: Seleccionar un símplex C = C k <strong>de</strong> Λ j7: Evaluar C8: Calcular f L (C) y b L i (C), i = 1, . . . , t k9: if C no pue<strong>de</strong> ser eliminado then10: if C satisface la regla <strong>de</strong> terminación then11: Almacenar C en Q j12: else13: Dividir C en C ns+1 , C ns+214: C := arg mín{f L (C ns+1 ), f L (C ns+2 )}15: Almacenar {C ns+1 , C ns+2 } \ C en Λ j16: ns := ns + 217: Ir a 718: end if19: end if20: j := (j mód 2) + 121: end while22: return Q 1 y Q 2globales <strong>de</strong>ntro <strong>de</strong> la precisión establecida) requiereel diseño <strong>de</strong> un algoritmo <strong>de</strong> Ramificación y Acotación(Branch & Bound, B&B) específico. Los métodosB&B se caracterizan por cuatro reglas: Ramificación,Selección, Acotación y Eliminación [11], [12]. Se<strong>de</strong>be incluir una regla <strong>de</strong> Terminación para problemasdon<strong>de</strong> las soluciones vienen <strong>de</strong>terminadas poruna precisión establecida. En los algoritmos B&B,la región <strong>de</strong> búsqueda es dividida recursivamente enpartes disjuntas (ramificación) sobre las cuales se <strong>de</strong>terminanlos límites <strong>de</strong> un valor <strong>de</strong> la solución óptima(acotación). Se <strong>de</strong>fine el límite superior global f U comoel valor <strong>de</strong> la función objetivo <strong>de</strong> la mejor soluciónε-robusta encontrada hasta ahora. De esta forma, sepue<strong>de</strong>n <strong>de</strong>scartar subconjuntos C k con un límite inferiorfkL <strong>de</strong> la función objetivo que sean mayores queel límite superior f U , ya que se pue<strong>de</strong> garantizar queno contienen una solución óptima.Una <strong>de</strong>scripción <strong>de</strong>tallada <strong>de</strong>l Algoritmo 1 se pue<strong>de</strong>encontrar en [6]. El Algoritmo 1 usa una lista <strong>de</strong>trabajo Λ j y una lista final Q j para cada producto.Aquí resumiremos las características más relevantespara el <strong>de</strong>sarrollo <strong>de</strong> una versión paralela. Cadasímplex es una región que satisface (1) y sus vérticesson posibles recetas o mezclas (véase la Figura 1).<strong>La</strong>s reglas B&B usadas en el Algoritmo 1 se <strong>de</strong>scribena continuación:Ramificación: Se divi<strong>de</strong> el símplex por el ladomás largo o por aquel lado <strong>de</strong>finido por los vérticesmás caro y más barato.Acotación: Para cada símplex se calculan doslímites inferiores:Coste: f L (C) es el límite inferior <strong>de</strong>l coste <strong>de</strong> unsímplex C y es proporcionado por el vérticecuyo coste es menor, <strong>de</strong>bido a que los símplicesson convexos y la función <strong>de</strong> coste es lineal.Cantidad <strong>de</strong> cada materia prima: b L i (C) es ellímite inferior <strong>de</strong>l uso <strong>de</strong> cada materia prima ien un símplex C. Este límite inferior es obtenido<strong>de</strong> manera análoga al límite inferior <strong>de</strong>lcoste.Selección: Se realiza una búsqueda híbrida: combinación<strong>de</strong> la búsqueda en profundidad y labúsqueda ✭✭primero el mejor✮✮. Se selecciona elsímplex más barato, basado en la suma <strong>de</strong> loscostes <strong>de</strong> sus vértices, y se realiza una selecciónen profundidad hasta que el símplex no puedaser dividido más (véase el Algoritmo 1, las líneas6, 14 y 17). De esta forma, se preten<strong>de</strong> reducirel consumo <strong>de</strong> memoria <strong>de</strong>l algoritmo.Eliminación: Se aplica un conjunto <strong>de</strong> tests basadosen restricciones lineales, cuadráticas y <strong>de</strong>robustez a los símplices <strong>de</strong> un producto, véase[4]. A<strong>de</strong>más, existen otros tests <strong>de</strong> rechazo don<strong>de</strong>hay que tener en cuenta ambos productos.Estos tests son los siguientes:Test <strong>de</strong> disponibilidad: Se <strong>de</strong>fineβi,j L = D j × mín x i (2)x∈C∈Λ j∪Q jcomo el límite inferior <strong>de</strong> la <strong>de</strong>manda <strong>de</strong> materiaprima i en el espacio <strong>de</strong> búsqueda actual<strong>de</strong>l producto j. Un símplex C k en el productoj no satisface la restricción <strong>de</strong> disponibilidadsiD j × b L i (C k ) + β L i,j ′ > B i, (3)don<strong>de</strong> j ′ hace referencia al otro producto.Test <strong>de</strong> Pareto: Si se encuentra un par <strong>de</strong> mezclasfactibles (x, y), siendo x ∈ C ∈ Λ 1 ∪ Q 1e y ∈ C ∈ Λ 2 ∪ Q 2 , con f(x) + f(y) f U ω(x,y) , (5)con x ∈ C k e y ∈ P u,j ′.Terminación: Los símplices no rechazados quealcanzan el tamaño requerido α son almacenadosen Q j .El resultado <strong>de</strong>l Algoritmo 1 es un conjunto <strong>de</strong>mezclas Pareto-óptimas (<strong>de</strong>ntro <strong>de</strong> la precisión α) ylas listas finales Q j , j = 1, 2, que, a<strong>de</strong>más <strong>de</strong> lasmezclas, contienen los símplices que no han sido rechazados.Durante la ejecución <strong>de</strong>l algoritmo, se actualizanlos límites inferiores βi,j L y ϕL u,j basándose en los<strong>JP2011</strong>-23


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Algoritmo 2 Comb1: for j = 1, 2 do2: for all C ∈ Q j no marcado como válido do3: if ∃ C ′ ∈ Q j ′ que satisfaga (6) y (7) then4: Marcar C ′ como válido5: Continuar con el siguiente símplex C{Los restantes C ′ ∈ Q j ′ no son visitados}6: else7: Eliminar C8: end if9: end for10: end forvértices no rechazados, así como el frente <strong>de</strong> Paretofp U . Por lo tanto, se <strong>de</strong>be realizar una combinaciónfinal entre los símplices <strong>de</strong> Q 1 y Q 2 para rechazaraquellos símplices C que no contengan una soluciónPareto-óptima:f L (C) + f L (C ′ ) > f U ω(x,y) ; x ∈ C, y ∈ C′ (6)o no satisfagan la restricción <strong>de</strong> disponibilidad:b L i (C) + bL i (C′ ) > B i ; i = 1, . . . , n, (7)para todos los símplices C ′ ∈ Q j ′.Esta operación se realiza en el Algoritmo 2. Enla primera iteración (j = 1) <strong>de</strong>l bucle externo, sise encuentra un símplex C ′ ∈ Q 2 que junto con Csatisfaga (6) y (7), C ′ es marcado como válido y noserá procesado en la línea 2 <strong>de</strong> la siguiente iteración(j = 2).III. Estrategia paralelaEl problema <strong>de</strong> bi-mezcla se resuelve en dos fases:en la fase B&B se obtienen las listas Q 1 y Q 2con todos los símplices finales para ambos productos(Algoritmo 1) y en la fase Comb se filtran aquellassoluciones no factibles (Algoritmo 2). Como la salida<strong>de</strong>l Algoritmo 1 es la entrada <strong>de</strong>l Algoritmo 2, laparalelización <strong>de</strong> ambos algoritmos se pue<strong>de</strong> realizar<strong>de</strong> forma in<strong>de</strong>pendiente.El número <strong>de</strong> símplices finales obtenidos por el Algoritmo1 <strong>de</strong>pen<strong>de</strong>rá <strong>de</strong> varios factores: la dimensión<strong>de</strong>l problema, la precisión α <strong>de</strong> la regla <strong>de</strong> terminacióny el tamaño <strong>de</strong> la región factible <strong>de</strong> cada producto.Experimentos preliminares muestran que estenúmero pue<strong>de</strong> ser relativamente alto. Por lo tanto,el Algoritmo 2 pue<strong>de</strong> ser mucho más costoso computacionalmenteque el Algoritmo 1, siendo la paralelización<strong>de</strong> esta fase la principal prioridad <strong>de</strong> esteestudio.El Algoritmo 2 hace uso <strong>de</strong> un bucle anidado y<strong>de</strong> las dos listas finales Q 1 y Q 2 . Para cada símplexC ∈ Q j , se busca un símplex C ′ ∈ Q j ′ que satisfaga(6) y (7) <strong>de</strong> forma que C no se elimine. En el peor <strong>de</strong>los casos (cuando el símplex C se elimina), la listaQ j ′ se explora completamente (todos los símplicesC ′ ∈ Q j ′ son visitados).Para evitar contención entre hebras en el accesoa la lista enlazada Q j , los símplices no son rechazadossino marcados para ser eliminados posteriormente.De otro modo, la lista podría ser modificada porvarias hebras cuando los símplices son eliminados,haciendo necesario el uso <strong>de</strong> exclusión mutua.<strong>La</strong> siguiente notación es necesaria para la <strong>de</strong>scripción<strong>de</strong> las distintas estrategias:Pos(C, Q j ): posición <strong>de</strong>l símplex C en Q j .NT h: número total <strong>de</strong> hebras.Id(T h): i<strong>de</strong>ntificación <strong>de</strong> la hebra T h. Los números<strong>de</strong> i<strong>de</strong>ntificación son consecutivos y comienzanen cero.Existen varias formas <strong>de</strong> paralelizar el Algoritmo 2mediante el uso <strong>de</strong> hebras. En este artículo abordaremosdos estrategias:Estrategia 1: Asignar NT h/2 hebras a cada listafinal Q j , j = 1, 2. De este modo, las iteraciones1 y 2 <strong>de</strong>l bucle exterior se llevan a cabo en paralelo,trabajando sobre las dos listas simultáneamente.Esta estrategia requiere que NT h ≥ 2.Cada hebra T h analiza los símplices C ∈ Q jque satisfacen módulo (Pos(C, Q j )/(NT h/2)) =Id(T h). Después <strong>de</strong> recorrer ambas listas, el borrado<strong>de</strong> los nodos <strong>de</strong> las listas Q j , j = 1, 2, esrealizado por una hebra para cada lista.Estrategia 2: Asignar NT h hebras al bucle interiorpara llevar a cabo una iteración <strong>de</strong>l bucle exterior.Cada hebra T h analiza los símplices C ∈Q j que satisfacen módulo (Pos(C, Q j )/NT h) =Id(T h). Ahora se preten<strong>de</strong> procesar sólo una listaen paralelo, borrando los símplices no factiblesantes <strong>de</strong> procesar la siguiente lista en paralelo.El borrado <strong>de</strong> los nodos (marcados paratal fin) <strong>de</strong> Q j es realizado por una sola hebra alfinal <strong>de</strong> la cada iteración j.<strong>La</strong> paralelización <strong>de</strong>l Algoritmo 1 es más difícilporque el trabajo computacional pendiente no es conocido<strong>de</strong> antemano. Un estudio <strong>de</strong> la predicción <strong>de</strong>ltrabajo en algoritmos <strong>de</strong> Ramificación y Acotaciónpara problemas <strong>de</strong> Optimización Global basado enAritmética <strong>de</strong> Intervalos se pue<strong>de</strong> encontrar en [13].Aunque los autores <strong>de</strong> este trabajo presentan algoritmosparalelos <strong>de</strong> Ramificación y Acotación en [10],[14], [15] y [16], estos artículos estudian la paralelización<strong>de</strong> un único algoritmo B&B. Sin embargo, laresolución <strong>de</strong>l problema <strong>de</strong> bi-mezcla se pue<strong>de</strong> vercomo dos instancias <strong>de</strong>l mismo algoritmo B&B, unapara cada producto, que comparten β L i,j , ϕL u,j y f U p(véase las Ecuaciones 2, 3, 4 y 5). Cada hebra j trabajacon una lista <strong>de</strong> trabajo Λ j y una lista final Q j .El problema es <strong>de</strong>terminar cuántas hebras se <strong>de</strong>dicana cada producto. Aquí, utilizaremos una hebra porproducto para mostrar la dificultad <strong>de</strong> la fase B&B,<strong>de</strong>jando para trabajos futuros el uso <strong>de</strong> un númeromayor <strong>de</strong> hebras en esta fase.IV. Resultados experimentalesPara evaluar el rendimiento <strong>de</strong> las distintas versiones<strong>de</strong>l algoritmo paralelo, se han utilizado unpar <strong>de</strong> productos <strong>de</strong> cinco dimensiones, llamadosUniSpec1-5 y UniSpec5b-5. Ambos han sido adaptados<strong>de</strong> dos productos <strong>de</strong> siete dimensiones (UniSpec1<strong>JP2011</strong>-24


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011y UniSpec5b, respectivamente) tomados <strong>de</strong> [4], eliminandolos elementos {a i,j ∈ A : i = 6, 7; j = 6, 7}y {b i ∈ b : i = 6, 7} <strong>de</strong> las restricciones cuadráticas.Este problema ha sido resuelto con una robustezε = √ 2/100, una precisión α = ε y una dosismínima md = 0,03. <strong>La</strong> <strong>de</strong>manda <strong>de</strong> cada productoes D T = (1, 1). <strong>La</strong> disponibilidad <strong>de</strong> la materia primauno (RM1) y <strong>de</strong> RM3 está restringida a 0,62 y0,6, respectivamente; mientras las otras materias notienen limitación alguna.Los algoritmos se han codificado en C y han sidoevaluados en una máquina Dell PowerEdge R810 conun procesador Intel Xeon 1.87 GHz <strong>de</strong> ocho núcleos,16 GB <strong>de</strong> RAM y sistema operativo Linux con kernel2.6. Para la creación y el manejo <strong>de</strong> las hebras, se hautilizado la librería <strong>de</strong> POSIX Threads. También seha usado la librería LAPACK para algunos cálculosmatemáticos realizados por el algoritmo.<strong>La</strong> Tabla I proporciona información sobre el esfuerzocomputacional realizado por el algoritmo secuencial(BiBlendSeq) y el algoritmo paralelo (Bi-BlendPar). <strong>La</strong> Tabla II muestra el tiempo <strong>de</strong> ejecución<strong>de</strong> BiBlendSeq y BiBlendPar. BiBlendPar utilizaNT h = 2 en la fase B&B. Para la fase Comb,se han usado NT h = 2, 4 y 8 en la Estrategia 1 yNT h = 1, 2, 4 y 8 en la Estrategia 2 (véase la SecciónIII). Los datos mostrados en las Tablas I y II esel valor medio <strong>de</strong> cinco ejecuciones.<strong>La</strong> siguiente notación ha sido utilizada para ambastablas:NEvalS: Número <strong>de</strong> símplices evaluados.NEvalV: Número <strong>de</strong> vértices evaluados.QLR: Número <strong>de</strong> símplices rechazados por restriccioneslineales, cuadráticas o <strong>de</strong> robustez.Pareto: Número <strong>de</strong> símplices rechazados por eltest <strong>de</strong> Pareto.Capacity: Número <strong>de</strong> símplices rechazados porel test <strong>de</strong> disponibilidad.|Q S |: Número <strong>de</strong> símplices almacenados en laslistas finales Q j , j = 1, 2.|Q V |: Número <strong>de</strong> vértices asociados a los símplicesen Q j , j = 1, 2.NT h: Número <strong>de</strong> hebras creadas.T h j time: El tiempo <strong>de</strong> ejecución <strong>de</strong> T h j , j =1, 2, en segundos.Time: El tiempo <strong>de</strong> ejecución en segundos.Speedup: Aceleración obtenida.<strong>La</strong> aceleración con respecto al tiempo <strong>de</strong> ejecución<strong>de</strong> un algoritmo paralelo con p unida<strong>de</strong>s <strong>de</strong> procesose <strong>de</strong>fine como S(p) = t(1)/t(p), don<strong>de</strong> t(p) es eltiempo <strong>de</strong> ejecución cuando p unida<strong>de</strong>s <strong>de</strong> procesoson utilizadas.<strong>La</strong> fase B&B <strong>de</strong> BiBlendPar es la misma para lasEstrategias 1 y 2. En esta fase se obtiene una ligeraaceleración en el tiempo <strong>de</strong> ejecución. No se alcanzauna aceleración lineal <strong>de</strong>bido a la diferencia <strong>de</strong>complejidad entre los dos productos: UniSpec1-5 tieneuna región factible <strong>de</strong>finida por unas restriccionescuadráticas <strong>de</strong> menor complejidad que UniSpec5b-5.En cuanto a la fase Comb, la Estrategia 2 exhi-TABLA IEsfuerzo computacionalFase B&BBiBlendSeq BiBlendParNEvalS 2.536.862 2.537.430NEvalV 168.186 168.299QLR 887.609 888.004Pareto 54.050 54.050Capacity 18.277 18.211|Q S | 308.443 308.465|Q V | 49.317 49.324Fase CombBiBlendSeq BiBlendParPareto 27.284 27.284Capacity 105.499 105.521|Q S | 175.660 175.660|Q V | 24.861 24.861be una buena escalabilidad y aceleración comparadocon BiBlendSeq, obteniéndose una aceleración lineal.Nótese que en esta fase se filtran casi la mitad <strong>de</strong> lossímplices finales obtenidos en la fase B&B, <strong>de</strong> ahí sucomplejidad. En cambio, la Estrategia 1 ofrece unaaceleración muy pobre en comparación con la Estrategia2. Uno <strong>de</strong> los principales motivos es que en laEstrategia 1 no se borran los símplices hasta el final,siendo las listas <strong>de</strong>l mismo tamaño durante toda laejecución <strong>de</strong>l Algoritmo 1. A<strong>de</strong>más, la Estrategia 2evalúa menos comparaciones (evaluación <strong>de</strong> (6) y posiblemente(7)) entre símplices (una media <strong>de</strong> 5.421millones) que la Estrategia 1 (5.487 millones).Para el problema <strong>de</strong> mezcla <strong>de</strong>scrito anteriormente(UniSpec1-5 & UniSpec5b-5), se han encontrado dossoluciones con un número diferente <strong>de</strong> materias primasinvolucrado: (x ⋆[1]∗,1 , x⋆[1] ∗,2 ) y (x⋆[2] ∗,1 , x⋆[2] ∗,2 ). <strong>La</strong> primera<strong>de</strong> ellas hace uso <strong>de</strong> cuatro materias primas(RM1, RM3, RM4 y RM5):x ⋆[1] =UniSpec1-5 UniSpec5b-5⎛⎞RM1 0,428125 0,146875RM2 0,0 0,0RM3 ⎜ 0,4352344 0,1640625⎟RM4 ⎝ 0,0 0,2328125 ⎠RM5 0,1366406 0,4562500El valor <strong>de</strong> coste <strong>de</strong> esta solución es f bi (x ⋆[1]∗,1 , x⋆[1] ∗,2 ) =111,09 + 116,334375 = 227,424375. <strong>La</strong> segunda solucióninvolucra las cinco materias primas:x ⋆[2] =UniSpec1-5 UniSpec5b-5⎛⎞RM1 0,428125 0,156172RM2 0,0 0,03RM3 ⎜ 0,442344 0,152852⎟RM4 ⎝ 0,0 0,212617 ⎠RM5 0,129531 0,448359El valor <strong>de</strong> coste <strong>de</strong> esta solución es f bi (x ⋆[2]∗,1 , x⋆[2] ∗,2 ) =111,033125 + 116,172422 = 227,205547.<strong>JP2011</strong>-25


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA IIAceleraciónFase B&B Fase Comb (Estrategia 1) TotalNT h T h 1 T h 2 Time Speedup NT h Time Speedup Time Speedup– – – 7,23 – – 1.991,46 – 1.998,70 –2 0,85 7,09 7,09 1,02 2 1.428,88 1,39 1.436,17 1,392 0,83 7,13 7,13 1,01 4 696,39 2,86 703,52 2,842 0,78 7,00 7,00 1,03 8 338,92 5,88 345,91 5,78Fase B&B Fase Comb (Estrategia 2) TotalNT h T h 1 T h 2 Time Speedup NT h Time Speedup Time Speedup– – – 7,23 – – 1.991,46 – 1.998,70 –2 0,83 7,03 7,03 1,03 1 1.966,51 1,01 1.973,54 1,012 0,81 7,03 7,03 1,03 2 956,01 2,08 936,05 2,082 0,76 6,96 6,96 1,04 4 465,02 4,28 471,98 4,232 0,81 7,00 7,00 1,03 8 228,63 8,71 235,63 8,48V. ConclusionesSe ha estudiado la paralelización <strong>de</strong> un algoritmocon la finalidad <strong>de</strong> resolver el problema <strong>de</strong> diseño <strong>de</strong>dos productos obtenidos mediante mezcla <strong>de</strong> materiasprimas para un problema <strong>de</strong> tamaño medio. Estecaso particular muestra las dificulta<strong>de</strong>s <strong>de</strong> este tipo<strong>de</strong> algoritmos. El algoritmo <strong>de</strong> bi-mezcla incrementalos retos <strong>de</strong> la paralelización <strong>de</strong>bido a la utilización<strong>de</strong> dos algoritmos B&B que comparten información.A<strong>de</strong>más, en los algoritmos <strong>de</strong> bi-mezcla, se ha <strong>de</strong> realizaruna combinación <strong>de</strong> símplices finales <strong>de</strong>spués <strong>de</strong>la fase B&B para <strong>de</strong>scartar regiones no factibles. Estafase <strong>de</strong> combinación es varios ór<strong>de</strong>nes <strong>de</strong> magnitudmás costosa computacionalmente que la fase B&B.Por ello, aquí sólo se ha utilizado una hebra por productoen la fase B&B y varias hebras en la fase <strong>de</strong>combinación. Los resultados muestran aceleracioneslineales en una máquina <strong>de</strong> ocho núcleos con memoriacompartida cuando se paraleliza el recorrido <strong>de</strong>una lista final y <strong>de</strong>spués el <strong>de</strong> la otra, en vez <strong>de</strong> realizarambos recorridos en paralelo.Nuestra intención es experimentar con problemas<strong>de</strong> mayor dimensión, intentando reducir su costecomputacional. Otra línea <strong>de</strong> investigación a continuares <strong>de</strong>sarrollar el algoritmo n-mezcla y su versiónparalela, problema que es <strong>de</strong> interés para la industria.Agra<strong>de</strong>cimientosEl presente trabajo ha sido parcialmente financiadopor el Ministerio <strong>de</strong> Ciencia e Innovación(TIN2008-01117), la Junta <strong>de</strong> Andalucía (P08-TIC-3518) y el Fondo Europeo <strong>de</strong> Desarrollo Regional(FEDER). Eligius M. T. Hendrix es un investigadorpost-doctoral contratado a través <strong>de</strong>l SubprogramaRamón y Cajal.Referencias[1] J. Ashayeri, A.G.M. van Eijs, and P. Ne<strong>de</strong>rstigt, “Blendingmo<strong>de</strong>lling in a process manufacturing: A casestudy,” Eur. J. Oper. Res., vol. 72, no. 3, pp. 460–468,1994.[2] J.W.M. Bertrand and W.G.M.M. Rutten, “Evaluationof three production planning procedures for the use ofrecipe flexibility,” Eur. J. Oper. Res., vol. 115, no. 1, pp.179–194, 1999.[3] L.G. Casado, E.M.T. Hendrix, and I. García, “Infeasibilityspheres for finding robust solutions of blendingproblems with quadratic constraints,” J. Global Optim.,vol. 39, no. 4, pp. 577–593, 2007.[4] E.M.T. Hendrix, L.G. Casado, and I. García, “The semicontinuousquadratic mixture <strong>de</strong>sign problem: Descriptionand branch-and-bound approach,” Eur. J. Oper.Res., vol. 191, no. 3, pp. 803–815, 2008.[5] L.G. Casado, I. García, B.G. Tóth, and E.M.T. Hendrix,“On <strong>de</strong>termining the cover of a simplex by spheres centeredat its vertices,” J. Global Optim., pp. 1–11, 2010.[6] J.F.R. Herrera, L.G. Casado, E.M.T. Hendrix, andI. García, “Pareto optimality and robustness in biblendingproblems,” TOP, 2011, Submitted.[7] H.P. Williams, Mo<strong>de</strong>l Building in Mathematical Programming,Wiley & Sons, Chichester, 1993.[8] L.G. Casado, I. García, J.A. Martínez, and E.M.T. Hendrix,“Shared memory parallel exhaustive search ofepsilon-robust mixture <strong>de</strong>sign solutions,” in Volume ofAbstracts of 22nd European Conference on OperationalResearch (EURO XXII), 2007, p. 178.[9] B. Gendron and T.G. Crainic, “Parallel branch-andboundalgorithms: Survey and synthesis,” Oper. Res.,vol. 42, no. 6, pp. 1042–1066, 1994.[10] L.G. Casado, J.A. Martínez, I. García, and E.M.T. Hendrix,“Branch-and-bound interval global optimizationon shared memory multiprocessors,” Optim. Method.Softw., vol. 23, pp. 689–701, 2008.[11] T. Ibaraki, “Theoretical comparisons of search strategiesin branch and bound algorithms,” Int. J. Comput. Inf.Sci., vol. 5, no. 4, pp. 315–344, 1976.[12] L.G. Mitten, “Branch and bound methods: general formulationand properties,” Oper. Res., vol. 18, no. 1, pp.24–34, 1970.[13] J.L. Berenguel, L.G. Casado, I. García, and E.M.T. Hendrix,“On estimating workload in interval branch-andboundglobal optimization algorithms,” J. Global Optim.,2011, Submitted.[14] J.F.S. Estrada, L.G. Casado, and I. García, “Adaptiveparallel interval global optimization algorithms basedon their performance for non-<strong>de</strong>dicated multicore architectures,”in Parallel, Distributed and Network-BasedProcessing (PDP), 2011 19th Euromicro InternationalConference on, February 2011, pp. 252–256.[15] J.A. Martínez, L.G. Casado, J.A. Alvarez, and I. García,“Interval parallel global optimization with Charm++,”in Applied Parallel Computing. State of the Art in ScientificComputing, Jack Dongarra, Kaj Madsen, and JerzyWasniewski, Eds., vol. 3732 of Lecture Notes in ComputerScience, pp. 161–168. Springer Berlin / Hei<strong>de</strong>lberg,2006.[16] J.F. Sanjuan-Estrada, L.G. Casado, and I. García,“Adaptive parallel interval branch and bound algorithmsbased on their performance for multicore architectures,”J. Supercomput., pp. 1–9, 2011.<strong>JP2011</strong>-26


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Optimización <strong>de</strong>l Método BST para laReducción <strong>de</strong> Mo<strong>de</strong>los en ArquitecturasMultinúcleoPablo Ezzatti 1 , Enrique S. Quintana-Ortí 2 and Alfredo Remón 3Resumen— <strong>La</strong> reducción <strong>de</strong> mo<strong>de</strong>los es unaherramienta importante en diversas aplicacionescientíficas y <strong>de</strong> ingeniería. Dada su relevancia, esposible encontrar en la literatura diversos métodospara resolver este problema. Entre ellos <strong>de</strong>stacanlos métodos basados en la <strong>de</strong>scomposición <strong>de</strong> valoressingulares por sus buenas características numéricas.Pero estos métodos requieren un alto coste computacional,O(n 3 ) operaciones aritméticas en comaflotante, don<strong>de</strong> n es el or<strong>de</strong>n <strong>de</strong>l mo<strong>de</strong>lo original y seencuentra en el rango 10 3 − 10 5 en numerosas aplicacionesprácticas. Consecuentemente, la aplicabilidad<strong>de</strong> estos métodos está condicionada al uso <strong>de</strong> arquitecturasy técnicas <strong>de</strong> computación <strong>de</strong> altas prestaciones.En este estudio se han <strong>de</strong>sarrollado y evaluado diversasimplementaciones para uno <strong>de</strong> estos métodos,el método BST, sobre una arquitectura con procesadoresmultinúcleo. Los resultados experimentalesavalan la eficiencia <strong>de</strong> los códigos <strong>de</strong>sarrollados y suescalabilidad.Palabras clave— Reducción <strong>de</strong> mo<strong>de</strong>los, sistemasdinámicos lineales, ecuaciones <strong>de</strong> Lyapunov, métodosSVD, GPUs.I. IntroducciónNUMEROSOS procesos físicos y químicos pue<strong>de</strong>nser <strong>de</strong>scritos mediante mo<strong>de</strong>los matemáticos.Estos mo<strong>de</strong>los pue<strong>de</strong>n ser empleados, por ejemplo,para anticipar el comportamiento <strong>de</strong>l proceso y seaplican con éxito en áreas tan dispares como eldiseño <strong>de</strong> controladores, la simulación <strong>de</strong> circuitos oel diseño <strong>de</strong> estructuras. En particular, consi<strong>de</strong>ra unsistema lineal invariante en el tiempo que, por ejemplo,<strong>de</strong>scribe un proceso físico, <strong>de</strong>finido en el mo<strong>de</strong>lo<strong>de</strong> espacio <strong>de</strong> estados porẋ(t) = Ax(t) + Bu(t), t > 0, x(0) = x 0 ,y(t) = Cx(t) + Du(t), t ≥ 0,(1)don<strong>de</strong> A ∈ R n×n , B ∈ R n×m , C ∈ R p×n , D ∈R p×m , x 0 ∈ R n es el estado inicial <strong>de</strong>l sistema, y nes el or<strong>de</strong>n <strong>de</strong>l mo<strong>de</strong>lo. El objetivo <strong>de</strong> la reducción<strong>de</strong> mo<strong>de</strong>los es encontrar un mo<strong>de</strong>lo <strong>de</strong> or<strong>de</strong>n menorẋ r (t) = A r x r (t) + B r u(t), t > 0, x r (0) = ˆx 0 ,y r (t) = C r x r (t) + D r u(t), t ≥ 0,(2)don<strong>de</strong> A r ∈ R r×r , B r ∈ R r×m , C r ∈ R p×r ,D r ∈ R p×m , ˆx 0 ∈ R n es el estado inicial <strong>de</strong>l sistema,r es el or<strong>de</strong>n <strong>de</strong>l nuevo mo<strong>de</strong>lo, con r ≪ n,1 Centro <strong>de</strong> Cálculo-Instituto <strong>de</strong> Computación, <strong>Universidad</strong><strong>de</strong> la República, e-mail: pezzatti@fing.edu.uy2 Depto. <strong>de</strong> Ingeniería y Ciencia <strong>de</strong> Computadores, <strong>Universidad</strong>Jaume I, e-mail: quintana@icc.uji.es3 Depto. <strong>de</strong> Ingeniería y Ciencia <strong>de</strong> Computadores, <strong>Universidad</strong>Jaume I, e-mail: quintana@icc.uji.esy ‖y − y r ‖ es “pequeño”. Es <strong>de</strong>cir, el propósito <strong>de</strong>la reducción <strong>de</strong> mo<strong>de</strong>los es obtener un nuevo mo<strong>de</strong>locon un or<strong>de</strong>n menor (r), que potencialmente pue<strong>de</strong>reemplazar el mo<strong>de</strong>lo original en posteriores cálculosreportando importantes reducciones <strong>de</strong> los requerimientoscomputacionales. Mientras que hace unosaños, la reducción <strong>de</strong> mo<strong>de</strong>los con un espacio <strong>de</strong>estados en el or<strong>de</strong>n <strong>de</strong> las <strong>de</strong>cenas <strong>de</strong> miles o superior,requería <strong>de</strong>l uso <strong>de</strong> un cluster <strong>de</strong> computadorascon un número mo<strong>de</strong>rado <strong>de</strong> nodos [1], losprocesadores multinúcleo actuales proporcionan unpo<strong>de</strong>r <strong>de</strong> cómputo suficiente como para, en tiempos<strong>de</strong> cómputo razonable, ejecutar la mayor parte <strong>de</strong> lasoperaciones matriciales requeridas para la reducción<strong>de</strong> mo<strong>de</strong>los.En trabajos anteriores tratamos los casos en losque la matriz <strong>de</strong> espacio <strong>de</strong> estados A es dispersa [2],una matriz general <strong>de</strong>nsa [3], y una matriz banda[4]. En este trabajo nos centramos en el caso enel que la matriz −A es una matriz <strong>de</strong>nsa simétrica<strong>de</strong>finida positiva (en a<strong>de</strong>lante SPD, <strong>de</strong>l inglés SymmetricPositive Definite). En este caso, la estructuray propieda<strong>de</strong>s <strong>de</strong> la matriz pue<strong>de</strong>n ser explotadaspara reducir el número <strong>de</strong> operaciones aritméticasnecesarias.<strong>La</strong> estructura <strong>de</strong>l resto <strong>de</strong>l artículo es la siguiente:en la Sección II se revisan los métodos y bibliotecasempleadas en la reducción <strong>de</strong> mo<strong>de</strong>los, en laSección III se <strong>de</strong>scribe el método <strong>de</strong> la función signopara la resolución <strong>de</strong> ecuaciones <strong>de</strong> Lyapunov, en lasSecciones IV y V se presentan diferentes métodospara la inversión <strong>de</strong> matrices SPD y las implementaciones<strong>de</strong> altas prestaciones propuestas para esta operación,finalmente, las Secciones VI y VII muestranlos resultados experimentales y las conclusiones alcanzadasen este trabajo.II. Algoritmos y bibliotecas para lareducción <strong>de</strong> mo<strong>de</strong>losComo se ha comentado, existen diversos métodospara la reducción <strong>de</strong> mo<strong>de</strong>los, pero entre ellos<strong>de</strong>stacan por sus cualida<strong>de</strong>s numéricas los métodosbasados en la <strong>de</strong>scomposición en valores singulares(SVD). Estos métodos se caracterizan por la preserveración<strong>de</strong> importantes cualida<strong>de</strong>s <strong>de</strong> la matriz<strong>de</strong> estados, como por ejemplo la estabilidad o la pasividad.A<strong>de</strong>más, estos métodos proporcionan cotasal error introducido por el nuevo mo<strong>de</strong>lo. Por contra,su alto coste computacional condiciona su aplicabilidada problemas <strong>de</strong> dimensión mo<strong>de</strong>rada. Elcoste computacional <strong>de</strong> estos métodos se concentra<strong>JP2011</strong>-27


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011en la resolución <strong>de</strong> dos ecuaciones <strong>de</strong> Lyapunov. Alaplicar el método <strong>de</strong>l truncamiento balanceado a (1),las ecuaciones <strong>de</strong> Lyapunov que se <strong>de</strong>ben resolver sonAW c + W c A T + BB T = 0,A T W o + W o A + C T C = 0.(3)En general, A es una matriz estable (es <strong>de</strong>cir, todossus valores propios tienen parte real negativa) y consecuentemente,W c , W o son matrices SPDs. Desafortunadamente,W c , W o son <strong>de</strong>nsas, cuadradas y <strong>de</strong> dimensiónn×n incluso a pesar <strong>de</strong> que A sea una matrizdispersa. Estas ecuaciones pue<strong>de</strong>n ser resueltas mediantemétodos directos [5][6] como los incluidos enla biblioteca SLICOT [7], permitiendo la reducción<strong>de</strong> mo<strong>de</strong>los <strong>de</strong> dimensión reducida (n < 5.000) en lascomputadoras mo<strong>de</strong>rnas. Problemas <strong>de</strong> dimensiónmayor, con <strong>de</strong>cenas <strong>de</strong> miles <strong>de</strong> variables en el espacio<strong>de</strong> estados, pue<strong>de</strong>n ser reducidos utilizando elmétodo <strong>de</strong> la función signo en arquitecturas paralelas<strong>de</strong> altas prestaciones, por ejemplo mediante las rutinasincluidas en la biblioteca PLiCMR [8][1]. <strong>La</strong>s dificulta<strong>de</strong>s<strong>de</strong> explotar la habitual estructura dispersa<strong>de</strong> las matrices que aparecen en las ecuaciones <strong>de</strong>Lyapunov durante su resolución mediante métodosdirectos o mediante el método <strong>de</strong> la función signo,limita la aplicabilidad <strong>de</strong> estas dos bibliotecas a problemas<strong>de</strong> dimensión mo<strong>de</strong>rada. No obstante, dichasbibliotecas están completamente basadas en núcleoscomputacionales <strong>de</strong> bibliotecas <strong>de</strong> álgebra numérica<strong>de</strong> altas prestaciones, en particular <strong>de</strong> las bibliotecasBLAS y LAPACK, reportando un rendimiento nada<strong>de</strong>s<strong>de</strong>ñable.III. El método <strong>de</strong> la función signoEl método <strong>de</strong> la función signo fue presentado en [9]como un método eficiente para resolver la ecuación<strong>de</strong> Lyapunov estándar. Una <strong>de</strong> las posibles implementaciones<strong>de</strong> este método se basa en el método<strong>de</strong> la iteración <strong>de</strong> Newton [10]. A continuación, se<strong>de</strong>scriben los pasos a seguir en esta variante:Algorithm CECLNC:A 0 ← A, ˜S 0 ← B T , ˜R 0 ← Ck ← 0repeat(A k+1 ← √ 1 Ak 2+ A −1 )k˜S k+1 ← 1 √2[˜Sk ,˜R k+1 ← 1 √2[˜Rk ,k ← k + 1until convergence˜Sk (A −1]˜Rk A −1kk )T ]Al converger, tras j iteraciones, ˜S = √2 1 ˜Sj y˜R = √ 1 ˜Rj 2<strong>de</strong> dimensiones ˜k o × n y ˜k c × n son, respectivamente,aproximaciones <strong>de</strong> S y R, <strong>de</strong> formaque W c = S T S ≈ ˜S T ˜S y Wo = R T R ≈ ˜R T ˜R.Este método es propicio para la resolución <strong>de</strong> ecuaciones<strong>de</strong> Lyapunov en las arquitecturas <strong>de</strong> computaciónmo<strong>de</strong>rnas, en las que se dispone <strong>de</strong> unnúmero elevado <strong>de</strong> unida<strong>de</strong>s computacionales. Enprimer lugar, presenta una convergencia cuadráticaque asegura un número <strong>de</strong> iteraciones mo<strong>de</strong>rado; ensegundo lugar, presenta un alto nivel <strong>de</strong> paralelismo,permitiendo extraer gran rendimiento a estas arquitecturas.Cada iteración <strong>de</strong>l algoritmo CECLNC requiereO(n 3 ) operaciones artiméticas en coma flotante, oflops (<strong>de</strong>l inglés floating-point arithmetic operations),don<strong>de</strong> n es la dimensión <strong>de</strong> la matriz A. En particular,las cuatro operaciones ejecutadas en cada pasoson:1. Obtener la matriz A −1k, la matriz inversa <strong>de</strong> lamatriz SPD A k (n 3 flops)2. Calcular la suma <strong>de</strong> dos matrices simétricas yescalar el resultado (n 2 flops)3. Calcular ˜S k+1 mediante un producto <strong>de</strong> matrices(n 2 × ˜k o flops)4. Calcular ˜R k+1 mediante un producto <strong>de</strong> matrices(n 2 × ˜k c flops)Como se pue<strong>de</strong> ver, el coste computacional <strong>de</strong>lalgoritmo <strong>de</strong>scrito se concentra en el cálculo <strong>de</strong> lamatriz inversa A −1 k . Esta afirmación, basada en elcoste teórico, se refuerza con los resultados experimentalesalcanzados en un trabajo anterior, don<strong>de</strong> elmismo método era utilizado para resolver una únicaecuación <strong>de</strong> Lyapunov (pasos 1 a 3) con una matriz<strong>de</strong> coeficientes general [3]. En dicho trabajo, a pesar<strong>de</strong>l uso <strong>de</strong> una GPU para acelerar el cómputo <strong>de</strong>la matriz inversa, esta operación requería <strong>de</strong> entreel 85% y el 91% <strong>de</strong>l tiempo total <strong>de</strong> cómputo parados problemas <strong>de</strong> dimensión 5.177 y 9.699 respectivamente.A<strong>de</strong>más, se dispone <strong>de</strong> implementaciones optimizadaspara arquitecturas multinúcleo para elresto <strong>de</strong> las operaciones requeridas por el algoritmoCECLNC. Por ejemplo, pue<strong>de</strong>n utilizarse rutinas <strong>de</strong> labiblioteca BLAS para calcular los productos <strong>de</strong> matrices(pasos 3 y 4), o directivas OpenMP para optimizarla suma <strong>de</strong> matrices y el escalado <strong>de</strong>l resultado(paso 2).Consecuentemente, el <strong>de</strong>sarrollo <strong>de</strong> una implementaciónoptimizada <strong>de</strong> la inversión <strong>de</strong> una matrizSPD es la única herramienta necesaria para alcanzarun resolutor <strong>de</strong> ecuaciones <strong>de</strong> Lyapunov <strong>de</strong> altasprestaciones sobre arquitecturas multinúcleo, y conello, un método eficiente para la reducción <strong>de</strong> mo<strong>de</strong>los.El resto <strong>de</strong>l artículo se centra en el <strong>de</strong>sarrollo <strong>de</strong>un núcleo computacional eficiente para la inversión<strong>de</strong> matrices SPD sobre arquitecturas multinúcleo.IV. Inversión <strong>de</strong> matrices SPDEn esta sección revisitamos dos algoritmos diferentespara el cálculo <strong>de</strong> la matriz inversa <strong>de</strong> unamatriz SPD. El primer algoritmo se basa en la computación<strong>de</strong> la factorización <strong>de</strong> Cholesky, mientrasque el segundo algoritmo se basa en el método <strong>de</strong>la eliminación <strong>de</strong> Gauss-Jordan [11]. Ambos algoritmospresentan el mismo coste computacional, perolas propieda<strong>de</strong>s <strong>de</strong>l procedimiento <strong>de</strong> la emilinación<strong>JP2011</strong>-28


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Algorithm: [A] := GJE blk v1 (A)„ «AT L A T RPartition A →⋆ A BRwhere A T L is 0 × 0 and A BR is n × nwhile m(A T L ) < m(A) doDetermine block size bRepartition„ «AT L A T R⋆ A BR0→ @where A 11 is b × bA 00 A 01 A 021⋆ A 11 A 12 AW := −A 00 · A 01 SYMMA 11 := A 11 + A T 01 · A 01 GEMMA 11 := chol(A 11 ) POTRFtriu(A 11 ) := triu(A 11 ) −1 TRTRIW := W · A 11 TRMMA 01 := W · A T 11 TRMMA 00 := A 00 + W · W T SYRKA 11 := triu(A 11 ) · triu(A 11 ) T LAUUMendwhileContinue with„ «AT L A T R⋆ A BR0← @A 00 A 01 A 021⋆ A 11 A 12 AFig. 1. Algoritmo por bloques para la inversión <strong>de</strong> matrices SPD via GJE (Variant 1).Algorithm: [A] := GJE blk v2 (A)„ «ATPartition A → L A T R⋆ A BRwhere A T L is 0 × 0 and A BR is n × nwhile m(A T L ) < m(A) doDetermine block size bRepartition„ «AT L A T R⋆ A BR0→ @where A 11 is b × bA 00 A 01 A 021⋆ A 11 A 12 AA 11 := chol(A 11 ) POTRFtriu(A 11 ) := triu(A −111 ) TRTRIA 01 := A 01 · A 11 TRMMA 00 := A 00 + A 01 · A T 01 SYRKA 01 := A 01 · A 11 TRMMA 12 := A −T11 · A 12 TRMMA 22 := A 22 − A T 12 · A 12 SYRKA 02 := A 02 − A 01 · A 12 GEMMA 12 := −(A 11 · A 12 ) TRMMA 11 := A 11 · A T 12 LAUUMendwhileContinue with„ «AT L A T R⋆ A BR0← @A 00 A 01 A 021⋆ A 11 A 12 AFig. 2. Algoritmo por bloques para la inversión <strong>de</strong> matrices SPD via GJE (Variant 2).<strong>de</strong> Gauss-Jordan son más propicias para su ejecuciónsobre arquitecturas paralelas.A. Inversión <strong>de</strong> matrices mediante la factorización<strong>de</strong> CholeskyEl método tradicional para calcular la inversa <strong>de</strong>una matriz SPD A ∈ R n×n se basa en la factorización<strong>de</strong> Cholesky y consiste en los tres siguientes pasos:1. Calcular la factorización <strong>de</strong> Cholesky A =U T U, don<strong>de</strong> U ∈ R n×n es una matriz triangularsuperior2. Invertir el factor triangular U → U −13. Obtener la inversa mediante el producto <strong>de</strong> matricesU −1 U −T = A −1Explotando la estructura simétrica <strong>de</strong> A, el costecomputacional y espacial <strong>de</strong>l algoritmo pue<strong>de</strong> ser reducidoconsi<strong>de</strong>rablemente. En particular, como se hacomentado, el coste computacional es n 3 flops (frentea los 2n 3 flops requeridos para invertir una matrizno-simétrica). Este algoritmo permite implementacionesin-place, <strong>de</strong> forma que la matriz resultadosobreescribe la matriz original, reportando una im-<strong>JP2011</strong>-29


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011portante reducción <strong>de</strong> los requerimientos espaciales.A<strong>de</strong>más, sólo la parte superior <strong>de</strong> A es referenciadadurante el método, y sólo la parte superior <strong>de</strong> A −1 esescrita, <strong>de</strong> forma que se reducen los accesos a memoria.No obstante, con el fin <strong>de</strong> aumentar las prestaciones,la matriz A se almacena como una matrizcompleta n × n.B. Inversión <strong>de</strong> matrices basada en el algoritmo <strong>de</strong>la eliminación <strong>de</strong> Gauss-JordanEl algoritmo <strong>de</strong> la eliminación <strong>de</strong> Gauss-Jordan es,esencialmente, una reor<strong>de</strong>nación <strong>de</strong> las operacionesejecutadas en el algoritmo tradicional. Por lo tanto,ambos presentan el mismo coste computacional. <strong>La</strong>reor<strong>de</strong>nación <strong>de</strong> operaciones reduce notablemente elnúmero <strong>de</strong> accesos a memoria requerido, a<strong>de</strong>más <strong>de</strong>proveer un método más propicio para su ejecuciónen arquitecturas provistas con múltiples unida<strong>de</strong>s <strong>de</strong>cómputo, gracias a un mejor balanceo <strong>de</strong> carga [12].Este método pue<strong>de</strong> ser cuidadosamente diseñadopara explotar la estructura simétrica <strong>de</strong> la matriz yobtener una implementación in-place.<strong>La</strong>s Figuras 1 y 2 <strong>de</strong>scriben dos algoritmos porbloques basados en la eliminación <strong>de</strong> Gauss-Jordanutilizando la notación FLAME [13][14]. En ellos, lafunciones m(·) y triu(·) <strong>de</strong>vuelven el número <strong>de</strong> filasy la parte triangular superior <strong>de</strong> la matriz argumentorespectivamente, mientras que “⋆” <strong>de</strong>scribe bloquesen la parte triangular inferior <strong>de</strong> la matriz, que noson referenciados en el método. Creemos que el resto<strong>de</strong> la notación es intuitiva. A la <strong>de</strong>recha <strong>de</strong> cada operaciónse <strong>de</strong>fine el núcleo computacional <strong>de</strong> BLASque proporciona la funcionalidad necesaria para sucómputo. En ambos algoritmos, la inversa <strong>de</strong> la matrizsobreescribe la matriz inicial (son, por lo tanto,variantes in-place).En el algoritmo mostrado en la Figura 1 se ejecutanocho operaciones en cada iteración. Dos factoreslimitan las prestaciones <strong>de</strong> su implementaciónsobre arquitecturas paralelas: en primer lugar, lasnumerosas <strong>de</strong>pen<strong>de</strong>ncias <strong>de</strong> datos entre las operacionesobligan a su ejecución secuencial, en segundo lugar,excepto la actualización <strong>de</strong>l bloque A 00 , el resto<strong>de</strong> operaciones involucran únicamente bloques <strong>de</strong> dimensiónreducida (teniendo en cuenta que, para aumentarlas prestaciones, el tamaño <strong>de</strong> bloque b sefija a un valor pequeño comparado con la dimensión<strong>de</strong> la matriz, n). Ambos factores limitan el paralelismoinherente <strong>de</strong> la variante, especialmente durantelas primeras iteraciones <strong>de</strong>l bucle, cuando A 00es también un bloque pequeño.<strong>La</strong> Figura 2 muestra una segunda variante <strong>de</strong>l algoritmobasado en la eliminación <strong>de</strong> Gauss-Jordanen la que todos los elementos <strong>de</strong> la parte triangularsuperior <strong>de</strong> la matriz son actualizados en cadaiteración. De nuevo, las <strong>de</strong>pen<strong>de</strong>ncias <strong>de</strong> datos obligana serializar la ejecución <strong>de</strong> la mayor parte <strong>de</strong> lasoperaciones.De forma que el paralelismo pue<strong>de</strong> ser extraídoúnicamente durante la ejecución <strong>de</strong> cada operación.En esta variante, las actualizaciones <strong>de</strong> los bloquesA 00 y A 22 concentran la mayor parte <strong>de</strong> los cálculos,mientras que el resto <strong>de</strong> las operaciones involucranbloques pequeños. Esta implementación presentados ventajas respecto a la variante anterior:1. No requiere espacio <strong>de</strong> almacenamiento adicional2. El coste computacional <strong>de</strong> cada iteración esconstanteV. Implementaciones <strong>de</strong> altas prestacionesA. Implementaciones basadas en la factorización <strong>de</strong>CholeskyEl algoritmo basado en la factorización <strong>de</strong>Cholesky para el cálculo <strong>de</strong> la matriz inversa <strong>de</strong>una matriz SPD (ver la Sección IV-A) se compone<strong>de</strong> tres etapas que <strong>de</strong>ben ser ejecutadas secuencialmente.Esto significa que el paralelismo pue<strong>de</strong> serextraído durante la ejecución <strong>de</strong> cada etapa pero no<strong>de</strong> la ejecución concurrente <strong>de</strong> etapas.<strong>La</strong> biblioteca Intel MKL [15] ofrece rutinas para elcálculo <strong>de</strong> la factorización <strong>de</strong> Cholesky <strong>de</strong> una matrizSPD (rutina potrf, etapa 1) y el cálculo <strong>de</strong> lainversa <strong>de</strong> una matriz SPD dado su factor triangular(rutina potri, etapas 2 y 3). De forma que po<strong>de</strong>mosfácilmente obtener una implementación <strong>de</strong> estealgoritmo, eficiente y paralela, para arquitecturasmultinúcleo, utilizando una implementación multithread<strong>de</strong> la biblioteca MKL.B. Implementaciones basadas en el método <strong>de</strong> laeliminación <strong>de</strong> Gauss-JordanEn esta subsección <strong>de</strong>scribimos dos implementacionespara las sendas variantes <strong>de</strong>l algoritmo GJEpresentadas en la Sección IV.En las dos variantes, la mayor parte <strong>de</strong> las operacioneshan sido reescritas en forma <strong>de</strong> productos<strong>de</strong> matrices. En particular, la operación que precisa<strong>de</strong> un mayor número <strong>de</strong> flops es una actualizaciónsimétrica <strong>de</strong> rango-k (un caso particular <strong>de</strong>l producto<strong>de</strong> matrices).<strong>La</strong> biblioteca MKL incluye implementaciones <strong>de</strong>altas prestaciones para este núcleo computacional,así como para el resto <strong>de</strong> operaciones implicadas enlos algoritmos GJE BLK V 1 y GJE BLK V 2 . <strong>La</strong>s rutinasGJE v1 y GJE v2 implementan estos algoritmosutilizando los núcleos computacionales <strong>de</strong> MKL. Elparalelismo es obtenido, <strong>de</strong> nuevo, en la ejecución <strong>de</strong>cada operación mediante la invocación <strong>de</strong> las rutinasmulti-thread <strong>de</strong> MKL. El cómputo concurrente<strong>de</strong> distintas operaciones está limitado por la <strong>de</strong>pen<strong>de</strong>ncia<strong>de</strong> datos.VI. Resultados experimentalesEn esta sección se evalúan las diferentes implementacionespropuestas en la sección V.Todos los experimentos en esta sección fueron <strong>de</strong>sarrolladosutilizando aritmética IEEE <strong>de</strong> simple precisión.Se experimentó con matrices SPD <strong>de</strong> dimensión1.000, . . . , 15.000. Se evaluaron diferentestamaños <strong>de</strong> bloque (1024, 512, 256, 128, 64 y 32)<strong>JP2011</strong>-30


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA IHardware empleado en los experimentos.Procesadores #cores Freq. L2 Memoria(GHz) (MB) (GB)Intel Xeon X7550 (8×4) 32 2.0 18 124350300LAPACKGJE_V1GJE_V235030025025032 THREADSGFLOPS20015010050GFLOPS2001501005016 THREADS8 THREADS4 THREADS2 THREADS1 THREAD00 2000 4000 6000 8000 10000 12000 14000 16000Dimensión <strong>de</strong> la matriz00 2000 4000 6000 8000 10000 12000 14000 16000Dimensión <strong>de</strong> la matrizFig. 3. Rendimiento <strong>de</strong> las distintas implementaciones <strong>de</strong> lainversión <strong>de</strong> matrices SPD.350Fig. 4. Rendimiento <strong>de</strong> la rutina GJE V1.para cada implementación, pero únicamente los resultadosobtenidos con el tamaño <strong>de</strong> bloque óptimoson mostrados.<strong>La</strong> plataforma empleada en los experimentos estáformada por cuatro procesadores Intel Xeon X7550(con 8 cores por procesador) a una frecuencia <strong>de</strong> 2.0GHz. <strong>La</strong> tabla I incluye más <strong>de</strong>talles sobre esta computadora.<strong>La</strong> mayor parte <strong>de</strong> las operaciones fueronejecutadas utilizando las rutinas <strong>de</strong> la biblioteca IntelMKL en su versión 11.0.<strong>La</strong> Figura 3 muestra las prestaciones obtenidas porla implementación basada en las rutinas LAPACKy las basadas en el algoritmo <strong>de</strong> la eliminación <strong>de</strong>Gauss-Jordan <strong>de</strong>scritas en la sección anterior. Entodas ellas se emplea 32 threads (uno por cadauno <strong>de</strong> los núcleos disponibles en la arquitectura).<strong>La</strong> implementación <strong>de</strong> la primera variante <strong>de</strong>l algoritmo,GJE V1, es notablemente más eficiente quela implementación proporcionada por LAPACK, especialmenteen la inversión <strong>de</strong> matrices <strong>de</strong> gran dimensión(por ejemplo, para matrices <strong>de</strong> dimensión15.000 es aproximadamente 8× más rápida). No obstante,las mejores prestaciones se obtienen con laimplementación <strong>de</strong> la segunda variante <strong>de</strong>l algoritmo,GJE V2, superando los 300 GFLOPS para matrices<strong>de</strong> dimensión 15.000, y siendo más <strong>de</strong> 10× másrápida que LAPACK. Esto se <strong>de</strong>be a las propieda<strong>de</strong>s<strong>de</strong> esta variante, que la hacen más a<strong>de</strong>cuada para suejecución en computadoras paralelas.<strong>La</strong> Figura 4 muestra los resultados obtenidos porla variante GJE V1 empleando 1, 2, 4, 8, 16 y 32threads. El uso <strong>de</strong> más threads reporta un incrementoen las prestaciones consi<strong>de</strong>rable, excepto parala inversión <strong>de</strong> matrices con dimensión superior a8.000 cuando se emplean más <strong>de</strong> 16 threads. LosGFLOPS3002502001501005032 THREADS16 THREADS8 THREADS4 THREADS2 THREADS1 THREAD00 2000 4000 6000 8000 10000 12000 14000 16000Dimensión <strong>de</strong> la matrizFig. 5. Rendimiento <strong>de</strong> la rutina GJE V2.resultados obtenidos <strong>de</strong>muestran la escalabilidad <strong>de</strong>la rutina GJE V1.Finalmente, la Figura 5 es la análoga para la varianteGJE V2. Destacar en ella, a<strong>de</strong>más <strong>de</strong> laeficiencia alcanzada, la escalabilidad <strong>de</strong> la implementaciónGJE V2.VII. ConclusionesSe han presentado diferentes implementaciones <strong>de</strong>altas prestaciones para la inversión <strong>de</strong> matrices SPDen arquitecturas multinúcleo. Esta operación esnecesaria para la reducción <strong>de</strong> mo<strong>de</strong>los y requiere<strong>de</strong> un alto coste computacional. Por lo tanto, requiere<strong>de</strong> la aplicación <strong>de</strong> hardware y técnicas <strong>de</strong>computación <strong>de</strong> altas prestaciones. El trabajo incluyela evaluación <strong>de</strong> dos algoritmos para la inversión<strong>de</strong> matrices, el algoritmo tradicional basadoen la factorización <strong>de</strong> Cholesky, y otro basado en elalgoritmo <strong>de</strong> la eliminación <strong>de</strong> Gauss-Jordan, mása<strong>de</strong>cuado para arquitecturas paralelas.<strong>JP2011</strong>-31


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Diferentes implementaciones <strong>de</strong> cada algoritmo sehan presentado y evaluado sobre una arquitecturacon 4 procesadores multinúcleo. <strong>La</strong>s implementaciones<strong>de</strong>sarrolladas se fundamentan en el uso <strong>de</strong>núcleos computacionales <strong>de</strong> altas prestaciones <strong>de</strong> labiblioteca Intel MKL.Los resultados experimentales <strong>de</strong>muestran quelas mejores prestaciones se obtienen con las rutinasbasadas en el algoritmo <strong>de</strong> la eliminación <strong>de</strong>Gauss-Jordan. <strong>La</strong>s características <strong>de</strong> este algoritmolo hacen muy propicio para su implementaciónen arquitecturas paralelas, proporcionando un granrendimiento y una notoria escalabilidad.Agra<strong>de</strong>cimientosLos autores quieren agra<strong>de</strong>cer a Francisco Igualpor su soporte técnico, así como a Manuel Ujaldón(<strong>de</strong> la <strong>Universidad</strong> <strong>de</strong> Málaga) por facilitar el accesoa la plataforma hardware empleada para la evaluaciónexperimental <strong>de</strong> las nuevas rutinas. EnriqueS. Quintana-Ortí y Alfredo Remón recibieron financiación<strong>de</strong>l proyecto CICYT TIN2008-06570-C04.Referencias[1] Peter Benner, Enrique S. Quintana-Ortí, and GregorioQuintana-Ortí, “State-space truncation methods for parallelmo<strong>de</strong>l reduction of large-scale systems,” ParallelComputing, vol. 29, no. 11-12, pp. 1701 – 1722, 2003.[2] José M. Badía, Peter Benner, Rafael Mayo, and EnriqueS. Quintana-Ortí, “Parallel algorithms for balancedtruncation mo<strong>de</strong>l reduction of sparse systems,” in AppliedParallel Computing, vol. 3732 of Lecture Notes inComputer Science, pp. 267–275. Springer Berlin / Hei<strong>de</strong>lberg,2006.[3] Peter Benner, Pablo Ezzatti, Daniel Kressner, Enrique S.Quintana-Ortí, and Alfredo Remón, “A mixed-precisionalgorithm for the solution of Ļyapunov equations on hybridCPU-GPU ¸ platforms,” Parallel Computing, 2010.[4] Alfredo Remón, Enrique S. Quintana-Ortí, and GregorioQuintana-Ortí, “Solution of band linear systems in mo<strong>de</strong>lreduction for VSLI circuits,” in Scientific Computing inElectrical Engineering, vol. 11 of Mathematics in Industry,pp. 387–393. Springer Berlin Hei<strong>de</strong>lberg, 2007.[5] R. H. Bartels and G. W. Stewart, “Solution of the matrixequation ax + xb = c [f4],” Commun. ACM, vol. 15, pp.820–826, September 1972.[6] S. J. Hammarling, “Numerical Solution of the Stable,Non-negative Definite Ļyapunov Equation,” IMA Journalof Numerical Analysis, vol. 2, no. 3, pp. 303–323,1982.[7] SLICOT (Control and Systems Library).[8] Peter Benner, Enrique S. Quintana-Ortí, and GregorioQuintana-Ortí, “Balanced Truncation Mo<strong>de</strong>l Reductionof <strong>La</strong>rge-Scale Dense Systems on Parallel Computers,”Mathematical and Computer Mo<strong>de</strong>lling of DynamicalSystems, vol. 6, pp. 383–405, 2000.[9] J.D. Roberts, “Linear mo<strong>de</strong>l reduction and solution ofthe algebraic Riccati equation by use of the sign function,”Internationa Journal of Control, vol. 32, pp.677–687, 1980, (Reprint of Technical Report No. TR-13, CUED/B-Control, Cambridge University, EngineeringDepartment, 1971).[10] Peter Benner, Enrique S. Quintana-Ortí, and GregorioQuintana-Ortí, “Solving linear-quadratic optimal controlproblems on parallel computers,” Optimization MethodsSoftware, vol. 23, pp. 879–909, December 2008.[11] G.H. Golub and C.F. Van Loan, Matrix Computations,Johns Hopkins University Press, Baltimore, third edition,1996.[12] Paolo Bientinesi, Brian Gunter, and Robert A. van <strong>de</strong>Geijn, “Families of algorithms related to the inversionof a symmetric positive <strong>de</strong>finite matrix,” ACM Trans.Math. Softw., vol. 35, pp. 3:1–3:22, July 2008.[13] Paolo Bientinesi, John A. Gunnels, Margaret E. Myers,Enrique S. Quintana-Ortí, and Robert A. van <strong>de</strong> Geijn,“The science of <strong>de</strong>riving <strong>de</strong>nse linear algebra algorithms,”ACM Trans. Math. Softw., vol. 31, pp. 1–26, March 2005.[14] John A. Gunnels, Fred G. Gustavson, Greg M. Henry,and Robert A. van <strong>de</strong> Geijn, “Flame: Formal linearalgebra methods environment,” ACM Transactions onMathematical Software, vol. 27, no. 4, pp. 422–455, Dec.2001.[15] Intel Corporation., http://www.intel.com/.[16] Vasily Volkov and James Demmel, “LU¸ , QR ¸ andÇholesky factorizations using vector capabilities ofGPU ¸ s,” Technical Report No. UCB/EECS, vol. 49, May2008.[17] Sergio Barrachina, Maribel Castillo, Francisco D. Igual,Rafael Mayo, Enrique S. Quintana-Ortí, and GregorioQuintana-Ortí, “Exploiting the capabilities of mo<strong>de</strong>rngpus for <strong>de</strong>nse matrix computations,” Concurr. Comput.: Pract. Exper., vol. 21, pp. 2457–2477, December 2009.[18] Enrique S. Quintana, Gregorio Quintana, Xiaobai Sun,and Robert van <strong>de</strong> Geijn, “A note on parallel matrixinversion,” SIAM Jorunal on Scientific Computing, vol.22, no. 5, pp. 1762–1771, 2001.[19] P. Benner, P. Ezzatti, E. S. Quintana, and A. Remón,“Using hybrid CPU-GPU ¸ platforms to accelerate thecomputation of the matrix sign function,” in LectureNotes in Computer Science, 7th Int. Workshop on Algorithms,Mo<strong>de</strong>ls and Tools for Parallel Computing onHeterogeneous Networks – HeteroPar’09, 2009.[20] B.D. Tapley, B.E. Schutz, and G.H. Born, StatisticalOrbit Determination, Elsevier Aca<strong>de</strong>mic Press, 2004.[21] Nicholas J. Higham, Accuracy and Stability of NumericalAlgorithms, Society for Industrial and Applied Mathematics,Phila<strong>de</strong>lphia, PA, USA, second edition, 2002.[22] Nvidia Corporation, http://www.nvidia.com/cuda/.[23] E. An<strong>de</strong>rson, Z. Bai, C. Bischof, L. S. Blackford,J. Demmel, Jack J. Dongarra, J. DuCroz, S. Hammarling,A. Greenbaum, A. McKenney, and D. Sorensen,LAPACK Users’ gui<strong>de</strong> (third ed.), Society for Industrialand Applied Mathematics, Phila<strong>de</strong>lphia, PA, USA,1999.[24] A.C. Antoulas, Approximation of <strong>La</strong>rge-Scale DynamicalSystems., SIAM Publications, 2005.[25] V. Mehrmann P. Benner, Dimension Reduction of <strong>La</strong>rge-Scale Systems, Springer-Verlag Berlin Hei<strong>de</strong>lberg, 2005.<strong>JP2011</strong>-32


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Genetic Algorithm to Predict WaveletCoefficients SignRicardo García and Otoniel López and Pablo Piñol and Miguel Martínez and Manuel P.Malumbres 1 and Antonio Martí 2AbstractMost wavelet based enco<strong>de</strong>rs, do not compressthe wavelet coefficients sign because it has been assumedto be inefficient for a long time. However,in the last years several image enco<strong>de</strong>rs like JPEG2000 inclu<strong>de</strong> sign coding capabilities. In this paper,we present a new sign coding approximationwhich uses a genetic algorithm to efficiently predictthe sign of wavelet coefficients. Preliminary resultsshow that, by including sign coding capabilities to anon-embed<strong>de</strong>d enco<strong>de</strong>r, the compression gain is upto 17.35%, being the Rate-Distortion (R/D) performanceimprovement up to 0.25 dB.Keywordssign coding, wavelets, image coding, genetic algorithms.I. IntroductionWAVELET transforms have proved to bevery powerful tools for image compression.Many state-of-the-art image co<strong>de</strong>cs, including theJPEG2000 standard [1], employ a wavelet transformin their algorithms. One advantage is the provisionof both frequency and spatial localization of imageenergy. The image energy is compacted into a smallfraction of the transform coefficients and compressioncan be achieved by coding these coefficients.The energy of a wavelet transform coefficient is restrictedto non-negative real numbers, but the coefficientsthemselves are not, and they are <strong>de</strong>fined byboth a magnitu<strong>de</strong> and a sign. Shapiro stated in [2]that a transform coefficient is equally likely to bepositive or negative and thus one bit should be usedto enco<strong>de</strong> the sign. In recent years, several authorshave begun to use context mo<strong>de</strong>ling for sign coding[3][4][5].For example, in [5], A. Deever and S. Hemami examinessign coding in <strong>de</strong>tail in the context of an embed<strong>de</strong>dwavelet image co<strong>de</strong>r. The paper shows that aPeak Signal to Noise Ratio (PSNR) improvement upto 0.7 dB is possible when sign entropy coding anda new extrapolation technique based on the mutualinformation that biorthogonal basis vectors provi<strong>de</strong>to improve the estimation of insignificant coefficientsare combined. However, the contribution of sign codingby itself to the PSNR improvement is only up to0.4 dB.In [4] the Embed<strong>de</strong>d Block Coding with OptimizedTruncation of the embed<strong>de</strong>d bit-streams (EBCOT),1 <strong>Universidad</strong> Miguel Hernán<strong>de</strong>z, e-mail: r.garcia,otoniel, pablop, mmrach, mels@umh.es2 <strong>Universidad</strong> Politécnica <strong>de</strong> Valencia, e-mail:amarti@disca.upv.escore coding tool of the JPEG 2000 standard, enco<strong>de</strong>sthe sign of wavelet coefficients using contextinformation from the sign of horizontal and verticalneighbor coefficients (North, South, East, West directions).Five context are used to mo<strong>de</strong>l the signcoding stage.In [3], X. Wu presents a high or<strong>de</strong>r context mo<strong>de</strong>lingenco<strong>de</strong>r. In this co<strong>de</strong>r, the sign and the texturesshare the same context mo<strong>de</strong>ling. This mo<strong>de</strong>lis based on a different neighborhood for the HL, LHand HH wavelet subbands. For the HL subband,the information of North, North-West, North-East,North-North and South sign is used to predict thecurrent coefficient sign. The neighbors sign informationused for the LH subband are North, North-West, North-East, West-West and East. Finally, forthe HH subband, an inter-band prediction is used besi<strong>de</strong>sthe intra-band prediction used by the HL andLH subbands.Genetic algorithms were first introduced by Hollandin [6] and they are nowadays well known techniquesfor finding nearly optimal solutions of verylarge problems and also, they have been used in imageprocessing [7][8].In a genetic algorithm, the evolution usually startsfrom a population of randomly generated individualsand happens in generations. In each generation,the fitness of every individual in the populationis evaluated by means of a cost function that <strong>de</strong>terminesthe optimal <strong>de</strong>gree we are looking for (i.ecompression rate). Multiple individuals are stochasticallyselected from the current population (basedon their fitness), and modified (recombined and possiblyrandomly mutated) to form a new population.The new population is then used in the next iterationof the algorithm. Commonly, the algorithmterminates when either a maximum number of generationshas been produced, or a satisfactory fitnesslevel has been reached for the population.In this paper, we will <strong>de</strong>sign a genetic algorithmto efficiently predict the wavelet coefficient signs. Ifthe sign prediction is really good, a binary entropyenco<strong>de</strong>r will be able to get significant compressionrates. So, our goal is to <strong>de</strong>fine a genetic algorithmthat finds out the paremeters of our sign predictorthat achieve the best prediction performance. Asstudied in the literature, the parameters to be foundby our genetic algorithm will be a) the neighbor setthat <strong>de</strong>fines the prediction context, and b) the signvalues (sign patterns) of wavelet coefficient neighborset with the correspon<strong>de</strong>nt sign prediction for currentwavelet coefficient.<strong>JP2011</strong>-33


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011After running the genetic algorithm and configuredthe sign predictor, we will evaluate the impactof the sign coding module in the overall performanceof an image wavelet enco<strong>de</strong>r. In particular, we willuse the LTW wavelet enco<strong>de</strong>r [9] to <strong>de</strong>termine thebit-rate savings for several test images.The remain<strong>de</strong>r of the paper is organized as follows:Section II <strong>de</strong>scribes our sign coding approximationand also the genetic algorithm structure. In SectionIII, we show the results of the global enco<strong>de</strong>r system(with sign coding stage) and compare it withSPIHT and JPEG 2000. Finally, in Section IV someconclusions are drawn.II. Wavelet sign predictionMost wavelet image co<strong>de</strong>cs do not consi<strong>de</strong>r the useof sign coding tools since the wavelet coefficients locatedat the high frequency subbands form a zeromeanprocess, and therefore equally likely positiveas negative.Schwartz, Zandi and Boliek were the first authorsto consi<strong>de</strong>r sign coding, using one neighboring pixelin their context mo<strong>de</strong>ling algorithm [10]. The maini<strong>de</strong>a behind this approach is to find correlations alongand across edges.The HL subbands of a multi-scale 2-D wavelet <strong>de</strong>compositionare formed from low-pass vertical filteringand high-pass horizontal filtering. The high-passfiltering <strong>de</strong>tects vertical edges, thus the HL subbandscontain mainly vertical edge information. Oppositely<strong>de</strong>fined are the LH subbands that contain primarilyhorizontal edge information.As Deever explained in [5], given a vertical edge inan HL subband, it is reasonable to expect that neighboringcoefficients along the edge have the same signas the coefficient being co<strong>de</strong>d. This is because verticalcorrelation often remains very high along verticaledges in images. When a low-pass filter is appliedalong the image columns, it results in a series of similarrows, as elements in a row tend to be very similarto elements directly above or below due to the highvertical correlation. Subsequent high-pass filteringalong similar rows is expected to yield vertically correlatedtransform coefficients.It is also important to consi<strong>de</strong>r correlation acrossedges, being the nature of the correlation directly affectedby the structure of the high pass filter. ForDaubechies’ 9/7 filters, wavelet coefficient signs arestrongly negatively correlated across edges becausethis filter is very similar to a second <strong>de</strong>rivative of aGaussian, so, it is expected that wavelet coefficientswill change sign as the edge is crossed. Althoughthe discrete wavelet transform involves sub sampling,the sub sampled coefficients remain strongly negativelycorrelated across edges. In this manner, whena wavelet coefficient is optimally predicted as a functionof its across-edge neighbors (e.g. left and rightneighbors in HL subbands), the optimal predictioncoefficients are negative, indicating an expected signchange. This conclusion is general for any waveletwith a shape similar to a second <strong>de</strong>rivative of a Gaussian.To estimate sign correlation in a practical way, wehave applied a 6-level Dyadic Wavelet Transform <strong>de</strong>compositionof the source image and then a low quantizationlevel to the resulting wavelet coefficients. Asa first approach and taking into account that thesign neighborhood correlation <strong>de</strong>pends on the subbandtype (HL,LH,HH) as Deever assesses in [5], wehave used three different neighbors <strong>de</strong>pending on thesubband type. So, for HL subband, the neighborsused are N, NN and W. Taking into account symmetry,for the LH subband, those neighbors are W,WW, and N. For the HH subband they are N, W,and NW, exploiting the correlation along and acrossthe diagonal edges. This lead us to a maximum of3 3 Neighbor Sign Patterns (NSP) for each subbandtype.TABLE IProbability distribution of neighbor sign patterns(NSPs) of HL 6 subband (8x8 coefficients) in LenaimageC N NN W Occurrences %Probability+ + + + 13 20.31+ + + - 8 12.50- - - + 8 12.50- + + + 6 9.38- - + + 6 9.38Others 23 35.93In Table I we show the NSP probability distributionfor HL 6 subband (from the sixth <strong>de</strong>compositionlevel) of Lena test image. As shown, the probabilitythat the current coefficient (C) is positive when its N,NN and W neighbors are also positive is around 20%.Besi<strong>de</strong>s, if the N and NN neighbors have the samesign and the W neighbor has the opposite sign, thecurrent coefficient (C) has the opposite sign of its Wneighbor with a probability of 25% as shown in rowstwo and three in Table I. The visible sign neighborhoodcorrelation suggest that the sign bits of waveletcoefficients are compressible. Using the previouslymentioned neighborhood for each subband type, wehave <strong>de</strong>veloped a genetic algorithm (GA) in or<strong>de</strong>r tofind an accurate sign estimation.A. Genetic algorithm for wavelet sign predictionThe goal of the <strong>de</strong>sired genetic algorithm wouldbe to find a table where for each Sign NeigborhoodPattern (V k ) we have a sign prediction (S i,j ) for coefficientC i,j . There is no an univocal relationshipbetween a neighbor sign combination, i.e not alwaysfor a same V k pattern, S i,j is always positive or negative.However, it is possible that for a V k pattern,S i,j is more probably to be positive or negative. But,the problem is still more complex, because a sign predictionfor a neighbor sign pattern could fit well foran image and not for others. Therefore, the i<strong>de</strong>a isto find suboptimal neighbor sign pattern predictionsthat better fit for a representative set of images.<strong>JP2011</strong>-34


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011The use of genetic algorithms to compress the signof wavelet coefficients is twofold. First, when thenumber of neighbors used to analyze the sign correlationgrows or when there is a great number ofimages to be used in the analysis, the search space isexcessively wi<strong>de</strong>. Second, it is not intuitive to find away of combining the predictions obtained for severalimages.In Figure 1 we show the genetic algorithm pseudoco<strong>de</strong>for sign prediction. First of all we <strong>de</strong>fine eachindividual, containing a sign prediction for each 3 3NSP, then each NSP sign prediction of each individualof the universe is randomly initialized as apositive or negative sign.During evolution, sequences mate and mutate togenerate new sequences in the population and bestsequences are selected for survival on the basis oftheir fitness function. The mating of sequences isperformed through crossover operator, where parentsare randomly selected and its gens (NSPs) are mixed.The best two individuals, the ones that exhibit bestprediction performance, are selected for survival. Individualscan also un<strong>de</strong>rgo mutation, where a sequenceprediction is randomly modified.Finally, after performing the maximum iterations,the algorithm finishes, obtaining an optimal/suboptimalsign prediction for each NSP. Wehave performed the fitness evaluation over Lena andBarbara test images, because these images are representativefor both low and high textured imagesrespectively.Individual Structure{//Prediction array for each neighbor sign pattern combinationsign[NSP];//indicates the goodness of the individualfitness;}Individual universe[NUM-POPULATION];function SignPrediction (SubbandType, ImageFiles,mutation Probability)//Initialization phase:sign[NSPs]= random(POSITIVE/NEGATIVE)Initialize(universe, NUM-POPULATION, NSP);//we evaluate each individual of the universe.For each image in ImageFilesEvaluateFitness(SubbandType, ImageFiles, universe);for i=0 to NUM-ITERATIONS//Select the best two individuals from universe for survival.best = SelectBestIndividuals(2);//CrossovercrossPoint=random(NSP);//randomly selects a father and a mother to mix gensSelectFatherAndMother(random(NUM-POLUTATION));universe = MergeFatherAndMother(crossPoint);Mutation(universe, mutation Probability);universe = universe + best;EvaluateFitness(SubbandType, ImageFiles, universe);end//Finally get the best individual.best = SelectBestIndividuals(1);end of functionFig. 1.Genetic algorithm for sign predictionSeveral parameters should be taken into accountwhen training a genetic algorithm: The populationsize, the individuals initialization, the number of iterationsperformed, the mutation probability, thecrossover point, the crossover method, the selectioncriteria of the best sequences to be selected for survival,etc. We have performed lots of tests varyingthese parameters to tune the genetic algorithm.The parameters used to obtain the sign predictionare: population size (100), individuals initialization(ramdomly), number of iterations (1000), mutationprobability (0.001), crossover point (ramdomly) andcrossover method (best two fitness individuals overfour randomly selected parents).After running the genetic algorithm for each subbandtype, we obtain an individual containing theprediction of the current coefficient sign ( SC ˆ i,j [k]),for each NSP (k) of each subband type. So, what weare going to enco<strong>de</strong> is the correctness of this prediction,i.e., a binary valued symbol from SC ˆ i,j [k]·SC i,j(see Table II). In or<strong>de</strong>r to compress this binary valuedsymbol, we use two contexts in the arithmeticenco<strong>de</strong>r for each subband type, distributing all signcoding predictions from NSPs between them so asto minimize the zero or<strong>de</strong>r entropy of both contexts.The selection criterion is to isolate in one contextthose NSPs with the highest correctness predictionprobability and highest number of occurrences <strong>de</strong>rivedfrom the probability distribution found in theprevious analysis. The rest of them are grouped intothe other context. However, there are certain NSPswith low correctness probability but with a greatamount of occurrences, so we have to heuristically<strong>de</strong>termine the convenience of including them in thefirst context or not.TABLE IISign prediction for HL subband in Lena image forsome NSPsNSP(k) N NN W Prediction( SC ˆ i,j [k])0 * * * -. . .13 + + + +14 + + - +. . .26 - - - +III. Performance EvaluationIn this section we analyze the behavior of the signcoding when implemented on LTW image enco<strong>de</strong>r[9]. This new enco<strong>de</strong>r implementation is called S-LTW. We will also compare the S-LTW enco<strong>de</strong>r versusJPEG2000 (Jasper 1.701.0) and SPIHT (Spiht8.01) in terms of R/D and coding <strong>de</strong>lay. All enco<strong>de</strong>rshave been tested on an Intel PentiumM Dual Core3.0 GHz with 2 Gbyte RAM memory.The test images used in the evaluation are: Barbara(512x512), Bike (2560x2048), Boat (512x512),Cafe (2560x2048), GoldHill (512x512), Lena(512x512), Mandrill (512x512), Woman (2560x2048)and Zelda (512x512).In Table III we show the relative compression gainwith respect to the original LTW due only to the signcoding capability for Barbara and Bike test images.As we can see, the maximum sign compression gain<strong>JP2011</strong>-35


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLE IIISign compression performance at different bit-rates.Bit-rate S-LTW SPIHT %Gain(bpp) #Significant #Bits #Significant #BitsCoefficients Saved Coefficients SavedBarbara (512x512)1 45740 7936 54657 9482 17.350.5 22331 3648 27535 4499 16.340.25 10484 1520 13460 1951 14.500.125 4343 304 6016 421 7.00Bike (2048x2560)1 855266 115200 1371280 184711 13.470.5 412212 64424 798202 124758 15.630.25 198943 30472 366927 56213 15.320.125 91767 11992 162990 21302 13.07P PSNR (d dB)0.5 S-LTW vs SPIHT0.4LTW vs SPIHTS-LTW vs JPEG20000.3LTW vs JPEG20000.20.100-0.10.5 1 1.5 2-0.2-0.3-0.4-0.5Fig. 2.Bit-rate (bpp)PSNR-Gain for Bike imageis 17.35%. Furthermore, we show an estimation ofthe bit savings for SPIHT enco<strong>de</strong>r.TABLE IVCoding <strong>de</strong>lay (seconds).Bit-rate JPEG SPIHT LTW S-LTW(bpp) 2000 Orig.CODING Barbara (512x512)1 0.080 0.042 0.037 0.0230.5 0.076 0.026 0.022 0.0140.25 0.074 0.018 0.013 0.0090.125 0.073 0.014 0.010 0.006CODING Bike (2048x2560)1 2.623 0.920 0.647 0.4300.5 2.543 0.521 0.381 0.2590.25 2.507 0.323 0.224 0.1620.125 2.518 0.221 0.158 0.117In Figure 2 we show the R/D improvement whencomparing original LTW versus JPEG2000/SPIHTand S-LTW versus JPEG2000/SPIHT. As shown,there is an increase in the PSNR difference betweenSPIHT and the new S-LTW enco<strong>de</strong>r, and regardingJPEG2000, we can see than now S-LTW has a minorloss in PSNR than original LTW.Regarding coding <strong>de</strong>lay, the use of a higher contextmo<strong>de</strong>ling in the arithmetic enco<strong>de</strong>r implies a highercomputational cost. In or<strong>de</strong>r to compensate the codingspeed loss, we have changed the arithmetic enco<strong>de</strong>rstage by a fast arithmetic enco<strong>de</strong>r [11]. Asit can be seen in Table IV, S-LTW enco<strong>de</strong>r is 49%faster on average in the coding process than SPIHTenco<strong>de</strong>r and 86% faster on average than JPEG2000.Furthermore, S-LTW enco<strong>de</strong>r is even faster than theoriginal LTW version which does not inclu<strong>de</strong> the signcoding stage (1.5 times faster on average in the codingprocess).IV. ConclusionsWe have presented a genetic algorithm that is ableto find a good sign predictor of wavelet coefficientsign. So, by encoding the sign prediction result (successor failure) with an arithmetic enco<strong>de</strong>r, the signinformation will be highly compacted in the final bitstream.In or<strong>de</strong>r to prove our proposal we have implementedthe sign predictor over the non-embed<strong>de</strong>dLTW enco<strong>de</strong>r. The new S-LTW proposed enco<strong>de</strong>rhas slightly better R/D performance (up to 0.25 dB),or in terms of bitstream, it is able to reduce the bitstreamsize up to 17% for the same quality level.Regarding coding <strong>de</strong>lay, the new image enco<strong>de</strong>r ison average 2 times as fast as SPIHT in the codingprocess and 1.5 times as fast as original LTW due tothe inclusion of a fast arithmetic enco<strong>de</strong>r.AcknowledgementsThanks to Spanish Ministry of education and Scienceun<strong>de</strong>r grant DPI2007-66796-C03-03 for funding.References[1] ISO/IEC 15444-1, “JPEG2000 image coding system,”2000.[2] J.M. Shapiro, “A fast technique for i<strong>de</strong>ntifying zerotreesin the EZW algorithm,” Proc. IEEE Int. Conf. Acoust.,Speech, Signal Processing, vol. 3, pp. 1455–1458, 1996.[3] X. Wu, “High-or<strong>de</strong>r context mo<strong>de</strong>ling and embed<strong>de</strong>dconditional entropy coding of wavelet coefficients for imagecompression,” in Proc. of 31st Asilomar Conf. onSignals, Systems, and Computers, 1997, pp. 1378–1382.[4] D. Taubman, “High performance scalable image compressionwith EBCOT,” IEEE Transactions on ImageProcessing, vol. 9, no. 7, pp. 1158–1170, July 2000.<strong>JP2011</strong>-36


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011[5] Aaron Deever and Sheila S. Hemami, “What’s your sign?:Efficient sign coding for embed<strong>de</strong>d wavelet image coding,”in Proc. IEEE Data Compression Conf., Snowbird,UT, 2000, pp. 273–282.[6] J.H. Holland, Adaption in Natural and Artificial Systems,University of Michigan Press, 1975.[7] S. Chabrier, C. Rosenberger, B. Emile, , and H. <strong>La</strong>urent,“Optimization-based image segmentation by genetic algorithms,”EURASIP Journal on Image and Vi<strong>de</strong>o Processing,vol. 2008, pp. 1–10, 2008.[8] Sarawat Anam, Md. Shohidul Islam, M.A. Kashem, M.N.Islam, M.R. Islam, and M.S. Islam, “Face recognition usinggenetic algorithm and back propagation neural network,”in International MultiConference of Engineersand Computer Scientists, Hong Kong, 2009.[9] J. Oliver and M. P. Malumbres, “Low-complexitymultiresolution image compression using wavelet lowertrees,” IEEE Transactions on Circuits and Systems forVi<strong>de</strong>o Technology, vol. 16, no. 11, pp. 1437–1444, 2006.[10] Edward L. Schwartz, Ahmad Z, and Martin Boliek,“CREW: Compression with reversible embed<strong>de</strong>dwavelets,” in In Proc SPIE, 1995, pp. 212–221.[11] Amir Said, “Comparative analysis of arithmetic codingcomputational complexity,” Tech. Rep., Hewlett-Packard<strong>La</strong>boratories HPL-2004-75, 2004.<strong>JP2011</strong>-37


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-38


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Resolución <strong>de</strong>l Empaquetado 2DMultiobjetivizado con un AlgoritmoMemético ParaleloCoromoto León, Carlos Segura y Eduardo Segredo 1Resumen— El problema <strong>de</strong> corte y empaquetadoes un problema <strong>de</strong> optimización NP-completo conmúltiples aplicaciones prácticas. En la sesión <strong>de</strong> competiciones<strong>de</strong> gecco 2008 se propuso una variante <strong>de</strong>este problema. En la misma, los mejores resultadosfueron obtenidos a través <strong>de</strong> la aplicación <strong>de</strong> un algoritmomemético mono-objetivo. Posteriores estudioshan revelado que el método propuesto sufre <strong>de</strong>estancamiento en mínimos locales en diversas instancias.<strong>La</strong> técnica <strong>de</strong>nominada multiobjetivización escapaz <strong>de</strong> transformar un problema mono-objetivo enuno multi-objetivo. Pue<strong>de</strong> ser útil para evitar problemas<strong>de</strong> estancamiento. En este trabajo, el problemaes multiobjetivizado y abordado mediante unalgoritmo memético multi-objetivo. Se han analizadovarias alternativas para multiobjetivizar el problema.A<strong>de</strong>más, se propone una paralelización <strong>de</strong> dicho algoritmo.Los resultados computacionales han <strong>de</strong>mostradola vali<strong>de</strong>z <strong>de</strong> las propuestas secuenciales yparalelas. Se ha conseguido aumentar la calidad <strong>de</strong> lassoluciones obtenidas, a la vez que se ha disminuido eltiempo necesario para obtenerlas.Palabras clave— Multiobjetivización, Mo<strong>de</strong>los Paralelelosbasados en Islas, Algoritmos Meméticos,Corte y Empaquetado.I. IntroducciónEL problema <strong>de</strong> empaquetado es un problema <strong>de</strong>optimización combinatoria NP-completo, en elque se preten<strong>de</strong> empaquetar un conjunto <strong>de</strong> elementosen un objeto geométrico mayor, optimizando unafunción objetivo. Este problema tiene gran relacióncon el problema <strong>de</strong> corte, cuyo objetivo es dividiruna <strong>de</strong>terminada pieza en otro conjunto <strong>de</strong> piezasmás pequeñas. Dada la estrecha relación entre ambosproblemas, en múltiples trabajos se han analizado <strong>de</strong>forma conjunta, siendo referenciado en dichos casoscomo el problema <strong>de</strong> corte y empaquetado (Cuttingand Packing - c&p). Los problemas <strong>de</strong> corte y empaquetadotienen numerosas aplicaciones prácticas,como la carga <strong>de</strong> contenedores o la optimización <strong>de</strong>la distribución <strong>de</strong> piezas en circuitos eléctricos. Durantela sesión <strong>de</strong> competiciones <strong>de</strong>l gecco 2008 1se propuso una nueva variante <strong>de</strong> empaquetado 2D(Two-Dimensional Bin Packing Problem - 2dpp) conel objetivo <strong>de</strong> analizar las fortalezas <strong>de</strong> distintos algoritmosal abordar dicho problema.Los problemas <strong>de</strong> c&p han sido ampliamente analizadosen la literatura. Entre las técnicas propuestaspo<strong>de</strong>mos i<strong>de</strong>ntificar algunas estrategias exactas. Elprincipal inconveniente <strong>de</strong> dichas técnicas es al alto1 Dpto. <strong>de</strong> Estadística, I.O y Computación, <strong>Universidad</strong><strong>de</strong> <strong>La</strong> <strong>La</strong>guna, Edificio <strong>de</strong> Física y Matemáticas, Avda. AstrofísicoFco. Sánchez s/n, 38271 <strong>La</strong> <strong>La</strong>guna, Tenerife, e-mail:(cleon|csegura|esegredo)@ull.es.1 http://www.sigevo.org/gecco-2008/competitions.htmlcoste computacional asociado a las mismas. Conel objetivo <strong>de</strong> reducir el tiempo requerido para suresolución, se han propuesto diversas paralelizaciones<strong>de</strong> estos algoritmos. Sin embargo, incluso utilizandotécnicas paralelas, la gran mayoría <strong>de</strong> instancias<strong>de</strong>l problema con interés práctico, no pue<strong>de</strong>n serabordadas utilizando dichas técnicas. <strong>La</strong>s técnicasaproximadas solventan parcialmente este problema.Entre estas técnicas cabe mencionar la amplia utilización<strong>de</strong> meta-heurísticas. Concretamente, los AlgoritmosMeméticos (Memetic Algorithms - mas) [1]son una <strong>de</strong> las técnicas que han obtenido resultadosmás prometedores. Los mas son una sinergia entrelos Algoritmos Evolutivos (Evolutionary Algorithms- eas) y las técnicas <strong>de</strong> aprendizaje individual.Existen numerosos estudios que han analizado laposibilidad <strong>de</strong> paralelizar los eas [2] (peas). El mo<strong>de</strong>lobasado en islas [3] es una <strong>de</strong> las paralelizacionesmás populares. Este esquema divi<strong>de</strong> la poblaciónen un conjunto <strong>de</strong> subpoblaciones in<strong>de</strong>pendientes.Cada subpoblación constituye una isla, y sobre lamisma se aplica un ea. A<strong>de</strong>más, se integra una fase<strong>de</strong> migración que posibilita el intercambio <strong>de</strong> individuosentre las islas. De esta forma, durante lamayor parte <strong>de</strong> las ejecuciones <strong>de</strong> un pea cada subpoblaciónes evolucionada <strong>de</strong> forma in<strong>de</strong>pendiente,y sólo ocasionalmente, se producen comunicaciones.El mo<strong>de</strong>lo basado en islas se ha aplicado también ala paralelización <strong>de</strong> mas (pmas).<strong>La</strong> variante <strong>de</strong>l problema <strong>de</strong> empaquetado propuestaen gecco 2008 fue abordada con múltiplestécnicas. Los mejores resultados para la instanciapropuesta fueron obtenidos mediante un ma monoobjetivo.En [4] se propuso un mo<strong>de</strong>lo basado enislas que hace uso <strong>de</strong> dicho ma. A pesar <strong>de</strong> que seobtuvieron resultados <strong>de</strong> alta calidad para la instanciapropuesta en la competición, posteriores estudiosrevelaron que dicho mo<strong>de</strong>lo sufre <strong>de</strong> estancamientoen mínimos locales para otras instancias. Con el objetivo<strong>de</strong> abordar los problemas <strong>de</strong> estancamiento,se han diseñado una gran cantidad <strong>de</strong> técnicas [5].Entre ellas cabe <strong>de</strong>stacar la multiobjetivización [6].<strong>La</strong> técnica <strong>de</strong>nominada multiobjetivización transformaun problema mono-objetivo en uno multiobjetivo.Su principio <strong>de</strong> funcionamiento es que medianteesta conversión, se pue<strong>de</strong>n cambiar las características<strong>de</strong>l problema, con lo que pue<strong>de</strong> ser útilpara evitar problemas <strong>de</strong> estancamiento [6]. Sin embargo,también es posible que la nueva versión <strong>de</strong>lproblema sea más compleja [7]. <strong>La</strong>s técnicas <strong>de</strong> multiobjevizaciónpue<strong>de</strong>n ser clasificadas en dos tipos:<strong>JP2011</strong>-39


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011técnicas <strong>de</strong> <strong>de</strong>scomposición y técnicas <strong>de</strong> agregación.<strong>La</strong>s técnicas <strong>de</strong> <strong>de</strong>scomposición están basadas en dividirla función objetivo original en varias funcionesin<strong>de</strong>pendientes. <strong>La</strong>s técnicas <strong>de</strong> agregación consi<strong>de</strong>ran,junto a la función objetivo original, otras funcionesagregadas <strong>de</strong> forma artificial.En este trabajo se analizan las ventajas y <strong>de</strong>sventajas<strong>de</strong> multiobjetivizar el 2dpp. Para ello se hanpropuesto un conjunto <strong>de</strong> multiobjetivizaciones y seles ha aplicado un ma multi-objetivo. Los resultadosobtenidos han sido comparados con los obtenidos porla mejor técnica secuencial propuesta en [4]. Dadoque la técnica más a<strong>de</strong>cuada ha <strong>de</strong>pendido <strong>de</strong> lainstancia consi<strong>de</strong>rada, no se ha podido <strong>de</strong>mostrarla superioridad <strong>de</strong> las técnicas mono-objetivo, ni <strong>de</strong>las técnicas multi-objetivo. Por ello, la aplicación<strong>de</strong> esquemas <strong>de</strong> resolución <strong>de</strong> más alto nivel comolas hiperheurísticas, para automatizar la selección<strong>de</strong> qué técnica usar, parece muy prometedor. Estastécnicas han sido ampliamente utilizadas en conjuncióncon los mo<strong>de</strong>los paralelos basados en islas[8]. Por ello, en este trabajo también se analizanla vali<strong>de</strong>z <strong>de</strong>l mo<strong>de</strong>lo basado en islas con las multiobjetivizacionespropuestas. Los resultados computacioneshan <strong>de</strong>mostrado la vali<strong>de</strong>z <strong>de</strong> la multiobjetivizacióny <strong>de</strong> la paralelización propuesta.El resto <strong>de</strong>l trabajo se estructura <strong>de</strong> la siguientemanera: la formación matemática <strong>de</strong>l 2dpp se <strong>de</strong>tallaen la Sección II. En la Sección III se <strong>de</strong>scribeel esquema <strong>de</strong> optimización aplicado. El mo<strong>de</strong>lobasado en islas es <strong>de</strong>scrito en la Sección IV. En lasección V se <strong>de</strong>tallan los diferentes experimentos realizadosy se presentan los resultados computacionalesobtenidos. Por último, en la sección VI se presentanlas conclusiones y las líneas <strong>de</strong> trabajo futuro.II. Formulación Matemática <strong>de</strong>l 2DPPEl problema propuesto durante la competición esuna variante <strong>de</strong>l problema <strong>de</strong> empaquetado bidimensional.Una instancia <strong>de</strong>l problema viene dada porlos siguientes datos:• <strong>La</strong>s dimensiones X, Y <strong>de</strong> una rejilla rectangular.• El número máximo que pue<strong>de</strong> ser asignado en lasceldas <strong>de</strong> la rejilla: N. En cada celda se <strong>de</strong>beasignar un número entero en el rango [0, N].• <strong>La</strong> puntuación asociada a la aparición <strong>de</strong> cadapareja (a, b), en don<strong>de</strong> a, b ∈ [0, N]: v(a, b). <strong>La</strong>puntuación asociada a la aparición <strong>de</strong> (a, b) noes necesariamente igual a la aparición <strong>de</strong> (b, a).Una solución candidata se constituye asignando acada celda <strong>de</strong> la rejilla un valor en el rango válido.Por ello, el espacio <strong>de</strong> búsqueda está formado por(N + 1) X·Y soluciones candidatas. El objetivo consisteen encontrar la asignación <strong>de</strong> números que maximicela suma <strong>de</strong> las puntuaciones <strong>de</strong> las parejasque aparecen en la rejilla. Se consi<strong>de</strong>ra que unapareja (a, b) aparece en la rejilla, si los números ay b son asignados en casillas vecinas. Dos casillasson vecinas si una está junta a la otra en cualquierfila, columna, o diagonal <strong>de</strong> la rejilla. Para el cálculoAlgorithm 1 Pseudocódigo <strong>de</strong> un ma1: Generar población inicial2: Evaluar individual <strong>de</strong> la población3: while (critero <strong>de</strong> parada no se cumpla) do4: Selección <strong>de</strong> padres5: Aplicar operador <strong>de</strong> crossover con probablidad p c6: Aplicar operador <strong>de</strong> mutación con probabilidad p m7: Aplicar el proceso <strong>de</strong> aprendizeje individual con probabilidadp l8: Evaluar los nuevos individuos9: Selección <strong>de</strong> supervivencia10: end while<strong>de</strong> la función objetivo, el valor asociado a la aparición<strong>de</strong> cada pareja sólo pue<strong>de</strong> ser contabilizado una vez.De esta forma, el objetivo <strong>de</strong>l problema es encontraruna rejilla G que maximice la función <strong>de</strong> fitness f.don<strong>de</strong>f =N∑a=0 b=0N∑v 2 (a, b){0 si (a, b) no son adyacentesv 2 (a, b) =v(a, b) si (a, b) son adyacentesIII. Esquema <strong>de</strong> OptimizaciónA. Algoritmos MeméticosLos algoritmos meméticos [9], [1] (mas) son unasinergia entre las estrategias poblacionales, y unmétodo <strong>de</strong> aprendizaje individual. Los mas hanmostrado un rendimiento muy superior a los algoritmosgenéticos tradicionales en varios dominios [10].Existen diferentes versiones <strong>de</strong> los mas, habiendosido aplicados tanto en entornos mono-objetivo [11],como multi-objetivo [12]. El Algoritmo 1 muestra unpseudocódigo <strong>de</strong> una estrategia memética integradaen un ea. <strong>La</strong> principal diferencia respecto a los eases la aplicación <strong>de</strong> un proceso <strong>de</strong> aprendizaje individual(línea 7). Existen dos formas principales <strong>de</strong>integrar dicho proceso [13]. En el aprendizaje <strong>La</strong>marckianoel genotipo <strong>de</strong>l individuo refleja los cambiosrealizados durante el aprendizaje. Por el contrario,en el aprendizaje <strong>de</strong> Baldwinian el contenidogenético permanece intacto. Ambos tipos <strong>de</strong> aprendizajehan aportado beneficios en múltiples campos[14].El proceso <strong>de</strong> aprendizaje es generalmente computacionalmentecostoso. Por ello, no se suele aplicaren todas las generaciones, sino con una cierta probabilidadp l . En el 2dpp se hace indispensable la aplicación<strong>de</strong>l proceso <strong>de</strong> aprendizaje individual en todaslas generaciones para obtener soluciones <strong>de</strong> alta calidad.Por ello, en este trabajo se aplicó el proceso <strong>de</strong>aprendizaje individual en cada generación.En este trabajo se han comparado dos mas <strong>de</strong>primera generación [15]. El primero <strong>de</strong> ellos (Var-PopEA), es la estrategia mono-objetiva presentadaen [4]. Concretamente es un ma que combina un algoritmoevolutivo modificado con selección <strong>de</strong> tipo(1 + 1), y un aprendizaje individual específicamentediseñado para el 2dpp. El algoritmo comienza comportándosecomo un algoritmo basado en trayecto-<strong>JP2011</strong>-40


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011ria, es <strong>de</strong>cir, se genera una población inicial con unindividuo. Sin embargo, si se <strong>de</strong>tecta que el algoritmoestá sufriendo estancamiento en mínimos locales,se aña<strong>de</strong>n otros individuos a la población, comportándoseentonces como un algoritmo poblacional.El segundo ma analizado en este trabajo es unamodificación <strong>de</strong>l algoritmo evolutivo multi-objetivoNon-Dominated Sorting Evolutionary Algorithm-II(nsga-ii). El único cambio realizado sobre el nsga-iiconsistió en integrar en cada generación la ejecución<strong>de</strong>l procedimiento <strong>de</strong> aprendizaje individual. Esteprocedimiento es integrado tras la fase <strong>de</strong> variacióngenética. En ambas versiones <strong>de</strong> los mas los individuoshan sido codificados utilizando un vector bidimensional<strong>de</strong> número enteros, G, en don<strong>de</strong> G(x, y)representa el número asignado a la celda (x, y).B. Aprendizaje Individual para el 2DPPEn general, los mas multi-objetivo hacen uso<strong>de</strong> técnicas <strong>de</strong> aprendizaje individual multiobjetivo[16]. Sin embargo, dado que el 2dpp ha sidomultiobjetivizado, el interés final es optimizar sólo elobjetivo original. Por ello, se <strong>de</strong>cidió aplicar un proceso<strong>de</strong> aprendizaje mono-objetivo. El proceso <strong>de</strong>aprendizaje aplicado es <strong>de</strong> tipo <strong>La</strong>marckiano. Concretamente,se ha realizado utilizando una variante<strong>de</strong> búsqueda local por escalada. En la misma, el or<strong>de</strong>nen que los vecinos son explorados es aleatorio,y se acepta cualquier movimiento que mejore a lasolución actual. Finalmente, cuando no existan vecinosque mejoren la puntuación actual, se da porterminado el proceso <strong>de</strong> aprendizaje individual.El número <strong>de</strong> vecinos <strong>de</strong> las soluciones candidatasviene <strong>de</strong>terminado por el número <strong>de</strong> casillas vecinas<strong>de</strong> la rejilla. Específicamente, para cada par<strong>de</strong> celdas vecinas (i, j) y (k, l), se <strong>de</strong>termina cuál esla mejor asignación posible que se podría hacer adichas celdas, consi<strong>de</strong>rando que no se pue<strong>de</strong>n modificarlas asignaciones realizadas en el resto <strong>de</strong> casillas.Para obtener dicha asignación se diseñó un métodoque evita enumerar todas las posibles opciones. Enprimer lugar, se consi<strong>de</strong>ran todas las posibles asignacionesn ∈ [0, N] <strong>de</strong> valores a la casilla (i, j), calculándosela contribución <strong>de</strong> cada asignación v ij (n).Para el cálculo <strong>de</strong> este valor se asume que la casilla(k, l) no está asignada. Posteriormente, se realizael mismo proceso para la casilla (k, l), calculándosev kl (n). En este caso se consi<strong>de</strong>ra que la casilla (i, j)no está asignada. <strong>La</strong> contribución <strong>de</strong> fitness que seobtiene al asignar el valor a a la celda (i, j), y el valorb a la celda (k, l), viene dado por:v ij (a) + v kl (b) + v ′ (a, b) − v repdon<strong>de</strong> v ′ (a, b) es v(a, b) + v(b, a) si la pareja (a, b) noaparece en otra parte <strong>de</strong> la rejilla, o 0 en caso contrario,y v rep es el valor asociado a aquellas parejasque se produjeron tanto por la asignación <strong>de</strong> a en(i, j), como <strong>de</strong> b en (k, l). Un límite superior <strong>de</strong> lacontribución <strong>de</strong> fitness viene dado por:v ij (a) + v kl (b) + min(bestV (a), bestV (b))don<strong>de</strong> bestV (n) es el máximo valor asociado acualquier pareja (n, m), m ∈ [0, N], es <strong>de</strong>cir,max{(v(n, m) + v(m, n)}. Siendo bestF it la mayorpuntuación encontrada para una asignación <strong>de</strong> lasposiciones (i, j), y (k, l), los únicos valores a ′ , b ′que tienen que ser consi<strong>de</strong>rados, son aquellos enlos que se cumple la relación v ij (a ′ ) + v kl (b ′ ) +min(bestV (a ′ ), bestV (b ′ )) > bestF it. El coste computacionalasociado a la generación <strong>de</strong> individuosse redujo drásticamente <strong>de</strong>scartando aquellas asignacionesen las que la relación anterior no se cumplía.C. Operadores GenéticosEn cada generación <strong>de</strong>l algoritmo <strong>de</strong>scrito se aplicauna fase <strong>de</strong> variación. En [4] se analizó el comportamiento<strong>de</strong> varios operadores genéticos. En estetrabajo se han aplicado aquellos que obtuvieron losmejores resultados. El operador <strong>de</strong> cruce es el operadorbidimensional <strong>de</strong> cruce <strong>de</strong> subca<strong>de</strong>nas (ssx- Two-dimensional Sub-string Crossover) propuestoen [17]. Es una extensión <strong>de</strong>l cruce <strong>de</strong> un punto acromosomas bidimensionales. En primer lugar, se selecciona<strong>de</strong> forma aleatoria una celda <strong>de</strong> la rejilla queactuará como celda <strong>de</strong> división. A continuación, conigual probabilidad, se linealiza el cromosoma por filaso por columnas, y se aplica el operador <strong>de</strong> cruce <strong>de</strong>un punto, consi<strong>de</strong>rando la celda <strong>de</strong> división elegida.El operador <strong>de</strong> mutación utilizado consiste en unamutación uniforme, que incluye información <strong>de</strong> dominio(umd - Uniform Mutation with Domain Information).En umd inicialmente se genera un númeroaleatorio entre min p m y max p m . A continuación,cada gen es mutado con una probabilidad igual alnúmero generado. El nuevo valor asignado a cadagen es elegido <strong>de</strong> forma aleatoria entre aquellos valorescuyo fitness asociado - puntuación obtenida porrealizar dicha asignación - no sea cero.D. MultiobjetivizacionesEn este trabajo se han analizado varias formas<strong>de</strong> multiobjetivizar el 2dpp. Concretamente, hansido multiobjetivizaciones por agregación, en las quea<strong>de</strong>más <strong>de</strong> utilizar el objetivo original <strong>de</strong>l 2dpp, seha añadido un objetivo alternativo. Tres <strong>de</strong> las funcionesalternativas hacen uso <strong>de</strong> la distancia Euclí<strong>de</strong>aen el espacio <strong>de</strong> <strong>de</strong>cisión. En estos casos, se intentamaximizar dicha función. El cálculo <strong>de</strong> la funciónalternativa es realizado <strong>de</strong> la siguiente forma:• dcn - Distance to the closest neighbour: distanciaal individuo más cercano.• adi - Average distance to all population individuals:distancia media al resto <strong>de</strong> individuos enla población.• dbi - Distance to the best population individual:distancia al mejor individuo <strong>de</strong> la población.A<strong>de</strong>más, se analizaron otras dos funciones:• Random: la función alternativa se calcula <strong>de</strong>forma aleatoria, y se intenta minimizar.• Reverse: se consi<strong>de</strong>ra la función inversa a lafunción <strong>de</strong> fitness.<strong>JP2011</strong>-41


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Primera InstanciaSegunda Instancia5.13e+081.01e+095.12e+081e+09Fitness5.11e+085.1e+085.09e+085.08e+08ADIDBI_THRDCNDBIVarPopEAReverseRandom0 15000 30000 45000 60000 75000Tiempo (s)Fitness9.9e+089.8e+08VarPopEADBI_THRDCN9.7e+08DBIADIRandomReverse9.6e+080 15000 30000 45000 60000 75000Tiempo (s)Fig. 1.Evolución <strong>de</strong>l Fitness para la Primer InstanciaFig. 2.Evolución <strong>de</strong>l Fitness para la Segunda InstanciaA<strong>de</strong>más, también se analizó una variante <strong>de</strong> dbi(dbi thr), consistente en añadir un valor umbralpara penalizar a las soluciones que no cumplanunos requisitos mínimos <strong>de</strong> calidad. Concretamente,se utiliza un parámetro p, y se penaliza a aquellassoluciones cuyo valor <strong>de</strong> fitness sea inferior ap∗bestCurrentF it, siendo bestCurrentF it el fitness<strong>de</strong>l mejor individuo <strong>de</strong> la población. <strong>La</strong> penalizaciónconsiste en asignar el valor 0 a la función alternativa.IV. Mo<strong>de</strong>los Basados en IslasLos mo<strong>de</strong>los basados en islas divi<strong>de</strong>n la poblaciónoriginal en un conjunto <strong>de</strong> subpoblaciones in<strong>de</strong>pendientes.Sobre cada subpoblación se aplica una configuración<strong>de</strong> un ma, constituyendo una isla. Generalmente,cada isla es evolucionada <strong>de</strong> forma in<strong>de</strong>pendientedurante un cierto tiempo. Sin embargo,dado que los esquemas colaborativos suelen alcanzarmejores resultados, se incluye una fase <strong>de</strong> migraciónque permite el intercambio <strong>de</strong> individuos entre islas.Existen diversos tipos <strong>de</strong> mo<strong>de</strong>los basados en islas[3]. En este trabajo se analiza el mo<strong>de</strong>lo homogéneo.En este mo<strong>de</strong>lo todas las islas ejecutanuna misma configuración <strong>de</strong> un ma. <strong>La</strong> migraciónes uno <strong>de</strong> los pasos más importantes en este mo<strong>de</strong>lo.En este proceso se <strong>de</strong>be fijar la topología, el número<strong>de</strong> individuos a migrar, la probabilidad <strong>de</strong> migración,y las estrategias <strong>de</strong> selección y reemplazo.En [4] se aplicó un mo<strong>de</strong>lo basado en islas al 2dppmono-objetivo. En dicho caso, las islas ejecutabanconfiguraciones <strong>de</strong> VarPopEA. <strong>La</strong> migración se configurócon una topología totalmente conectada, y sehizo uso <strong>de</strong> esquemas <strong>de</strong> selección y reemplazo elitistas.Concretamente, sólo se producían migracionescuando se generaban individuos hijos mejores quecualquiera <strong>de</strong> los individuos <strong>de</strong> la población padre.En la isla <strong>de</strong>stino, se producía un reemplazamientosi dicho individuo era mejor que todos los individuos<strong>de</strong> la isla <strong>de</strong>stino. En tal caso, se reemplazaba alindividuo con menor valor <strong>de</strong> fitness. En este trabajose utiliza una fase <strong>de</strong> migración similar. Sólose diferencia en que el reemplazamiento es realizadomediante el esquema Elitist Ranking [18]. Este esquemautiliza el operador <strong>de</strong> crowding <strong>de</strong>l nsga-iipara separar el frente original en subfrentes. Finalmente,se reemplaza un individuo <strong>de</strong>l peor subfrente.V. Resultados ComputacionalesEn esta sección se <strong>de</strong>scriben los experimentos realizadospara validar las multiobjetivizaciones y el mo<strong>de</strong>lobasado en islas previamente <strong>de</strong>scrito. Los resultadosobtenidos con estas propuestas han sido comparadoscon los obtenidos por sus correspondientesversiones mono-objetivas. Los experimentos han sidoejecutados en una máquina <strong>de</strong> 4 procesadores amdR○ Opteron TM (mo<strong>de</strong>lo 6164HE) a 1.7 GHz, y conuna memoria RAM <strong>de</strong> 64 GB. Los compiladores utilizadoshan sido gcc 4.4.5, y OpenMPI 1.4.2. Toda lacomparativa ha sido realizada consi<strong>de</strong>rando dos instancias<strong>de</strong>l 2dpp. <strong>La</strong> primera viene caracterizada porlos siguientes parámetros: X = 10, Y = 10, N = 99,y contiene 9032 posibles parejas. <strong>La</strong> segunda es laque se propuso para la competición. Sus parámetrosson los siguientes: X = 20, Y = 20, N = 399, ycontiene 15962 posibles parejas.Dado que los algoritmos consi<strong>de</strong>rados en este trabajono son <strong>de</strong>terministas, cada ejecución se harepetido 30 veces, y las comparativas han sido realizadasaplicando test estadísticos. Primero, se llevaa cabo el test <strong>de</strong> Shapiro-Wilk para comprobar silos resultados siguen una distribución normal. Encaso afirmativo, se lleva a cabo el test <strong>de</strong> Levenepara comprobar la homogeneidad <strong>de</strong> las varianzas.Si los resultados tienen igual varianza, se comparanlos datos con el test anova. En los casos en que losdatos no cumplen con una distribución normal, selleva a cabo el test <strong>de</strong> Welch. Los test se han llevadoa cabo con un nivel <strong>de</strong> confianza <strong>de</strong>l 95%.En el primer experimento se analizan el comportamiento<strong>de</strong> las diferentes multiobjetivizacionespropuestas. Se han analizado los resultadosobtenidos con el algoritmo memético multi-objetivoal utilizar las 7 multiobjetivizaciones propuestas enla Sección III-D. En el caso <strong>de</strong> dbi thr el valorp se fijo a 0.99. Los resultados han sido comparadoscon los obtenidos con la versión mono-objetiva<strong>de</strong>l 2dpp. En dicho caso el algoritmo utilizado esVarPopEA. En todos los casos los algoritmos fueronejecutados durante 24 horas. En los casos multiobjetivizadosse utilizado una población <strong>de</strong> tamaño 10.El resto <strong>de</strong> parámetros han sido comunes para todaslas configuraciones. En concreto se utilizaron lasmejores parametrizaciones <strong>de</strong> VarPopEA publicadas<strong>JP2011</strong>-42


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fitness5.10e+08 5.13e+08 5.16e+08Primera InstanciaFitness1.000e+09 1.010e+09 1.020e+09Segunda InstanciaMultiIsland MonoIsland ADI VarPopEAMonoIsland MultiIsland VarPopEA DBI_THRFig. 3.Boxplots <strong>de</strong> la Primera Instancia (12 Horas)Fig. 5.Boxplots <strong>de</strong> la Segunda Instancia (12 Horas)Primera InstanciaSegunda Instancia11Ratio <strong>de</strong> Exito0.80.60.40.2MultiIslandMonoIslandADIVarPopEARatio <strong>de</strong> Exito0.80.60.40.2MonoIslandMultiIslandVarPopEADBI_THR00 5000 10000 15000 20000 25000 30000 35000 40000Tiempo (s)00 5000 10000 15000 20000 25000 30000 35000 40000Tiempo (s)Fig. 4.RLD <strong>de</strong> la Primer InstanciaFig. 6.RLD <strong>de</strong> la Segunda Instanciaen [4]. En el operador umd se fijo min p m = 0.1 ymax p m = 0.15. En el operador ssx se utilizó p c = 1.<strong>La</strong> Figura 1 muestra, para la primera instancia,la evolución <strong>de</strong>l fitness medio <strong>de</strong> los distintos esquemas.Se pue<strong>de</strong> apreciar que cuatro mo<strong>de</strong>los multiobjetivizadoshan sido capaces <strong>de</strong> superar a VarPopEA.Los test estadísticos revelan que las diferencias entrelas tres mejores configuraciones multiobjetivizadas yVarPopEA son significativas. <strong>La</strong> Figura 2 muestrala evolución para la segunda instancia. En este casoVarPopEA es el algoritmo que mejores resultadosobtuvo. A<strong>de</strong>más, las diferencias con respecto a todaslas versiones multiobjetivizadas se confirman estadísticamente.De esta forma, con las parametrizacionesrealizadas, la a<strong>de</strong>cuación o no <strong>de</strong> las multiobjetivizaciones<strong>de</strong>pen<strong>de</strong> <strong>de</strong> la instancia a resolver. Taly como se había mencionado anteriormente, la utilidad<strong>de</strong> las multiobjetivizaciones es <strong>de</strong>pendiente <strong>de</strong>lproblema e incluso instancia, lo que se ha confirmadocon los resultados obtenidos para el 2dpp.Se hizo a<strong>de</strong>más, un segundo experimento, con el fin<strong>de</strong> validar la utilización <strong>de</strong>l mo<strong>de</strong>lo basado en islaspara paralelizar el método anterior. Concretamentese hizo uso una comparativa entre dos mo<strong>de</strong>los homogéneos.En el primer <strong>de</strong> ellos (Mono-Island), encada isla se utilizó la <strong>de</strong>finición original <strong>de</strong>l 2dpp,junto con el VarPopEA. En el otro (Multi-Island),se utilizó en cada isla la multiobjetivización quemejores resultados obtuvo en el primer experimentopara cada instancia. Ambos mo<strong>de</strong>los fueron ejecutadoscon cuatro islas, estableciendo un criterio <strong>de</strong>parada <strong>de</strong> 12 horas. <strong>La</strong> Figura 3 muestra, parala primera instancia, los boxplots <strong>de</strong> los resultadosobtenidos por las estrategias secuenciales y paralelasa las 12 horas <strong>de</strong> ejecución. Se pue<strong>de</strong> apreciar queambos mo<strong>de</strong>los paralelos fueron capaces <strong>de</strong> obtenermejores resultados que los correspondientes secuenciales.A<strong>de</strong>más, también se aprecian las ventajas<strong>de</strong> utilizar la multiobjetivización para esta instancia.<strong>La</strong> Figura 5 muestra la misma información parala segunda instancia. Al igual que en la primer instanciala ventaja <strong>de</strong> los mo<strong>de</strong>los paralelos es clara.Sin embargo, en este caso, los mejores resultadosson obtenidos con los mo<strong>de</strong>los mono-objetivo. Esteanálisis ha <strong>de</strong>mostrado la utilidad <strong>de</strong> los mo<strong>de</strong>los paralelosen términos <strong>de</strong> la calidad obtenida al final <strong>de</strong>las ejecuciones. Sin embargo, es importante cuantificarla ganancia que cada mo<strong>de</strong>lo ha conseguidoen relación a su versión secuencial. Para ello se hanutilizado las Run-length Distributions (rld). <strong>La</strong>srld muestran la relación entre el tiempo y el porcentaje<strong>de</strong> veces que un <strong>de</strong>terminado mo<strong>de</strong>lo es capaz<strong>de</strong> alcanzar una <strong>de</strong>terminada calidad <strong>de</strong> soluciones(fitness objetivo). Se calcularon las rld paralos mejores mo<strong>de</strong>los mono-objetivo y multi-objetivo,así como para sus parelizaciones. El fitness objetivose fijó al fitness medio alcanzado por el peor <strong>de</strong> losmo<strong>de</strong>los anteriores. <strong>La</strong> Figura 4 muestra la rld parala primera instancia. Muestra la clara superioridad<strong>de</strong> los mo<strong>de</strong>los paralelos. Consi<strong>de</strong>rando el tiempo requeridopara obtener un 50% <strong>de</strong> porcentaje <strong>de</strong> éxitose han obtenido aceleraciones superlineales en amboscasos. Los mo<strong>de</strong>los paralelos han sido capaces <strong>de</strong>evitar mínimos locales en los que los mo<strong>de</strong>los secuen-<strong>JP2011</strong>-43


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011ciales se estancaban. En la Figura 6 se muestran lasrld <strong>de</strong> la segunda instancia. En este caso, al consi<strong>de</strong>rarun porcentaje <strong>de</strong> éxito <strong>de</strong>l 50% se han obtenidoaceleraciones <strong>de</strong> 1.95 para Mono-Island, y <strong>de</strong> 2.42en Multi-Island. Al consi<strong>de</strong>rar otros porcentajes <strong>de</strong>éxito la aceleración ha variado ligeramente. Concretamente,al utilizar porcentajes entre el 25% y el75%, la aceleración ha variado entre 1.95 y 2.13 paralas versiones mono-objetivas y entre 1.89 y 2.13 enlas versiones multi-objetivas.VI. Conclusiones y Trabajos FuturosEl problema <strong>de</strong> empaquetado es un problema <strong>de</strong>optimización np-completo con múltiple aplicacionesprácticas. En este trabajo se ha abordado una variante<strong>de</strong>l mismo (2dpp) que fue propuesta en lasesión <strong>de</strong> competiciones <strong>de</strong>l gecco 2008. Hastael momento, los mejores resultados para el mismohabían sido obtenidos por un algoritmo meméticomono-objetivo <strong>de</strong>nominando VarPopEA. Sin embargo,se sabía que este esquema en ocasiones sufría<strong>de</strong> estancamiento en mínimos locales. En esteartículo se ha analizado la utilización <strong>de</strong> la técnica<strong>de</strong>nominada multiobjetivización, como una estrategiapara facilitar el escape <strong>de</strong> mínimo locales. Sehan analizado varias multiobjetivizaciones, a las quese les ha aplicado un algoritmo memético basado enel nsga-ii. Los resultados obtenidos han mostradoque multiobjetivizar el 2dpp es útil para algunas instancias,pero no para todas. Por tanto, la técnicamás a<strong>de</strong>cuada <strong>de</strong>pen<strong>de</strong> <strong>de</strong> la instancia a resolver.Debido a esto, la aplicación <strong>de</strong> hiperheurística al2dpp parece muy prometedor. Dado que éstas suelenser utilizadas junto con el mo<strong>de</strong>lo <strong>de</strong> paralelizaciónbasado en islas, se ha analizado la adaptación <strong>de</strong>l mo<strong>de</strong>lobasado en islas al 2dpp. Concretamente, se haanalizado el mo<strong>de</strong>lo homogéneo tanto mono-objetivo,como multiobjetivizado. Los resultados computacioneshan mostrado que esta paralelización ha aportadobeneficios en términos <strong>de</strong> calidad <strong>de</strong> solucionesy ahorro <strong>de</strong> tiempo.El trabajo futuro se enfocará en la aplicación<strong>de</strong> hiperheurísticas paralelas multiobjetivizadas al2dpp. Por ello, sería interesante realizar un estudio<strong>de</strong> la escalabilidad <strong>de</strong>l mo<strong>de</strong>lo basado en islas.A<strong>de</strong>más, dado que los mo<strong>de</strong>los mono-objetivose comportan mejor que los multiobjetivizados paraalgunas instancias, sería interesante <strong>de</strong>sarrollar unahiperheurística que pueda combinar esquemas <strong>de</strong> optimizaciónmono-objetivos y multi-objetivos.Agra<strong>de</strong>cimientosEste trabajo ha sido financiado con fondos ec(fe<strong>de</strong>r) y <strong>de</strong>l Ministerio <strong>de</strong> Ciencia e Innovación,<strong>de</strong>ntro <strong>de</strong>l ‘Plan Nacional <strong>de</strong> i+d+i’ con el proyectocon número <strong>de</strong> referencia tin2008-06491-c04-02.Parte <strong>de</strong>l trabajo también ha sido financiado confondos <strong>de</strong>l Gobierno <strong>de</strong> Canarias correspondientes alproyecto pi2007/015. El trabajo <strong>de</strong> Carlos Segura y<strong>de</strong> Eduardo Segredo ha sido financiado con las becasfpu-ap2008-03213 y fpu-ap2009-0457.Referencias[1] Yew-Soon Ong, Meng-Hiot Lim, Ning Zhu, and Kok WaiWong, “Classification of adaptive memetic algorithms: acomparative study,” IEEE Trans. on Systems, Man, andCybernetics, Part B, vol. 36, no. 1, pp. 141–152, 2006.[2] Enrique Alba, Parallel Metaheuristics: A New Class ofAlgorithms, Wiley-Interscience, 2005.[3] C. A. Coello, G. B. <strong>La</strong>mont, and D. A. Van Veldhuizen,Evolutionary Algorithms for Solving Multi-Objective Problems, Genetic and Evolutionary Computation.Springer, 2007.[4] Coromoto Leon, Gara Miranda, and Carlos Segura, “Amemetic algorithm and a parallel hyperheuristic islandbasedmo<strong>de</strong>l for a 2d packing problem,” in Proceedings ofthe 11th Annual conference on Genetic and evolutionarycomputation, New York, NY, USA, 2009, GECCO ’09,pp. 1371–1378, ACM.[5] Fred W. Glover and Gary A. Kochenberger, Handbook ofMetaheuristics (International Series in Operations Research& Management Science), Springer, January 2003.[6] Joshua D. Knowles, Richard A. Watson, and DavidCorne, “Reducing local optima in single-objective problemsby multi-objectivization,” in Proceedings of theFirst International Conference on Evolutionary Multi-Criterion Optimization, London, UK, 2001, EMO ’01,pp. 269–283, Springer-Verlag.[7] Dimo Brockhoff, Tobias Friedrich, Nils Hebbinghaus,Christian Klein, Frank Neumann, and Eckart Zitzler,“Do additional objectives make a problem har<strong>de</strong>r?,” inProceedings of the 9th annual conference on Genetic an<strong>de</strong>volutionary computation, New York, NY, USA, 2007,GECCO ’07, pp. 765–772, ACM.[8] Carlos Segura, Gara Miranda, and Coromoto León, “Parallelhyperheuristics for the frequency assignment problem,”Memetic Computing, pp. 1–17, 2010.[9] Minh Nghia Le, Yew-Soon Ong, Yaochu Jin, and BernhardSendhoff, “<strong>La</strong>marckian memetic algorithms: localoptimum and connectivity structure analysis,” MemeticComputing, vol. 1, no. 3, pp. 175–190, 2009.[10] Poonam Garg, “A comparison between memetic algorithmand genetic algorithm for the cryptanalysis of simplifieddata encryption standard algorithm,” InternationalJournal of Network Security & Its Applications,vol. 1, no. 1, pp. 34 – 42, April 2009.[11] Q. H. Nguyen, Y. S. Ong, and M. H. Lim, “A ProbabilisticMemetic Framework,” IEEE Trans. EvolutionaryComputation, vol. 13, no. 3, pp. 604–623, 2009.[12] Karthik Sindhya, Ankur Sinha, Kalyanmoy Deb, andKaisa Miettinen, “Local search based evolutionary multiobjectiveoptimization algorithm for constrained and unconstrainedproblems,” in Proceedings of the Eleventhconference on Congress on Evolutionary Computation,Piscataway, NJ, USA, 2009, CEC’09, pp. 2919–2926,IEEE Press.[13] L. Darrell Whitley, V. Scott Gordon, and Keith E. Mathias,“<strong>La</strong>marckian evolution, the baldwin effect and functionoptimization,” in Proceedings of the InternationalConference on Evolutionary Computation. The ThirdConference on Parallel Problem Solving from Nature:Parallel Problem Solving from Nature, London, UK,1994, PPSN III, pp. 6–15, Springer-Verlag.[14] Zhan-fang Zhao Li-xiao Ma, Kun-qi Liu and Ning Li,“Exploring the effects of lamarckian evolution and baldwineffect in differential evolution,” in Communicationsin Computer and Information Science. 2010, vol. 107 ofComputational Intelligence and Intelligent Systems, pp.127–136, Springer.[15] Quang Huy Nguyen, Yew Soon Ong, and Meng Hiot Lim,“Non-genetic transmission of memes by diffusion,” inProceedings of the 10th annual conference on Geneticand evolutionary computation, New York, NY, USA,2008, GECCO ’08, pp. 1017–1024, ACM.[16] Andrzej Jaszkiewicz, “Genetic local search for multiobjectivecombinatorial optimization,” European Journalof Operational Research, vol. 137, no. 1, pp. 50 – 71,2002.[17] Tzung-Pei Hong, Ming-Wen Tsai, and Tung-Kuan Liu,“Two-dimentional encoding schema and genetic operators,”in JCIS. 2006, Atlantis Press.[18] David A. Van Veldhuizen, Jesse B. Zydallis, and Gary B.<strong>La</strong>mont, “Consi<strong>de</strong>rations in engineering parallel multiobjectiveevolutionary algorithms,” IEEE Trans. EvolutionaryComputation, vol. 7, no. 2, pp. 144–173, 2003.<strong>JP2011</strong>-44


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Diseño <strong>de</strong> Filtros con Técnicas Evolutivas parala Clasificación <strong>de</strong> Señales <strong>de</strong> EncefalogramaCoromoto León, Yanira González y Carlos Segura 1Resumen— <strong>La</strong>s interfaces cerebro-máquina (bci,Brain Computer Interface) permiten crear un canal<strong>de</strong> comunicación directo entre el cerebro humano y uncomputador. En este campo, uno <strong>de</strong> los principalesproblemas es la clasificación <strong>de</strong> las señales <strong>de</strong> encefalograma(eeg) capturadas. Investigaciones previashan <strong>de</strong>mostrado que las técnicas <strong>de</strong> clasificación mejoransi la señal eeg es preprocesada. Generalmente, elpreproceso se realiza a través <strong>de</strong> la aplicación <strong>de</strong> unconjunto <strong>de</strong> filtros. En este trabajo se han usado algoritmosevolutivos para generar filtros <strong>de</strong> preprocesadoque optimicen la clasificación. Este esquema hahecho uso <strong>de</strong> una formulación multi-objetiva <strong>de</strong>l problema.En primer lugar, se ha analizado la influencia<strong>de</strong> los operadores genéticos en el correcto <strong>de</strong>sempeño<strong>de</strong> las técnicas. A<strong>de</strong>más, con el objetivo <strong>de</strong> acelerarla generación <strong>de</strong> los filtros se ha aplicado un mo<strong>de</strong>loparalelo basado en islas. Los resultados computacionaleshan mostrado la importancia <strong>de</strong> utilizaruna variación genética a<strong>de</strong>cuada. A<strong>de</strong>más, se ha comprobadola importancia <strong>de</strong> configurar correctamenteel mo<strong>de</strong>lo basado en islas para conseguir reducir eltiempo requerido para obtener filtros a<strong>de</strong>cuados.Palabras clave— Interfaz Cerebro-Máquina, Clasificación,Mo<strong>de</strong>los Paralelos basados en Islas.I. IntroducciónUNA interfaz cerebro-máquina o bci (BrainComputer Interface) es un canal <strong>de</strong> comunicacióndirecto entre el cerebro humano y un computador[1], [2]. Este tipo <strong>de</strong> sistemas tienen aplicacionesprácticas en múltiples campos, como en eldiseño <strong>de</strong> sistemas robóticos [3], en la asistencia a pacienteincapacitados [4], o en la eleboración <strong>de</strong> vi<strong>de</strong>ojuegos[5], [6]. Atendiendo a su nivel <strong>de</strong> intrusismolos sistemas bci se pue<strong>de</strong>n clasificar en invasivos, parcialmenteinvasivos, y no invasivos [7]. Los bcis noinvasivos son los más empleados ya que no requieren<strong>de</strong> cirugía para su utilización. En este grupo <strong>de</strong> interfaces,los más comunes están basados en el uso <strong>de</strong>las señales <strong>de</strong> electro-encefalograma (eeg) emitidaspor las células nerviosas <strong>de</strong>l córtex cerebral. Estossistemas tratan <strong>de</strong> explotar la relación existente entrelos pensamientos y las señales eeg. <strong>La</strong>s señaleseeg se capturan mediante la utilización <strong>de</strong> un conjunto<strong>de</strong> electrodos dispuestos sobre el cuero cabelludo.Existen estudios que han analizado [8] cómo<strong>de</strong>ben ubicarse estos electrodos, así como su relacióncon los patrones generados. Existen otras señales quetambién pue<strong>de</strong>n ser empleadas por los sistemas bci.Cabe <strong>de</strong>stacar las señales basadas en la magnetoencefalografía(meg) o las imágenes por resonanciamagnética funcional (firm, functional magnetic resonanceimaging).1 Dpto. <strong>de</strong> Estadística, I.O y Computación, <strong>Universidad</strong><strong>de</strong> <strong>La</strong> <strong>La</strong>guna, Edificio <strong>de</strong> Física y Matemáticas, Avda. AstrofísicoFco. Sánchez s/n, 38271 <strong>La</strong> <strong>La</strong>guna, Tenerife, e-mail:(cleon|ygonzalez|csegura)@ull.es.El principal reto en los sistemas bci basados eneeg es diseñar un sistema <strong>de</strong> clasificación que, dadauna señal eeg, permita discriminar entre un conjunto<strong>de</strong> pensamientos. Dado que la relación entrepensamiento y señales eeg difiere entre personas, lossistemas <strong>de</strong> clasificación se <strong>de</strong>ben personalizar paracada sujeto. Por este motivo, se suelen empleartécnicas <strong>de</strong> aprendizaje automático [9], cuyo fin esdiseñar sistemas <strong>de</strong> clasificación <strong>de</strong> señales eeg paraun individuo concreto. Estos clasificadores son entrenadosa partir <strong>de</strong> datos generados por el sujeto através <strong>de</strong> un aprendizaje supervisado.Generalmente, los datos capturadas por los electrodosson preprocesados con el fin <strong>de</strong> facilitar laclasificación. Existen tres clases <strong>de</strong> transformacionescomúnmente usadas: el filtro espacial (L), la transformada<strong>de</strong> Fourier (FFT, Fast Fourier Transform)y el filtro pasa banda (B). El filtro espacial seaplica sobre la señal en bruto, realizando transformacionesen el dominio <strong>de</strong>l tiempo. <strong>La</strong> transformada <strong>de</strong>Fourier transforma la señal al dominio <strong>de</strong> la frecuencia.Finalmente, el filtro pasa banda (B), seleccionalas bandas <strong>de</strong> frecuencia que van a ser consi<strong>de</strong>radaspor el sistema <strong>de</strong> clasificación. Generalmente, sólo seconsi<strong>de</strong>ran frecuencias entre los 8 y 30Hz.En [10] se aplicó un algoritmo basado en estrategiasevolutivas al diseño automático <strong>de</strong>l filtro espacialy el filtro pasa-banda. Una vez aplicado el filtro,se hacía uso <strong>de</strong>l clasificador lineal <strong>de</strong> Fisher (fd,Fisher Discriminant). El estudio fue realizado conlas señales eeg publicadas en [11]. A partir <strong>de</strong> losdatos obtenidos por 32 sensores se <strong>de</strong>bía clasificar laseñal en 3 clases diferentes. <strong>La</strong>s estrategias diseñadasfueron capaces <strong>de</strong> generar filtros que alcanzaron tasas<strong>de</strong> error similares a las obtenidas por filtros generadospor expertos. En este trabajo se analiza laaplicación <strong>de</strong> un Algoritmo Evolutivo Multi-Objetivo(moea - Multi-objective Evolutionary Algorithms) auna formulación multiobjetiva <strong>de</strong>l bci. El propósitoes diseñar un método que sea capaz <strong>de</strong> alcanzar erroressimilares o mejores que los ya publicados, y queevite el estancamiento en mínimos locales. En laformulación aplicada se intentan minimizar la tasa<strong>de</strong> error <strong>de</strong>l clasificador y el número <strong>de</strong> bandas <strong>de</strong>frecuencia consi<strong>de</strong>radas. <strong>La</strong> utilización <strong>de</strong>l segundoobjetivo tiene como propósito posibilitar el escape <strong>de</strong>mínimos locales. Sin embargo, dado que el objetivofinal sigue siendo minimizar la tasa <strong>de</strong> error, los resultadosse han analizado consi<strong>de</strong>rando como únicoobjetivo la minimización <strong>de</strong> dicha tasa. Se ha realizadoun análisis sobre la influencia <strong>de</strong> los operadoresgenéticos en el correcto <strong>de</strong>sempeño <strong>de</strong> estas técnicas.<strong>La</strong> obtención <strong>de</strong> filtros <strong>de</strong> alta calidad con la<strong>JP2011</strong>-45


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011técnica propuesta conlleva realizar ejecuciones <strong>de</strong>larga duración. Con el fin <strong>de</strong> reducir el tiempo <strong>de</strong> ejecución<strong>de</strong> los algoritmos evolutivos (eas), se han propuestovarios mo<strong>de</strong>los paralelos [12]. Entre los mo<strong>de</strong>losexistentes, el mo<strong>de</strong>lo basado en islas [13] aportavarios beneficios notables: se adapta fácilmente alas arquitecturas paralelas, permite exten<strong>de</strong>r el espacio<strong>de</strong> búsqueda <strong>de</strong> soluciones pudiendo evitar lacaída en óptimos locales, y pue<strong>de</strong> ser utilizado juntoa las hiperheurísticas para diseñar métodos <strong>de</strong> optimizaciónmás generales. A<strong>de</strong>más, han mostradobuen rendimiento y estabilidad en muchas áreas [12].En este trabajo, se ha analizado la a<strong>de</strong>cuación <strong>de</strong>lmo<strong>de</strong>lo paralelo basado en islas para el bci.El resto <strong>de</strong>l artículo se estructura <strong>de</strong> la siguientemanera: en la Sección II se da una visión <strong>de</strong> comose realiza el preprocesamiento <strong>de</strong> la señal eeg. En laSección III se <strong>de</strong>talla la evolución <strong>de</strong> los filtros L yB. En la Sección IV se <strong>de</strong>scriben los algoritmos evolutivosy operadores géneticos empleados. El mo<strong>de</strong>loparalelo basado en islas se <strong>de</strong>talla en la Sección V.En la Sección VI se <strong>de</strong>finen los experimentos realizados,y se analizan los resultados computacionalesobtenidos con las técnicas <strong>de</strong>scritas. Finalmente, enla Sección VII se presentan las conclusiones y algunasposibles líneas <strong>de</strong> trabajo futuro.II. Preprocesamiento Señales eegCon el objetivo <strong>de</strong> entrenar un clasificador <strong>de</strong>pendiente<strong>de</strong>l usuario, es necesario almacenar los datoseeg generados durante las sesiones <strong>de</strong> adquisición.Los datos eeg en bruto no se suelen usar directamentepara el entrenamiento, sino que se preprocesancon un conjunto <strong>de</strong> filtros. Finalmente, se proce<strong>de</strong>con la fase <strong>de</strong> aprendizaje <strong>de</strong>l clasificador. Esteproceso se lleva a cabo en modo off-line. Los filtrosobtenidos junto con el clasificador podrán ser usadosmás tar<strong>de</strong> <strong>de</strong> forma on-line por el sujeto. Durantela etapa on-line, los datos eeg son primeropreprocesados, luego clasificados, y finalmente usadospara el control <strong>de</strong> periféricos o dispositivos. Enprácticamente todos los casos <strong>de</strong> bcis existe un mo<strong>de</strong>lo<strong>de</strong> retroalimentación, don<strong>de</strong> el sujeto observa larespuesta <strong>de</strong>l sistema a las señales producidas porel cerebro. Este circuito cerrado exige un aprendizajemutuo don<strong>de</strong> la máquina apren<strong>de</strong> <strong>de</strong> los datosobtenidos, y el sujeto <strong>de</strong> la respuesta obtenida.En este trabajo, el preprocesamiento se inicia aplicandoun filtro espacial sobre los datos almacenadosen la sesión <strong>de</strong> adquisición <strong>de</strong> datos. A los datosresultantes <strong>de</strong> este proceso se le aplica la TransformadaRápida <strong>de</strong> Fourier (fft), transformando laseñal al dominio frecuencial, don<strong>de</strong> es posible <strong>de</strong>tectarmás fácilmente algunas características, como lasSMR (sensorimotor rythm). Finalmente, se seleccionanlas bandas <strong>de</strong> frecuencia más relevantes con elfiltro pasabanda. En esta sección, se explica cómo seproduce el preprocesado <strong>de</strong> la señal asumiendo queel filtro espacial ya ha sido ajustado, y que el filtropasabanda ya ha sido seleccionado. Eliminando,con este último, las frecuencias que no interesan yal mismo tiempo intentando reducir la información aextraer para simplificar la tarea <strong>de</strong>l clasificador.Inicialmente, la señal eeg recogida a partir <strong>de</strong>c electrodos es discretizada usando una frecuencia<strong>de</strong> muestreo f, que representa el número <strong>de</strong> muestrasrecogidas por segundo (Hz). Si la sesión <strong>de</strong>adquisición dura n segundos, se genera una serie temporal<strong>de</strong> f ∗ n puntos. En cada instante, sólo unaparte <strong>de</strong> la señal eeg es consi<strong>de</strong>rada. Se <strong>de</strong>nota comoS n a la enésima parte <strong>de</strong> la eeg. S n es una matriz t xc, don<strong>de</strong> t = s∗f, siendo s la duración <strong>de</strong>l fragmento<strong>de</strong> señal seleccionado, y f la frecuencia <strong>de</strong> muestreo.<strong>La</strong> primera fase <strong>de</strong> la etapa <strong>de</strong> preprocesamiento(filtro espacial) se representa a través <strong>de</strong> laecuación 1. El filtro espacial L es una matriz c xc ′ . Si c ′ = c entonces, S ′ n tiene el mismo número<strong>de</strong> columnas (canales) que la matriz original S n . Elnúmero <strong>de</strong> canales <strong>de</strong> S ′ n se reduce en el caso quec ′ < c. En cierto sentido, el filtro espacial L transformael número <strong>de</strong> canales c original a c ′ .S ′ n = S n ∗ L (1)<strong>La</strong> segunda fase en el preprocesamiento <strong>de</strong> la señaleeg consiste en transformar la señal <strong>de</strong>s<strong>de</strong> el dominiotemporal al dominio frecuencial aplicando lafft. Puesto que la fft es aplicada sobre una parteS ′ n <strong>de</strong> la señal se ha optado por usar la transformada<strong>de</strong> Fourier <strong>de</strong> corta duración (stft, Short Time FastFourier). <strong>La</strong> aplicación <strong>de</strong> la stft sobre S ′ n vienerepresentada en la ecuación 2.S ′′n = |F F T (S′ n )| (2)don<strong>de</strong> el operador || computa el módulo <strong>de</strong> cadauno <strong>de</strong> los componentes <strong>de</strong> la matriz resultante <strong>de</strong>la fft. <strong>La</strong> fft <strong>de</strong>vuelve un número complejo, confase y módulo, pero muchas investigaciones realizadassobre el bci tratan únicamente el módulo [14],por lo que en este caso se ha ignorando la fase. S ′′nen la ecuación 2 es igualmente una matriz <strong>de</strong> t xc ′ , pero ahora las filas <strong>de</strong> la matriz pertenecen aldominio <strong>de</strong> la frecuencia. Tras aplicar la transformaciónfft, las filas <strong>de</strong>s<strong>de</strong> la 1 hasta la t/2 <strong>de</strong> lamatriz S ′′n representan el conjunto <strong>de</strong> bandas <strong>de</strong> frecuencias[0 − f/2]Hz (don<strong>de</strong> f es la frecuencia <strong>de</strong>muestreo y t el tamaño <strong>de</strong> la ventana), con una resoluciónδf = (f/t)Hz. <strong>La</strong>s bandas <strong>de</strong> frecuenciascontenidas en la matriz son [0 − δf], [δf − 2 ∗ δf],etc. En ocasiones, la resolución δt es más pequeña<strong>de</strong> lo necesario, así que es conveniente trabajar conunas bandas <strong>de</strong> frecuencias más amplias. Es conocido,que las frecuencias fuera <strong>de</strong>l rango [8 − 30]Hzno contienen información fisiológica <strong>de</strong> interés para elbci. Por lo tanto, únicamente se seleccionan las filasque se encuentran <strong>de</strong>s<strong>de</strong> ⌈8/δf⌉+1 hasta ⌈30/δf⌉+1.Con el propósito <strong>de</strong> simplificar la notación, se asumeque S ′ n está compuesta únicamente por aquellas bandas<strong>de</strong> frecuencias en la que existe información fisiológica.El número <strong>de</strong> filas restantes en S ′′n est ′ = ⌈8/δf⌉ − ⌈30/δf⌉ + 1.<strong>JP2011</strong>-46


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>La</strong> última fase <strong>de</strong>l preprocesado <strong>de</strong> la señal eegselecciona el conjunto <strong>de</strong> bandas <strong>de</strong> frecuencias másrelevantes para un usuario en particular. Este pasoes representado por el filtro B en la ecuación 3. Bes una matriz con dimensiones iguales a S ′′n , perocompuesta sólo por valores binarios (0 ó 1). Así,si la componente B(i, j) = 0 entonces, S ′′n (i, j)será eliminada <strong>de</strong>l conjunto <strong>de</strong> bandas <strong>de</strong> frecuenciasdisponibles. Solamente aquellas componentes <strong>de</strong>(i, j) con B(i, j) = 1 permanecen intactas.S ′′nS ′′′n= S′′ n ⊗ B (3)<strong>La</strong> ecuación 4 resume las fases <strong>de</strong>l preprocesadosobre la matriz S n para generar una instancia <strong>de</strong> entrenamiento.Algorithm 1 Pseudocódigo <strong>de</strong> un ea1: Generar población inicial2: Evaluar individual <strong>de</strong> la población3: while (criterio <strong>de</strong> parada no se cumpla) do4: Selección <strong>de</strong> padres5: Aplicar operador <strong>de</strong> crossover con probabilidad p c6: Aplicar operador <strong>de</strong> mutación con probabilidad p m7: Evaluar los nuevos individuos8: Selección <strong>de</strong> supervivencia9: end whilesi i pertenece al resto <strong>de</strong> clases. Cada F D i (x) es unhiperplano representado por F D i (x) = w i ∗ x + b i .<strong>La</strong> ecuación 5 presenta cómo se clasifica una instanciax empleando el enfoque uno contra todos en elclasificador lineal fd. Se elige el valor i tal que F D ies máximo.F D(x) = arg max i (F D i (x)) = arg max i (w i ∗ x + b i ) (5)I n = flatten(|(F F T (S n ∗ L))| ⊗ B) (4)don<strong>de</strong> flatten construye una lista con todas componentes<strong>de</strong> la matriz.III. Evolución <strong>de</strong>l Filtro Espacial ySelección <strong>de</strong> FrecuenciasEl objetivo <strong>de</strong> este trabajo es evolucionar el filtroespacial L y seleccionar el conjunto <strong>de</strong> bandas<strong>de</strong> frecuencias B, que optimicen la operación <strong>de</strong> unclasificador C. Ambos filtros son evolucionados <strong>de</strong>forma conjunta. Con el propósito <strong>de</strong> resolver elproblema haciendo uso <strong>de</strong> algoritmos evolutivos se<strong>de</strong>ben <strong>de</strong>finir, la representación <strong>de</strong> las soluciones candidatas(cromosoma) y las función <strong>de</strong> optimización.El cromosoma contiene los parámetros que seránoptimizados, es <strong>de</strong>cir, la matriz <strong>de</strong> filtro espacial Ly el filtro <strong>de</strong> selección <strong>de</strong> frecuencias B. Ambas matricesse codifican <strong>de</strong> forma directa en el cromosoma.<strong>La</strong> matriz L está compuesta por número reales, mientrasque la matriz B es un vector <strong>de</strong> números binarios.Con el fin <strong>de</strong> evaluar la calidad <strong>de</strong> los filtrosL y B codificados en el cromosoma, un clasificadorC es construido sobre el conjunto <strong>de</strong> datos <strong>de</strong> entrenamientoI n generados a partir <strong>de</strong> los datos eeg <strong>de</strong>entrenamiento. El objetivo <strong>de</strong> la clasificación consisteen i<strong>de</strong>ntificar a qué clase pertenece un <strong>de</strong>terminadoobjeto (señal en el caso consi<strong>de</strong>rado). Unclasificador lineal logra esto tomando una <strong>de</strong>cisión <strong>de</strong>clasificación basada en el valor <strong>de</strong> una combinaciónlineal <strong>de</strong> sus características. En este trabajo, se hautilizado el clasificador lineal <strong>de</strong> Fisher (fd, FisherDiscriminant). Se ha elegido el fd porque estudiosprevios han <strong>de</strong>mostrado que el mismo pue<strong>de</strong> ser unabuena opción para esta área.Con el fin <strong>de</strong> hacer frente a problemas multiclases,el enfoque <strong>de</strong> uno contra todos es aplicado para elfd. Un problema <strong>de</strong> clasificación <strong>de</strong> N c clases estransformado a N c problemas <strong>de</strong> clasificación binarios,don<strong>de</strong> el objetivo es separar la clase i <strong>de</strong>l resto<strong>de</strong> clases. Los clasificadores binarios tienen comoobjetivo diseñar una función <strong>de</strong> clasificación tal queF D i (x) > 0 si x pertenece a la clase i y F D i (x) < 0En el presente trabajo, las soluciones candidatasson evaluadas acor<strong>de</strong> a dos objetivos: el error <strong>de</strong> entrenamiento<strong>de</strong>l clasificador fd y el número <strong>de</strong> bandas<strong>de</strong> frecuencias seleccionadas. El error <strong>de</strong> entrenamientoes el error que se comete al clasificar lasinstancias I n , tras aplicar un <strong>de</strong>terminado preprocesamientoy el discriminante <strong>de</strong> Fisher. El número <strong>de</strong>bandas <strong>de</strong> frecuencias seleccionadas es dado por elnúmero <strong>de</strong> componentes con valor 1 en B. Ambosobjetivos son a minimizar.IV. Algoritmos Evolutivos yOperadores Genéticos<strong>La</strong>s técnicas <strong>de</strong> optimización multi-objetivo tratan<strong>de</strong> obtener un conjunto <strong>de</strong> individuos no dominados,lo más cercano posible al Frente <strong>de</strong> Pareto.Entre estas estrategias cabe <strong>de</strong>stacar los algoritmosevolutivos multi-objetivo (Multi-Objective OptimizationEvolutionary Algorithms - moeas). Se trata<strong>de</strong> técnicas que se inspiran en la evolución <strong>de</strong> lanaturaleza para realizar la optimización. El Algoritmo1 muestra un pseudocódigo <strong>de</strong> un ea. Losmoeas han <strong>de</strong>mostrado ser métodos a<strong>de</strong>cuados paraabordar problemas <strong>de</strong> optimización complejos. Estetipo <strong>de</strong> estrategias se basan en mantener <strong>de</strong> formaparalela un conjunto <strong>de</strong> soluciones candidatas queluchan y cooperan entre ellas para mejorar las solucionesobtenidas. <strong>La</strong> codificación <strong>de</strong> los individuosconsiste en un string real/binario, con tantos genescomo valores en los filtros L y B. Cada gen binariorepresenta si se selecciona o no una <strong>de</strong>terminadabanda <strong>de</strong> frecuencia, mientras que los valores reales<strong>de</strong>terminan los valores <strong>de</strong>l filtro espacial.Los moeas están basados en unos patrones comunes.Sin embargo, existen diversas formas <strong>de</strong> llevarestas i<strong>de</strong>as a la práctica. Por ello han surgido enla literatura una gran cantidad <strong>de</strong> moeas. Con el fin<strong>de</strong> comprobar la adaptación <strong>de</strong> estas estrategias albci se escogió Non-Dominated Sorting Genetic AlgorithmII [15] (nsga2), uno <strong>de</strong> los algoritmos evolutivosmulti-objetivo más populares.Los moeas están basados en una fase <strong>de</strong> variaciónen la se <strong>de</strong>ben aplicar operadores <strong>de</strong> cruce y mutación<strong>JP2011</strong>-47


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011a un conjunto <strong>de</strong> individuos que son seleccionadospor cada estrategia. Tal y como se pue<strong>de</strong> observaren el Algoritmo 1 estos operadores son aplicados conuna probabilidad p c y p m , respectivamente. El funcionamiento<strong>de</strong> estos operadores no viene <strong>de</strong>terminadopor cada algoritmo, sino que se <strong>de</strong>ben escoger<strong>de</strong> forma in<strong>de</strong>pendiente. En este trabajo se analizael comportamiento <strong>de</strong> los algoritmos anteriores haciendouso <strong>de</strong> diversos operadores <strong>de</strong> variación. Dadoque el cromosoma está formado por una parte real yotra binaria se han empleado operadores <strong>de</strong> variación<strong>de</strong> ambos tipos. En el cruce <strong>de</strong> individuos se hantesteado los operadores <strong>de</strong> cruce <strong>de</strong> un punto (opc -One Point Crossover) y el cruce uniforme (ux) parala parte binaria. El cruce en la parte real siempreha sido realizado utilizando el cruce uniforme (ux -Uniform Crossover). En la proceso <strong>de</strong> mutación <strong>de</strong>individuos se ha testeado la mutación uniforme (um)y la mutación polinomial (pol - Polynomial Mutation)para la parte real. En la parte binaria en todocaso se ha aplicado el operador Binary Flip Mutation.V. Mo<strong>de</strong>los Basados en islasLos mo<strong>de</strong>los basados en islas divi<strong>de</strong>n la poblaciónoriginal en un conjunto <strong>de</strong> sub-poblaciones in<strong>de</strong>pendientes.Cada sub-población es asociada a unaisla, y sobre cada isla se ejecuta una configuración<strong>de</strong> moea <strong>de</strong> forma in<strong>de</strong>pendiente durante un ciertotiempo. Una configuración está constituida porun algoritmo <strong>de</strong> optimización con sus respectivosparámetros. Generalmente, cada procesador constituyeuna isla, <strong>de</strong> forma que cada isla evolucionaen paralelo <strong>de</strong> forma in<strong>de</strong>pendiente. Sin embargo,dado que los esquemas colaborativos suelen alcanzarmejores resultados, se incluye una fase <strong>de</strong> migraciónque permite el intercambio <strong>de</strong> individuos entre islas.Este comportamiento colaborativo aña<strong>de</strong> al esquemabasado en islas la posibilidad <strong>de</strong> obtener un mejorcomportamiento. Existen cuatro mo<strong>de</strong>los basados enislas diferentes [13]: todas las islas ejecutan la mismaconfiguración (homogéneo), todas las islas ejecutanuna configuración diferente (heterogéneo), cada islaevalúa un subconjunto diferente <strong>de</strong> funciones objetivoy cada isla representa una región distinta en losdominios <strong>de</strong>l fenotipo o <strong>de</strong>l genotipo. En este trabajose analiza el mo<strong>de</strong>lo <strong>de</strong> islas homogéneo. En este mo<strong>de</strong>lotodas las islas ejecutan la misma configuración<strong>de</strong> un moea. En esta clase <strong>de</strong> mo<strong>de</strong>lo paralelo, elproceso <strong>de</strong> migración que permite el intercambio <strong>de</strong>individuos entre islas es esencial. Dado que cadaalgoritmo evolutivo podría explorar regiones <strong>de</strong>l espaciodiferentes, este mecanismo pue<strong>de</strong> permitir enriquecerlas soluciones locales <strong>de</strong> cada isla, pudiendoobtenerse a la larga una mayor eficiencia en el esquema[16]. Para <strong>de</strong>finir el esquema <strong>de</strong> migraciónse <strong>de</strong>ben especificar una serie <strong>de</strong> componentes: latopología <strong>de</strong> migración (i<strong>de</strong>ntifica hacía don<strong>de</strong> migranlos individuos), el ratio <strong>de</strong> migración (número<strong>de</strong> individuos a migrar), el porcentaje <strong>de</strong> migración(<strong>de</strong>termina con qué frecuencia se migra), la estrate-Error <strong>de</strong> Entrenamiento (%)Fig. 1.0.380.360.340.320.30.280.26UX_POLUX_UMOPC_POLOPC_UM0.240 1000 2000 3000 4000 5000 6000 7000EvaluacionesEvolución <strong>de</strong>l Porcentaje <strong>de</strong> Error <strong>de</strong> Entrenamientogia <strong>de</strong> selección <strong>de</strong> individuos a migrar y la estrategia<strong>de</strong> reemplazamiento en la isla <strong>de</strong>stino. Otra <strong>de</strong>cisiónque pue<strong>de</strong> influir enormemente en los resultados finaleses el tamaño <strong>de</strong> las subpoblaciones [16]. Algunosautores divi<strong>de</strong>n la población original usada enlos esquemas secuenciales, <strong>de</strong> forma que la suma <strong>de</strong>las subpoblaciones sea igual a dicha población original.En otros casos se usan poblaciones tan gran<strong>de</strong>scomo en el esquema secuencial. Cada uno <strong>de</strong> estosesquemas tiene ventajas y <strong>de</strong>sventajas.VI. Resultados ComputacionalesEn esta Sección se <strong>de</strong>scriben los experimentos llevadosa cabo con los diferentes esquemas <strong>de</strong> optimizaciónpresentados en la Sección IV, así comosus paralelizaciones. <strong>La</strong>s pruebas se han lanzadoen una máquina con sistema operativo DebianGNU/Linux, 4 procesadores amd R○ Opteron TM(mo<strong>de</strong>lo 6164HE) que corren a 1.7 GHz, y con unamemoria RAM <strong>de</strong> 64 GB. El compilador utilizadoha sido gcc 4.4.5. El compilador mpi ha sido Open-MPI 1.4.2. <strong>La</strong> validación ha sido realizada utilizandolos datos proporcionados por el instituto <strong>de</strong> investigaciónIDIAP [11]. Concretamente se ha utilizado elSujeto 1 <strong>de</strong>l conjunto <strong>de</strong> datos V. Para este sujeto sedisponen <strong>de</strong> 4 sesiones. <strong>La</strong>s 3 primeras han sido utilizadascomo conjunto <strong>de</strong> entrenamiento, mientrasque la última fue utilizada como conjunto <strong>de</strong> validación.Se han analizado los resultados tanto parael conjunto <strong>de</strong> entrenamiento como para el conjunto<strong>de</strong> validación. Ambos análisis han llevado a similaresconclusiones. Por ello, sólo se presentan resultadoshaciendo uso <strong>de</strong>l conjunto <strong>de</strong> entrenamiento.Dado que los algoritmos consi<strong>de</strong>rados en este trabajono son <strong>de</strong>terministas, cada ejecución se harepetido 30 veces, y las comparativas han sido realizadasutilizando los siguientes test estadísticos [17].Primero, se aplica el test <strong>de</strong> Shapiro-Wilk para comprobarsi los resultados siguen una distribución normal.En caso afirmativo, se lleva a cabo el test <strong>de</strong>Levene para comprobar la homogeneidad <strong>de</strong> las varianzas.Si los resultados tienen igual varianza, secomparan los datos con el test anova. En los casosen que los datos no cumplen con una distribuciónnormal, el test <strong>de</strong> Welch es aplicado. Los test se hanllevado a cabo con un nivel <strong>de</strong> confianza <strong>de</strong>l 95%.<strong>JP2011</strong>-48


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA IComparativa Estadística <strong>de</strong> los Mo<strong>de</strong>los SecuencialesOPC UM OPC POL UX UM UX POLOPC UM ↔ ↑ ↑ ↑OPC POL ↓ ↔ ↔ ↔UX UM ↓ ↔ ↔ ↑UX POL ↓ ↔ ↓ ↔TABLA IIAceleración <strong>de</strong>l Mo<strong>de</strong>lo Paralelo Basado en IslasSubPop = 8 SubPop = 30p m = 0.1 1.38 1.30p m = 0.5 1.63 1.44p m = 1 1.7 1.441.21Island-Mo<strong>de</strong>l (SubP 8)Island-Mo<strong>de</strong>l (SubP 30)OPC_UMRatio <strong>de</strong> Exito0.80.60.40.205000 10000 15000 20000 25000 30000 35000 40000 45000Tiempo (s)Fig. 2.Errores <strong>de</strong> entrenamiento en 22000 sFig. 3.RLD <strong>de</strong> los mejores mo<strong>de</strong>los secuenciales y paralelosEn el primer experimento se ha analizado el comportamiento<strong>de</strong> los algoritmos evolutivos al ser aplicados<strong>de</strong> forma secuencial. Se ha utilizado el algoritmoevolutivo multi-objetivo Non-Dominated SortingEvolutionary Algorithm-II (nsga2). Con el fin<strong>de</strong> analizar la influencia <strong>de</strong> los operadores genéticosen el correcto <strong>de</strong>sempeño <strong>de</strong> las técnicas, éste hasido ejecutado con los operadores genéticos previamentepresentados. Concretamente, se han ejecutados4 configuraciones que combinan los operadores<strong>de</strong> cruce binario opc y ux, con los operadores <strong>de</strong>mutación real um y pol. El valor p c fue fijado a 1 entodo caso. Por su parte, p m fue fijado a 1 Men para losoperadores <strong>de</strong> mutación binaria, siendo M el número<strong>de</strong> genes <strong>de</strong> la parte binario, y a 1 Npara los operadores<strong>de</strong> mutación real, siendo N el número <strong>de</strong> genes<strong>de</strong> la parte real. Estas configuraciones serán referenciadascon la forma X Y , en don<strong>de</strong> X es el crucebinario utilizado, e Y es la mutación real aplicada.<strong>La</strong>s configuraciones fueron ejecutadas estableciendocomo criterio <strong>de</strong> parada la ejecución <strong>de</strong> 7000 evaluaciones.<strong>La</strong> Figura 1 muestra la evolución <strong>de</strong>l error <strong>de</strong>entrenamiento para cada configuración. En la mismapo<strong>de</strong>mos observar que los resultados obtenidos por laconfiguración con mutación um y cruce opc superanal resto <strong>de</strong> configuraciones. <strong>La</strong> Tabla I muestra losresultados <strong>de</strong> los tests estadísticos realizados para estasconfiguraciones con los resultados obtenidos alfinal <strong>de</strong> las ejecuciones. En cada celda se indicasi la configuración correspondiente a dicha fila esestadísticamente superior (↑), no diferente (↔), opeor (↓), que la configuración correspondiente a lacolumna. Los test estadísticos confirman la superioridad<strong>de</strong>l mo<strong>de</strong>lo opc um, mostrando la importancia<strong>de</strong> seleccionar correctamente la variación genética.Se hizo a<strong>de</strong>más, un segundo experimento, con elfin <strong>de</strong> validar la utilización <strong>de</strong>l mo<strong>de</strong>lo basado enislas para paralelizar el método anterior. Concretamentese aplicó el mo<strong>de</strong>lo basado en islas ho-mogéneo, utilizando la mejor configuración encontradaen el primer experimento. Los tests fueron realizadosutilizando cuatro islas. Se ejecutaron seisconfiguraciones diferentes <strong>de</strong> este mo<strong>de</strong>lo, combinandotres valores diferentes <strong>de</strong> probabilida<strong>de</strong>s <strong>de</strong>migración, con dos valores diferentes <strong>de</strong> tamaños <strong>de</strong>las subpoblaciones. <strong>La</strong>s probabilida<strong>de</strong>s <strong>de</strong> migracióntesteadas fueron: 0.1, 0.5 y 1. Los tamaños <strong>de</strong> lassubpoblaciones fueron 8 y 30. De esta forma, al utilizarel valor 8, la población <strong>de</strong>l método secuencialoriginal se está distribuyendo entre las islas, mientrasque al utilizar el valor 30 se está haciendo crecerla población original. <strong>La</strong> migración se configuró conuna topología en anillo, y se hizo uso <strong>de</strong> esquemas<strong>de</strong> selección y reemplazo elitistas. Concretamente,sólo se producían migraciones cuando se generabanindividuos hijos mejores que cualquiera <strong>de</strong> los individuos<strong>de</strong> la población padre. El reemplazamiento enlas islas <strong>de</strong>stino, es realizado mediante el esquemaElitist Ranking [16]. Este esquema utiliza el operador<strong>de</strong> crowding <strong>de</strong>l nsga2 para separar el frenteoriginal en subfrentes. Finalmente, se reemplaza unindividuo <strong>de</strong>l peor subfrente. <strong>La</strong> Figura 2 muestralos boxplots <strong>de</strong>l error <strong>de</strong> entrenamiento alcanzado en2200 segundos por la mejor configuración secuencial(opc um), y por las cuatro mejores configuracionesparalelas. Se aprecia que las configuraciones paralelasson capaces <strong>de</strong> alcanzar errores menores que laconfiguración secuencial. A<strong>de</strong>más, los mo<strong>de</strong>los queutilizan tamaños <strong>de</strong> subpoblación 8 han obtenidoserror ligeramente menores que los que han utilizadosubpoblaciones <strong>de</strong> tamaño 30. Estos resultados indicanque los mo<strong>de</strong>los paralelos son capaces <strong>de</strong> acelerarla convergencia a filtros <strong>de</strong> alta calidad. Sinembargo, dado que éstos están usado más recursoscomputaciones, dicha mejora <strong>de</strong>be ser cuantificada.Para ello se han utilizado las Run-length Distributions[18] (rld). <strong>La</strong>s rld muestran la relación entreel tiempo y el porcentaje <strong>de</strong> veces que un <strong>de</strong>terminadomo<strong>de</strong>lo es capaz <strong>de</strong> alcanzar una <strong>de</strong>terminada<strong>JP2011</strong>-49


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011calidad <strong>de</strong> soluciones (porcentaje <strong>de</strong> error). Se calcularonlas rld para la mejor configuración secuencialy para todos los mo<strong>de</strong>los paralelos. El error objetivose fijó al 27, 5%. <strong>La</strong> Tabla II muestra la aceleración<strong>de</strong> los mo<strong>de</strong>los paralelos respecto al secuencial,consi<strong>de</strong>rando el tiempo requerido para obtenerun 50% <strong>de</strong> éxito. <strong>La</strong> Figura 3 muestra la rld para elmejor mo<strong>de</strong>lo secuencial, y los mejores mo<strong>de</strong>los paralelosfijando los tamaños <strong>de</strong> subpoblación a 8 y 30.Se pue<strong>de</strong> apreciar que, aunque los mo<strong>de</strong>los paraleloshan permitido acelerar la convergencia a soluciones<strong>de</strong> alta calidad, dicha aceleración está bastante limitada.Por ello, se hace necesario seguir analizandomás a fondo este mo<strong>de</strong>lo, con el fin <strong>de</strong> hacer un mejoruso <strong>de</strong> los recursos computacionales.VII. Conclusiones y Trabajos Futuros<strong>La</strong>s interfaces cerebro-máquina (bci, Brain ComputerInterface) permiten crear un canal <strong>de</strong> comunicacióndirecto entre el cerebro humano y un computador.En este campo uno <strong>de</strong> los principales retoses el diseño <strong>de</strong> algoritmos, capaces <strong>de</strong> clasificarlas señales eeg en un conjunto <strong>de</strong> pensamientos <strong>de</strong>lsujeto. Generalmente, antes <strong>de</strong> aplicar los clasificadores,se preprocesan las señales eeg mediante unconjunto <strong>de</strong> filtros. En este trabajo, se ha aplicael algoritmo evolutivo multi-objetivo nsga2 paragenerar <strong>de</strong> forma automática estos filtros. nsga2ha sido aplicado utilizando varias configuraciones <strong>de</strong>variación genética. Los resultados computacionaleshan mostrado la importancia <strong>de</strong> seleccionar <strong>de</strong> formaa<strong>de</strong>cuada los operadores genéticos. Los resultadosobtenidos son similares a los mejores publicadoshasta el momento, <strong>de</strong> entre aquellas técnicas queusan como entrada directa las señales eeg. Dado elalto coste computacional asociado a cada ejecuciónse ha explorado la posibilidad <strong>de</strong> utilizar el mo<strong>de</strong>loevolutivo basado en islas. Se escogió este mo<strong>de</strong>loporque se pue<strong>de</strong> hibridizar fácilmente con las hiperheurísticas,con las ventajas que ello conlleva. Serealizó un análisis utilizando diferentes tamaños <strong>de</strong>subpoblaciones, así como diferentes porcentajes <strong>de</strong>migración. Los resultados computacionales muestranque se ha conseguido acelerar la generación <strong>de</strong>filtros <strong>de</strong> alta calidad. Sin embargo, se hace patenteque el aprovechamiento <strong>de</strong> los recursos computacionesno ha sido máximo.Los trabajos futuros se centrarán en analizar mása fondo el mo<strong>de</strong>lo basado en islas, con el fin <strong>de</strong>acelerar aún más la computación. Concretamente,se quieren explorar otros esquemas <strong>de</strong> migración yaque éste generalmente tiene una gran influencia sobrelos resultados obtenidos. A<strong>de</strong>más, sería interesanteanalizar los resultados obtenidos con otros sujetos.Dado que con alta probabilidad, la variacióngenética a<strong>de</strong>cuada <strong>de</strong>pen<strong>de</strong> <strong>de</strong>l sujeto al que se aplicael esquema, utilizar algunos esquemas que hibridizanlos mo<strong>de</strong>los basados en islas con las hiperheurísticasparece prometedor. Esto permitiría disponer <strong>de</strong> unesquema que <strong>de</strong> forma automática seleccione la fase<strong>de</strong> variación genética a<strong>de</strong>cuada.Agra<strong>de</strong>cimientosEste trabajo ha sido financiado con fondos ec(fe<strong>de</strong>r) y <strong>de</strong>l Ministerio <strong>de</strong> Ciencia e Innovación,<strong>de</strong>ntro <strong>de</strong>l ‘Plan Nacional <strong>de</strong> i+d+i’ con el proyectotin2008-06491-c04-02. Parte <strong>de</strong>l trabajo tambiénha sido financiado con fondos <strong>de</strong>l Gobierno <strong>de</strong> Canariascorrespondientes al proyecto pi2007/015. Eltrabajo <strong>de</strong> Carlos Segura ha sido financiado graciasa las beca fpu-ap2008-03213.Referencias[1] Wolpaw JR, Birbaumer N, McFarland DJ, PfurtschellerG, and Vaughan TM, “Brain-computer interfaces forcommunications and control,” Neurophys, pp. 767–791,2002.[2] E.A. Curran and M.J. Stokes, “Learning to control brainactivity: a review of the production and control of eggcomponents for driving braincomputer interface (bci) systems,”Brain Cognition, 51, 2003.[3] Mourino J Millan J <strong>de</strong>l R, Renkens F, and W. Gerstner,“Noninvasive brain-actuated control of a mobile robot byhuman eeg,” IEEE Trans Biomed Eng,51, 2004.[4] R. Singla, R. Pahuja, and S. Pahuja, “Environment controlusing bci,” in Bioinformatics and Biomedical Engineering,2007. ICBBE 2007. The 1st International Conferenceon, july 2007, pp. 1293 –1295.[5] D.P.O. Bos, B. Reu<strong>de</strong>rink, B. <strong>La</strong>ar, H. Gurkok, C. Muhl,M. Poel, D. Heylen, and A. Nijholt, “Human-computerinteraction for bci games: Usability and user experience,”in Cyberworlds (CW). 2010 International Conference on,pp. 277–281, IEEE.[6] D.P.O. Bos, B. Reu<strong>de</strong>rink, B. <strong>La</strong>ar, H. Gurkok, C. Muhl,M. Poel, A. Nijholt, and D. Heylen, “Brain-ComputerInterfacing and Games,” Brain-Computer Interfaces, pp.149–178, 2010.[7] Andrea Kubler and Klaus Robert Muller, Toward Brain-Computer Interfacing, MIT Press, 2007.[8] G. Pfurtscheller and F.H.L. da Silva, “Event-related synchronizationof mu rhythm in the egg over the corticalhand area in man,” NeuroScience Letters,174, 1994.[9] G. Dornhege, B. Blankertz, M. Krauledat, F. Losch,G. Curio, and K. R. Muller, “Combined Optimizationof Spatial and Temporal Filters for Improving Brain-Computer Interfacing,” IEEE Transactions on BiomedicalEngineering, vol. 53, no. 11, pp. 2274–2281, Nov.2006.[10] R. Aler, I.M. Galván, and J.M. Valls, “Evolving spatialand frequency selection filters for brain-computer interfaces,”in IEEE Congress on Evolutionary Computation,2010, pp. 1–7.[11] J. <strong>de</strong>l R. Millán, “On the need for on-lin learning in braincomputerinterfaces.,” in Proceedings of the InternationalJoint Conference on Neural Networks, Budapest, Hungary,July, 2004, IDIAP-RR 03-30.[12] Enrique Alba, Parallel Metaheuristics: A New Class ofAlgorithms, Wiley-Interscience, 2005.[13] C. A. Coello, G. B. <strong>La</strong>mont, and D. A. Van Veldhuizen,Evolutionary Algorithms for Solving Multi-Objective Problems, Genetic and Evolutionary Computation.Springer, 2007.[14] Guido Dornhege et al. (eds), Towards Brian-ComputerInterfacing, chapter General Signal Processing and MachineLearning Tools for BCI Analysis, MIT Press, 2007.[15] Kalyanmoy Deb, Amrit Pratap, Sameer Agarwal, andT. Meyarivan, “A fast and elitist multiobjective geneticalgorithm: NSGA-II,” IEEE Transactions on EvolutionaryComputation, vol. 6, pp. 182–197, 2002.[16] David A. Van Veldhuizen, Jesse B. Zydallis, and Gary B.<strong>La</strong>mont, “Consi<strong>de</strong>rations in engineering parallel multiobjectiveevolutionary algorithms,” IEEE Trans. EvolutionaryComputation, vol. 7, no. 2, pp. 144–173, 2003.[17] Janez Demšar, “Statistical comparisons of classifiers overmultiple data sets,” Journal of Machine Learning Research,vol. 7, pp. 1–30, 2006.[18] Holger Hoos, Fachbereich Informatik, Holger H. Hoos,Thomas Stutzle, Thomas Stutzle, Fachgebiet Intellektik,and Fachgebiet Intellektik, “On the run-time behaviorof stochastic local search algorithms for sat,” in In ProceedingsAAAI99, 1999, pp. 661–666.<strong>JP2011</strong>-50


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Ranking <strong>de</strong> listas enlazadas en procesadoresmulticoreHugo María Vegas 1 , Thierry Gautier 2 , Carlos García 3 y Manuel Prieto 4Resumen— En este estudio hemos revisado la implementación<strong>de</strong> algoritmos paralelos para el ranking <strong>de</strong>listas enlazadas en procesadores multicore. Este tipo<strong>de</strong> algoritmos exhibe patrones <strong>de</strong> acceso a memoriafuertemente irregulares que no se benefician <strong>de</strong> losmecanismos agresivos que integran las arquitecturasactuales para ocultar los costosos accesos a memoria(caches, mecanismos <strong>de</strong> prebúsqueda, ...). Debidoa esta característica intrínseca, el rendimiento <strong>de</strong>cualquier algoritmo para el ranking <strong>de</strong> listas esta limitadopor los accesos a memoria no consecutivos. Enlos algoritmos paralelos los problemas <strong>de</strong> rendimientose agravan ya que los patrones <strong>de</strong> acceso irregular suelenprovocar mayor contención por recursos compartidosy por lo tanto, continua siendo un importante<strong>de</strong>safío diseñar algoritmos eficientes para esta aplicación.Tras explorar distintas alternativas, nos hemos centradoen el algoritmo <strong>de</strong> Helman y Jájá. Comoplataforma experimental hemos seleccionado un servidor<strong>de</strong> memoria compartida con dos procesadores IntelWestmere <strong>de</strong> seis cores. Se han analizado dosimplementaciones, una <strong>de</strong> ellas siguiendo el mo<strong>de</strong>lo<strong>de</strong> ejecución convencional fork-join soportado por elestándar OpenMP, y otra que utiliza la librería TBB(Threading Building Blocks) <strong>de</strong> Intel, con la que es posiblerepartir trabajo utilizando work stealing. Comoprincipal aportación mostramos como es posible mejorarla implementación estándar <strong>de</strong> Helman y Jájá reduciendoel número <strong>de</strong> accesos a memoria no consecutivos.<strong>La</strong>s mejoras son notables con ambos mo<strong>de</strong>los,aunque son especialmente significativas para laversión basada en Intel TBB, cuya implementaciónestándar no consigue aceleraciones respecto al algoritmosecuencial.Palabras clave— List Ranking, Helman y Jájá, Algoritmosirregulares, OpenMP, Intel TBB, Workstealing.I. IntroducciónEn este estudio hemos revisado la implementación<strong>de</strong>l algoritmo irregular <strong>de</strong> list ranking en multiprocesadores<strong>de</strong> memoria compartida basados en procesadoresmulticore. Los últimos estudios que se hanpublicado sobre este problema se han realizado utilizandoGPUs como plataforma hardware [1]. Sinembargo, a pesar <strong>de</strong>l auge <strong>de</strong> este tipo <strong>de</strong> aceleradores,el mercado técnico y comercial en el que encajaeste tipo <strong>de</strong> algoritmos irregulares, sigue estandodominado por servidores basados en procesadoresmulticore y es útil una revisión <strong>de</strong> los trabajos previosen sistemas tipo SMP.Después <strong>de</strong> explorar varias alternativas, nos centramosen el algoritmo <strong>de</strong> Helman y JáJá [2].1 Grupo ArTeCS, <strong>Universidad</strong> Complutense <strong>de</strong> Madrid, e-mail: hugovegas@fdi.ucm.es2 INRIA Rennes, IRISA, e-mail:thierry.gautier@inrialpes.fr3 Grupo ArTeCS, <strong>Universidad</strong> Complutense <strong>de</strong> Madrid, e-mail: garsanca@dacya.ucm.es4 Grupo ArTeCS, <strong>Universidad</strong> Complutense <strong>de</strong> Madrid, e-mail: mpmatias@dacya.ucm.esExisten estudios previos sobre dicho algoritmo enmúltiples arquitecturas y con diferentes propósitos[3][2][4][5],[6][7][8]. En multiprocesadores <strong>de</strong> memoriacompartida tipo SMP [4][6], las aceleraciones conseguidashan sido francamente buenas. Sin embargo,nuestros primeros resultados con procesadores multicore<strong>de</strong> la familia Intel Xeon no fueron tan satisfactorios.<strong>La</strong> raíz <strong>de</strong>l problema, que es inherente almismo, y que limita la escalabilidad <strong>de</strong> cualquier algoritmoparalelo <strong>de</strong> list ranking está en la naturalezairregular <strong>de</strong>l mismo. Como propuesta presentamosoptimizaciones que permiten reducir los accesos noconsecutivos a memoria, mejorando <strong>de</strong> este modo lalocalidad espacial, lo que permite alcanzar mayoresaceleraciones.Nuestras implementaciones se han <strong>de</strong>sarrolladocon dos tecnologías <strong>de</strong> paralelización diferentes:OpenMP e Intel TBB. Con la primera exploramos elmo<strong>de</strong>lo <strong>de</strong> ejecución fork-join y las estrategias convencionales<strong>de</strong> paralelización <strong>de</strong> bucles. Con la segundaanalizamos las posibilida<strong>de</strong>s que nos ofrece elparalelismo dinámico basado en tareas [9]. En amboscasos, las mejoras que hemos conseguido respecto a laimplementación estándar <strong>de</strong>l algoritmo, han sido significativas.<strong>La</strong> versión basada en OpenMP es la queconsigue mejores prestaciones frente al algoritmo secuencialpero comparativamente, es la versión basadaen Intel TBB la que más se beneficia <strong>de</strong> nuestraspropuestas.El resto <strong>de</strong>l artículo se compone <strong>de</strong> las siguientessecciones. El problema <strong>de</strong> list ranking y el entornoexperimental utilizado se <strong>de</strong>scriben con más <strong>de</strong>tallesen las secciones II y III respectivamente. <strong>La</strong>s estrategias<strong>de</strong> implementación que mejores resultadosnos han ofrecido se presentan en la sección IV.Losresultados obtenidos se presentan y analizan en lasección V. Finalmente, concluimos en la sección VIcon un resumen e i<strong>de</strong>as <strong>de</strong> trabajo futuro.II. El problema <strong>de</strong> List RankingLos algoritmos utilizados para resolver el problema<strong>de</strong> list ranking son ejemplos muy conocidos <strong>de</strong> algoritmosirregulares cuyas implementaciones paralelaspresentan serias dificulta<strong>de</strong>s para conseguir aceleracionessatisfactorias en los multiprocesadores actuales.Entre otros motivos po<strong>de</strong>mos <strong>de</strong>stacar lossiguientes:• Al igual que ocurre en otros algoritmos <strong>de</strong> naturalezairregular, su escalabilidad está limitadapor patrones <strong>de</strong> acceso a memoria con poca localida<strong>de</strong>spacial y por la existencia <strong>de</strong> <strong>de</strong>pen<strong>de</strong>nciasque sólo pue<strong>de</strong>n revelarse en tiempo <strong>de</strong>ejecución.<strong>JP2011</strong>-51


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011• <strong>La</strong> versión secuencial <strong>de</strong>l algoritmo es extremadamentesimple y aunque también exhibelos problemas <strong>de</strong> localidad espacial inherentes almismo, requiere menos sobrecargas que los algoritmosparalelos.En la Figura 1 ilustramos gráficamente el problema.Dada una lista formada por enlaces arbitrariosalmacenada en un área contigua <strong>de</strong> memoria,se <strong>de</strong>be <strong>de</strong>terminar, para cada nodo <strong>de</strong> la lista,la distancia (número <strong>de</strong> enlaces) que le separa <strong>de</strong>lprimer elemento (nodo cabecera) <strong>de</strong> la misma [10].Dado que los nodos sucesores pue<strong>de</strong>n encontrarse encualquier posición <strong>de</strong>l rango <strong>de</strong> memoria en el quese almacena la lista, el recorrido <strong>de</strong> la misma requiereaccesos a memoria con escasa localidad, queno se benefician <strong>de</strong> los típicos mecanismos agresivosque integran las arquitecturas actuales para reducirlas crecientes latencias <strong>de</strong> acceso a memoria principal(jerarquías <strong>de</strong> memoria agresivas, mecanismos <strong>de</strong>pre-búsqueda hardware, ...).(1)FirstFirstNULL<strong>La</strong> propuesta <strong>de</strong> Helman y Jájá para resolver enparalelo el problema <strong>de</strong> list ranking <strong>de</strong> forma eficientese basa en reducir el tamaño <strong>de</strong> la lista aO( nlog n) nodos usando para ello un número lineal<strong>de</strong> operaciones. El Algoritmo 1 y la Figura 2 <strong>de</strong>scribenla propuesta. Si se asume que el elementocabecera <strong>de</strong> la lista es <strong>de</strong>sconocido (es el caso quehemos consi<strong>de</strong>rado en este trabajo), es necesario unaetapa preliminar que recorre todo el vector en elque se encuantra almacenada la lista, acumulandolos valores nS <strong>de</strong> todos los nodos, ya que se pue<strong>de</strong><strong>de</strong>mostrar que el índice <strong>de</strong>l nodo cabecera viene dadopor 1 2n(n − 1) − Z, don<strong>de</strong> Z es la suma <strong>de</strong> todos losvalores <strong>de</strong> los sucesores nS <strong>de</strong> la lista [2]. Es importante<strong>de</strong>stacar que este primer recorrido <strong>de</strong>l vectorpue<strong>de</strong> hacerse con localidad espacial, sin necesidad<strong>de</strong> recorrer en or<strong>de</strong>n los elementos <strong>de</strong> la lista.Algorithm 1 Algoritmo <strong>de</strong> list ranking <strong>de</strong> Helmany Jáján1: Distribuir la lista <strong>de</strong> entrada enlog nbloques{Bi}, cada uno con O(log n) nodos seleccionandonlog n − 1 divisores.2: Calcular (en paralelo) el rango <strong>de</strong> cada uno <strong>de</strong> losnodos <strong>de</strong>ntro <strong>de</strong> su bloque (rango local) medianteun algoritmo secuencial óptimo.3: Combinar los rangos locales con un algoritmoparalelo con complejidad O(log n).(2)NULLFig. 1. El problema <strong>de</strong>l list ranking para una lista cuyoselementos están almacenados <strong>de</strong> forma or<strong>de</strong>nada en posicionesconsecutivas <strong>de</strong> memoria (1) y para el caso generalen el que los nodos se encuentran en posiciones arbitrarias<strong>de</strong> la misma (2)Existen múltiples variantes <strong>de</strong>l problema enfunción <strong>de</strong>l los tipos <strong>de</strong> datos utilizados. <strong>La</strong> instanciahabitual que suele estudiarse en la mayoría <strong>de</strong>los trabajos asume que la lista L esta representadamediante un vector <strong>de</strong> nodos <strong>de</strong> tamaño n cuyos elementoscontienen al menos los siguientes campos:struct no<strong>de</strong>{in<strong>de</strong>x nS ;in<strong>de</strong>x R;} ;siendo nS el índice <strong>de</strong>l nodo sucesor en el vector Ly R el rango <strong>de</strong>l nodo. Inicialmente pue<strong>de</strong> asumirseque el rango <strong>de</strong> todos los elementos es el mismo exceptopara el último nodo, que pue<strong>de</strong> contener unvalor especial (por ejemplo R = 0 para el primernodo y R = 1 para el resto). Pue<strong>de</strong> asumirse tambiénque para distinguir el final <strong>de</strong> la lista, el sucesor <strong>de</strong>lúltimo nodo toma el valor nS = -n, mientras que parael resto nS es ≥ 0. Por simplicidad y para facilitarcomparaciones con trabajos previos y futuros, estaes también la instancia <strong>de</strong>l problema <strong>de</strong> list rankingque hemos estudiado.En [2] se <strong>de</strong>muestra que en términos <strong>de</strong> complejidad,el algoritmo es “eficiente”: el número <strong>de</strong> operacionesque son necesarias para resolver el problemaes, por encima <strong>de</strong> una constante, el mismo que enel algoritmo secuencial y a<strong>de</strong>más el tiempo paraleloesperado viene dado por O( Tseqp), siendo Tseq eltiempo secuencial.En multiprocesadores <strong>de</strong> memoria compartida,el número <strong>de</strong> divisores suele ser consi<strong>de</strong>rablementemayor que el número <strong>de</strong> hilos <strong>de</strong> ejecucióndisponibles p y la opción habitual <strong>de</strong> implementaciónse muestra en el Algoritmo 2.El algoritmo <strong>de</strong> list ranking <strong>de</strong> Helman y JájáFig. 2.Algoritmo <strong>de</strong> list ranking <strong>de</strong> Helman y Jájá<strong>JP2011</strong>-52


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Algorithm 2 Implementación estándar <strong>de</strong>l algoritmo<strong>de</strong> Helman y Jájá en multiprocesadores <strong>de</strong>memoria compartida1: Recorrer el vector en el que se almacena la listapara acumular en Z los valores <strong>de</strong> nS y conocer elnodo cabecera según la expresión 1 2n(n − 1) − Z.2: Distribuir la lista en nlog n sublistas S i escogiendolos correspondientes divisores3: En paralelo y mientras haya sublistas sin procesador,cada uno <strong>de</strong> los hilos p i disponibles recorre<strong>de</strong> forma secuencial (e in<strong>de</strong>pendientemente <strong>de</strong> losotros hilos), los elementos <strong>de</strong> la sublista S j paracalcular sus rangos locales (los rangos respectoa la cabecera <strong>de</strong> la sublista). Provisionalmente,dichos rangos locales se almacenan en los camposL[i].R.4: Calcular <strong>de</strong> forma secuencial el prefijo <strong>de</strong> cadauna <strong>de</strong> las sublistas. El prefijo <strong>de</strong> cada sublista esel tamaño acumulado <strong>de</strong> las sublistas anteriores,siendo cero para la sublista que incluye al nodocabecera global <strong>de</strong> la lista.5: En paralelo y mientras haya sublistas sin procesador,cada uno <strong>de</strong> los hilos p i disponibles recorre<strong>de</strong> forma secuencial e in<strong>de</strong>pendientemente <strong>de</strong> losotros hilos, los elementos <strong>de</strong> una sublista S j ,añadiendo el correspondiente prefijo S j .pref alos rangos locales, almacenándose el rango finalen L[i].R.III. Entorno Experimental<strong>La</strong>s características <strong>de</strong> la máquina que hemos utilizadopara llevar a cabo nuestros experimentos asícomo el compilador y las opciones <strong>de</strong> optimizaciónutilizadas vienen <strong>de</strong>scritos en la tabla I. Para estudiarel comportamiento <strong>de</strong> las diferentes implementacionesse utilizó la herramienta oprofile, con la quees posible monitorizar los distintos contadores hardware<strong>de</strong>l procesador, y en particular los fallos <strong>de</strong>cache <strong>de</strong> último nivel.Xeon X5670 2 chips (2,93 GHz)Procesadorx 6 coresL1 Cache (per Core) 32KBL2 Unified Cache 256KBL3 Unified Cache 12MBMemoria 48 GB, 32 GB/s, 3xDDR3-1333Sistema Operativo GNU/Linux 2.6.32-5-amd64Compilador -O3 -openmp -std=c++0xIntel icc 11.0Intel TBB Version 3.0ProfilingoprofileAfinidadsched getaffinityTABLA IInformación <strong>de</strong>l entorno experimentalIntel (TBB) [11] es una librería <strong>de</strong>sarrollada porIntel que ofrece la posibilidad <strong>de</strong> expresar paralelismoen programas C++ a programadores con poca experienciaen la programación con hilos. El objetivo esmejorar la productividad <strong>de</strong> los programadores medianteun mo<strong>de</strong>lo en el que el paralelismo pue<strong>de</strong> expresarseen alto nivel mediante la <strong>de</strong>finición <strong>de</strong> tareasque permiten abstraer los <strong>de</strong>talles <strong>de</strong> la plataformaen la que trabajamos. <strong>La</strong> responsabilidad <strong>de</strong> asignartareas a hilos <strong>de</strong> ejecución es transparente al programadory resi<strong>de</strong> en la librería. Adicionalmente soportaparalelismo anidado, permite construir componentesparalelos a partir <strong>de</strong> otros componentes.<strong>La</strong> arquitectura Westmere <strong>de</strong>l procesador XeonX5670 soporta multithreading simultaneo (hyperthreading).En los experimentos hasta 12 hiloshemos fijado los hilos a cores diferentes y por lotanto no se aprovecha esta capacidad. No obstante,para evaluar los beneficios que reporta, se han hechoexperimentos con 24 hilos en los que se aprovechatoda la capacidad <strong>de</strong> la plataforma. Para controlarla afininidad hemos usado la llamada al sistemasched getaffinity.IV. Mejorando la localidad en elalgoritmo <strong>de</strong> Helman y JájáEn esta sección <strong>de</strong>scribimos las dos estrategias quemejores resultados nos han dado para aumentar lalocalidad <strong>de</strong>l algoritmo <strong>de</strong> Helman y Jájá. Ambasestrategias tratan <strong>de</strong> minimizar los accesos a posiciones<strong>de</strong> memoria no adyacentes, ya que éste es elproblema más serio (en términos <strong>de</strong> rendimiento) quepresenta este algoritmo. De hecho, los propios autoresen [2], presentan un mo<strong>de</strong>lo <strong>de</strong> memoria quetiene en cuenta el coste <strong>de</strong> acce<strong>de</strong>r a posiciones noconsecutivas en memoria con el que <strong>de</strong>rivan los tiempos<strong>de</strong> ejecución esperados.1. SLIn<strong>de</strong>x: Durante el proceso <strong>de</strong> cálculo <strong>de</strong> losrangos locales (etapa 2 <strong>de</strong>l Algoritmo 2), paracada nodo <strong>de</strong> la lista se registra en un arrayauxiliar (sLin<strong>de</strong>x) el índice <strong>de</strong> la sublista en laque esta incluido. Guardando esta información,es posible transformar la etapa 4 <strong>de</strong>l Algoritmo 2para que los accesos a la lista sean con localida<strong>de</strong>spacial. En este caso, cada hilo pi, en lugar <strong>de</strong>recorrer varias sublistas, actualiza el rango <strong>de</strong>los nodos consecutivos con índice global [ib, (i+ 1)b) con:L [ i ] . R += S [ sLin<strong>de</strong>x [ i ] ] . pR ;Con esta transformación se pue<strong>de</strong> acce<strong>de</strong>r <strong>de</strong>forma consecutiva a la lista L. A<strong>de</strong>más, el arrayS en el que se guarda la información <strong>de</strong> lasdiferentes sublistas estará almacenado en lacache con gran probabilidad ya que inclusopara listas gran<strong>de</strong>s, el número <strong>de</strong> sublistas esrelativamente pequeño. Como contrapartida,esta implementación requiere un vector adicional(sLin<strong>de</strong>x) para almacenar los ids <strong>de</strong> lassublistas y se aumentan los accesos totales.2. Rango acumulado: Actualizar provisionalmenteel rango local en la etapa 2 <strong>de</strong>l Algoritmo2 implica n escrituras no consecutivas en L[i].R.En la etapa 4, este valor vuelve a actualizarse.<strong>La</strong>s escrituras <strong>de</strong> la etapa 2 pue<strong>de</strong> eliminarse <strong>de</strong>lsiguiente modo:<strong>JP2011</strong>-53


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011(a) Etapa 2: para cada sublista, el hilo correspondienterecorre sus nodos y <strong>de</strong>vuelveúnicamente el último rango local acumulado,sin salvar en L[i].R el valor local <strong>de</strong> cadauno <strong>de</strong> sus nodos.(b) Etapa 3: sin cambios. Los prefijos <strong>de</strong> cadasublista se almacenan en sL[j].pR(c) Etapa 4: en lugar <strong>de</strong> actualizar los rangosprovisionales, se calcula directamente el rangosglobal <strong>de</strong> cada uno <strong>de</strong> los nodos a partir<strong>de</strong>l rango <strong>de</strong>l nodo pre<strong>de</strong>cesor en la correspondientesublista según:L[i].R = sL[j].pR + L[pred(i)].R + 1De esta manera, eliminamos la necesidad <strong>de</strong> realizarlas n escrituras no contiguas en la segundaetapa y las n lecturas no contiguas en la cuartaetapa.V. ResultadosA. Impacto <strong>de</strong> la localidadEn primer lugar hemos evaluado cual es el impacto<strong>de</strong> la localidad en el rendimiento final. En la Figura3 ilustramos como varía el tiempo <strong>de</strong> ejecución en laversión secuencial <strong>de</strong>l algoritmo (un único recorrido<strong>de</strong> la lista siguiendo los índices <strong>de</strong> los nodos sucesores)en función <strong>de</strong> como están emplazados los nodos<strong>de</strong> lista en memoria. Cuando los nodos adyacentesestán almacenados en posiciones consecutivas (listasor<strong>de</strong>nadas), el tiempo <strong>de</strong> ejecución es un or<strong>de</strong>n <strong>de</strong>magnitud inferior que cuando los nodos están localizadosen posiciones arbitrarias (listas aleatorias).Fig. 4.Fallos <strong>de</strong> L3 (miles) con listas or<strong>de</strong>nadas y aleatoriascon OpenMP para distintos tamaños <strong>de</strong> lista y <strong>de</strong>número <strong>de</strong> hilos (THS):Fig. 5. Variación <strong>de</strong>l tiempo <strong>de</strong> ejecución con el número <strong>de</strong>divisores para listas <strong>de</strong> 1 millón <strong>de</strong> nodos usando OpenMPFig. 3. Tiempos <strong>de</strong> ejecución <strong>de</strong>l algoritmo secuencial paralistas or<strong>de</strong>nadas y aleatoriasLos resultados <strong>de</strong> la Figura 4 ponen <strong>de</strong> manifiestola causa <strong>de</strong> esta variación. El número <strong>de</strong> fallos <strong>de</strong>cache <strong>de</strong> último nivel es muy inferior para listas or<strong>de</strong>nadas.Actualizar GraficaB. Elección <strong>de</strong>l número <strong>de</strong> divisoresUn aspecto importante <strong>de</strong>l algoritmo <strong>de</strong> Helman yJájá es la elección <strong>de</strong>l número <strong>de</strong> sublistas necesariaspara alcanzar los tiempos <strong>de</strong> ejecución óptimos. Losautores postularon que el tamaño <strong>de</strong> sublista óptimonlog nes <strong>de</strong>l or<strong>de</strong>n <strong>de</strong> , siendo n el tamaño <strong>de</strong> la listaglobal. En las Figuras 5 y 6 exploramos la variación<strong>de</strong>l tiempo <strong>de</strong> ejecución con el número <strong>de</strong> divisorespara la implementación estándar (los resultadosson similares para las otras versiones) <strong>de</strong>l algoritmoFig. 6. Variación <strong>de</strong>l tiempo <strong>de</strong> ejecución con el número<strong>de</strong> divisores para listas <strong>de</strong> 64 millones <strong>de</strong> nodos usandoOpenMPCon Intel TBB el comportamiento es similar (Figuras7 y 8).En <strong>de</strong>finitiva, los resultados obtenidos validan laestimación <strong>de</strong> Helman y Jájá. No obstante, el rango<strong>de</strong> valores óptimos es bastante amplio pudiendo trabajarcon una cantidad <strong>de</strong> posibles divisores válidosmucho mayor. Los resultados que mostramos enel resto <strong>de</strong>l artículo correspon<strong>de</strong>n siempre a valoresobtenidos con número <strong>de</strong> divisores óptimos.C. Ganancias <strong>de</strong> la implementación estándar<strong>La</strong>s Figuras 9 y 10 muestran las ganancias respectoal algoritmo secuencial que se obtienen con la implementaciónestándar <strong>de</strong>l algoritmo <strong>de</strong> Helman yJájá utilizando OpenMP y la librería Intel TBB res-<strong>JP2011</strong>-54


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 7. Variación <strong>de</strong>l tiempo <strong>de</strong> ejecución con el número <strong>de</strong>divisores para listas <strong>de</strong> 1 millón <strong>de</strong> nodos usando IntelTBBFig. 9. Ganancias <strong>de</strong> la implementación estándar <strong>de</strong>l algoritmo<strong>de</strong> Helman y Jájá con listas aleatorias utilizandoOpenMPFig. 8. Variación <strong>de</strong>l tiempo <strong>de</strong> ejecución con el número <strong>de</strong>divisores para listas <strong>de</strong> 64 millones <strong>de</strong> nodos usando IntelTBBpectivamente. <strong>La</strong> paralelización con OpenMP establecedos zonas paralelas con #pragma omp parallelfor, una para la etapa <strong>de</strong> cálculo <strong>de</strong> los rangoslocales y otra para la fase final <strong>de</strong> cálculo <strong>de</strong>los rangos globales. En función <strong>de</strong>l número <strong>de</strong> divisoresque se hayan seleccionado, las correspondientessublistas se distribuyen entre los hilos disponiblesdinámicamente. Se han explorado varias alternativas,pero en la Figura 9 sólo se indica los resultadosobtenidos utilizando la mejor granularidad (sedistribuyen sublistas individuales). En la versiónIntelTBB la manera <strong>de</strong> expresar el paralelismo essimilar con la primitiva parallel for(), aunque la notaciónes diferente ya que se utilizan expresiones<strong>La</strong>mbda [12] que mejoran la expresividad. Al igualque OpenMP pue<strong>de</strong> fijarse una granularidad para ladistribución, obteniéndose también los mejores resultadosdistribuyendo sublistas individuales.Con OpenMP las ganancias son razonables.Usando hyperthreading se consiguen ciertos beneficiosadicionales – comparando los tiempos <strong>de</strong> ejecuciónutilizando 12 y 24 hilos, las mejoras oscilanentre un 11% y un 14% –, aunque inferiores a losvalores reportados en otras aplicaciones en este tipo<strong>de</strong> arquitectura. Es evi<strong>de</strong>nte que la competencia entrehilos <strong>de</strong>ntro <strong>de</strong> un mismo core pue<strong>de</strong> <strong>de</strong>gradarel rendimiento al ejercerse una fuerte presión en lajerarquía <strong>de</strong> memoria.Con Intel TBB sin embargo, los resultados sonfrancamente malos y en el mejor <strong>de</strong> los casos solopo<strong>de</strong>mos aproximarnos al tiempo secuencial.Fig. 10. Ganancias <strong>de</strong> la implementación estándar <strong>de</strong>l algoritmo<strong>de</strong> Helman y Jájá con listas aleatorias utilizando lalibrería Intel TBBD. Ganancias <strong>de</strong> la implementaciones SLIn<strong>de</strong>x yRango Acumulado<strong>La</strong>s Figuras 11 y 12 muestran las ganancias que seobtienen con las implementaciones SLIn<strong>de</strong>x y RangoAcumulado utilizando OpenMP. <strong>La</strong> versión SLIn<strong>de</strong>xes la que consigue mejores resultados y para listasgran<strong>de</strong>s supera a la implementación estándar entreun 20% y un 40%. Ambas versiones se benefician<strong>de</strong>l hyperthreading, aunque el beneficio porcentual esmayor con Rango Acumulado.Utilizando la librería Intel TBB, los resultados sonequivalentes, es <strong>de</strong>cir SLIn<strong>de</strong>x es también la mejoropción. Pero a<strong>de</strong>más, como se muestra en la Figura13), las ganancias si son ahora más razonables y sepue<strong>de</strong> superar al algoritmo secuencial. No obstante,siguen siendo mejores los resultados con OpenMP.Fig. 11. Ganancias <strong>de</strong> la implementación SLIn<strong>de</strong>x <strong>de</strong>l algoritmo<strong>de</strong> Helman y Jájá con listas aleatorias utilizandoOpenMP<strong>JP2011</strong>-55


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>de</strong> accesos a memoria y existen compromisos que esinteresante analizar. También preten<strong>de</strong>mos exten<strong>de</strong>rel estudio a sistemas <strong>de</strong> mayor escala y analizar losposibles beneficios que podrían conseguirse en sistemasheterogéneos.Agra<strong>de</strong>cimientosEl presente trabajo ha sido financiado por losproyectos TIN2008-00508 e Ingenio 2010 Consoli<strong>de</strong>rESP00C-07-20811.Fig. 12. Ganancias <strong>de</strong> la implementación Rango acumulado<strong>de</strong>l algoritmo <strong>de</strong> Helman y Jájá con listas aleatorias utilizandoOpenMPFig. 13.SpeedUps para listas <strong>de</strong>sor<strong>de</strong>nadas usando TBBVI. ConclusionesEn este trabajo hemos explorado distintas optimizacionesque permiten mejorar el rendimiento <strong>de</strong>lalgoritmo <strong>de</strong> Helman y Jájá en sistemas multicore.De las distintas alternativas analizadas los mejoresresultados se han obtenido con la versión que <strong>de</strong>nominamosSLIn<strong>de</strong>x. Con esta versión se consiguenreducir los accesos no consecutivos a memoria en laetapa final <strong>de</strong>l algoritmo, a cambio <strong>de</strong> añadir un vectoradicional y las correspondientes escrituras y lecturasadicionales a dicho vector. Se ha comprobadoque la elección <strong>de</strong>l número <strong>de</strong> divisores es fundamentalpara conseguir tiempos <strong>de</strong> ejecución óptimos yque las estimaciones <strong>de</strong> Helman y Jájá son validas,aunque el rango <strong>de</strong> divisores óptimo es bastante másamplio. Los mejores resultados se han obtenido siempreutilizando OpenMP. De hecho, el rendimiento<strong>de</strong> la implementación directa <strong>de</strong>l algoritmo con IntelTBB es especialmente pobre y no consigue batir nia la implementación secuencial. Con las optimizacionespropuestas si se ha conseguido que las versionescon Intel TBB obtengan unos resultados razonables.Habilitando hyperthreading se consiguenbeneficios adicionales (entre un 10% y un 20%), perobastante inferiores a los que se consiguen en otrasaplicaciones.Como trabajo futuro preten<strong>de</strong>mos analizar cual esla mejor opción teniendo en cuenta los compromisosconsumo/rendimiento. Intuitivamente, reducir eltiempo <strong>de</strong> ejecución lleva asociado una reducción <strong>de</strong>lconsumo <strong>de</strong>bido al componente estático <strong>de</strong>l mismo,pero las diferentes alternativas varían en el númeroReferencias[1] M. Suhail Rehman, Kishore Kothapalli, and P. J.Narayanan, “Fast and scalable list ranking on the GPU,”in ICS ’09: Proceedings of the 23rd international conferenceon Supercomputing, New York, NY, USA, 2009, pp.235–243, ACM.[2] David R. Helman and Joseph JáJá, “Designing practicalefficient algorithms for symmetric multiprocessors,” inSelected papers from the International Workshop on AlgorithmEngineering and Experimentation, London, UK,1999, ALENEX ’99, pp. 37–56, Springer-Verlag.[3] Margaret Reid-Miller, “List ranking and list scan on thecray c-90,” in Proceedings of the sixth annual ACM symposiumon Parallel algorithms and architectures, NewYork, NY, USA, 1994, SPAA ’94, pp. 104–113, ACM.[4] David A. Ba<strong>de</strong>r, Sukanya Sreshta, and Nina R. Weisse-Bernstein, “Evaluating arithmetic expressions using treecontraction: A fast and scalable parallel implementationfor symmetric multiprocessors (smps) (exten<strong>de</strong>d abstract),”in Proceedings of the 9th International Conferenceon High Performance Computing, London, UK,UK, 2002, HiPC ’02, pp. 63–78, Springer-Verlag.[5] Isabelle Guérin <strong>La</strong>ssous and Jens Gustedt, “Portable listranking: an experimental study,” J. Exp. Algorithmics,vol. 7, pp. 7–, December 2002.[6] David A. Ba<strong>de</strong>r and Guojing Cong, “A fast, parallelspanning tree algorithm for symmetric multiprocessors(smps),” J. Parallel Distrib. Comput., vol. 65, pp. 994–1006, September 2005.[7] David A. Ba<strong>de</strong>r, Guojing Cong, and John Feo, “Onthe architectural requirements for efficient execution ofgraph algorithms,” in Proceedings of the 2005 InternationalConference on Parallel Processing, Washington,DC, USA, 2005, pp. 547–556, IEEE Computer Society.[8] David A. Ba<strong>de</strong>r, Guojing Cong, and John Feo, “Onthe architectural requirements for efficient execution ofgraph algorithms,” in Proceedings of the 2005 InternationalConference on Parallel Processing, Washington,DC, USA, 2005, pp. 547–556, IEEE Computer Society.[9] Robert D. Blumofe, Christopher F. Joerg, Bradley C.Kuszmaul, Charles E. Leiserson, Keith H. Randall, andYuli Zhou, “Cilk: An efficient multithrea<strong>de</strong>d runtimesystem,” in Journal Of Parallel And Distributed Computing,1995, pp. 207–216.[10] Richard J. An<strong>de</strong>rson and Gary L. Miller, “A simple randomizedparallel algorithm for list-ranking,” InformationProcessing Letters, vol. 33, no. 5, pp. 269–273, January1990.[11] James Rein<strong>de</strong>rs, Intel threading building blocks; outfittingC++ for multi-core processor parallelism, O’ReillyMedia, July 2007.[12] James Rein<strong>de</strong>rs, “Parallel for is easier with lambdas,”Disponible online en software.intel.com/enus/blogs/author/james-rein<strong>de</strong>rs/,August 2009.<strong>JP2011</strong>-56


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Parallelizing Biblio-MetReS, a data mining toolOussama Ab<strong>de</strong>lli 1 , Anabel Usié 1,2 , Hiren Karathia 2 , Jordi Vilaplana 1 , Francesc Solsona 1 and Rui Alves 2Abstract—Biblio-MetReS is a single-thread data miningapplication that facilitates the reconstruction ofbiomolecular networks based on automated text miningand analysis of published scientific literature. Thisapplication is very CPU-intensive and, due to the amountof execution tasks, it can be quite slow. Those tasks arerepetitive, and consist in mining the information fromlarge sets of scientific documents, a situation where thetime performance of the application could be improvedthrough paralellization. This paper presents an applicationthat paralelizes Biblio-MetReS. The multithreadingapplication P(aralell)-Biblio-MetReS, splits the workamong copies of the same Java class, each mining acollection of documents obtained in a previous searchphase from different literature sources of Internet.Through this article, we bring to light the performance andscalability topics of multithrea<strong>de</strong>d Java applications onmulti-threading systems in the context of this application.Experimental results corroborate the good performance ofP-Biblio-MetReS, pinpointing specific aspects that stillneed to be improved.In<strong>de</strong>x terms—Multithreading, Scalability, parallelization,pathway reconstruction, data mining.RI. INTRODUCTIONeconstructing molecular networks that areresponsible for regulating biological processes is afundamental task in molecular biology [11]. In recentyears many alternative methods have been proposed toachieve such a reconstruction [1, 2]. One type of methodrelies on the automated analysis of published scientificliterature that is available in public databases over theInternet to i<strong>de</strong>ntify genes and proteins that co-occur inthe same document(s) [3-10].Given the large number of available documents(inclu<strong>de</strong>d in web pages, databases, journals, etc), it isimpossible for one person to mine all the availableinformation in or<strong>de</strong>r to reconstruct networks and circuitsof interest. This justifies the need for a tool such asBiblio-MetReS [14], a data mining application forreconstructing gene/protein networks.Biblio-MetReS is a user-friendly tool implemented inJava, which does on-the-fly analyses of full textscientific documents that are freely available on theInternet, and uses that analysis for automatedreconstruction of literature gene/protein networks. Indoing so, it i<strong>de</strong>ntifies if genes co-occur in sentences,paragraphs and/or documents. Results showing theobtained networks are <strong>de</strong>picted in both, graphical andtabular form.1 Dept. d’Informàtica i Enginyeria Industrial, Av. Jaume II 32, 25001Lleida, Universitat <strong>de</strong> Lleida (UdL), Spain. e-mails:{ab<strong>de</strong>lli.oussama3@gmail.com, jvilaplana@alumnes.udl.cat,francesc@diei.udl.cat}2 Dept <strong>de</strong> Ciències Mediques Bàsiques & Institut <strong>de</strong> RecercaBiomèdica <strong>de</strong> Lleida (IRBLleida), Montserrat Roig 2, 25008 Lleida,Universitat <strong>de</strong> Lleida (UdL), Spain. e-mails: {ausie@diei.udl.cat,hiren@cmb.udl.cat, ralves@cmb.udl.cat}The on-the-fly feature of Biblio-MetReS permits theaccess to a wi<strong>de</strong> range of documents that is always up todate. This is an advantage with respect to other wellknown data mining tools (iHOP [3], STRING[4,5] and<strong>La</strong>itor [6]), which only have access to pre-processed listsof documents, saved in a precompiled database. Themain drawback of Biblio-MetReS is the elevate<strong>de</strong>xecution time of a reconstruction in Biblio-MetReSwhen compared to applications that pre-process thedocuments.There are two strategies to improve this executiontime. First, one can combine on-the-fly analysis of newdocuments with pre-processed analysis of documentsthat have already been previously mined. This is astrategy that is already being pursued. Second, and dueto the nature of the processes in Biblio-MetReS, it islikely that parallelization of the application willsignificantly improve the on-the-fly processing time.Thus, the main goal of this work is to start theimplementation of the second strategy and reduce theserial execution time of network reconstruction inBiblio-MetReS.Parallel computing is a form of computation in whichmany calculations are carried out simultaneously,operating on the principle that large problems can oftenbe divi<strong>de</strong>d into smaller ones, which are then solvedconcurrently ("in parallel"). Parallelism has beenemployed for many years in computer programs, mainlyin high-performance computing. Interest in this strategyhas grown lately due to many factors, such as theincreasing number of multiprocessing computers, theemergence of cloud computing, and the physicalconstraints preventing frequency scaling of serialcomputations.Parallel computer programs are more difficult to writethan sequential ones, because concurrency introducesseveral new classes of potential software bugs, of whichrace conditions are the most common. Communicationand synchronization between the different subtasks aretypically one of the greatest obstacles to getting goodparallel program performance.There are no conceptual differences between a Javaprogram running on a machine with one processor andthe same program running in a machine with two ormore processors; the threads behave exactly the same inboth cases. However, the key difference between singleprocessorand multiprocessor systems is that the first canonly run one thread at a time while the latter cansimultaneously run multiple threads. A workstation canhave multiple, multicore, processors. In this case,several threads can simultaneously be distributed amongthe many processors, and, within each processor, amongthe different cores, that can also be multithreading. Forexample a bi-processor machine with four two-threadingcores can execute an amount of 16 threads in parallel.From now on, we simply refer the multithreadingmachines, without distinguishing what type ofmultithreading that machine can do.<strong>JP2011</strong>-57


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011There are several different forms of parallelcomputing: bit-level, instruction level, data, andfunctional parallelism. In this work, we mainly exploreddata parallelism.As power consumption (and consequently heatgeneration) by computers has become a concern inrecent years, parallel computing has become thedominant paradigm in computer architecture, mainly inthe form of cluster, grid and multi-core processors. Inthis work we explore the latest, also calledmultiprocessor systems.Our challenge is to profit as much as possible thefeatures of multithreading computers in the execution ofP-Biblio-MetReS, the parallel version of Biblio-MetReS. P-Biblo-MetReS follows a data parallelphilosophy, that is, multiple copies of the same functionprocesses different input data.This paper presents the first results of thisparallelization. Section II introduces the Biblio-MetReSmo<strong>de</strong> of operation and its main features. Section III andIV explains the <strong>de</strong>sign and implementation <strong>de</strong>cisions ofP-Biblio-MetReS respectively. A comparison of thecomputational aspects of P-Biblio-MetReS with respectto its serial version is presented and analyzed in sectionV. Finally, section VI presents the conclusions of theanalysis, and section VII discusses future work.Fig. 1. Flowchart of Biblo-MetReS.II. BIBLIO-METRESBiblio-MetReS was implemented in JAVA. Itsworkings are explained in the following (see Fig. 1).First of all, users must register to login into Biblio-MetReS (Fig. 1.1). Next (Fig. 1.2), users must choose anorganism to work with. The application loads all genesfrom this organism that are present in the centraldatabase that contains lists of all annotated genes oforganisms with fully sequenced genomes. The databaseof gene names was built by matching the KEGG [12]gene names to their NCBI [13] names and synonyms.Once the loading is finished, the user is presented withthe main window (see Fig. 1.3), where s/he has to selectthe data sources as well as the genes to be analyzed. Thedata sources are (see Fig. 1 for a <strong>de</strong>tailed list): GeneralEngines (Yahoo, Live Search, Altavista, etc.), LiteratureDatabase (Medline, Pubmed, Biomed Central, etc.) andJournals (Nature, Science, etc.).Once the choices are ma<strong>de</strong> and the search is started,the tool i<strong>de</strong>ntifies and downloads the documents thatcontain the gene names and its synonyms from theselected data sources.Then, Biblio-MetReS parses each document, andanalyses the co-occurrence of genes by i<strong>de</strong>ntifying theoccurrence in the text of genes that are present in thedatabase. The parsing results are represented as twographs. One of the graphs presents the co-occurrence ofgenes in sentences (Fig. 1.4A) and the other representsthe co-occurrence of genes in paragraphs and documents<strong>JP2011</strong>-58


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011(Fig. 1.4B). Biblio-MetReS implements parsers forHTM, PDF and ASCII documents.Each no<strong>de</strong> or vertex in the graphs is a gene/proteinand each edge refers to an instance of co-occurrencebetween different genes in sentences, paragraphs, ordocuments. The thickness of the edge is proportional tothe mutual information between two genes and the colorof the edge is proportional to a p-value that measureshow much more enriched is the co-occurrence betweentwo genes in sentences or paragraphs with respect todocuments. See [14] for more <strong>de</strong>tails.The whole process <strong>de</strong>scribed above is done on the fly.The serial time in executing all the Biblio-MetReSprocesses can be very high, and it would strongly benefitfrom parallelization.III. P-BIBLIO-METRESIn this section we <strong>de</strong>scribe the main <strong>de</strong>cisions taken inthe <strong>de</strong>sign of the parallel version of Biblio-MetReS, P-Biblio-MetReS.As was pointed out in the Introduction, there areseveral forms of parallel computing: bit-level,instruction level, data, and functional parallelism.Biblio-MetReS is written in a high-level language, Java.Parallelization in the bit or instruction level will bealmost impossible. Instead, parallelism was performedin an upper level, at the Java co<strong>de</strong>.As P-Bilbio-MetReS is <strong>de</strong>signed to be executed on amultithreading machine, the following aspects must betaken into account:• We cannot assume that any running thread has thehighest priority. A higher-priority thread may berunning on a different processor.• We cannot assume that a low-priority thread willnot run. There may be enough processors to give ita chance at execution.• We cannot assume that threads of differentpriorities will not be running at the same time.• We cannot assume that a given race conditions canbe ignored, just because it is unlikely to occur. Raceconditions in a multiprocessor system present a realproblem, whereas race conditions in a singleprocessorsystem are more <strong>de</strong>pen<strong>de</strong>nt on thescheduling engine of the Java virtual machine.Taking these issues into account, the key question ofthe parallelization problem at hand is a) thei<strong>de</strong>ntification of the Java co<strong>de</strong> to be executed in paralleland b) implementing this co<strong>de</strong> in one class (or object)that can be run in multiple threads. Multiple threads arecreated, one for each copy of the object, and then theyare executed in parallel. As all the threads are executedin the same machine, our parallel implementationrequires <strong>de</strong>fining an optimal multithreading policy.Without re<strong>de</strong>signing a program, the parts of the co<strong>de</strong>whose execution is most likely to benefit fromparallelization are those where the application is CPUbound - that is, the sets of instructions where theprogram is mainly using processing cycles, and at thesame time E/S resources (network and secondarystorage) are idle -.We discard the parallelization of E/S parts of co<strong>de</strong>because Biblio-MetReS does not <strong>de</strong>al with an amount ofinformation that makes it necessary to increase the speedof access to the secondary storage. If we would want toincrease the network bandwidth, P-Biblio-MetReS couldalso be simultaneously executed in different machines,each with an individual IP. Distributed environments(for example Grid, Volunteer, Cloud or P2P computing)could be consi<strong>de</strong>red for such an execution.Thus, first and foremost, we are interested in<strong>de</strong>termining the CPU bound objects in Biblio-MetReS.By taking into account the class architecture of Biblio-MetReS (see Fig. 2), we i<strong>de</strong>ntified the objects where a)documents are obtained from different data sources, andb) the parsing of those documents is ma<strong>de</strong> as thosewhere the application is CPU-boun<strong>de</strong>d. These objectsare thus the natural candidates to be executedconcurrently in multiple threads.Fig. 2. Class diagram representing relationships betweenclasses used in the parallelization.Second, we must also consi<strong>de</strong>r that there is no reasonto execute the serial program ‘Biblio-MetReS’ CPUboundobjects in parallel if, during its run, the programdoes not use 100% of the available single physicalthreads. We should control for this possibility whenchoosing a parallelization policy to execute P-Biblio-MetReS.Third, we are interested in getting the appropriatenumber of threads to be created and executed in parallel,so that an optimal run time is obtained. More precisely,we are interested in un<strong>de</strong>rstanding the relationshipbetween the available processing power (the number ofhardware threads) and the number of logical threads wecan create at once in or<strong>de</strong>r to i<strong>de</strong>ntify the ratio R optimalbetween the two quantities that optimizes execution timeof the program. I<strong>de</strong>ntifying this ratio will allow us tocreate an application that scales well.Because there is, to our knowledge, no systematicmethod to i<strong>de</strong>ntify R optimal , we test three heuristicpolicies to <strong>de</strong>termine which of these gives the bestperformance:1. The first method (S1) consists in creating a threadfor every search engine. Each thread handles thelinks returned by the search engine. Then, it parsesthe returned documents. The various threads are<strong>JP2011</strong>-59


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011properly synchronized. Once all the results havebeen collected and processed, information about theco-occurrence of genes is obtained, as well as thecreation of graphs that illustrate the variousrelations between them.2. In the second method (S2), each thread that iscreated parses a number of documents given by theratio between the total number of documents andthe number of physical threads.3. In the third method (S3), the parsing of documentsis divi<strong>de</strong>d into synchronized subphases. In eachsubphase, P-Biblio-MeteS creates as many localthreads as physical threads in the system. Eachthread is assigned with one document to beprocessed. This process continues until the overalldocuments are processed.In our case, P-Biblio-MetReS scaling <strong>de</strong>pends onmany factors: the operating system, the Java virtualmachine implementation, the application server, the Javaengine of the virtual machine and the Java applicationitself. We will analyse this in <strong>de</strong>pth in the next section.The procedure for creating threads based on theRunnable interface is as follows:• The RunnableDistributer class implements therunnable interface, providing the run() methodthat will be executed by the thread. This methodcontains the main task that we are executing. Inour case the run method launches the procedure ofparsing documents and returns the results of theanalysis.• We create an object of the Thread class by passingan instance of the class RunnableDistributer asargument to the Thread constructor. The Threadobject now has a Runnable object that implementsthe run() method.• To begin the execution of the thread, we call themethod start(). This method allows the JavaVirtual Machine to call the run method of thethread.V. EXPERIMENTAL RESULTSIV. IMPLEMENTATIONIn this section, the methodologies used inimplementing P-BiblioMetReS are <strong>de</strong>scribed.P-Biblio-MetReS is implemented in Java. Every threadin Java is created and controlled by the java.lang.Threadclass. A Java program can have many threads, and thesethreads can run concurrently, either synchronously orasynchronously.There are two ways to create threads in java. One is byimplementing the Runnable interface provi<strong>de</strong>d by thepackage java.lang.Runnable. The other is by Extendingthe Thread class <strong>de</strong>fined in java.lang.Thread. (seefugure 3)Fig. 3. Classes and methods in the creation of a thread.We implemented the interface java.lang.Runnablebecause it allows for multiple inheritance. This enablessimultaneous creation of threads and facilitates theirmanagement.The experiments have been carried out on a serverwith eight cores and 16GB of Memory (machine 8c), alaptop with a CPU Intel i7 with 4 cores (machine 4c)and 6GB of Memory, and finally a laptop with 2 coresand 4GB of Memory (machine 2c). Windows 7 x64 isused as an OS. In or<strong>de</strong>r to avoid miscellaneous influenceskewing the results, the single user mo<strong>de</strong> of OS is used.We have chosen the organism Saccharomyces cerevisiae(budding yeast) to perform our experiments. Theseexperiments consist in reconstructing the network ofgenes that co-occur with the genes FBA1, PGM1,CDC19, which are involved in glycolysis.Concerning the first series of experiments (1), Fig. 4shows the run time of the serial execution of Biblio-MetReS, when executed in just a single threa<strong>de</strong>d mannerin a single core laptop with 2GB of Memory. Fig. 5shows the comparable results for running theparallelized P-Biblio-MetReS, following strategy S1 andcreating a thread for every search engine. This run usedthe 2c machine. A comparison of the two figures showsthat the parallel version obtains mo<strong>de</strong>rate gains. This islikely to be due to the fact that each search enginereturns a different number of documents, which areanalyzed in serial manner within that search engines’<strong>de</strong>dicated thread. Thus, the search engine with theslowest processing time would dominate run time andcause run-time differences between the serial andparallel versions of the program to be smaller than theycould. Nevertheless, further analysis is required to betterun<strong>de</strong>rstand these results.The second series of experiments implement P-Biblio-MetReS using the two remaining strategies <strong>de</strong>scribedabove (S2 and S3). Results are shown in Figs 6, 7, and8.One immediate inference that can be drawn is that theoptimal runtime <strong>de</strong>pends on the number of threads anddocuments, in<strong>de</strong>pen<strong>de</strong>ntly on the Internet sources used.Above an amount of documents to be parsed, beyond the<strong>JP2011</strong>-60


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Main Memory limit, the performance <strong>de</strong>creased in allthe situations (by varying the Internet sources).Fig. 4. Time of execution in single threa<strong>de</strong>d.Fig. 7. Execution times for Biomed Central,Cell and Systems Biology.Fig 5. Time of execution in multi-threa<strong>de</strong>d.The key objective is the finding for the optimalnumber of threads that returns as many documents aspossible that fits in Main Memory. It can be seen in theexperiments as there is an optimal range for the numberof threads that can be launched. This optimal range wasbetween 8 and 16 threads, with 16 being the number ofthreads that provi<strong>de</strong>d the fastest runtime in mostexperiments. However, this range of optimality wasalmost flat and differences in runtime using a number ofthreads between 8 and 16 were small.Fig. 8. Execution times for Lycos, Ask andPubmed.Fig. 9. Comparison of execution times between theserial version and the parallel one.Fig. 6. Times for Medline (Database)In other experiment we compare the results obtained inFig. 8 with 16 threads with those for the serial version ofBiblio-MetReS. The gains in run-time by P-Biblio-MetRes with respect to Biblio-MetReS are significant(Fig. 9).Finally, we analyzed the effect of Memory usage onrun-time by varying the number of search enginesbetween 5 and 20,while using policy S3. The number ofdocuments was very high and increased rapidly with thenumber of search engines. The results are shown in Fig.10. At a given point, the increasing in the number ofsearch engines led to the creation of a number of threadsthat was too high. The application ran into out ofmemory errors and crashed, making it clear that it isnecessary to consi<strong>de</strong>r hardware memory specifications<strong>JP2011</strong>-61


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011to limit the number of threads that can be created inpolicy S3. Thus, policy S3 must be re<strong>de</strong>signed.Fig. 10. Execution times incrementing the number ofsearching engines.VI. CONCLUSIONSThe essential objective of this study was to <strong>de</strong>creasethe run time of the application Biblio-MetReS byparallelizing the parsing and analysis of the documentsby the application. In doing so, we wanted to establish astrategy that would be close to optimal in creating thea<strong>de</strong>quate number of threads for <strong>de</strong>creasing the run timeof the application. Our preliminary results suggest that astrategy that fairly divi<strong>de</strong>s the number of documents tobe analyzed by the number of physical hardware threadsthat are available in the machine is, in most cases, thebest policy.VII. FUTURE WORKWe are now planning the <strong>de</strong>sign of new efficientscheduling algorithms to distribute the parser phasebetween cores of one no<strong>de</strong>. Once this is accomplished,we will consi<strong>de</strong>r clusters of workstations. In doing so,we want to classify documents according to their types(pdf, text or HTML) and sizes. Then scheduling<strong>de</strong>cisions will try to balance the load between thethreads assigned to the cores according to such aclassification.Future challenges will go in the direction of alsoparallelize the search phase, which is another step that ishighly amenable to parallelization. We will analyze thebest policy for distributing the bandwidth worldwi<strong>de</strong>between no<strong>de</strong>s located in Internet.ACKNOWLEDGEMENTSThis work was supported by the MEyC-Spain un<strong>de</strong>rcontracts BFU2007-62772/BMC, BFU2010-17704,TIN2008-05913 and CSD-2007-00050, by Generalitat<strong>de</strong> Catalunya, through research groups 2009SGR809 and2009SGR145 and the CUR of DIUE of GENCAT, andby the European Social Fund.REFERENCES1. Alves R, Sorribas A: In silico pathwayreconstruction: Iron-sulfur cluster biogenesis inSaccharomyces cerevisiae. BMC Syst Biol 2007,1:10.2. Markowetz F, Spang R: Inferring cellular networks--a review. BMC Bioinformatics 2007, 8 Suppl 6:S5.3. Hoffmann R, Valencia A: Implementing the iHOPconcept for navigation of biomedical literature.Bioinformatics 2005, 21 Suppl 2:ii252-258.4. Hoffmann R, Valencia A: A gene network fornavigating the literature. Nat Genet 2004,36(7):664.5. von Mering C, Jensen LJ, Kuhn M, Chaffron S,Doerks T, Kruger B, Snel B, Bork P: STRING 7--recent <strong>de</strong>velopments in the integration andprediction of protein interactions. Nucleic Acids Res2007, 35(Database issue):D358-362.6. Barbosa-Silva A, Soldatos TG, Magalhaes IL,Pavlopoulos GA, Fontaine JF, Andra<strong>de</strong>-NavarroMA, Schnei<strong>de</strong>r R, Ortega JM: LAITOR--LiteratureAssistant for I<strong>de</strong>ntification of Terms co-Occurrences and Relationships. BMCBioinformatics 2010, 11:70.7. Kemper B, Matsuzaki T, Matsuoka Y, Tsuruoka Y,Kitano H, Ananiadou S, Tsujii J: PathText: a textmining integrator for biological pathwayvisualizations. Bioinformatics 2010, 26(12):i374-381.8. Krallinger M, Leitner F, Valencia A: Analysis ofbiological processes and diseases using text miningapproaches. Methods Mol Biol 2010, 593:341-382.9. Krallinger M, Valencia A, Hirschman L: Linkinggenes to literature: text mining, informationextraction, and retrieval applications for biology.Genome Biol 2008, 9 Suppl 2:S8.10. Hahn U, Valencia A: Semantic Mining inBiomedicine (Introduction to the papers selectedfrom the SMBM 2005 Symposium, Hinxton, U.K.,April 2005). Bioinformatics 2006, 22(6):643-644.11. McIntosh T, Curran JR: Challenges forautomatically extracting molecular interactionsfrom full-text articles. BMC Bioinformatics 2009,10:311.12. Aoki KF, Kanehisa M: Using the KEGG databaseresource. Curr Protoc Bioinformatics 2005, Chapter1:Unit 1 12.13. Geer LY, Marchler-Bauer A, Geer RC, Han L, He J,He S, Liu C, Shi W, Bryant SH: The NCBIBioSystems database. Nucleic Acids Res 2010,38(Database issue):D492-496.14. Usié A, Karathia H, Solsona F, Alves R. Biblio-MetReS: A Bibliometric Reconstruction Server.ICMSB 2011.<strong>JP2011</strong>-62


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Paralelización <strong>de</strong> una Plataforma para laResolución <strong>de</strong> Problemas NP-completosMediante Algoritmos EvolutivosJosé M. <strong>La</strong>nza-Gutiérrez 1 , Juan A. Gómez-Pulido 1 , Miguel A. Vega-Rodríguez 1 , Juan M. Sánchez 1Resumen— El avance científico en todas sus vertientesprovoca la continua aparición <strong>de</strong> problemas <strong>de</strong>optimización NP-completos, los cuales requieren <strong>de</strong>técnicas específicas para su resolución. Entre lasmetodologías más habituales se encuentran los algoritmosevolutivos. Dado que la implementación <strong>de</strong> estos algoritmospue<strong>de</strong> resultar compleja, han surgido plataformas, comoPISA, que facilitan la resolución <strong>de</strong> problemas <strong>de</strong>optimización suministrando algoritmos evolutivos yaimplementados por la comunidad científica. <strong>La</strong>herramienta PISA posee una importante <strong>de</strong>ficiencia, y esque no está preparada para ser ejecutada en un sistemaparalelo, algo muy importante hoy día cuando se<strong>de</strong>mandan gran<strong>de</strong>s esfuerzos computacionales. En esteartículo se propone una metodología <strong>de</strong> paralelización <strong>de</strong>PISA, así como un caso <strong>de</strong> estudio en el que se ha resueltoun problema multi-objetivo para el diseño <strong>de</strong> re<strong>de</strong>s <strong>de</strong>comunicaciones, comprobando las ventajas que aporta.Palabras clave—Algoritmos evolutivos, optimizaciónmultiobjetivo, framework PISA, paralelización, MPI,diseño <strong>de</strong> re<strong>de</strong>s <strong>de</strong> comunicaciones.EI. INTRODUCCIÓNn muchas áreas científicas aparecen constantementeproblemas complejos <strong>de</strong> optimización, en los quehay que estudiar el comportamiento <strong>de</strong> múltiplesfactores <strong>de</strong> forma conjunta. <strong>La</strong> incorporación <strong>de</strong> unelevado número <strong>de</strong> incógnitas a un problema provocaque el número <strong>de</strong> posibles soluciones crezcaexponencialmente con respecto a los datos <strong>de</strong> entrada.Por este motivo, la ciencia <strong>de</strong> la computación trata <strong>de</strong>proporcionar técnicas que permitan la resolución <strong>de</strong> estetipo <strong>de</strong> problemas, <strong>de</strong>nominados NP-completos [1].Estas técnicas tratan <strong>de</strong> evitar recorrer todo el espacio <strong>de</strong>soluciones posibles (como ocurre con las estrategias <strong>de</strong>búsqueda tradicionales) con el fin <strong>de</strong> reducir el tiempotomado en su resolución, obteniendo a cambio unasolución lo más cercana posible a la óptima.Una <strong>de</strong> las primeras técnicas utilizadas con estepropósito fueron las heurísticas. <strong>La</strong>s heurísticas secentran en la utilización <strong>de</strong> algoritmos que proporcionanbuenas soluciones en tiempos <strong>de</strong> ejecución razonables,para problemas concretos [2]. Estas técnicas no aseguran1 Dep. Tecnología <strong>de</strong> Computadores y Comunicaciones. EscuelaPolitécnica. Campus Universitario s/n, 10003 Cáceres.{jmlanza,jangomez, mavega,sanperez}@unex.es2 A Platform and Programming <strong>La</strong>nguage In<strong>de</strong>pen<strong>de</strong>nt Interface forSearch Algorithms (PISA), web: http://www.tik.ee.ethz.ch/pisa/.3A Framework for Multi-Objective Optimization (JMetal), web:http://jmetal.sourceforge.net/.que los resultados obtenidos sean realmente cercanos alos óptimos. Muchos autores las han utilizado endiversos campos, como por ejemplo Jan et al. [3](<strong>de</strong>sarrollaron una técnica basada en branch and boundpara optimizar el coste <strong>de</strong> una red sobre unos valores <strong>de</strong>confiabilidad concretos) y Ersoy et al. [4] (usaron unatécnica <strong>de</strong> optimización sobre el retardo medio para eldiseño <strong>de</strong> re<strong>de</strong>s LAN y MAN interconectadas).Otra <strong>de</strong> las técnicas habituales son los algoritmosevolutivos, que resuelven problemas <strong>de</strong> optimizaciónmediante técnicas basadas en la evolución y selecciónnatural [5]. Estos algoritmos son muy populares porqueaportan, en general, buenos resultados. Pue<strong>de</strong>n dividirseen dos tipos; por un lado, los que tratan <strong>de</strong> optimizar unúnico objetivo; por otro lado, los que tratan <strong>de</strong> optimizarmúltiples objetivos <strong>de</strong> forma simultánea. Por ejemplo, yen el ámbito <strong>de</strong> las telecomunicaciones, po<strong>de</strong>mosencontrar un caso <strong>de</strong> optimización evolutiva monoobjetivoen Abuali et al. [6] (minimizaron el coste <strong>de</strong> lared a la vez que consi<strong>de</strong>raban los valores máximos <strong>de</strong>capacidad) y <strong>de</strong> optimización evolutiva multi-objetivoen Barnerjee et al. [7] (estudiaron el diseño <strong>de</strong> re<strong>de</strong>sbasadas en mo<strong>de</strong>los <strong>de</strong> trafico habituales, mediante laoptimización <strong>de</strong>l coste y el retardo). Los estudios sobreoptimización multi-objetivo están cobrando últimamentemucho interés dada la naturaleza <strong>de</strong> muchos problemas<strong>de</strong> optimización <strong>de</strong>l mundo real.No todo son ventajas en la utilización <strong>de</strong> los algoritmosevolutivos; la principal dificultad es que suimplementación es a veces compleja, puesto quehabitualmente se centran en complejas teoríasmatemáticas. Esto provoca que su utilización que<strong>de</strong>habitualmente relegada a ciertos sectores científicosmuy cualificados (informáticos, matemáticos…).Para facilitar el uso <strong>de</strong> estas técnicas han surgido unaserie <strong>de</strong> entornos, plataformas o frameworks, para quepersonas no expertas en programación <strong>de</strong> algoritmos <strong>de</strong>optimización evolutivos puedan abordar la resolución <strong>de</strong>problemas <strong>de</strong> optimización. Entre estas plataformas seencuentran PISA 2 y JMetal 3 . Estas plataformas tratan <strong>de</strong>separar, por un lado, la implementación <strong>de</strong>l algoritmo <strong>de</strong>selección (como el NSGA-II -Non-dominated SortingGenetic Algorithm II- [8] o el SPEA-II -Strength ParetoEvolutionary Algorithm II- [9]); y por otro, la <strong>de</strong>finición<strong>de</strong>l problema que se <strong>de</strong>sea resolver. <strong>La</strong> estrategiaconsiste en que el algoritmo <strong>de</strong> selección seaimplementado por un experto en el ámbito científico <strong>de</strong>lproblema, mientras que el resto <strong>de</strong> la aplicación pue<strong>de</strong>ser implementada por cualquier persona conconocimientos básicos <strong>de</strong> programación.<strong>JP2011</strong>-63


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011En este artículo se ha optado por trabajar con el entornoPISA, <strong>de</strong>bido al peso que tiene en la comunidadcientífica. Una vez estudiadas las características <strong>de</strong> estaplataforma, se observo cómo no tiene <strong>de</strong>sarrollada unacompatibilidad con su ejecución en sistemas paralelos.Este fue el motivo para abordar la paralelización <strong>de</strong> laplataforma, y que mostramos en este artículo, con elobjetivo <strong>de</strong> aprovechar todo su potencial al po<strong>de</strong>rejecutarse en clústeres <strong>de</strong> computadores paralelos.Como caso <strong>de</strong> estudio <strong>de</strong> la estrategia aquí expuesta, seresolvió un problema <strong>de</strong> optimización multi-objetivopara el diseño <strong>de</strong> re<strong>de</strong>s <strong>de</strong> comunicaciones, utilizandopara ello dos algoritmos evolutivos proporcionados porla comunidad <strong>de</strong> la plataforma.El resto <strong>de</strong>l artículo se estructura como sigue: en lasegunda sección se proporciona una breve <strong>de</strong>scripción<strong>de</strong> la plataforma PISA. En la tercera, la propuesta <strong>de</strong>paralelización <strong>de</strong>l entorno para su utilización enclústeres <strong>de</strong> computadores paralelos. En la cuartasección se expone un caso <strong>de</strong> estudio y, por último,relatamos las conclusiones y trabajos futuros.II. DESCRIPCIÓN DE LA PLATAFORMA PISAEn esta sección proporcionamos una breve <strong>de</strong>scripción<strong>de</strong> la plataforma utilizada en este trabajo. Para una<strong>de</strong>scripción más completa, recomendamos consultar lareferencia [10].Como ya se ha mencionado anteriormente, PISA es unaplataforma diseñada para facilitar la resolución <strong>de</strong>problemas <strong>de</strong> optimización mediante la utilización <strong>de</strong>algoritmos evolutivos. <strong>La</strong> plataforma está compuesta portres elementos principales: el optimizador, el monitor yel evaluador <strong>de</strong> resultados (figura 1).El optimizador se encarga <strong>de</strong> resolver un <strong>de</strong>terminadoproblema <strong>de</strong> optimización multi-objetivo mediante lautilización <strong>de</strong> técnicas evolutivas. Este elemento sedivi<strong>de</strong> a su vez en dos módulos: por un lado, el módulovariator, que contiene <strong>de</strong>talles específicos <strong>de</strong>l problemaque se <strong>de</strong>sea resolver (representación <strong>de</strong> la informaciónen forma <strong>de</strong> cromosomas, funciones <strong>de</strong> fitness, estrategiaen mutaciones y cruces…); y por otro lado, el<strong>de</strong>nominado selector, que contiene un algoritmo <strong>de</strong>selección (como NSGA-II o SPEA-II), que <strong>de</strong>terminarácómo se seleccionan los individuos en su evolución.Cada uno <strong>de</strong> estos módulos son aplicacionesin<strong>de</strong>pendientes que se comunican mediante archivos <strong>de</strong>texto. El formato <strong>de</strong> entrada/salida <strong>de</strong> cada uno <strong>de</strong> ellosse <strong>de</strong>talla perfectamente, lo que permite que todos losmódulos sean interoperables, in<strong>de</strong>pendientemente <strong>de</strong>llenguaje <strong>de</strong> programación utilizado.Esta estrategia modular permite, a<strong>de</strong>más <strong>de</strong> lareusabilidad, facilitar la implementación, pues el usuariotan solo <strong>de</strong>be centrarse en la realización <strong>de</strong>, al menos, unalgoritmos. De este modo, al experto en algoritmosevolutivos le interesará implementar un nuevo móduloselector, sobre un problema ya <strong>de</strong>sarrollado en lacomunidad, mientras que el experto en el área científica<strong>de</strong>l problema (biología, por ejemplo) implementará unnuevo problema mediante su correspondiente módulovariator, para así ejecutarlo contra los algoritmosselectores ya <strong>de</strong>sarrollados.Cada uno <strong>de</strong> estos módulos tiene asociado un archivo <strong>de</strong>configuración que permite ajustar los parámetrosnecesarios, permitiendo <strong>de</strong>finir múltiplesconfiguraciones para un mismo problema. Por ejemplo,para un módulo variator podría ajustarse la probabilidad<strong>de</strong> cruce, <strong>de</strong> mutación, el tamaño <strong>de</strong> la población, elnúmero <strong>de</strong> iteraciones, etc.A la hora <strong>de</strong> resolver un problema <strong>de</strong> optimización bastacon ejecutar cada uno <strong>de</strong> estos módulos variator yselector con una configuración asociada. Durante laejecución, el control va pasando <strong>de</strong> un módulo a otromediante la utilización <strong>de</strong> los archivos intermedios,dando la impresión <strong>de</strong> que ambos se ejecutan como sifueran un todo. Los pasos seguidos durante la ejecución<strong>de</strong>l optimizador son los siguientes (figura 2):• Paso 1: El módulo variator genera la poblacióninicial y calcula los valores <strong>de</strong> fitness para cadaindividuo.• Paso 2: El módulo selector selecciona losindividuos candidatos a evolucionar en estaprimera iteración.• Paso 3: El módulo variator toma los individuosanteriormente seleccionados y proce<strong>de</strong> arealizar sobre ellos mutaciones y cruces. Elnúmero <strong>de</strong> individuos en la población semantiene constante, para lo cual se eliminanaquellos no seleccionados previamente.• Paso 4: Una vez más, el módulo selector realizala selección <strong>de</strong> individuos, volviendo <strong>de</strong> nuevoal paso 3. El procedimiento finaliza cuando sellega a la condición <strong>de</strong> parada, normalmente unnúmero <strong>de</strong>terminado <strong>de</strong> iteraciones.• Paso 5: Se genera el archivo <strong>de</strong> resultados conel correspondiente frente <strong>de</strong> Pareto (gráfico <strong>de</strong>resultado en las técnicas <strong>de</strong> optimización multiobjetivo).Se notifica al módulo selector que yase ha obtenido la solución y que por tantopue<strong>de</strong> finalizar su ejecución.Fig. 1. Elementos que conforman la plataforma PISA.Fig. 2. Diferentes estados por los que pasan los módulos queconforman el optimizador durante su ejecución.<strong>JP2011</strong>-64


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Otro componente importante <strong>de</strong> la plataforma es elevaluador <strong>de</strong> resultados (figura 1). Una vez obtenidoslos resultados experimentales, este módulo permite<strong>de</strong>terminar si alguno <strong>de</strong> los algoritmos <strong>de</strong> selecciónutilizados ofrece un comportamiento significativamentesuperior al resto. Para ello se utilizan indicadoresestadísticos como el hipervolumen o el épsilon, y testsestadísticos (Wincoxon-Sign, Kruscal-Wallis, etc) [11].Por último, el componente <strong>de</strong>nominado monitor (figura1) ejecuta los módulos selector y variator <strong>de</strong> formasimultánea, ofreciendo la posibilidad <strong>de</strong> repetir estaejecución repetidas veces, para dar vali<strong>de</strong>z estadística.Se profundizará un poco más en la siguiente sección.Como ya se ha comentado, la utilización <strong>de</strong> estaplataforma sigue una concepción mono-procesadora,evitando que pueda ser ejecutada en un clúster. Por estarazón <strong>de</strong>cidimos ofrecer una alternativa paralela a estecomponente monitor, <strong>de</strong>sarrollando un componente quepermita repartir el trabajo <strong>de</strong> optimación por todo elclúster, tal y como se explica a continuación.III. PROPUESTA DE PARALELIZACIÓN DEL ENTORNOEn este apartado se <strong>de</strong>talla la propuesta <strong>de</strong> paralelización<strong>de</strong> la plataforma, consistente en sustituir la aplicaciónmonitor por una que funcione <strong>de</strong> forma paralela.Como pue<strong>de</strong> observarse en el Algoritmo 1, el monitororiginal trata <strong>de</strong> resolver un problema <strong>de</strong> optimizaciónmediante la utilización <strong>de</strong> diversos algoritmos <strong>de</strong>selección, ejecutando cada uno <strong>de</strong> ellos en múltiplesocasiones (siempre con la misma configuración) para asíobtener vali<strong>de</strong>z estadística en los resultados. <strong>La</strong>concepción secuencial <strong>de</strong> PISA provoca que el tiempo<strong>de</strong> cómputo necesario se presuma elevado. Nuestra i<strong>de</strong>aconsiste en aprovechar la capacidad <strong>de</strong> cálculo <strong>de</strong> unclúster para aligerar el tiempo <strong>de</strong> cómputo necesario,aumentando así la productividad <strong>de</strong>l sistema.<strong>La</strong> estrategia que abordamos requiere <strong>de</strong> la utilización<strong>de</strong> dos tecnologías: una librería <strong>de</strong> paso <strong>de</strong> mensajesMPI (Message Passing Interface) [20] para lacomunicación entre los procesos y un protocolo para elacceso a sistemas <strong>de</strong> archivos remotos <strong>de</strong> forma seguraSFTP (SSH File Transfer Protocol), para obtener losarchivos <strong>de</strong> resultados <strong>de</strong> los distintos nodos <strong>de</strong>l clúster.El nuevo monitor se <strong>de</strong>scribe en el Algoritmo 2. Paracada módulo selector que se <strong>de</strong>see utilizar contra unmismo módulo variator se reparten (mediante MPI)<strong>de</strong>s<strong>de</strong> el nodo principal todas las repeticiones entre cadauno <strong>de</strong> los nodos <strong>de</strong>l clúster, permitiendo tantasejecuciones por nodo como cores tenga disponible. Unavez finalizada la ejecución en todos los nodos se recogenlos resultados mediante SFTP y se repite elprocedimiento <strong>de</strong> nuevo para otro algoritmo selector. <strong>La</strong>salida <strong>de</strong> este monitor es un archivo con las solucionesconcatenadas, al igual que el <strong>de</strong>l monitor original.<strong>La</strong> forma en la que se reparten las ejecuciones por elclúster <strong>de</strong>pen<strong>de</strong> principalmente <strong>de</strong>l número <strong>de</strong>repeticiones que se <strong>de</strong>seen obtener. En la figura 3 pue<strong>de</strong>observarse un ejemplo <strong>de</strong> un clúster con 5 nodos, cadauno <strong>de</strong> ellos con 4 cores. Si se <strong>de</strong>sean obtener 40repeticiones, <strong>de</strong>ben utilizarse todos los cores <strong>de</strong>l clústerrealizando cada uno <strong>de</strong> ellos dos ejecuciones. Si porejemplo se <strong>de</strong>sean obtener 20 repeticiones, se utilizarían<strong>de</strong> nuevo todos los cores, realizando cada uno <strong>de</strong> ellosuna ejecución. Si fueran necesarias 10, se utilizarían los5 nodos, pero tan solo 2 cores <strong>de</strong> cada uno; y asísucesivamente.Algoritmo 1 Pseudocódigo Monitor <strong>de</strong> PISA1: para i toma valores <strong>de</strong> {selector1, selector2,…,selectorN} hacer2: para j=0 a MAX_REPETICIONES hacer3: Ejecutar módulo variator para una configuración dada4: Ejecutar módulo selector i para una configuración dada5: Esperar que finalicen los módulos6: Escribir el resultado en el archivo <strong>de</strong> salida i7: fin para8: fin paraAlgoritmo 2 Pseudocódigo <strong>de</strong>l MONITOR propuesto1: Repartir los datos necesarios por el clúster: módulo variator yselector, archivos <strong>de</strong> configuración, datos <strong>de</strong>l problema… (SFTP)2: para i toma valores <strong>de</strong> {selector1, selector2,…,selectorN} hacer3: para j=0 a NUM_NODOS hacer4: para k=0 a NUM_CORES hacer5: para z=0 a MAX_REPETICIONES/(NUM_NODOS*NUM_6: CORES) hacer //Repeticiones por core7: <strong>La</strong>nzar módulo variator en nodo j (MPI)8: <strong>La</strong>nza módulo selector i en nodo j (MPI)9: finpara10: finpara11: finpara12: para j=0 a NUM_NODOS hacer13: para k=0 a NUM_CORES hacer14: para z=0 a MAX_REPETICIONES/(NUM_NODOS*NUM_15: CORES) hacer //Repeticiones por core16: Esperar señal <strong>de</strong> finalización <strong>de</strong>l nodo j (MPI)17: Obtener el archivo <strong>de</strong> resultado <strong>de</strong>l nodo j (SFTP)18: Escribir el resultado en el archivo <strong>de</strong> salida i19: finpara20: finpara21: finpara22: finparaFig. 3. Ejemplo <strong>de</strong> una distribución <strong>de</strong> carga con el monitor propuestoComo cabría esperar, la productividad <strong>de</strong>l sistemaaumenta, pues la ejecución <strong>de</strong> cada uno <strong>de</strong> estosprocesos <strong>de</strong> optimización requiere una gran cantidad <strong>de</strong>ciclos <strong>de</strong> CPU, a cambio <strong>de</strong> un pequeño tiempo <strong>de</strong>comunicación entre las máquinas. Este aspecto se tratará<strong>de</strong>tenidamente en la siguiente sección, en la que,partiendo <strong>de</strong> un problema real, se analizarán las ventajas<strong>de</strong> utilizar esta estrategia.<strong>JP2011</strong>-65


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>La</strong>s únicas modificaciones necesarias paracompatibilizar el monitor aquí planteado con losmódulos ya <strong>de</strong>sarrollados son dos: la inclusión <strong>de</strong> lastípicas directivas <strong>de</strong> inicialización <strong>de</strong> MPI para ambosmódulos y el envío <strong>de</strong>l mensaje <strong>de</strong> finalización hacia elnodo principal <strong>de</strong>s<strong>de</strong> el estado 4 <strong>de</strong>l módulo variator(ver Figs. 1 y 2), ambas muy sencillas.IV. CASO DE ESTUDIOEn esta sección se <strong>de</strong>talla un caso <strong>de</strong> éxito en el que seha resuelto un problema <strong>de</strong> optimización mediante lapropuesta aquí explicada.El problema resuelto consiste en el diseño <strong>de</strong> re<strong>de</strong>s <strong>de</strong>comunicaciones para Internet. Es un problema queinvolucra una gran cantidad <strong>de</strong> factores; entre los máshabituales suelen encontrarse aquellos que afectan alcoste y a la calidad <strong>de</strong> red (retardo, confiabilidad, etc)[12]. Ambos factores (coste y calidad) son influyentesentre sí. En <strong>de</strong>finitiva, estamos ante un problema <strong>de</strong>optimización NP-completo que requiere <strong>de</strong> técnicasespecíficas que faciliten su resolución [1].Este problema ha sido abordado mediante diversasmetodologías, como por ejemplo heurísticas [3][4] yacitadas en la introducción. No obstante, estas heurísticasno permiten asegurar que las soluciones obtenidasrealmente sean las óptimas, por lo que surgen otrasalternativas: Usando algoritmos evolutivos monoobjetivo,Abuali et al. [6] y Ko et al. [14] optimizan elcoste <strong>de</strong> la red a la vez que mantienen valores constantes<strong>de</strong> retardo. Consi<strong>de</strong>rando algoritmos evolutivos multiobjegivo,Barnerjee et al. [7] y R. Kumar et al. [15]optimizan sobre el coste y el retardo usando el PCGA.Son precisamente los algoritmos multi-objetivo los quemejor <strong>de</strong> adaptan a este tipo <strong>de</strong> problemas [16].En la comunidad PISA existe una serie <strong>de</strong> algoritmosevolutivos implementados con sus correspondientesmódulos selectores, como por ejemplo: SPEA-II [9],NSGA-II [8], FEMO (Fair Evolutionary MultiobjetiveOptimizer) [17], IBEA (Indicator Based EvolutionaryAlgorithm) [17], etc. Para resolver este problema <strong>de</strong>diseño se han utilizado los módulos selectores queimplementan los algoritmos NSGA-II y SPEA-II, ambossobradamente conocidos.Como instancia (conjunto <strong>de</strong> datos que <strong>de</strong>finen elproblema) <strong>de</strong> prueba se han utilizado únicamente losdatos proce<strong>de</strong>ntes <strong>de</strong> Ko et al. [14], que reproducen lacomunicación entre las diez ciuda<strong>de</strong>s chinas máspobladas, puesto que no se ha encontrado otra instanciasuficientemente <strong>de</strong>tallada.A. Detalles <strong>de</strong> diseño <strong>de</strong>l problemaEn este problema se optimizan los dos factores másimportantes en el diseño <strong>de</strong> re<strong>de</strong>s <strong>de</strong> Internet: el coste <strong>de</strong>instalación (no <strong>de</strong> mantenimiento) <strong>de</strong> la red y el retardo<strong>de</strong> las comunicaciones [12].Una instancia particular <strong>de</strong> este problema se <strong>de</strong>finemediante el número <strong>de</strong> nodos <strong>de</strong> la red (N), la distanciaentre los nodos (D, una matriz <strong>de</strong> NxN elementos), eltrafico estimado entre los nodos (T, una matriz <strong>de</strong> NxNelementos), el número <strong>de</strong> tipos <strong>de</strong> nodos disponibles (K,con sus características <strong>de</strong> coste y capacidad), el número<strong>de</strong> tipos <strong>de</strong> enlaces existentes (M, con sus respectivosvalores <strong>de</strong> coste y capacidad), el coste <strong>de</strong> losamplificadores <strong>de</strong> señal (A) y la máxima distancia que laseñal pue<strong>de</strong> viajar a través <strong>de</strong> la red sin necesidad <strong>de</strong>amplificación (L). Estos dos últimos parámetros (A y L)son <strong>de</strong>bidos a que se trata <strong>de</strong> una red <strong>de</strong> fibra óptica.<strong>La</strong>s funciones objetivos son dos. Por un lado, el coste <strong>de</strong><strong>de</strong>spliegue <strong>de</strong> la red y 1 ,, que es <strong>de</strong>finido en base al coste<strong>de</strong> los nodos, el coste <strong>de</strong> los amplificadores <strong>de</strong> señal y elcoste <strong>de</strong> los enlaces. Y, por otro lado, el retardo y 2 , quese establece en base al mo<strong>de</strong>lo <strong>de</strong> tráfico utilizado; eneste caso se ha <strong>de</strong>cidido utilizar Poisson [18], un mo<strong>de</strong>lopara re<strong>de</strong>s convencionales. Nótese que con Co NEi sequiere hacer referencia al coste <strong>de</strong> un <strong>de</strong>terminado nodollamado i, con Co Linki,j al coste <strong>de</strong> el enlace entre losnodos i y j, y con Cp Linki,j a la capacidad <strong>de</strong> el enlaceentre los nodos i y j.Dijy Co(NECo )1Link A1ijii j i j L T _ acuij T_ acuiji j CpLinkijy2CpLinkijAmbas funciones objetivo han sido utilizadas en otrosestudios [7] [15].B. Implementación <strong>de</strong>l módulo variatorPara la implementación <strong>de</strong>l módulo variator que <strong>de</strong>fineel problema aquí planteado, se ha seguido al pie <strong>de</strong> letrala especificación <strong>de</strong> la plataforma en [10], para asíasegurar la correcta comunicación <strong>de</strong>l módulo con losselectores ya implementados. Se podría hablar<strong>de</strong>talladamente sobre la codificación <strong>de</strong> cada uno <strong>de</strong> losestados <strong>de</strong> módulo variator, pero <strong>de</strong>bido al escasoespacio disponible tan solo se hablará <strong>de</strong> los aspectosbásicos <strong>de</strong> diseño en algoritmos evolutivos.1) Codificación utilizadaLos individuos han sido codificados en forma <strong>de</strong>cromosomas. Cada uno representa una posibletopología-solución. Este cromosoma <strong>de</strong> longitud fija sedivi<strong>de</strong> en dos partes, como se observa en la figura 4. <strong>La</strong>primera parte es la responsable <strong>de</strong> <strong>de</strong>finir el tipo <strong>de</strong> cadauno <strong>de</strong> los nodos <strong>de</strong> la red. <strong>La</strong> segunda representa losenlaces existentes entre los nodos, don<strong>de</strong> uno indica laexistencia <strong>de</strong> un enlace y cero lo contrario.Fig. 4. Cromosoma <strong>de</strong> longitud fija que representa a los individuos <strong>de</strong>lproblema.ij<strong>JP2011</strong>-66


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20112) Generación <strong>de</strong> la población inicial<strong>La</strong> población inicial es generada mediante una mezcla<strong>de</strong> procesos aleatorios y <strong>de</strong>terministas. En primer lugar,se asigna <strong>de</strong> forma aleatoria el tipo a cada uno <strong>de</strong> losnodos. A continuación, se obtiene el árbol mínimo <strong>de</strong>distancias entre todos los nodos, utilizando el algoritmo<strong>de</strong> Prim [19]. Finalmente se aña<strong>de</strong>n <strong>de</strong> forma aleatorianuevos enlaces al árbol generado. Una vez generado elindividuo, se comprueba que sea una topología válida(ver apartado B-3) y que no se encuentre repetido. Si escorrecto se almacena, en caso contrario, se <strong>de</strong>scarta.3) Evaluación <strong>de</strong> los individuosPara cada individuo, a<strong>de</strong>más <strong>de</strong> obtener los valores <strong>de</strong>sus correspondientes funciones objetivo, se <strong>de</strong>termina siconforma una solución válida. Para ello se comprueba sicumple con las condiciones <strong>de</strong>l problema: biconexidad(la red <strong>de</strong>be ser confiable, cada nodo accesible al menos<strong>de</strong>s<strong>de</strong> dos rutas diferentes), tipos <strong>de</strong> nodos válidos(podría haber tipos inexistentes producidos pormutaciones) y si la capacidad <strong>de</strong> cada enlace essuficiente para el tráfico generado en la red (se utiliza lapropuesta <strong>de</strong> Dijsktra [19] para obtener los requisitos <strong>de</strong>cada enlace <strong>de</strong>bido al tráfico total <strong>de</strong> red). Si unindividuo no es válido, su coste y retardo tomaránvalores infinitos, <strong>de</strong>sechándose en iteraciones sucesivas.4) Estrategias en cruces y mutaciones<strong>La</strong> recombinación se ha realizado atendiendo a que loscromosomas se encuentran divididos en dos partes biendiferenciadas. Se realiza el cruce entre las primeraspartes <strong>de</strong> los individuos seleccionando el punto <strong>de</strong> cruce<strong>de</strong> forma que no modifique la codificación <strong>de</strong> los tipos<strong>de</strong> nodos. De este modo, la recombinación <strong>de</strong> dosindividuos dará lugar a un tercero en el que los tipos <strong>de</strong>nodos posibles serán únicamente los <strong>de</strong> sus padres; encaso contrario generaría una gran cantidad <strong>de</strong> individuosinválidos. El punto <strong>de</strong> cruce en la segunda parte se sitúa<strong>de</strong> forma completamente aleatoria. <strong>La</strong> mutación tambiénse ha realizado teniendo en cuenta esta mismacircunstancia, realizando un número <strong>de</strong> mutaciones quepue<strong>de</strong> ir <strong>de</strong>s<strong>de</strong> 0 hasta el número <strong>de</strong> bits totales <strong>de</strong>lcromosoma. El punto <strong>de</strong> cruce <strong>de</strong> la primera y segundaparte sigue criterios similares a los <strong>de</strong> la recombinación.C. Resultados experimentalesEn este apartado se exponen los datos obtenidos en laresolución <strong>de</strong>l problema mediante el módulo variatorimplementado y un par <strong>de</strong> módulos selectores yaexistentes en la comunidad PISA: NSGA-II y SPEA-II.A la hora <strong>de</strong> ejecutar la plataforma se ha utilizado elmonitor paralelo propuesto en este artículo, realizandouna comparativa con el ya existente.Todos los experimentos han sido realizados en unclúster <strong>de</strong> procesadores paralelos compuesto por 5nodos, cada uno <strong>de</strong> ellos con cuatro procesadores Intel®Xeon a 3.0Ghz y 1 <strong>de</strong> GB memoria RAM.A la hora <strong>de</strong> realizar la experimentación se ha utilizadouna sencilla estrategia. Primero se <strong>de</strong>terminan lasconfiguraciones con las que se obtienen los mejoresresultados para cada algoritmo. Después, y en base aestos resultados, se estudia si alguno <strong>de</strong> los dosalgoritmos ofrece un comportamiento superior al otro.Como se ha selñalado anteriormente, el primer paso <strong>de</strong>la experimentación consiste en ajustar los parámetrosmás habituales para <strong>de</strong>terminar con qué configuración seobtienen los mejores resultados. Estos parámetros son:número <strong>de</strong> generaciones, tamaño <strong>de</strong> la población,probabilidad <strong>de</strong> cruce y probabilidad <strong>de</strong> mutación. Estametodología es similar a la propuesta por A. Rubio-<strong>La</strong>rgo et al. [13], en la que, partiendo <strong>de</strong> unaconfiguración por <strong>de</strong>fecto, se van fijando los valores <strong>de</strong>los parámetros uno a uno en su valor óptimo, hasta quese han ajustado todos.A la hora <strong>de</strong> establecer el grado <strong>de</strong> bondad que tienenlos frentes obtenidos para cada configuración, esnecesario utilizar algún tipo <strong>de</strong> medida. En este caso seha <strong>de</strong>cidido utilizar una medida habitual en este tipo <strong>de</strong>estudios: el hipervolumen [11]. A mayor valor <strong>de</strong>hipervolumen, mejor es la solución. A la hora <strong>de</strong>calcular este valor <strong>de</strong> evaluación es necesario <strong>de</strong>finir lospuntos <strong>de</strong> referencia máximo y mínimo. Así, essuficienet contar con los puntos {1.000.000, 0.9} comomáximo y {0, 0} como mínimo, para las tuplas {coste,retardo}, pues envuelven a todos los frentes obtenidos.TABLA ICONFIGURACIONES IDÓNEAS OBTENIDAS PARA CADA UNO DE LOSALGORITMOSAlgoritmos GeneracionesPoblaciónProb.CruceProb.MutaciónHipervolumenNSGA-II 800 250 0.8 0.5 0.975SPEA-II 800 250 0.6 0.5 0.976TABLA IITIEMPOS DE EJECUCIÓN EN LA UTILIZACIÓN DE AMBOS MONITORESPARA UN NÚMERO VARIABLE DE REPETICIONESTiempo <strong>de</strong> ejecución (s)SPEA-II NSGA-II Repeti Configuración <strong>de</strong>lSec Par Sec Par ciones clúster480 100 690 150 5 5 nodos con 1 core1000 102 1320 152 10 5 nodos con 2 cores1970 105 2437 151 20 5 nodos con 4 cores2960 201 3658 261 30 5 nodos con 3 coresy 2 repeticiones4050 205 4925 263 40 5 nodos con 4 coresy 2 repeticionesFig. 5. Comparativa entre los tiempos obtenidos en la ejecución <strong>de</strong>ambos monitores, para diferente número <strong>de</strong> repeticiones.Utilizando las configuraciones mostradas en la tabla 1.<strong>JP2011</strong>-67


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Siguiendo la metodología comentada, po<strong>de</strong>mos afirmarque los algoritmos ofrecen sus mejores resultados conlas configuraciones expuestas en la Tabla 1, obteniendo<strong>de</strong> media unos hipervolúmenes superiores el algoritmoSPEA-II frente al algoritmo NSGA-II.Este procedimiento se ha realizado utilizando ambosmonitores. Como es <strong>de</strong> esperar, las conclusionesobtenidas han sido las mismas, puesto que los resultadosobtenidos son exactamente iguales. Lo que sí se ha vistoafectado ha sido el tiempo necesario a la hora <strong>de</strong>ejecutar todas estas pruebas, puesto que para cada una<strong>de</strong> las configuraciones probadas se han realizado un total<strong>de</strong> 20 ejecuciones para obtener vali<strong>de</strong>z estadística.Para mostrar <strong>de</strong> forma sencilla la ventaja que aporta elmonitor propuesto con respecto al ya existente, se harealizado un sencillo experimento (Tabla 2): cadaconfiguración mostrada en la Tabla 1 se ejecuta unnúmero variable <strong>de</strong> ocasiones (Tabla 2: campoRepeticiones) utilizando ambos monitores (Tabla 2: sectiempo utilizando el monitor original y par para elmonitor propuesto). Dependiendo <strong>de</strong>l número <strong>de</strong>repeticiones será necesario utilizar una <strong>de</strong>terminadaconfiguración <strong>de</strong>l clúster (como ya se comentó en laaanterior sección). Esta configuración <strong>de</strong>l clúster seespecifica en el campo config.Cluster <strong>de</strong> la Tabla 2.Como pue<strong>de</strong> observarse en la figura 5 los tiemposproporcionados por el monitor propuesto son muchomenores que los ofrecidos por el monitor original. Elaumento <strong>de</strong>l número <strong>de</strong> repeticiones provoca una crecidalineal <strong>de</strong> los tiempos <strong>de</strong>l monitor PISA, mientras quecon el propuesto los tiempos sufren un incrementomucho menor. A<strong>de</strong>más, pue<strong>de</strong> observase cómo paradiferente número <strong>de</strong> repeticiones (5, 10 y 20) lostiempos obtenidos son casi idénticos; esto se <strong>de</strong>be a querealmente para los dos primeros valores no se estáexprimiendo al máximo el potencial <strong>de</strong>l clúster, mientrasque para el último sí (Tabla 2). Estas pequeñasvariaciones observadas son fruto <strong>de</strong> las comunicaciones:a mayor volumen <strong>de</strong> datos más tiempo <strong>de</strong> comunicación.Situación similar ocurre con 30 y 40 repeticiones.Como se ha <strong>de</strong>mostrado experimentalmente, laalternativa propuesta en este trabajo supone una granventaja con respecto al sistema actualmente utilizado.V. CONCLUSIONES Y TRABAJOS FUTUROSEn este artículo se propone una paralelización <strong>de</strong> laplataforma PISA para a<strong>de</strong>cuar su utilización a entornos<strong>de</strong> computación paralela. Se ha <strong>de</strong>mostrado, mediante laresolución <strong>de</strong> un problema <strong>de</strong> optimización multiobjetivopara el diseño <strong>de</strong> re<strong>de</strong>s, cómo esta propuestaaporta gran<strong>de</strong>s ventajas en la productividad obtenida, alejecutar una <strong>de</strong>terminada configuración <strong>de</strong>l problema enmúltiples ocasiones, lo cual es necesario para dotar <strong>de</strong>vali<strong>de</strong>z estadística a los resultados. Como línea <strong>de</strong>trabajo futuro pensamos que esta propuesta podría servalidada contra otros problemas <strong>de</strong> optimización(módulos variator) ya existentes en la comunidadcientífica, <strong>de</strong> forma que pueda ser finalmente puesta adisposición <strong>de</strong> los usuarios para que la utilicenlibremente. A<strong>de</strong>más, podría estudiarse también laposibilidad <strong>de</strong> utilizar OpenMP [21] para paralelizar eltrabajo <strong>de</strong>ntro <strong>de</strong> cada nodo directamente.VI. AGRADECIMIENTOSEl presente trabajo ha sido parcialmente financiado porel Ministerio <strong>de</strong> Ciencia e Innovación y el FEDER(Fondo Europeo <strong>de</strong> Desarrollo Regional), bajo elproyecto TIN2008-06491-C04-04 (proyecto MSTAR), ypor la Junta <strong>de</strong> Extremadura, a través <strong>de</strong> la ayudaGR10025 al grupo TIC015.VII. REFERENCIAS[1] B. Dengiz, F. Altiparmak, y A.E. Smith, Local searchgenetic algorithm for optimal <strong>de</strong>sign of reliable networks, IEEE Trans.on Evolutionary Computation, vol.1, Sep.1997, pp. 179-188.[2] A. Mucherino y O. Seref, Mo<strong>de</strong>ling and Solving Real-LifeGlobal Optimization Problems with Meta-heuristic Methods, inAdvances in Mo<strong>de</strong>ling Agricultural Systems, vol. 25, Boston, MA:Springer US, 2009, págs. 1-17.[3] Rong-Hong Jan, Fung-Jen Hwang, , y , Sheng-Tzong Chen,Topological optimization of a communication network subject to areliability constraint, IEEE Trans. on Reliability, 42, 1993, pp. 63-70.[4] Cem Ersoy and Shivendra S. Panwar, Topological <strong>de</strong>sign ofinterconnected LAN/MAN networks, IEEE Journal on Selected Areasin Communications, vol. 11, 1993, pág. 1172--1182[5] C. Coello Coello, Evolutionary algorithms for solvingmulti-objective problems, 2nd ed. New York: Springer, 2007.[6] F.N. Abuali, D.A. Schoenefeld, y R.L. Wainwright,Designing telecommunications networks using genetic algorithms andprobabilistic minimum spanning trees, Proc. 1994 ACM symposiumon Applied computing, Phoenix, Arizona, USA: 1994, págs. 242-246.[7] N. Banerjee y R. Kumar, Multiobjective network <strong>de</strong>sign forrealistic traffic mo<strong>de</strong>ls, Proceedings of the 9th annual conference onGenetic and evolutionary computation - GECCO ’07, London,England: 2007, pág. 1904.[8] Kalyanmoy Deb, Samir Agrawal y Amrit Pratap y TMeyarivan, A Fast Elitist Non-dominated Sorting Genetic Algorithmfor Multi-objective Optimization: NSGA-II, Parallel Problem Solvingfrom Nature PPSN VI, 2000.[9] E. Zitzler, M. <strong>La</strong>umanns y L. Thiele, SPEA2: Improvingthe strength Pareto evolutionary algorithm, EUROGEN 2001.[10] Stefan Bleuler, Marco <strong>La</strong>umanns, Lothar Thiele, EckartZitzler, PISA - A Platform and Programming <strong>La</strong>nguaje In<strong>de</strong>pen<strong>de</strong>ntInterface for Search Algorithms, Berlin: Springer, Evolutionary Multi-Criterion Optimization, 2003.[11] Carlos M.Fonseca, Joshua D.Knowles, Lothar Thiele andEckart Zitzler, A Tutorial on the Performance Assessment ofStochastic Multiobjetive Optimizer. Guanajuato, Mexico: EMO, 2005[12] Andrew S. Tanenbaum, Computer Networks, Prentice Hall,2003.[13] A. Rubio-<strong>La</strong>rgo, M.A. Vega-Rodriguez, J.A. Gomez-Pulido, y J.M. Sanchez-Perez, A Differential Evolution with ParetoTournaments for solving the Routing and Wavelength Assignmentproblem in WDM networks, IEEE Congress on EvolutionaryComputation, Barcelona, Spain: 2010, págs. 1-8.[14] King-Tim Ko, Kit-Sang Tang y Cheung-Yau Chan y Kim-Fung Man, , y , Sam Kwong, Using genetic algorithms to <strong>de</strong>sign meshnetworks, Computer, vol. 30, Ago. 1997, págs. 56-61.[15] R. Kumar, P.P. Parida, y M. Gupta, Topological <strong>de</strong>sign ofcommunication networks using multiobjective genetic optimization,Proceedings of the 2002 Congress on Evolutionary Computation.CEC’02 (Cat. No.02TH8600), Honolulu, HI, USA: , págs. 425-430.[16] C. Coello Coello, Evolutionary algorithms for solvingmulti-objective problems, New York: Springer, 2007.[17] Marco <strong>La</strong>umanns, Lothar Thiele, Eckart Zitzler, EmoWelzl y Kalyanmoy Deb Asdf, Running Time Analysis of MultiobjectiveEvolutionary Algorithms on a Simple Discrete OptimizationProblem, London, Springer, 2002.[18] Mohsen Guizani, Ammar Rayes, Bilal Khan and Ala Al-Fuqaha.,Network Mo<strong>de</strong>ling and Simulation: A Practical Perspective,Wiley-Interscience, 2010.[19] T. Cormen, Introduction to algorithms, Cambridge Mass.:The MIT Press, 2001.[20] W. Gropp, Using MPI: portable parallel programmingwith the message-passing interface, Cambridge Mass.: MIT Press,1999.[21] B. Chapman, Using OpenMP: portable shared memoryparallel programming. Cambridge Mass.: The MIT Press, 2007.<strong>JP2011</strong>-68


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Comparando Mo<strong>de</strong>los Paralelos Basados enIslas para el Problema <strong>de</strong>l Posicionamiento <strong>de</strong>Antenas MultiobjetivizadoCoromoto León, Eduardo Segredo y Carlos Segura 1Resumen— El Problema <strong>de</strong>l Posicionamiento <strong>de</strong> Antenas– Antenna Positioning Problem (app), es un problema<strong>de</strong> optimización NP-completo enmarcado en elcampo <strong>de</strong> las telecomunicaciones. El objetivo es i<strong>de</strong>ntificarlas infraestructuras necesarias para estableceruna red inalámbrica. En este artículo se ha utilizadouna versión mono-objetivo <strong>de</strong>l mismo. El algoritmoque mejor se comporta actualmente para dicha versiónes una estrategia que incorpora información <strong>de</strong>pendiente<strong>de</strong>l problema. Sin embargo, también se han<strong>de</strong>finido otros métodos que minimizan el uso <strong>de</strong> información<strong>de</strong>pendiente <strong>de</strong>l problema. En particular, lamultiobjetivización proporciona soluciones <strong>de</strong> una calidadsimilar a las proporcionadas por estrategias queincorporan información <strong>de</strong>pendiente <strong>de</strong>l problema. Noobstante, se necesita una elevada cantidad <strong>de</strong> tiempopara converger a dichas soluciones <strong>de</strong> gran calidad. Elprincipal objetivo <strong>de</strong>l presente trabajo se ha centradoen disminuir el tiempo empleado para resolver el appmediante el uso <strong>de</strong> técnicas <strong>de</strong> multiobjectivización.Para ello, se ha aplicado un mo<strong>de</strong>lo paralelo basado enislas a dos instancias <strong>de</strong>l app. A<strong>de</strong>más, se han probadodiferentes esquemas <strong>de</strong> migración para comprobarla robustez <strong>de</strong> la aproximación. Finalmente, se ha llevadoa cabo un estudio <strong>de</strong> escalabilidad junto con elmejor esquema <strong>de</strong> migración. Los resultados computacionaleshan <strong>de</strong>mostrado la vali<strong>de</strong>z <strong>de</strong> la propuesta.Palabras clave— Multiobjetivización, Antenna PositioningProblem, Mo<strong>de</strong>los Paralelos basados en Islas.I. IntroducciónEL Problema <strong>de</strong>l Posicionamiento <strong>de</strong> Antenas –Antenna Positioning Problem (app) es uno <strong>de</strong>los principales problemas [1] <strong>de</strong> optimización queaparecen a la hora <strong>de</strong> establecer re<strong>de</strong>s <strong>de</strong> telecomunicacionesmóviles. Consiste en i<strong>de</strong>ntificar las infraestructurasnecesarias para establecer una red <strong>de</strong>comunicaciones inalámbrica. El app trata <strong>de</strong> i<strong>de</strong>ntificarlas ubicaciones más prometedoras en las queposicionar un conjunto <strong>de</strong> Estaciones Base – BaseStations (bs) o antenas. <strong>La</strong>s ubicaciones se seleccionan<strong>de</strong> un conjunto <strong>de</strong> candidatas. Dependiendo <strong>de</strong> laformulación <strong>de</strong>l problema, se pue<strong>de</strong>n tener en cuentadiferentes objetivos a optimizar. Los más típicos consistenen minimizar el número <strong>de</strong> antenas, maximizarla cantidad <strong>de</strong> tráfico soportado por la red, maximizarla calidad <strong>de</strong> servicio, y/o maximizar el área <strong>de</strong>cubrimiento. A<strong>de</strong>más, también se pue<strong>de</strong>n consi<strong>de</strong>rardiferentes restricciones. Este problema <strong>de</strong>sempeña unpapel muy importante en el ámbito <strong>de</strong> la industria,la ciencia y la ingeniería, <strong>de</strong>bido a que las solucionesobtenidas afectan en gran medida a los costes, benefi-1 Dpto. <strong>de</strong> Estadística, I.O y Computación, <strong>Universidad</strong> <strong>de</strong><strong>La</strong> <strong>La</strong>guna, Edificio <strong>de</strong> Física y Matemáticas, Avda. AstrofísicoFco. Sánchez s/n, 38271 <strong>La</strong> <strong>La</strong>guna, Tenerife, e-mail:(cleon|esegredo|csegura)@ull.es.cios y otros indicadores relevantes para una empresao negocio. Por ello, se <strong>de</strong>ben diseñar algoritmos <strong>de</strong> calidadpara resolver este tipo <strong>de</strong> problemas, dado quetienen un impacto directo sobre dichos indicadores.En el presente artículo, se trata el app. Este problematambién es conocido en la literatura como elproblema <strong>de</strong>l Diseño <strong>de</strong> Re<strong>de</strong>s <strong>de</strong> Radio – Radio NetworkDesign (rnd) o el Problema <strong>de</strong> la Localización<strong>de</strong> Estaciones Base Transmisoras – Base StationTransmitters Location Problem (bst-l). El app es unproblema np-completo [2]. Varias formulaciones <strong>de</strong>lproblema han sido propuestas [3], la mayoría <strong>de</strong> ellasmono-objetivo [4]. En [5], el app se trató como unproblema mono-objetivo, transformando el resto <strong>de</strong>objetivos en restricciones. En [6], se trató una versióncon varios objetivos y se aplicaron estrategias multiobjetivo.En este trabajo, se ha utilizado la variantemono-objetivo presentada en [7], [8]. En esta versión,la función <strong>de</strong> fitness tiene en cuenta el cubrimientologrado en la red y el número <strong>de</strong> bs <strong>de</strong>splegadas.Se han aplicado muchas estrategias a versionesmono-objetivo y multi-objetivo <strong>de</strong>l app. <strong>La</strong> mayoría<strong>de</strong> ellas incorporan información <strong>de</strong>pendiente <strong>de</strong>lproblema. Adaptar estas estrategias a otras variantes<strong>de</strong>l problema es uno <strong>de</strong> los principales inconvenientes<strong>de</strong> las mismas. Por otro lado, dichas aproximacionestienen un enorme coste <strong>de</strong> diseño asociado. En [9],[5], se diseñaron varias heurísticas a medida paratratar el app. En [7], [8], se aplicaron estrategiasevolutivas a este problema. En [8], se incorporó información<strong>de</strong>pendiente <strong>de</strong>l problema en los operadores<strong>de</strong> mutación. Una amplia comparativa <strong>de</strong> técnicasmono-objetivo aplicadas a la versión <strong>de</strong>l app tratadaen este artículo se expuso en [2]. En dicho trabajo,las técnicas que no incorporaban información <strong>de</strong>pendiente<strong>de</strong>l problema obtuvieron soluciones <strong>de</strong> peorcalidad que las obtenidas por las técnicas que usabaninformación <strong>de</strong>pendiente <strong>de</strong>l problema. No obstante,<strong>de</strong>bido a los inconvenientes <strong>de</strong> usar aproximacionesbasadas en información <strong>de</strong>pendiente <strong>de</strong>l problema,también se han probado diferentes alternativas quepermiten minimizar la utilización <strong>de</strong> este tipo <strong>de</strong> información.En [3], se aplicaron Algoritmos EvolutivosMulti-objetivo – Multi-objective Evolutionary Algorithms(moeas) al app. En dicho artículo se utilizóla formulación matemática <strong>de</strong> este mismo trabajo,con la diferencia <strong>de</strong> que el cubrimiento y elnúmero <strong>de</strong> bs se consi<strong>de</strong>raron como dos objetivos in<strong>de</strong>pendientes.En este caso, se consiguió mejorar ladiversidad <strong>de</strong> las soluciones. Sin embargo, los moeas<strong>JP2011</strong>-69


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011no consiguieron alcanzar valores <strong>de</strong> fitness tan altoscomo los obtenidos por las técnicas <strong>de</strong>pendientes<strong>de</strong>l problema. Otra posible alternativa para minimizarel uso <strong>de</strong> información <strong>de</strong>pendiente <strong>de</strong>l problemase pue<strong>de</strong> encontrar en la multiobjetivización. Eltérmino multiobjetivización se introdujo en [10] parareferirse a la técnica <strong>de</strong> convertir un problema monoobjetivoen uno multi-objetivo. En [11], un conjunto<strong>de</strong> aproximaciones basadas en multiobjetivizaciónconvergieron más lentamente a la resolución <strong>de</strong>l appque las técnicas <strong>de</strong>pendientes <strong>de</strong>l problema. No obstante,con ejecuciones más largas, fueron capaces <strong>de</strong>alcanzar soluciones <strong>de</strong> similar calidad.Para reducir el tiempo <strong>de</strong> cómputo, se han propuestonumerosos estudios que consi<strong>de</strong>ran la paralelización<strong>de</strong> moeas [12]. Los Algoritmos EvolutivosMulti-objetivo Paralelos – Parallel MultiobjectiveEvolutionary Algorithms (pmoeas), teniendoen cuenta el paradigma <strong>de</strong> programación paralelopara el que han sido diseñados, se pue<strong>de</strong>n clasificar[13] en: master-worker, basados en islas o difusión.Cuando se compara con otros mo<strong>de</strong>los paralelos,la aproximación basada en islas aporta dos beneficiosnotables: primero, se adapta fácilmente a lasarquitecturas paralelas, y segundo, permite exten<strong>de</strong>rel espacio <strong>de</strong> búsqueda <strong>de</strong> soluciones, tratando <strong>de</strong> evitarla caída en óptimos locales. A<strong>de</strong>más, los mo<strong>de</strong>losbasados en islas han <strong>de</strong>mostrado su buen rendimientoy su escalabilidad en numerosas áreas [12]. Conceptualmente,la población total <strong>de</strong> un pmoea se divi<strong>de</strong>en un número <strong>de</strong>terminado <strong>de</strong> sub-poblaciones,o lo que es lo mismo, se aplica un moea a una subpoblaciónen cada isla <strong>de</strong> manera totalmente in<strong>de</strong>pendiente.En cada isla, la población evoluciona <strong>de</strong>manera aislada la mayoría <strong>de</strong>l tiempo, pero algunasveces, los individuos pue<strong>de</strong>n migrar <strong>de</strong> una isla aotra. <strong>La</strong> migración es una operación esencial en estetipo <strong>de</strong> mo<strong>de</strong>los paralelos, dado que fomenta la cooperaciónentre islas. De ahí que su diseño sea unfactor <strong>de</strong>terminante para obtener un pmoea <strong>de</strong> altacalidad. En este artículo, se ha comprobado la vali<strong>de</strong>z<strong>de</strong> un mo<strong>de</strong>lo híbrido que combina un mo<strong>de</strong>lo paralelobasado en islas con técnicas <strong>de</strong> multiobjetivizaciónaplicadas al app. Para comprobar la robustez <strong>de</strong> lapropuesta, se ha llevado a cabo una comparativa entrediferentes esquemas <strong>de</strong> migración incorporadosal mo<strong>de</strong>lo. A<strong>de</strong>más, se ha realizado un estudio <strong>de</strong> escalabilidad<strong>de</strong> la aproximación, junto con el mejoresquema <strong>de</strong> migración <strong>de</strong> la comparativa anterior.El principal objetivo <strong>de</strong>l trabajo ha sido la disminución<strong>de</strong>l tiempo empleado por las técnicas basadasen multiobjetivización en alcanzar el mismo nivel <strong>de</strong>calidad que el obtenido por las estrategias que incorporaninformación <strong>de</strong>pendiente <strong>de</strong>l problema.El resto <strong>de</strong>l artículo se estructura tal y como sigue:la formulación matemática <strong>de</strong>l app se expone en laSección II. En la Sección III se <strong>de</strong>scribe el método<strong>de</strong> optimización utilizado. <strong>La</strong> estrategia secuencialse <strong>de</strong>talla en la Sección III-A. Específicamente, se<strong>de</strong>scriben los métodos <strong>de</strong> multiobjetivización y losoperadores genéticos utilizados. En la Sección III-B,se dan los <strong>de</strong>talles <strong>de</strong>l mo<strong>de</strong>lo paralelo basado enislas. A continuación, la Sección IV presenta los resultadoscomputacionales obtenidos durante los experimentos.Por último, se comparten algunas conclusionesy líneas <strong>de</strong> trabajo futuro en la Sección V.II. Formulación Matemática <strong>de</strong>l appEl app se <strong>de</strong>fine como el problema <strong>de</strong> i<strong>de</strong>ntificar lasinfraestructuras necesarias para establecer una red<strong>de</strong> comunicaciones inalámbrica. Esta formulación <strong>de</strong>lproblema trata <strong>de</strong> maximizar el cubrimiento <strong>de</strong> unárea geográfica dada, a la vez que trata <strong>de</strong> minimizarel número <strong>de</strong> bs <strong>de</strong>splegadas. Una bs es un dispositivo<strong>de</strong> transmisión <strong>de</strong> señales <strong>de</strong> radio que siguenun mo<strong>de</strong>lo <strong>de</strong> onda <strong>de</strong>terminado. <strong>La</strong> región <strong>de</strong>l áreacubierta por una bs se conoce con el nombre <strong>de</strong> célula.En la <strong>de</strong>finición <strong>de</strong>l app aquí consi<strong>de</strong>rada, una bssólo pue<strong>de</strong> posicionarse en una ubicación <strong>de</strong> entre unconjunto <strong>de</strong> potenciales ubicaciones. <strong>La</strong> formulaciónmatemática <strong>de</strong> esta versión <strong>de</strong>l app fue propuestaen [7], [8]. <strong>La</strong> función <strong>de</strong> fitness viene dada por:f(solucion) = CubrimientoαT ransmisoresObservando la ecuación anterior, se <strong>de</strong>be seleccionarun valor para α, teniendo en cuenta la importanciaque se le <strong>de</strong>sea dar al cubrimiento en comparacióncon el número <strong>de</strong> bs <strong>de</strong>splegadas. Tal y como se propusoen [7], [8], se ha utilizado un valor α = 2.El área geográfica G en la que se <strong>de</strong>be <strong>de</strong>splegar lared se discretiza en un número finito <strong>de</strong> puntos o localizaciones.T am x y T am y representan el número <strong>de</strong>sub-divisiones verticales y horizontales, respectivamente.Expertos en comunicaciones son los encargados<strong>de</strong> fijar estos parámetros en función <strong>de</strong> las características<strong>de</strong>l terreno y <strong>de</strong> las bs. U es el conjunto <strong>de</strong>localizaciones don<strong>de</strong> pue<strong>de</strong> <strong>de</strong>splegarse una bs: U ={(x 1 , y 1 ), (x 2 , y 2 ), ..., (x n , y n )}. U[i] hace referencia ala localización i. <strong>La</strong>s coor<strong>de</strong>nadas x e y <strong>de</strong> una localizacióni utilizan la notación U[i] x y U[i] y , respectivamente.Se dice que una célula C[i] se encuentracubierta si una bs se encuentra <strong>de</strong>splegada en la localizacióni. En el presente trabajo, las bs irradianuna señal que sigue un mo<strong>de</strong>lo isotrópico. El conjuntoP <strong>de</strong>termina las localizaciones cubiertas por unabs: P = {(∆x 1 , ∆y 1 ), (∆x 2 , ∆y 2 ), ..., (∆x m , ∆y m )}.Por ello, si se <strong>de</strong>spliega la bs i, las localizacionescubiertas por la misma son las siguientes: C[i] ={(U[i] x + ∆x 1 , U[i] y + ∆y 1 ), (U[i] x + ∆x 2 , U[i] y +∆y 2 ), ..., (U[i] x + ∆x m , U[i] y + ∆y m )}. Siendo B =[b 0 , b 1 , ..., b n ] el vector binario que <strong>de</strong>termina las bs<strong>de</strong>splegadas, se obtienen las siguientes <strong>de</strong>finiciones:Cubrimiento =T ransmisores = ∑ ni=0 b i∑ tamx∑ tamycubrir(i,j)i=0 j=0tam x×tam y× 100don<strong>de</strong>:{ 1 Si ∃ i/{(bi = 1) ∧ ((x, y) ∈ C[i])}cubrir(x, y) =0 En otro caso<strong>JP2011</strong>-70


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011III. Esquema <strong>de</strong> OptimizaciónA. Aproximación SecuencialEl esquema <strong>de</strong> optimización con mejor comportamiento<strong>de</strong> [11] ha sido aplicado en este artículo.El esquema se basa en el algoritmo Non-dominatedSorting Genetic Algorithm II (nsga-ii). El app seha multiobjetivizado añadiendo una función objetivoartificial. <strong>La</strong> multiobjetivización modifica la forma<strong>de</strong>l espacio <strong>de</strong> <strong>de</strong>cisión <strong>de</strong> un problema, por loque pue<strong>de</strong> ayudar a evitar la caída en óptimos locales[14]. No obstante, también pue<strong>de</strong> provocar queel problema pase a ser más difícil <strong>de</strong> resolver [15].Existen dos vías diferentes a la hora <strong>de</strong> multiobjetivizarun problema. <strong>La</strong> primera <strong>de</strong> ellas se basa en<strong>de</strong>scomponer la función objetivo original, mientrasque la segunda consiste en añadir nuevas funcionesobjetivo. <strong>La</strong> adición <strong>de</strong> nuevos objetivos se pue<strong>de</strong>llevar a cabo teniendo en cuenta información <strong>de</strong>pendienteo in<strong>de</strong>pendiente <strong>de</strong>l problema. Para multiobjetivizarel app, se escogió la función <strong>de</strong> fitness expuestaen la Sección II como primer objetivo, mientrasque para el segundo objetivo se utilizó una funciónartificial que trata <strong>de</strong> maximizar la diversidad<strong>de</strong> las soluciones. En [11], se comprobó el rendimiento<strong>de</strong> diferentes funciones artificiales. <strong>La</strong> que obtuvolos mejores resultados se basa en obtener la distanciaEuclí<strong>de</strong>a al mejor individuo <strong>de</strong> la población, es <strong>de</strong>cir,aquel que posee el valor <strong>de</strong> fitness más prometedor.Gracias a que la presión <strong>de</strong> selección disminuye, algunosindividuos <strong>de</strong> baja calidad podrían sobrevivirdurante varias generaciones. No obstante, en ciertomomento, podrían ayudar a escapar <strong>de</strong> óptimos locales.De hecho, la mejor estrategia basada en multiobjetivizaciónpropuesta en [11] fue capaz <strong>de</strong> obtener,en ejecuciones largas, soluciones <strong>de</strong> una calidadsimilar a las obtenidas por las estrategias que incorporabaninformación <strong>de</strong>pendiente <strong>de</strong>l problema.El algoritmo nsga-ii hace uso <strong>de</strong> una fase <strong>de</strong>variación, la cual consiste en la aplicación <strong>de</strong> un operador<strong>de</strong> cruce y <strong>de</strong> un operador <strong>de</strong> mutación. El esquema<strong>de</strong> optimización aplicado usa los operadoresgenéticos que mejor comportamiento <strong>de</strong>mostraronen [3]. El operador <strong>de</strong> mutación aplicado ha sido elBit Inversión Mutation. Con este operador, cada gen<strong>de</strong> un individuo se invierte con una probabilidad p m .Por otro lado, el operador <strong>de</strong> cruce utilizado ha sidoel Geographic Crossover y se ha aplicado con unaprobabilidad p c . Este operador intercambia las bsque se encuentran posicionadas a cierto radio r <strong>de</strong>una bs seleccionada al azar. Por último, mencionarque los individuos se han codificado como ca<strong>de</strong>nas binarias<strong>de</strong> n elementos, don<strong>de</strong> n representa el número<strong>de</strong> posibles localizaciones don<strong>de</strong> ubicar una bs.B. Aproximación ParalelaSe ha consi<strong>de</strong>rado la paralelización para reducir eltiempo <strong>de</strong> ejecución empleado por la estrategia secuencial<strong>de</strong>scrita en la Sección III-A durante la obtención<strong>de</strong> soluciones <strong>de</strong> alta calidad. En concreto,se ha aplicado un mo<strong>de</strong>lo paralelo basado en islas.En este tipo <strong>de</strong> mo<strong>de</strong>los, la población se divi<strong>de</strong> enun número <strong>de</strong>terminado <strong>de</strong> sub-poblaciones. Cadauna <strong>de</strong> estas sub-poblaciones se asocia con una isla<strong>de</strong>terminada, y sobre cada una <strong>de</strong> ellas se ejecutaun moea o configuración <strong>de</strong> manera in<strong>de</strong>pendiente.Generalmente, en cada isla, la población evoluciona<strong>de</strong> manera aislada la mayoría <strong>de</strong>l tiempo. No obstante,añadir cierto comportamiento colaborativo alesquema podría llevar a obtener un mejor comportamiento.Es por ello que se suele incorporar con bastantefrecuencia un esquema <strong>de</strong> migración que permitetransferir individuos <strong>de</strong> unas islas a otras.Existen cuatro mo<strong>de</strong>los basados en islas diferentes[13]: todas las islas ejecutan la misma configuración(homogéneo), todas las islas ejecutan una configuracióndiferente (heterogéneo), cada isla evalúaun subconjunto diferente <strong>de</strong> funciones objetivo y cadaisla representa una región distinta en los dominios<strong>de</strong>l fenotipo o <strong>de</strong>l genotipo. <strong>La</strong> aproximación paralelautilizada en el presente trabajo se basa en el mo<strong>de</strong>lo<strong>de</strong> islas homogéneo, con cada isla ejecutando laestrategia expuesta en la Sección III-A.El esquema <strong>de</strong> migración es un componente esencialen este tipo <strong>de</strong> mo<strong>de</strong>los paralelos <strong>de</strong>bido a quefomentan la colaboración entre islas. De ahí que sudiseño sea un factor <strong>de</strong>terminante para obtener unbuen rendimiento. Gracias a un buen esquema <strong>de</strong> migración,el espacio <strong>de</strong> búsqueda <strong>de</strong> soluciones se podríaexplorar con más profundidad, y se podrían obtenersoluciones <strong>de</strong> más alta calidad. Sin embargo, sino se aplica un esquema <strong>de</strong> migración o dicho esquemase encuentra mal diseñado, el efecto podría llegara ser similar, e incluso peor, al obtenido por un conjunto<strong>de</strong> moeas ejecutando <strong>de</strong> forma in<strong>de</strong>pendienteen un número <strong>de</strong> procesadores <strong>de</strong>terminado sinque exista ningún tipo <strong>de</strong> comunicación entre ellos.Los componentes que se <strong>de</strong>ben <strong>de</strong>finir a la hora <strong>de</strong>diseñar un esquema <strong>de</strong> migración son los siguientes:la topología <strong>de</strong> migración (dón<strong>de</strong> se migran los individuos),el índice <strong>de</strong> migración (el número máximo<strong>de</strong> individuos que se migran y con qué frecuencia semigra), la estrategia <strong>de</strong> selección <strong>de</strong> individuos quese van a migrar <strong>de</strong>s<strong>de</strong> la isla <strong>de</strong> origen y la estrategia<strong>de</strong> reemplazo <strong>de</strong> individuos en la isla <strong>de</strong> <strong>de</strong>stino.Dependiendo <strong>de</strong>l esquema <strong>de</strong> migración utilizado,la forma <strong>de</strong>l espacio <strong>de</strong> <strong>de</strong>cisión <strong>de</strong> un problema se veafectada [16]. Por ello, en este trabajo se ha comprobadoel funcionamiento <strong>de</strong>l mo<strong>de</strong>lo basado en islascon cuatro esquemas <strong>de</strong> migración diferentes. Los esquemasse han obtenido gracias a la combinación <strong>de</strong>diferentes estrategias <strong>de</strong> selección con diferentes estrategias<strong>de</strong> reemplazo. Se han probado dos estrategias<strong>de</strong> selección: Elitista (eli) y Aleatoria (rnd).Con la estrategia eli, se selecciona un individuo amigrar si es mejor que cualquiera <strong>de</strong> los miembros <strong>de</strong>la población <strong>de</strong> la generación anterior. <strong>La</strong> estrategiarnd elige los individuos a migrar <strong>de</strong> manera aleatoria.Por otro lado, también se han analizado dosestrategias <strong>de</strong> reemplazo: Elitist Ranking (eli), yAleatoria (rnd). <strong>La</strong> estrategia eli agrupa los individuos<strong>de</strong> la población <strong>de</strong> la isla <strong>de</strong> <strong>de</strong>stino en diferentesrankings haciendo uso <strong>de</strong>l operador <strong>de</strong> crowding<strong>JP2011</strong>-71


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011117.3Instancia ArtificialInstancia <strong>de</strong> Malaga117.2164117.1117162Fitness116.9116.8116.7ELI-RNDELI-ELI116.6RND-RNDRND-ELISEQ116.50 5000 10000 15000 20000Tiempo (s)Fitness160158156ELI-RNDELI-ELIRND-RNDRND-ELISEQ0 5000 10000 15000 20000Tiempo (s)Fig. 1. Evolución <strong>de</strong>l Fitness - Mo<strong>de</strong>los Paralelos con 4 IslasFig. 2. Evolución <strong>de</strong>l Fitness - Mo<strong>de</strong>los Paralelos con 4 Islas<strong>de</strong>l nsga-ii. A continuación, se reemplazan individuosseleccionados aleatoriamente <strong>de</strong>l peor rankingdisponible. Con el esquema rnd, los individuos areemplazar se seleccionan aleatoriamente. Cada uno<strong>de</strong> los cuatro esquemas <strong>de</strong> migración estudiados enel presente artículo siguen la siguiente nomenclaturapara su i<strong>de</strong>ntificación: selección – reemplazo. Porejemplo, eli-rnd significa que se ha aplicado un esquema<strong>de</strong> migración con una estrategia <strong>de</strong> selecciónelitista y una estrategia <strong>de</strong> reemplazo aleatoria.IV. Resultados ComputacionalesEn esta Sección se <strong>de</strong>scriben los experimentos llevadosa cabo con los diferentes esquemas <strong>de</strong> optimizaciónpresentados en la Sección III. <strong>La</strong>s pruebasse han lanzado en una máquina con sistema operativoDebian GNU/Linux, 4 procesadores amd R○Opteron TM (mo<strong>de</strong>lo 6164HE) que corren a 1.7 GHz,y con una memoria RAM <strong>de</strong> 64 GB. El compiladorutilizado ha sido gcc 4.4.5. El compilador mpi ha sidoOpenMPI 1.4.2. Se han analizado dos instancias<strong>de</strong>l app. <strong>La</strong> primera <strong>de</strong> ellas es una instancia realmo<strong>de</strong>lando la ciudad <strong>de</strong> Málaga. Esta instancia representaun área urbana <strong>de</strong> 27.2 km 2 . El terreno seha mo<strong>de</strong>lado utilizando una matriz <strong>de</strong> 450 x 300,don<strong>de</strong> cada una <strong>de</strong> las casillas representa una superficie<strong>de</strong> aproximadamente 15 x 15 m 2 <strong>La</strong> instanciacuenta con n = 1000 posibles localizaciones paraubicar las bs. <strong>La</strong> segunda instancia se ha generadoartificialmente. En este caso, el terreno se ha mo<strong>de</strong>ladoutilizando una matriz <strong>de</strong> 287 x 287, y cuentacon n = 349 posibles localizaciones.Debido a la utilización <strong>de</strong> algoritmos estocásticos,cada ejecución se ha repetido 30 veces. Cada experimentose ha llevado a cabo para cada una <strong>de</strong> las dosinstancias analizadas. Para po<strong>de</strong>r proporcionar losresultados con suficiente respaldo estadístico, se hanllevado a cabo las comparativas siguiendo el siguienteanálisis. Primero se lleva a cabo el test <strong>de</strong> Shapiro-Wilk para comprobar si los resultados siguen una distribuciónnormal (Gaussiana) o no. En caso afirmativo,se lleva a cabo el test <strong>de</strong> Levene para comprobarla homogeneidad <strong>de</strong> las varianzas. Si los resultadostienen igual varianza, se realiza el anova. En otrocaso, se lleva a cabo el test <strong>de</strong> Welch. Para distribucionesno Gaussianas, se utiliza el test no paramétrico<strong>de</strong> Kruskal-Wallis que comprueba las medianas <strong>de</strong>los resultados. Todos los test se han llevado a cabocon un nivel <strong>de</strong> confianza <strong>de</strong>l 95 %.Para todos los experimentos se ha utilizado la siguienteparametrización: r = 30, p c = 1, p m = 1 n .Los tamaños <strong>de</strong> población se han fijado a 50 y 100individuos para la instancia artificial y la instancia<strong>de</strong> Málaga, respectivamente.En el primer experimento se ha realizado un análisis<strong>de</strong> la robustez <strong>de</strong>l mo<strong>de</strong>lo paralelo en términos<strong>de</strong>l esquema <strong>de</strong> migración utilizado. El mo<strong>de</strong>lo paralelobasado en islas ha incorporado 4 esquemas<strong>de</strong> migración diferentes, tal y como se ha <strong>de</strong>scritoen la Sección III-B. El mo<strong>de</strong>lo paralelo, con cadauno <strong>de</strong> los esquemas <strong>de</strong> migración, ha sido ejecutadocon 4 islas y con un criterio <strong>de</strong> parada <strong>de</strong> 6 horas.Con todos los esquemas <strong>de</strong> migración se ha utilizadouna topología <strong>de</strong> migración totalmente conectada.A<strong>de</strong>más, la probabilidad <strong>de</strong> migración se ha fijado a0.01, migrando un único individuo cada vez.<strong>La</strong>s Figuras 1 y 2 muestran la evolución <strong>de</strong>l valor<strong>de</strong> fitness medio <strong>de</strong> las aproximaciones secuencial(seq) y paralelas, para la instancia artificial yla instancia <strong>de</strong> Málaga, respectivamente. El mo<strong>de</strong>loparalelo ha mejorado claramente los resultadosobtenidos por la estrategia secuencial en ambas instancias.También se pue<strong>de</strong> observar como los diferentesmo<strong>de</strong>los paralelos han obtenido valores <strong>de</strong> fitnesssimilares. De hecho, los análisis estadísticos han reveladoque las diferencias entre ellos no han sido significativas.No obstante, en ambas instancias, el valor<strong>de</strong> fitness medio más alto ha sido obtenido por el mo<strong>de</strong>loparalelo que incorpora el esquema <strong>de</strong> migracióneli-rnd. Al haber obtenido soluciones <strong>de</strong> alta calidadcon el mo<strong>de</strong>lo paralelo, in<strong>de</strong>pendientemente <strong>de</strong>lesquema <strong>de</strong> migración utilizado, se ha <strong>de</strong>mostrado larobustez <strong>de</strong> la propuesta.Debido a que los mo<strong>de</strong>los paralelos han utilizadomás recursos computacionales que la estrategia secuencial,la mejora <strong>de</strong>be cuantificarse. <strong>La</strong> Run-lengthDistribution (rld) es una herramienta muy útil parallevar a cabo esta tarea. Una rld muestra la relaciónexistente entre el ratio <strong>de</strong> éxito y el tiempo. El ratio<strong>de</strong> éxito se <strong>de</strong>fine como la probabilidad <strong>de</strong> alcanzarcierto nivel <strong>de</strong> calidad. <strong>La</strong>s rld se han calculado paralos mo<strong>de</strong>los paralelos y para la estrategia secuencial.En el caso <strong>de</strong> la instancia artificial, ya que cada mo<strong>de</strong>loparalelo ha sido capaz <strong>de</strong> alcanzar el mejor valor<strong>JP2011</strong>-72


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Instancia ArtificialInstancia <strong>de</strong> Malaga110.80.8Ratio <strong>de</strong> Exito0.60.4ELI-RNDELI-ELI0.2RND-RNDRND-ELISEQ00 10000 20000 30000 40000 50000 60000 70000 80000Tiempo (s)Ratio <strong>de</strong> Exito0.60.4ELI-RNDELI-ELI0.2RND-RNDRND-ELISEQ00 10000 20000 30000 40000 50000 60000 70000 80000Tiempo (s)Fig. 3. RLD - Mo<strong>de</strong>los Paralelos con 4 IslasFig. 5. RLD - Mo<strong>de</strong>los Paralelos con 4 Islas1Instancia Artificial1Instancia <strong>de</strong> Malaga0.80.8Ratio <strong>de</strong> Exito0.60.4Ratio <strong>de</strong> Exito0.60.40.2PAR_16PAR_8PAR_400 5000 10000 15000 20000Tiempo (s)0.2PAR_16PAR_8PAR_400 5000 10000 15000 20000Tiempo (s)Fig. 4. RLD - Mo<strong>de</strong>los Paralelos con 4, 8 y 16 IslasFig. 6. RLD - Mo<strong>de</strong>los Paralelos con 4, 8 y 16 Islas<strong>de</strong> fitness conocido hasta la fecha, dicho valor ha sidoseleccionado como el nivel <strong>de</strong> calidad a alcanzar.En la instancia <strong>de</strong> Málaga la varianza <strong>de</strong> los resultadosha sido superior que en la instancia artificial.De este modo, si se eligiera el mejor valor <strong>de</strong> fitnessconocido como el nivel <strong>de</strong> calidad a alcanzar, se obtendríanratios <strong>de</strong> éxito bajos. Por ello, el nivel <strong>de</strong>calidad se ha fijado <strong>de</strong> modo que todos los mo<strong>de</strong>losparalelos sean capaces <strong>de</strong> alcanzar un ratio <strong>de</strong> éxito<strong>de</strong>l 60 %. <strong>La</strong>s Figuras 3 y 5 muestran las rld <strong>de</strong> losmo<strong>de</strong>los paralelos y <strong>de</strong>l mo<strong>de</strong>lo secuencial, para lainstancia artificial y la instancia <strong>de</strong> Málaga, respectivamente.En el caso <strong>de</strong> la estrategia secuencial, seha consi<strong>de</strong>rado un tiempo máximo <strong>de</strong> ejecución <strong>de</strong> 24horas. Para los mo<strong>de</strong>los paralelos, el tiempo máximo<strong>de</strong> ejecución consi<strong>de</strong>rado ha sido <strong>de</strong> 6 horas. <strong>La</strong>s rldhan confirmado la superioridad <strong>de</strong> los mo<strong>de</strong>los paralelos.En algunos casos se han obtenido factores <strong>de</strong>aceleración superlineales. Esto se <strong>de</strong>be a la capacidad<strong>de</strong> los mo<strong>de</strong>los paralelos para evitar la caída enóptimos locales. <strong>La</strong>s rld también han mostrado lassimilitu<strong>de</strong>s entre los diferentes mo<strong>de</strong>los paralelos. Apesar <strong>de</strong> estas similitu<strong>de</strong>s, el mo<strong>de</strong>lo paralelo que incorporael esquema <strong>de</strong> migración eli-rnd ha sido elque mejor se ha comportado.El segundo experimento ha analizado la escalabilidad<strong>de</strong>l mo<strong>de</strong>lo paralelo propuesto. El mo<strong>de</strong>lo basadoen islas que incorpora el esquema <strong>de</strong> migraciónque mejor se ha comportado en el experimento anterior(eli-rnd, referenciado en este nuevo experimentocomo par4) se ha ejecutado con 8 (par8) y 16(par16) islas. <strong>La</strong>s Figuras 4 y 6 muestran sus rld,para la instancia artificial y la instancia <strong>de</strong> Málaga.Se ha consi<strong>de</strong>rado un tiempo máximo <strong>de</strong> ejecución <strong>de</strong>6 horas. <strong>La</strong>s rld muestran las ventajas <strong>de</strong> añadir unnúmero <strong>de</strong> procesadores mayor al mo<strong>de</strong>lo paralelo.Los factores <strong>de</strong> aceleración, tomando como referenciael mo<strong>de</strong>lo par4, se han calculado para ratios <strong>de</strong>éxito que varían entre un 25 % y un 75 %. En el caso<strong>de</strong> la instancia artificial, el factor <strong>de</strong> aceleración<strong>de</strong>l mo<strong>de</strong>lo par8 ha variado <strong>de</strong>s<strong>de</strong> 1.57 a 1.88. Parael mo<strong>de</strong>lo par16, el factor <strong>de</strong> aceleración ha variadoentre 1.62 y 3.57. Para esta instancia se han <strong>de</strong>tectadoproblemas <strong>de</strong> escalabilidad puntuales. De hecho,los mo<strong>de</strong>los par8 y par16 han obtenido factores <strong>de</strong>aceleración similares para ciertos ratios <strong>de</strong> éxito. Noobstante, par16 ha obtenido factores <strong>de</strong> aceleraciónmás altos para otros ratios <strong>de</strong> éxito, lo que <strong>de</strong>muestralas ventajas <strong>de</strong> aplicarlo. Para la instancia <strong>de</strong> Málaga,también se han <strong>de</strong>tectado algunos problemas <strong>de</strong>escalabilidad. El mo<strong>de</strong>lo par8 no ha <strong>de</strong>mostrado obtenerninguna ventaja significativa respecto al mo<strong>de</strong>lopar4, ya que como pue<strong>de</strong> observarse, las dosrld <strong>de</strong> estos mo<strong>de</strong>los son muy similares. Sin embargo,los factores <strong>de</strong> aceleración han aumentado con laaplicación <strong>de</strong>l mo<strong>de</strong>lo par16. Dichos factores <strong>de</strong> a-celeración, tomando como referencia el mo<strong>de</strong>lo par4han variado entre los valores 1.42 y 1.9.V. Conclusiones y Trabajo FuturoEl app es uno <strong>de</strong> los principales problemas <strong>de</strong> optimizaciónque surgen en el diseño <strong>de</strong> re<strong>de</strong>s <strong>de</strong> telecomunicacionesmóviles. En el presente artículo, seha llevado a cabo el análisis <strong>de</strong> una estrategia híbridaque combina un mo<strong>de</strong>lo paralelo basado en islascon diferentes estrategias <strong>de</strong> multiobjectivización<strong>JP2011</strong>-73


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011aplicadas al app. <strong>La</strong> multiobjetivización es una estrategiamás general que aquellas que hacen uso <strong>de</strong>información <strong>de</strong>pendiente <strong>de</strong>l problema. En [11], sepropusieron numerosas estrategias para multiobjetivizarel app. El esquema <strong>de</strong> optimización estababasado en el algoritmo nsga-ii. <strong>La</strong> mejor estrategiapara multiobjetivizar el app consistía en calcularla distancia Euclí<strong>de</strong>a al mejor individuo <strong>de</strong> lapoblación, es <strong>de</strong>cir, aquel con mayor valor <strong>de</strong> fitness.El peor inconveniente <strong>de</strong> esta estrategia era el aumento<strong>de</strong>l tiempo requerido para obtener soluciones<strong>de</strong> alta calidad, comparándola con las técnicas queincorporaban información <strong>de</strong>pendiente <strong>de</strong>l problema.Para disminuir el tiempo <strong>de</strong> convergencia, en estetrabajo se ha aplicado un mo<strong>de</strong>lo homogéneo basadoen islas. <strong>La</strong> configuración que se ha ejecutado en lasislas es la mejor encontrada para multiobjetivizar elapp [11]. <strong>La</strong>s migraciones son una operación esencialen este tipo <strong>de</strong> mo<strong>de</strong>los paralelos. Por ello, seha llevado a cabo un análisis <strong>de</strong> la robustez <strong>de</strong>l mo<strong>de</strong>loconsi<strong>de</strong>rando diferentes esquemas <strong>de</strong> migración.Los resultados computacionales han <strong>de</strong>mostrado larobustez <strong>de</strong> la propuesta, in<strong>de</strong>pendientemente <strong>de</strong>l esquema<strong>de</strong> migración utilizado. A<strong>de</strong>más, el mo<strong>de</strong>loparalelo ha superado los resultados obtenidos porla correspondiente estrategia secuencial. De hecho,se han obtenido factores <strong>de</strong> aceleración superlinealescuando se ha aplicado el mo<strong>de</strong>lo con 4 islas. Tambiénse ha llevado a cabo un análisis <strong>de</strong> escalabilidad<strong>de</strong>l mo<strong>de</strong>lo paralelo con el esquema <strong>de</strong> migración quemejores resultados ha obtenido (eli-rnd), variandoel número <strong>de</strong> islas hasta un máximo <strong>de</strong> 16. Para ambasinstancias, se han <strong>de</strong>tectado ciertos problemas <strong>de</strong>escalabilidad. El tiempo invertido en alcanzar soluciones<strong>de</strong> alta calidad ha disminuido gracias a la incorporación<strong>de</strong> más procesadores. No obstante, estadisminución no ha sido lineal.El trabajo futuro se centrará en la aplicación <strong>de</strong>hiperheurísticas paralelas al app. Ya que en general,el método <strong>de</strong> optimización a<strong>de</strong>cuado <strong>de</strong>pen<strong>de</strong> <strong>de</strong> lainstancia que se <strong>de</strong>sea resolver, la aplicación <strong>de</strong> hiperheurísticasparece una línea <strong>de</strong> investigación prometedora.<strong>La</strong>s hiperheurísticas, en combinación con elmo<strong>de</strong>lo paralelo presentado, permitirían seleccionar<strong>de</strong> forma automática el método a aplicar en cadaisla. También sería interesante analizar otras instancias<strong>de</strong>l app.Agra<strong>de</strong>cimientosEste trabajo ha sido financiado con fondos ec(fe<strong>de</strong>r) y <strong>de</strong>l Ministerio <strong>de</strong> Ciencia e Innovación,<strong>de</strong>ntro <strong>de</strong>l ‘Plan Nacional <strong>de</strong> i+d+i’ con el proyectocon número <strong>de</strong> referencia tin2008-06491-c04-02.Parte <strong>de</strong>l trabajo también ha sido financiado confondos <strong>de</strong>l Gobierno <strong>de</strong> Canarias correspondientes alproyecto pi2007/015. El trabajo <strong>de</strong> Eduardo Segredoy <strong>de</strong> Carlos Segura ha sido financiado gracias a lasbecas fpu-ap2009-0457 y fpu-ap2008-03213.Referencias[1] Hervé Meunier, El-Ghazali Talbi, and Philippe Reininger,“A Multiobjective Genetic Algorithm for Radio NetworkOptimization,” in In Proceedings of the 2000 Congresson Evolutionary Computation. 2000, pp. 317–324, IEEEPress.[2] S. P. Men<strong>de</strong>s, G. Molina, M. A. Vega-Rodríguez, J. A.Gómez-Pulido, Y. Sáez, G. Miranda, C. Segura, E. Alba,P. Isasi, C. León, and J. M. Sánchez-Pérez, “Benchmarkinga Wi<strong>de</strong> Spectrum of Meta-Heuristic Techniques forthe Radio Network Design Problem,” IEEE Trans. Evol.Comput., pp. 1133–1150, 2009.[3] Carlos Segura, Yanira González, Gara Miranda, andCoromoto León, “A Multi-Objective Evolutionary Approachfor the Antenna Positioning Problem,” inKnowledge-Based and Intelligent Information and EngineeringSystems, Rossitza Setchi, Ivan Jordanov, RobertHowlett, and <strong>La</strong>khmi Jain, Eds., vol. 6276 of LectureNotes in Computer Science, pp. 51–60. Springer Berlin /Hei<strong>de</strong>lberg, 2010.[4] Silvio Priem Men<strong>de</strong>s, Juan A. Gomez Pulido, MiguelA. Vega Rodriguez, Maria D. Jaraiz Simon, and JuanM. Sanchez Perez, “A Differential Evolution Based Algorithmto Optimize the Radio Network Design Problem,”in E-SCIENCE ’06: Proceedings of the SecondIEEE International Conference on e-Science and GridComputing, Washington, DC, USA, 2006, p. 119, IEEEComputer Society.[5] Dong wan Tcha, Young-Soo Myung, and June hyukKwon, “Base Station Location in a Cellular CDMA System,”Telecommunication Systems, vol. 14, no. 1-4, pp.163–173, 2000.[6] El-Ghazali Talbi and Hervé Meunier, “Hierarchical ParallelApproach for GSM Mobile Network Design,” J. ParallelDistrib. Comput., vol. 66, no. 2, pp. 274–290, 2006.[7] E. Alba, “Evolutionary Algorithms for Optimal Placementof Antennae in Radio Network Design,” InternationalParallel and Distributed Processing Symposium,vol. 7, pp. 168, 2004.[8] N. Weicker, G. Szabo, K. Weicker, and P. Widmayer,“Evolutionary Multiobjective Optimization for BaseStation Transmitter Placement with Frequency Assignment,”IEEE Trans. Evol. Comput., vol. 7, no. 2, pp.189–203, 2003.[9] Mohan R. Akella, Rajan Batta, Eric M. Delmelle, PeterA. Rogerson, Alan Blatt, and Glenn Wilson, “BaseStation Location and Channel Allocation in a CellularNetwork with Emergency Coverage Requirements,” EuropeanJournal of Operational Research, vol. 164, no. 2,pp. 301 – 323, 2005.[10] Joshua D. Knowles, Richard A. Watson, and DavidCorne, “Reducing Local Optima in Single-ObjectiveProblems by Multi-objectivization,” in Proceedings of theFirst International Conference on Evolutionary Multi-Criterion Optimization, London, UK, 2001, EMO ’01,pp. 269–283, Springer-Verlag.[11] Carlos Segura, Eduardo Segredo, Yanira González, andCoromoto León, “Multiobjectivisation of the AntennaPositioning Problem,” in International Symposium onDistributed Computing and Artificial Intelligence, AjithAbraham, Juan Corchado, Sara González, and JuanDe Paz Santana, Eds., vol. 91 of Advances in Intelligentand Soft Computing, pp. 319–327. Springer Berlin / Hei<strong>de</strong>lberg,2011.[12] Enrique Alba, Parallel Metaheuristics: A New Class ofAlgorithms, Wiley-Interscience, 2005.[13] C. A. Coello, G. B. <strong>La</strong>mont, and D. A. Van Veldhuizen,Evolutionary Algorithms for Solving Multi-Objective Problems, Genetic and Evolutionary Computation.2007.[14] Julia Handl, Simon C. Lovell, and Joshua Knowles, “Multiobjectivizationby Decomposition of Scalar Cost Functions,”in Proceedings of the 10th International Conferenceon Parallel Problem Solving from Nature: PPSN X,Berlin, Hei<strong>de</strong>lberg, 2008, pp. 31–40, Springer-Verlag.[15] Dimo Brockhoff, Tobias Friedrich, Nils Hebbinghaus,Christian Klein, Frank Neumann, and Eckart Zitzler, “DoAdditional Objectives Make a Problem Har<strong>de</strong>r?,” in Proceedingsof the 9th Annual Conference on Genetic andEvolutionary Computation, New York, NY, USA, 2007,GECCO ’07, pp. 765–772, ACM.[16] David A. Van Veldhuizen, Jesse B. Zydallis, and Gary B.<strong>La</strong>mont, “Consi<strong>de</strong>rations in Engineering Parallel MultiobjectiveEvolutionary Algorithms,” IEEE Trans. Evol.Comput., vol. 7, no. 2, pp. 144–173, 2003.<strong>JP2011</strong>-74


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Exhaustive Program’s Robustness Analysisagainst Transient FaultsJoao Gramacho *,1 , Dolores Rexachs *,2 y Emilio Luque *,3Abstract — Computer chips implementation technologiesevolving to obtain more performance are increasing theprobability of transient faults. As this probability growsand on-chip solutions are expensive or tend to <strong>de</strong>gra<strong>de</strong>processor performance, the efforts to <strong>de</strong>al with thesetransient faults in all levels (including the operating systemand even at the application level) are increasing. Softwarebased fault tolerance approaches against transient faultsoften use fault injection experiments to evaluate therobustness of applications with and without their fault<strong>de</strong>tection or fault tolerance proposals. Those fault injectionexperiments consumes lots of CPU time by running orsimulating the application being evaluated as many timesas necessary to obtain a reasonable valid statisticalapproximation. This paper presents the first step of ourpurpose of exhaustively analyzing program’s robustnessagainst transient faults. We use processor architectureinformation and a program trace to analyze the programrobustness in a one step evaluation without the need oftime consuming executions with fault injection.Keywords — Transient faults, robustness, reliability.TI. INTRODUCTIONhe ever growing die <strong>de</strong>nsity of computer processorsis one of the great factors of the astonishingimprovements in processing power of the last <strong>de</strong>ca<strong>de</strong>s.Computer chips are using smaller components, havingmore transistors, using those transistors with higher<strong>de</strong>nsity and also operating at lower voltage. The si<strong>de</strong>effect of such a scenario is that processors are lessrobust than ever against transient faults [1].Transient faults are those faults that might occur onlyonce in a system lifetime and never happen again thesame way. Transient faults in computer systems mayoccur in processors, memory, internal buses and <strong>de</strong>vices,often resulting in an inversion of a bit state (i.e. singlebit flip) on the faulty location [2]. Cosmic radiation,high operating temperature and variations in the powersupply subsystem are the most common cause oftransient faults in computer systems.A transient fault may cause an application tomisbehave (e.g. write into an invalid memory position;attempt to execute an inexistent instruction). Suchmisbehaved applications will then be abruptlyinterrupted by the operating system fail-stop mechanism.Nevertheless, an un<strong>de</strong>tected data corruption is thebiggest risk for applications. It happens when the flippedbit produced by the transient fault generates an incorrectfinal program result that might not be ever noticed.The errors that can be noticed by the transient faultseffect are called soft errors.We consi<strong>de</strong>r program’s robustness against transient* Computer Architecture and Operating Systems Department,Universitat Autònoma <strong>de</strong> Barcelona, Bellaterra (Barcelona), Spain.1 E-mail: joao.gramacho@caos.uab.es2 E-mail: dolores.rexachs@uab.es3 E-mail: emilio.luque@uab.esfaults as the ability of a program, one in presence of atransient fault, to keep running and give a correct resultwhen finish or to stop the execution when a soft error is<strong>de</strong>tected and inform about it.To evaluate a program robustness against transientfault, we consi<strong>de</strong>r that a program, running over an<strong>de</strong>termined architecture, will have a robustness againsttransient faults represented as a number that can varyfrom zero (0%) to one (100%), where zero implies norobustness at all (the program fail on every tested cases)and one implies the best robustness possible (theprogram gave the correct result or <strong>de</strong>tected the transientfault on every tested cases).In or<strong>de</strong>r to test a program behavior in presence oftransient faults, it is common to put a program to betested in an environment <strong>de</strong>signed to allow transient likefault injections. In this way, it is possible to evaluate ifthe program misbehaved in presence of a transient faultor if the program was robust and could finish properly or<strong>de</strong>tected the injected fault and stopped its executionavoiding the error propagation. These fault injections arema<strong>de</strong> often by flipping a bit of a processor register in agiven point during program execution.Using program execution in presence of faultinjections to evaluate its behavior can be a timeconsuming task. This is because of the need to executethe program in the fault injection environment as manytimes as nee<strong>de</strong>d (varying the fault injection point in timeand where to inject the fault) to have a result withsignificant statistical approximation, as we will show insection II.Our objective in this work is to propose a method tocalculate a program’s robustness, without any faultinjection execution. To do so, in section III we present amethod to calculate the amount of all possible unACEcases of a program running over a given processorarchitecture based a trace of the program execution overthe architecture and information about how thearchitecture instructions <strong>de</strong>al with processor registers.We want a method to have a precisely calculatedrobustness and also avoid the time consuming task ofdoing hundreds or thousands of program executions intransient fault injection environments.In section IV we present our experimental evaluationby comparing the result of fault injection campaignswith the results obtained using our analysis method andin section V we present our conclusion and explainabout the next steps of our method.II. ROBUSTNESS EVALUATION USING FAULT INJECTIONExperimental methods of injecting transient faults intoa program during its execution were proposed to testpurposed protection mechanisms against transient faults.On those methods, the program being evaluated isexecuted in an environment able to inject a fault in a<strong>JP2011</strong>-75


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011form of a bit flip on a program architectural state(usually a bit in a processor register). At the end of theprogram’s execution, its result is evaluated to check theeffect caused by the fault into the execution.When the program has finished correctly and haspresented the same result of a fault free execution theprogram’s architectural bit changed by the fault injectionis classified as unACE (unnecessary for anArchitecturally Correct Execution). On the other hand,when the program didn’t finished correctly, or haspresented a result different of the fault free execution,the program’s architectural bit changed by the faultinjection is classified as ACE (necessary for anArchitecturally Correct Execution).If the program being evaluated has some kind of fault<strong>de</strong>tection mechanism against transient faults theprogram architectural bits changed may trigger the fault<strong>de</strong>tection mechanism and lead the program to a fail stopavoiding the propagation of the fault effect in theprogram execution. On those cases, instead of beingclassified as ACE, as the execution finished doing a failstop and noticed that a fault happened the programarchitectural bit changed is classified as DUE (DetectedUnrecoverable Error).As changes in the ACE program architectural bits leadto an abnormal program behavior and also could lead toa result different of the obtained by a fault-freeexecution, it is common to classify those bits as SDC(Silent Data Corruption). = 1 (1)To evaluate how reliable a program is in presence oftransient faults with a sufficient large amount ofexecutions with fault injection, we can divi<strong>de</strong> theamount of executions that didn’t failed (those in whichthe program architectural bit changed was classified asunACE or DUE) by total amount of executions withfault injection performed. Also, it is important to have agood distribution in which program architectural bit ischanged on each execution, since it is randomly chosen.The authors of [3] propose a soft error <strong>de</strong>tectionmechanism based on source co<strong>de</strong> transformation rules.The new program (compiled with the source co<strong>de</strong>transformed with the fault <strong>de</strong>tection mechanism) has thesame functionality as the original program but is able to<strong>de</strong>tect bit-flips in memory and processor registers duringan execution.Evaluating programs with and without their fault<strong>de</strong>tection mechanism, the authors of [3] performed a setof fault injection experiments where on each execution abit was flipped in processor registers, program co<strong>de</strong>memory region or program data memory region. A totalof 52,728 executions with fault injection wereperformed to evaluate two programs (the original oneand the changed to <strong>de</strong>tect soft errors), 26,364 executionsper program on average.In Error Detection by Duplicated Instructions (EDDI)[4], the authors reduced the amount of SDC cases ofprograms by, during program’s compilation, copyinginstructions but using different processor registers andadding verification for errors by comparing the value ofthe original processor register used by the program withthe value of the processor register used in the newgenerated instruction.Executing a total of four evaluations (the originalprogram, the program with EDDI and the program withthree source co<strong>de</strong> based fault <strong>de</strong>tection mechanisms) pereach of the eight benchmarks evaluated and executing500 simulations with fault injection per evaluation, theauthors of [4] have ma<strong>de</strong> a total of 16,000 simulations toaccomplish their work.On Software-Controlled Fault Tolerance [5], theauthors presented a set of transient fault <strong>de</strong>tectiontechniques based on software and also hybrid (based onsoftware and hardware). Each of the proposedtechniques has a different cost/benefit relation byimproving reliability or performance.The first technique presented by [5] is SWIFT(Software Implemented Fault Tolerance) which reducesan application’s amount of SDC cases by changing theprogram during compilation time. The other techniquespresented are all hybrid. The set of those hybridtechniques is called CRAFT (Compiler-Assisted FaultTolerance). In general, reduces the amount of SDC caseseven more than SWIFT and also improve theperformance of the program in comparison withsoftware-only fault tolerance techniques.To evaluate the amount of SDC cases of an applicationwith and without the proposed fault tolerancemechanisms, the authors of [5] executed fault injectionexperiments in a simulator executing all programs to theend using a functional simulator and choosing when andwhere to inject the fault randomly. The authors classifiedthe fault injection simulation result as unACE if theflipped bit wasn’t necessary to the correct architecturalexecution, as DUE if the flipped bit triggered a fault<strong>de</strong>tection mechanism, or as SDC it the flipped bitgenerated a silence data corruption.The authors of [5] used a benchmark to evaluate howmany fault injections should be necessary to have asignificant statistical approximation of results. Theyexecuted 5,000 fault injection simulations with thebenchmark and observed that the confi<strong>de</strong>nce interval ofthe average of the SDC cases was ±2.0% after 946simulations, ±1.5% after 1,650 simulations and ±1.0%after 3,875 simulations.In a total of 10 sets of experiments, the authors of [5]evaluated the robustness of a set of benchmarks bysimulating 5,000 executions with fault injection (exceptfor two SWIFT variations that used 1,000 simulations).In each of 504,000 simulated executions with faultinjection a randomly chosen bit of one of 127 integerprocessor registers of IA64 processor architecture wasflipped.Because of the use of a simulator to execute <strong>de</strong>program with a fault injection, the authors of [5] couldsave some simulation time on the executions where thebit flipped was classified as unACE. On those cases, thesimulation could be interrupted when the simulatorobserved that the flipped bit was re-written with resultsfrom processor logical unit or with a write operationbefore having it content used.Continuing their research in fault tolerance fortransient faults, the authors of [5] propose Spot [6], atechnique to dynamically insert redundant instructions to<strong>de</strong>tect errors generated by transient faults. This insertionwas ma<strong>de</strong> in runtime using instrumentation.<strong>JP2011</strong>-76


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Besi<strong>de</strong>s using a different architecture from previouswork (in [6] they used IA32 and protected only the eightgeneral purpose 32 bit registers of the architecture), theauthors didn’t use simulators. All the analysis and faultinjections were ma<strong>de</strong> using an instrumentation tool. Theauthors of [6] evaluated 16 benchmarks and executed atotal of 1.03 million fault injections to obtain theirresults (keeping 5,000 executions with fault injection perbenchmark and configuration evaluated).In all related work studied, the execution of a programin a transient fault injection environment could beclassified in terms of basically three labels: unACE,DUE and SDC.To compute a program’s robustness against transientfaults using fault injection we only need to divi<strong>de</strong> theamount of unACE cases, plus the amount of DUE cases,by the amount of executions ma<strong>de</strong> in the experiment. = = 1 − (2) If all executions are classified as SDC, the robustnesswill be zero (the minimal robustness allowed). On theother hand, if all executions are classified as unACE orDUE, the robustness will be one (the maximumrobustness allowed).The robustness evaluation method using program’sexecutions with fault injection need a sufficient largeamount of executions varying the fault conditions (time,register and bit) to have a representative statisticalapproximation of the results.One aspect that must be took into account when usingfault injection to evaluate a program’s robustness is thatthis method is data <strong>de</strong>pen<strong>de</strong>nt. Faults injected in specificbits of floating point registers can lead to almost nochange in its value <strong>de</strong>pending on its original value. Also,as general purpose registers are often used as pointers tovectors or matrices of data, if this data is homogenous(e.g. a vector filled with ones) there are many changesthat can be done in registers that will make them point toa different memory position but with the same data,masking the fault injection result as unACE.Also, it is known that by using a fault injection base<strong>de</strong>valuation of robustness, the amount of executions toevaluate a program will affect the precision ofrobustness obtained [5].Finally, using simulators or dynamicallyinstrumentation to inject fault on every programexecution will increase time nee<strong>de</strong>d on each executionin comparison with a time spent by the program runningdirectly in the architecture without instrumentation.III. ANALYZING A PROGRAM’S ROBUSTNESSOur objective is to evaluate a program’s robustnessexhaustively and faster than using fault injectionexecutions, even knowing that our method is based onthe evaluation of the possible effect of a single bit flipfault injection in processor registers of a givenarchitecture.To do so, we will evaluate in this first work the unACEbits of all possible execution points of the program (allpoints of program execution that a fault injection toolcould stop the program execution, perform the faultinjection and let the program finish its execution) for allprocessor registers.This evaluation will be equivalent to running as muchfault injection executions as necessary to test all bits ofall processor registers at any program execution pointbut, instead of performing all this executions, we willuse a program trace generated on a single programexecution and containing all processor instructionsexecuted by the program in the or<strong>de</strong>r of execution.At this point of our research we are only evaluating theunACE cases. So, by knowing all unACE bits of aprogram execution, we can calculate the minimalprogram robustness as shown in equation 3.unACE bits 0 = (3)bits evaluatedThe work we have to do is, then, to evaluate allunACE bits of a program prog execution in a givenarchitecture A.From the architecture, we need a set of processorregisters (ProcReg) and a finite non-numerical sequenceRegSize representing the register sizes in bits <strong>de</strong>fined bythe f RegSize function. = , , ⋯ , (4) : ⟼ N = , , ⋯ , Also from architecture, we will need a set of processorinstructions (ProcIns) and a set ProcInsReg containingall or<strong>de</strong>red pairs of processor instructions and processorregisters of a given architecture. = , , ⋯ , (5) = , , ⋯ , , For each pair processor instruction and processorregister in ProcInsReg set, we will need two nonnumericalsequences: WrittenBits, <strong>de</strong>fined by the f wbitsfunction and ReadBits, <strong>de</strong>fined by the f rbits function.The f wbits function returns a vector of bits equivalent tosetting all bits of the processor register that are writtenby the processor instruction. : × ⟼ (6)The f rbits function returns a vector of bits equivalent tosetting all bits of a processor register that are read by aprocessor instruction. : × ⟼ (7)To know which processor instructions are used by theprogram being evaluated and in which sequence they areexecuted, we need a Trace prog×A as a finite sequence<strong>de</strong>fined by the function f prog that returns the processorinstruction executed by the program at given executionpoint. : N ⟼ (8) × = , , ⋯ , × Each instruction present on Trace prog×A is equivalent toa point in program execution in which is possible toinject a bit flip fault in a processor register.A. Robust state <strong>de</strong>finitionLet’s consi<strong>de</strong>r now robust state a property of aprocessor register in a given point of a programexecution in a form of a vector of bits where all register<strong>JP2011</strong>-77


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011bits that we can classify as unACE are set with 1 and allother register bits are cleared (with 0). The robust stateproperty can be <strong>de</strong>fined also by the function f rstate that wewill <strong>de</strong>tail later in this section. : × N ⟼ (9)To help us in the program robustness formula we needto <strong>de</strong>fine a function f abits that returns the amount of bitsset (with 1 as its value) in a given vector of bits. : ⟼ N (10)The robustness of a program prog executed over anarchitecture A can be calculated using the formula: × × = ∑ ∑ , × ∙∑ (11)In fact, the robustness of any contiguous part TPart ofthe Trace prog×A sequence (that is also a sequence),starting on point p begin until the point p end can becalculated using the formula: × =∑ ∑ , ∙∑ (12)With the robustness formula presented in equation 12we can calculate the robustness of a single instruction(by making p begin equals p end ) or the robustness of thewhole program (by making p begin equals one and p en<strong>de</strong>quals the number of instructions executed by theprogram) as shown in equation 11.B. Calculating an instruction × register robust stateOur proposed method of calculating the robust state ofa single register in a given execution point of a programis based in the method proposed by the authors of [5] tosave time on those simulations where it was possible tointerrupt a simulation after the fault injection when thesimulator noticed that the flipped bit was classified asunACE.In the mentioned work, the importance of the flippedbit was checked by monitoring the use of the processorregister affected by the injection. The simulator kepttrack of the register after the fault injection.If the processor register was rewritten with resultsfrom processors logical unit (as a result of someoperation that didn’t <strong>de</strong>pend on the processor registeraffected value) or with data from a read operation frommemory (that, also, didn’t <strong>de</strong>pend on the processorregister affected value), the authors assumed that theflipped bit could be classified as unACE and there wasno need to keep running the simulation because they wassure of the fact that the bit flipped by the injectionwasn’t necessary to programs correct execution. Insummary, the unACE cases represent those faultinjections where the flipped bit was discar<strong>de</strong>d beforeused.Besi<strong>de</strong>s the fact that we don’t use simulators in ourwork, to check the prece<strong>de</strong>nce use of processor registersvalues we have a trace of the executed program with allprocessor instructions in the or<strong>de</strong>r they are executed.By analyzing the trace backwards, we can, trace pointby trace point, evaluate the prece<strong>de</strong>nce use of processorregisters and then classify its bits (on each trace point)as unACE or no.We assume that all processor registers will have itsrobust state with all bits set (all bits unACE) after theexecution of the last program’s instruction in the trace.At this point, the program has finished its work and afault injected in any bit of any processor register won’taffect programs result. To this robust state just after thelast one present on the evaluated trace we will <strong>de</strong>fine thef endstate function. : ⟼ (13) = ∀: 1 ≤ ≤ → = 1Evaluating then the very last executed instruction inthe trace i, we will use the formula presented in equation14 to compute the robust state of processor registers atthis point. = × ; = (14) , = ∨ , ∧∼ , With the presented formula, if the instruction i don’tread from or write to a register reg, the values of f wbitsand f rbits will be zero and the resulting f rstate of theregister will be a copy of its f endstate .If the instruction i evaluated writes on a given registerreg, f wbits will have all its bits set to one. In this case, thevalue of the register in trace points with lower than theevaluated one will be discar<strong>de</strong>d at this point and so wecan assume that at this point (before executing theinstruction i at trace point n) all register bits can beclassified as unACE.If the instruction i evaluated read from a given registerreg, f rbits will have all its bits set to one. In this case, thevalue of the register in trace points with lower than theevaluated one will be nee<strong>de</strong>d at this point and so we canassume that at this point (before executing theinstruction i at trace point n) all register bits can beclassified as ACE.We assume that if a processor instruction reads a valuefrom a register, compute and store a result in the sameregister, the or<strong>de</strong>r of the operations are first the read andthen the write. But, as we analyze the program tracebackwards, in our formula we first use the f wbits and thenuse the f rbits .All other program trace instructions in which we needto analyze the robust state of processor registers will usea formula that guarantee the or<strong>de</strong>r used on the analysis.1 ≤ < × ; = (15) , = , 1 ∨ , ∧∼ , At this point of our analysis we have all formulasnee<strong>de</strong>d to compute the robustness of a program in agiven architecture.IV. EXPERIMENTAL EVALUATIONA. Proof of ConceptIn to check the i<strong>de</strong>a presented in this work, we haveselected a simple example as a proof of concept.We <strong>de</strong>veloped a simple exponentiation program for the6502 processor architecture that solves the followingequation: = . The source co<strong>de</strong> of theprogram is shown in Fig. 1.To evaluate the program using fault injection, we firstselected the program input parameters (three to the baseoperand and five to the exponent operand). Then, we ranthe program and stored what we consi<strong>de</strong>r a correctresult: 243 in the res memory position.<strong>JP2011</strong>-78


1<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011; exponentiation.65s.ORG $0200; Store machine co<strong>de</strong> starting hereLDX exponent ; Load the exponent into X registerBEQ ONE ; If it is zero, the result is oneDEXLDA base ; Load the base into accumulator registerBEQ ZERO ; If it is zero, finish the operation with zero as resultSTA res ; Store the accumulator register intoMULT1: STA mul ; Store the accumulator into multiplication resultLDY base ; Load the base into Y registerDEYMULT2: ADC mul ; Add the multiplication result to the accumulatorDEY; Decrement Y registerBNE MULT2 ; Jump if is still multiplyingSTA res ; Store the accumulator into the resultDEX; Decrement X register (exponent)BNE MULT1 ; Jump if is still operating the exponentiationJMP FINISHONE: LDA #$01 ; The result is 1 (zero on exponent)JMP FINISHZERO: LDA #$00 ; The result is 0 (zero on base)FINISH: STA res ; Store the result in byte labelled resBRK; Stop running the programbase: .DB $03 ; Base operan<strong>de</strong>xponent: .DB $05 ; Exponent operantres: .DB $00 ; Result of the operationmul: .DB $00 ; Auxiliar variable to multiplicationFig. 1. Simple exponentiation program source co<strong>de</strong>.The 6502 processor architecture has 11 registers (fourwith eight bits and seven with one bit).The program executed 57 instructions to compute untilthe end. Thinking about a fault injection evaluation,there are 57 different fault injection points to thisprogram with the selected input parameters. On eachfault injection point the architecture has 39 different bitsto be flipped (32 from the four eight bit registers and therest from the seven one bit registers).In or<strong>de</strong>r to evaluate the robustness of the programrunning over the presented architecture exhaustively wewill need 2223 program executions with fault injection.Our fault injection experiment used a 6502 simulatorto run the program, pausing its execution at a givenrandomly chosen point and performing a random bit flipin an also randomly chosen processor register. In ourexperiment, we take care of avoid repeating a faultinjection with the same injection point, bit and register.As shown in Fig. 2, we scored a final robustness of49.44% with all 2223 fault injection results. We obtaineda standard <strong>de</strong>viation of 5% after 266 fault injections,2.5% after 1102 fault injections and 2% after 1738 faultinjections, all with a 95% of confi<strong>de</strong>nce.By generating a trace with all program’s instructionsexecuted and analyzing the trace with our methodology,we have built a graph with the program basic blocks andtheir repetition during program’s execution, as shown inFig. 3.100%90%80%70%60%Robustness-std<strong>de</strong>v+std<strong>de</strong>vFig. 3. Program source co<strong>de</strong> and basic block execution graph.Evaluating our trace backwards, basic block by basicblock, calculating the robust state and the amount ofunACE bits for every basic clock instruction, weobtained a total of 1099 unACE bits, as show in Fig. 4.In or<strong>de</strong>r to compute the robustness using the formulapresented previously in equation 15 is necessary tocalculate the robust bits (unACE bits) of all register ofthe 6502 architecture in all 57 instruction of the programexecution trace.By dividing the amount of unACE bits of the programtrace evaluation (1099) by the amount programinstructions executed (57) multiplied by the sum of allprocessor registers sizes (39), we obtained therobustness evaluated with the analysis as 49.44%.This result was expected to be equal to the evaluationwith fault injection because, in this proof of concept, theevaluated program was sufficiently simple to allow us toperform an exhaustive fault injection campaign coveringall possible bits of all possible processor registers in allprogram execution points.Basic BlocksDescriptionInstructionA X Y N V B D I Z C SRegisters unACE bitsAll registers can be ignored. BREAK 8 8 8 1 1 1 1 1 1 1 8 39 1 39JRead from A: change its robustness to 0. STA $0232 0 8 8 1 1 1 1 1 1 1 8 31 1 31G (->J) Nothing changed. JMP $022B 0 8 8 1 1 1 1 1 1 1 8 31 1 31Read from Z: change its robustness to 0. BNE $020E 0 8 8 1 1 1 1 1 0 1 8 30 1 30Write on X, N and Z: change N and Z robustness to 1 and XF (->G) robustness to 8.DEX 0 0 8 1 1 1 1 1 1 1 8 23 1 23Read on X: change its robustness to 0.Read from A: change its robustness to 0. STA $0232 0 0 8 1 1 1 1 1 1 1 8 23 1 23Read from Z: change its robustness to 0. BNE $0215 0 0 8 1 1 1 1 1 0 1 8 22 4 88Write on Y, N and Z: change N and Z robustness to 1 and Yrobustness to 8.DEY 0 0 0 1 1 1 1 1 1 1 8 15 4 60E (->F) Read on Y: change its robustness to 0.Write on A, N, B, Z and C: change N, B, Z and C robustnessADC $0233 0 0 0 1 1 1 0 1 1 0 8 13 4 52to 1 and A robustness to 8.Read from A, C and D: change its robustness to 0.Read from Z: change its robustness to 0. BNE $0215 0 0 0 1 1 1 0 1 0 0 8 12 4 48Write on Y, N and Z: change N and Z robustness to 1 and Yrobustness to 8.DEY 0 0 0 1 1 1 0 1 1 0 8 13 4 52E (->E) Read from Y: change its robustness to 0.Write on A, N, B, Z and C: change N, B, Z and C robustnessADC $0233 0 0 0 1 1 1 0 1 1 0 8 13 4 52to 1 and A robustness to 8.Read from A, C and D: change its robustness to 0.Write on Y, N and Z: change N and Z robustness to 1 and YDEY 0 0 0 1 1 1 0 1 1 0 8 13 4 52robustness to 8.Read from Y: change its robustness to 0.D (->E) Write on Y, N and Z: change N and Z robustness to 1 and Yrobustness to 8. LDY $0230 0 0 8 1 1 1 0 1 1 0 8 21 4 84Read from A: change its robustness to 0. STA $0233 0 0 8 1 1 1 0 1 1 0 8 21 4 84Read from Z: change its robustness to 0. BNE $020E 0 0 8 1 1 1 0 1 0 0 8 20 3 60Write on X, N and Z: change N and Z robustness to 1 and XF (->D)DEX 0 0 8 1 1 1 0 1 1 0 8 21 3 63robustness to 8.Read from X: change its robustness to 0.Read from A: change its robustness to 0. STA $0232 0 0 8 1 1 1 0 1 1 0 8 21 3 63C (->D) Read from A: change its robustness to 0. STA $0232 0 0 8 1 1 1 0 1 1 0 8 21 1 21Read from Z: change its robustness to 0. BEQ $0229 0 0 8 1 1 1 0 1 0 0 8 20 1 20Write on A, N and Z: change N and Z robustness to 1 and Arobustness to 8. LDA $0230 8 0 8 1 1 1 0 1 1 0 8 29 1 29B (->C)Write on X, N and Z: change N and Z robustness to 1 and Xrobustness to 8.DEX 8 0 8 1 1 1 0 1 1 0 8 29 1 29Read from X: change its robustness to 0.Read from Z: change its robustness to 0. BEQ $0224 8 0 8 1 1 1 0 1 0 0 8 28 1 28A (->B) Write on X, N and Z: change N and Z robustness to 1 and Xrobustness to 8. LDX $0231 8 8 8 1 1 1 0 1 1 0 8 37 1 37unACE bitsRepetitionTotal unACE bitsTotal program unACE bits 109950%40%30%20%10%0%79157235313391469547625703781859937101510931171124913271405148315611639171717951873195120292107Fig. 2. Robustness chart using fault injection experiments.2185Fig. 4. Basic block analysis with the proposed methodology.B. Experimental EvaluationIn or<strong>de</strong>r to compare our methodology with a faultinjection campaign we <strong>de</strong>signed a set of experiments tocalculate the robustness against transient faults of fiveprograms: NAS Parallel Benchmark (version 3.3) BT,CG, FT, LU and SP with their smallest class (S).<strong>JP2011</strong>-79


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011The fault injection environment used in this part f theexperimental evaluation uses a tool based on Intel PIN[7] to flip a single randomly chosen bit of a randomlychosen processor register in an also randomly chosenpoint of a program execution.In or<strong>de</strong>r to calculate the selected benchmarksprogram’s robustness against transient faults using themethodology proposed in this work we used a tool basedon Intel PIN [7] to store in a trace file the data collectedduring a program execution. In the stored data are theamount and the or<strong>de</strong>r of execution of every executedprogram’s basic block, and also all processorinstructions that compose all stored basic blocks.We also <strong>de</strong>veloped a program to read the storedprogram trace and, based on information about howprocessor instructions <strong>de</strong>al with registers, calculate theprogram’s robustness of each processor register byanalyzing the program trace backwards, as suggests thepresented methodology.As we present in Fig. 5, the calculated robustnessusing our methodology is always lower than thecalculated using fault injection executions or it can behigher (but almost the same) <strong>de</strong>pending on the amountof executions done to calculate <strong>de</strong> robustness using faultinjection and the random number generator and seedused.Our methodology will score a lower robustnessbecause the approach of using fault injection is moredata <strong>de</strong>pen<strong>de</strong>nt than our proposal and can mask possibleDUE and SDC as unACE.On the analysis of the CPU time spent during therobustness calculation using the proposed methodologyin Fig. 6, we used on average almost 60% of the timenee<strong>de</strong>d to run enough experiments using the besttheoretical fault injection method and achieve 2% ofstandard <strong>de</strong>viation in the statistical approximation.Also, comparing the CPU time spent during therobustness calculation using the proposed methodologywith a real fault injection environment used based ondynamic instrumentation to inject the faults, we nee<strong>de</strong>don average only 1.22% of the time nee<strong>de</strong>d to achieve 2%of standard <strong>de</strong>viation in the fault injection statisticalapproximation.RobustnessTime (in seconds)100%90%80%70%60%50%40%30%20%10%0%100.000Fig. 5. Our methodology vs. fault injection robustness’s.10.0001.00010010129,88%420,6555,41%57,35%56,05%Fig. 6. Time spent on calculating robustness’s.49,71%BT CG FT LU SP1.205,7469.537,41Our Methodology251,11528,1618.877,20448,8362,34%Fault Injection687,68BT CG FT LU SPOur Methodology15.227,9628,93%143,38161,5239,14%Fault Injection theorical best time to achive 2% of standard <strong>de</strong>viationFault Injection using instrumentation to achive 2% of standard <strong>de</strong>viation21.590,25157,9439,18%268,0044,94%28.074,19V. CONCLUSION AND FUTURE WORKEvaluate a program’s robustness against transientfaults by using software based fault injectionenvironments and executing the evaluated program forhundreds or even thousands of times can be anexpensive task by the amount of CPU time nee<strong>de</strong>d toobtain a statistical approximation of the <strong>de</strong>sired result,even using any type of parallelism.In this paper we proposed a methodology calculate aprogram’s robustness against transient faults based oninformation about the processor architecture used and onan execution trace of the program running over thearchitecture.The proposed methodology calculate the preciseamount of unACE bits by analyzing the execution tracebackwards and saving time by using the partial results ofrepetitions that happened during program execution.We were able to calculate the robustness almost 41%faster on average than running the programs evaluatedwith the fastest theoretical fault injection mechanismenough times to score 2% of standard <strong>de</strong>viation of theunACE cases.The next step of our work is to improve ourexperimental evaluation with more benchmarks used bythe referenced work, evaluating both the robustness andthe amount of time nee<strong>de</strong>d to do all experimentation.Also, as in this first step of our methodology we onlyclassify the unACE bits, in a next step of our work wewill divi<strong>de</strong> the ACE bits in two classifications: DUE andSDC. By knowing precisely the amount of DUE bits of aprogram will improve even more our robustnessevaluation.ACKNOWLEDGESThis research has been supported by the MICINNSpain, un<strong>de</strong>r contract TIN2007-64974.REFERENCES[1] N. J. Wang, J. Quek, T. M. Rafacz, S. J. Patel, “Characterizingthe Effects of Transient Faults on a High-Performance ProcessorPipeline,” in Proceedings of the 2004 International Conferenceon Dependable Systems and Networks, pp. 61—70.[2] R. Baumann, “Soft errors in advanced computer systems,” inDesign & Test of Computers, 2005, vol. 22, pp. 258—266.[3] B. Nicolescu, R. Velazco, “Detecting soft errors by a purelysoftware approach: method, tools and experimental results,” inDesign, Automation and Test in Europe Conference andExhibition, 2003, pp. 57—62.[4] N. Oh, P. Shirvani, E. McCluskey, “Error <strong>de</strong>tection by duplicatedinstructions in super-scalar processors,” in IEEE Transactions onReliability, 2002, vol. 51, pp. 63—75.[5] G. A. Reis, J. Chang, N. Vachharajani, R. Rangan, D. I. August,S. S. Mukherjee, “Software-controlled fault tolerance,” in ACMTransactions on Architecture and Co<strong>de</strong> Optimization, 2005, vol.2, pp. 366—396.[6] G. A. Reis, J. Chang, D. I. August, R. Cohn, S. S. Mukherjee,“Configurable Transient Fault Detection via Dynamic BinaryTranslation,” in Proceedings of the 2nd Workshop onArchitectural Reliability (2006).[7] C. Luk, R. Cohn, R. Muth, H. Patil, A. Klauser, G. Lowney, S.Wallace, V. J. Reddi, K. Hazelwood. “Pin: building customizedprogram analysis tools with dynamic instrumentation” inProceedings of the 2005 ACM SIGPLAN conference onProgramming language <strong>de</strong>sign and implementation, pp. 190—200.<strong>JP2011</strong>-80


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Biblioteca <strong>de</strong> Altas Prestaciones para laResolución <strong>de</strong> Problemas MatricialesEstructuradosPedro Alonso-Jordá 1 , Pablo Martínez-Naredo 2 , F.J. Martínez-Zaldívar 3 , José Ranilla 4 yAntonio M. Vidal 5Resumen— Este artículo presenta StructPack, unabiblioteca o conjunto <strong>de</strong> subrutinas y programas queresuelven sistemas lineales estructurados, sobre arquitecturas<strong>de</strong> última generación, tanto secuenciales comoparalelas. Es un paquete <strong>de</strong> software en continuaevolución que actualmente contiene rutinas para laresolución <strong>de</strong> sistemas con matrices Toeplitz simétricastridiagonales y simétricas. StructPack pue<strong>de</strong> ser<strong>de</strong>scargado <strong>de</strong>s<strong>de</strong> http://www.inco2.upv.es.Palabras clave— Biblioteca <strong>de</strong> software, matrices estructuradas,ToeplitzI. IntroducciónEn numerosos problemas <strong>de</strong> Ingeniería y Ciencia,la computación matricial es útil, esencial y necesaria.A menudo, los tipos <strong>de</strong> problemas matriciales queaparecen en muchos <strong>de</strong> ellos son problemas estándarbien conocidos. <strong>La</strong>s bibliotecas matriciales existentesson una útil herramienta que permiten al especialista<strong>de</strong> un campo concreto centrarse en resolver su problema,ahorrando horas <strong>de</strong> programación <strong>de</strong> rutinasnuméricas con las que éste no suele estar familiarizado.En la actualidad, existe un gran número <strong>de</strong> bibliotecasmatriciales que cubren un amplio abanico<strong>de</strong> aplicaciones científicas y tecnológicas. Por citaralgunas <strong>de</strong> ellas, nos encontramos con: LAPACK[1], ScaLAPACK [2], PETSc [3], SuperLU [4], AR-PACK [5],. . . o implementaciones comerciales comoMatlab [6], Mathematica [7], etc. <strong>La</strong>s más significativas,por ejemplo las <strong>de</strong>scritas en [1], [2], [3] y[4], están diseñadas para obtener prestaciones óptimassobre computadores paralelos, bien con memoriacompartida o bien con memoria distribuida.Muchas <strong>de</strong> las bibliotecas matriciales están diseñadaspara una o más clases <strong>de</strong> matrices. Por ejemplo,LAPACK trabaja con matrices banda o <strong>de</strong>nsas ysus rutinas están optimizadas para este tipo <strong>de</strong> matrices.Similarmente, ARPACK está diseñada paratrabajar con matrices dispersas.Por otra parte, las matrices que surgen en muchosproblemas científicos o técnicos a menudo tie-1 Departamento <strong>de</strong> Sistemas Informáticos y Computación,Universitat Politècnica <strong>de</strong> València (Spain), email:palonso@dsic.uvp.es2 Departmento <strong>de</strong> Informática, <strong>Universidad</strong> <strong>de</strong> Oviedo(Spain), email: pmnaredo@gmail.com3 Departamento <strong>de</strong> Comunicaciones, Universitat Politècnica<strong>de</strong> València (Spain), email: fjmartin@dcom.upv.es4 Departmento <strong>de</strong> Informática, <strong>Universidad</strong> <strong>de</strong> Oviedo(Spain), email: ranilla@uniovi.es5 Departamento <strong>de</strong> Sistemas Informáticos y Computación,Universitat Politècnica <strong>de</strong> València (Spain), email:avidal@dsic.upv.esnen una estructura explícita (matrices estructuradas).Algunos ejemplos típicos <strong>de</strong> matrices estructuradasson las matrices Toeplitz, Hankel, Van<strong>de</strong>rmon<strong>de</strong>,Cauchy, matrices circulantes, etc. Existen numerosasáreas en las que a menudo pue<strong>de</strong>n verse estostipos <strong>de</strong> matrices. Sin ánimo <strong>de</strong> ser exhaustivospo<strong>de</strong>mos citar: procesado <strong>de</strong> imágenes y señales engeneral, resolución <strong>de</strong> ecuaciones diferenciales e integrales,cálculo <strong>de</strong> funciones spline, análisis <strong>de</strong> seriestemporales, ca<strong>de</strong>nas <strong>de</strong> Markov y Teoría <strong>de</strong> Colas,computación <strong>de</strong> series <strong>de</strong> potencias y polinómicas,etc. (véanse como ejemplos las referencias [8], [9],[10], [11], [12]).Existe un cierto vacío en el campo <strong>de</strong> las bibliotecasmatriciales: el <strong>de</strong> las matrices estructuradas. Escierto que ello representa un amplio y ambiguo conjunto<strong>de</strong> métodos <strong>de</strong> procesado que son <strong>de</strong>pendientes<strong>de</strong>l tipo <strong>de</strong> matriz. Asimismo, es difícil concebiruna biblioteca eficiente para un gran número <strong>de</strong> casosy con cierta coherencia en el uso <strong>de</strong> la tecnologíacomputacional. En otras palabras, la creación <strong>de</strong> unabiblioteca <strong>de</strong> estas característias es un importante<strong>de</strong>safío <strong>de</strong> trascen<strong>de</strong>ncia científica y tecnológica.Los prece<strong>de</strong>ntes más significativos para esta i<strong>de</strong>ason los <strong>de</strong>sarrollos presentados en Netlib [13] y SLI-COT [14]. El primero es un conjunto <strong>de</strong> rutinas queresuelven sistemas lineales <strong>de</strong> ecuaciones que datanprincipalmente <strong>de</strong> 1982 y llegan a formar parte <strong>de</strong>Netlib en los 90. El segundo prece<strong>de</strong>nte es un conjunto<strong>de</strong> subrutinas incluidas en el paquete SLICOTpara resolver sistemas <strong>de</strong> ecuaciones lineales con matricesToeplitz generales, matrices Toeplitz simétricasy <strong>de</strong>finidas positivas y matrices Toeplitz a bloques.Hemos empezado la tarea <strong>de</strong> <strong>de</strong>sarrollar una bibliotecapara el tratamiento <strong>de</strong> matrices estructuradas,motivados por su uso en numerosas aplicaciones<strong>de</strong> Procesado <strong>de</strong> Señal. <strong>La</strong> biblioteca, <strong>de</strong>nominadaStructPack, tiene como objetivo la resolución<strong>de</strong> problemas matriciales computacionales típicoscon matrices estructuradas. Estos problemas sonfundamentalmente la resolución <strong>de</strong> sistemas lineales<strong>de</strong> ecuaciones lineales, resolución <strong>de</strong> problemas <strong>de</strong>mínimos cuadrados, cálculo <strong>de</strong> autovalores y autovectores,y <strong>de</strong> la <strong>de</strong>scomposición en valores singulares.Algunos <strong>de</strong> estos problemas han sido tratadospor algunos <strong>de</strong> los autores durante los últimos años[15], [16], [17], [18], [19]. <strong>La</strong> biblioteca está concebidapara que pueda ejecutarse sobre arquitecturasparalelas, tanto en entornos <strong>de</strong> memoria compartida<strong>JP2011</strong>-81


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011como en entornos <strong>de</strong> memoria distribuida. A tal efectose están utilizando en su implementación entornoscomo OpenMP o MPI. También está previsto incorporarsubrutinas que permiten su utilización sobreGPU. Para ello se está utilizando el entorno CUDA<strong>de</strong> NVIDIA.Dada la amplia variedad <strong>de</strong> problemas queStructPack trata <strong>de</strong> abarcar, es inconcebible mostrarlocomo un producto cerrado y finalizado.Así pues, nuestros objetivos <strong>de</strong> diseño implican el<strong>de</strong>sarrollo progresivo <strong>de</strong> distintas rutinas. Esto tambiénpermitirá la retroalimentación necesaria paraasegurar la calidad en los <strong>de</strong>sarrollos.En este artículo presentamos las i<strong>de</strong>as básicas quehan ayudado a diseñar la biblioteca y mostramosuna perspectiva general <strong>de</strong> su funcionalidad. También<strong>de</strong>scribimos el estado actual <strong>de</strong> los <strong>de</strong>sarrollospresentes y cuáles son los siguientes a ser incluidos acorto plazo.El resto <strong>de</strong>l artículo está organizado <strong>de</strong> la siguientemanera: la sección 2 <strong>de</strong>scribe algunas característicasgenerales <strong>de</strong> la biblioteca y algunos problemas que yahan sido resueltos por las rutinas <strong>de</strong> StructPack; lasección 3 muestra las principales características <strong>de</strong> lapágina web que permite acce<strong>de</strong>r a la <strong>de</strong>scarga <strong>de</strong> labiblioteca y a su <strong>de</strong>scripción; la sección 4 presentalas capacida<strong>de</strong>s <strong>de</strong> la biblioteca y algunos ejemplos<strong>de</strong> uso; por último, la sección 5 muestra las futuraslíneas <strong>de</strong> trabajo.II. Resolución <strong>de</strong> problemas estructuradoscon StructPackStructPack es una biblioteca <strong>de</strong> rutinas numéricasque resuelven problemas <strong>de</strong> Álgebra LinealNumérica con matrices estructuradas. <strong>La</strong>s rutinasestán escritas en Fortran 90/95, pero también pue<strong>de</strong>nser llamadas <strong>de</strong>s<strong>de</strong> C para lo que se han proporcionadolas interfaces a<strong>de</strong>cuadas. Actualmente, laversión v0.1 está diseñada para un entorno Linuxy optimizada para su uso en CPU <strong>de</strong> tipo secuencialy multinúcleo, para lo cual se han utilizado lasAPI <strong>de</strong> OpenMP en su <strong>de</strong>sarrollo. <strong>La</strong>s versiones paraotros sistemas operativos como Windows u otrosparadigmas <strong>de</strong> programación como memoria distribuidao para unida<strong>de</strong>s aceleradoras gráficas (GPU),serán añadidas en sucesivas versiones.Los problemas a resolver con StructPack son losproblemas clásicos <strong>de</strong>l Álgebra Lineal Numérica, estoes, la solucion <strong>de</strong> sistemas lineales <strong>de</strong> ecuaciones, solucióna los problemas <strong>de</strong> mínimos cuadrados, cálculo<strong>de</strong> valores y vectores propios y <strong>de</strong> la <strong>de</strong>scomposiciónen valores singulares. Los algoritmos implementadosen StructPack para resolver los problemas citadosanteriormente actúan sobre diferentes tipos <strong>de</strong> matrices,como matrices Toeplitz, Hankel, Van<strong>de</strong>rmon<strong>de</strong>,matrices circulantes, . . . , y en general, sobre matricesque presentan estructura <strong>de</strong> <strong>de</strong>splazamiento [9]. Elloincluye casos específicos <strong>de</strong>ntro <strong>de</strong> cada uno <strong>de</strong> lostipos previamente indicados, como matrices Toeplitztridiagonales, matrices simétricas <strong>de</strong>finidas positivas,etc.StructPack ha sido diseñado utilizando algoritmoseficientes. Básicamente se utilizan algoritmosque usan las propieda<strong>de</strong>s <strong>de</strong> <strong>de</strong>splazamiento <strong>de</strong> matricesestructuradas, siendo éstos optimizados paraarquitecturas multinúcleo. Para operaciones simples<strong>de</strong> complejidad lineal o cuadrática, se han utilizadolos núcleos computacionales BLAS [20]. También seutilizan bibliotecas para el cálculo <strong>de</strong> la FFT, bien labiblioteca MKL <strong>de</strong> Intel [21] (si el usuario la proporciona),bien la biblioteca FFT Pack [22]. El códigofuente pue<strong>de</strong> ser compilado bien utilizando compiladores<strong>de</strong> dominio público, como GNU gcc [23], bienpor compiladores comerciales como los compiladores<strong>de</strong> Intel.Una característica adicional e importante <strong>de</strong> la bibliotecaes que proporciona comandos para resolverproblemas directamente <strong>de</strong>s<strong>de</strong> la línea <strong>de</strong> comandos.Esto proporciona una importante facilidad <strong>de</strong>uso inicial. StructPack también proporciona ficheros.mex permitiendo su uso en entornos <strong>de</strong> tipo Octave/Matlab.Actualmente, las rutinas incluidas en la bibliotecapue<strong>de</strong>n ser utilizadas para:Resolver sistemas lineales con matrices <strong>de</strong> tipoToeplitz tridiagonales y simétricas.Calcular autosistemas y <strong>de</strong>scomposición en valoressingulares <strong>de</strong> matrices Toeplitz tridiagonalessimétricas.Resolver sistemas lineales <strong>de</strong> ecuaciones <strong>de</strong> matricesToeplitz simétricas.Resolver sistemas lineales <strong>de</strong> ecuaciones <strong>de</strong> matricesToeplitz no simétricas.Próximamente, serán incorporadas rutinas para calcularvalores y vectores propios <strong>de</strong> matrices Toeplitzsimétricas.Toda la información sobre StructPack es <strong>de</strong> dominiopúblico y es accesible en [24]. <strong>La</strong>s siguientessecciones <strong>de</strong>scriben con <strong>de</strong>talle el contenido <strong>de</strong>la página web y las características principales <strong>de</strong>StructPack.III. Descripción <strong>de</strong> la página web<strong>La</strong> estructura <strong>de</strong> la página web <strong>de</strong> Struct-Pack está organizada <strong>de</strong> manera convencional.Así pues, tiene una página “Principal” (“Main page”)y algunas pestañas para la “Instalación” (“Installation”),“Documentacion” (“Documentation”),“Test”, “FAQs”, etc.<strong>La</strong> página principal muestra una presentación <strong>de</strong>lsitio web, la licencia <strong>de</strong> uso <strong>de</strong>l software y las noveda<strong>de</strong>s<strong>de</strong> la última versión. A<strong>de</strong>más, también apareceuna breve <strong>de</strong>scripción <strong>de</strong> los grupos <strong>de</strong> investigacióninvolucrados en el <strong>de</strong>sarrollo <strong>de</strong>l paquete, así comolos proyectos relacionados. Los siguientes ítems resumenlas pestañas más relevantes:“Documentation”: aquí se muestra un enlace ala documentación generada <strong>de</strong>l software. En estadocumentación podremos encontrar toda la especificación<strong>de</strong> las API, así como los comandosdisponibles.<strong>JP2011</strong>-82


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011“Test”: en esta pestaña se muestra cómo ejecutarlos tests <strong>de</strong> rendimiento para obtener losresultados <strong>de</strong> tiempos <strong>de</strong> ejecución y precisión<strong>de</strong>l paquete instalado en la máquina.“Working Notes”: las notas <strong>de</strong> trabajo o workingnotes estarán almacenadas en esta pestaña. Estasección contendrá toda la información <strong>de</strong>talladarelacionada con el paquete completo, con algunassubrutinas, resultados <strong>de</strong> rendimiento, conclusiones,etc. El acrónimo escogido es SPAWNpor StructPAck Working Notes.“FAQs”: la pestaña <strong>de</strong> preguntas más frecuentesincluyen cuestiones generales, <strong>de</strong> instalación,cómo utilizar o programar con StructPack,cuestiones o problemas respecto a diferentes plataformaso sistemas operativos, así como asuntosvarios.“Third Party Software”: o software <strong>de</strong> terceros,conteniendo esta pestaña enlaces hacia los sitiosweb <strong>de</strong> todo el software utilizado para producirStructPack. El software está agrupado <strong>de</strong> lasiguiente manera:• Compiladores: gcc, gfortran, icc and ifort.• Software para el control <strong>de</strong> versiones:subversion.• Documentación <strong>de</strong>l software generado:doxygen.• Edición <strong>de</strong> textos: vi (vim, gvim, ...)• Configuración <strong>de</strong>l entorno: libtool, autoconf• Etc.“References”: en esta pestaña po<strong>de</strong>mos encontrarreferencias bibliográficas utilizadas paraproducir StructPack. Se incluyen tanto el trabajoprevio propio en estos problemas algebraicoscomo otras publicaciones relacionadas.A<strong>de</strong>más, se incluyen enlaces hacia otros sitiosweb con contenidos similares.“Installation”: conteniendo las tres típicas secciones<strong>de</strong> “How to install” (“Cómo realizar lainstalación”), “Download” (“Descarga”) e “InstallationTest” (“Test <strong>de</strong> la instalación”). En lasección <strong>de</strong> “Download” cualquiera <strong>de</strong> las últimasversiones pue<strong>de</strong> ser escogida y <strong>de</strong>scargada. <strong>La</strong>pestaña <strong>de</strong> “Installation Test” muestra la forma<strong>de</strong> comprobar que la instalación ha sido correcta.En la sección <strong>de</strong> “How to Install” se muestran todoslos <strong>de</strong>talles sobre cómo obtener una instalacióncorrecta. Se utiliza un proceso típico <strong>de</strong> instalaciónbasado en tres pasos: $ ./configure,$ make y $ make install.En el paso <strong>de</strong> configure se chequea el sistemadon<strong>de</strong> el paquete va a ser instalado y se crean losoportunos ficheros Makefile para la construcción<strong>de</strong>l paquete. Algunas opciones, como por ejemplola ruta <strong>de</strong> instalación, compiladores y bibliotecas,etc., pue<strong>de</strong>n ser especificadas en tiempo<strong>de</strong> configuración si se <strong>de</strong>sea modificar los valorespor <strong>de</strong>fecto <strong>de</strong> la instalación. El paso Makeconsiste en la compilación y enlazado <strong>de</strong> todaslas bibliotecas y programas <strong>de</strong> StructPack. Seconstruyen tanto las versiones estáticas como lasdinámicas <strong>de</strong> las bibliotecas, a menos que se contraindiqueen el momento <strong>de</strong> la configuración.Finalmente, el paso <strong>de</strong> make install traslada elsoftware y la documentación hacia la carpeta<strong>de</strong>stino <strong>de</strong>seada.Por <strong>de</strong>fecto, los códigos fuente se compilan utilizandolos compiladores <strong>de</strong> GNU, aunque actualmentelos compiladores <strong>de</strong> Intel son igualmentesoportados.StructPack ha sido diseñado utilizando algoritmoseficientes que utilizan kernels computacionales<strong>de</strong> tipo BLAS para operaciones <strong>de</strong> complejidad<strong>de</strong> or<strong>de</strong>n cuadrático o lineal. Así pues, bienuna implementación genérica <strong>de</strong> BLAS (ésta esla opción por <strong>de</strong>fecto), bien la biblioteca MKL<strong>de</strong> Intel, bien cualquier otro paquete compatible<strong>de</strong>be estar <strong>de</strong> manera obligatoria previamenteinstalado. StructPack también incluye y utilizabibliotecas para el cálculo <strong>de</strong> la FFT. <strong>La</strong>biblioteca FFT Pack [22] es parte <strong>de</strong> Struct-Pack, pero el usuario pue<strong>de</strong> utilizar igualmentela solución provista por la biblioteca MKL <strong>de</strong>Intel.<strong>La</strong> figura 1 muestra parcialmente la informaciónque proporciona esta pestaña. Para una <strong>de</strong>scripción<strong>de</strong>tallada <strong>de</strong>l proceso <strong>de</strong> instalación se sugiereexaminar [24].IV. Utilización <strong>de</strong> la biblioteca y <strong>de</strong> loscomandosActualmente StructPack ofrece la solución a sistemaslineales Toeplitz don<strong>de</strong> la matriz problemapue<strong>de</strong> ser simétrica tridiagonal o completamentesimétrica. El usuario tiene dos posibilida<strong>de</strong>s en elmomento <strong>de</strong> utilizar el paquete para resolver esteproblema: pue<strong>de</strong> implementar su propia aplicaciónutilizando los módulos <strong>de</strong> la biblioteca proporcionadospor StructPack o pue<strong>de</strong> utilizar comandos disponibles<strong>de</strong>s<strong>de</strong> la consola <strong>de</strong>l sistema operativo pararesolver este problema.<strong>La</strong> manera más natural <strong>de</strong> utilizar nuestros móduloses mediante el diseño <strong>de</strong> una aplicación escritaen Fortran 90. Actualmente, el paquete proporcionalos módulos tpsysv_module (caso completamentesimétrico) y tpsytrid_module (caso tridiagonalsimétrico). Pue<strong>de</strong>n ser utilizados tal y como se muestraen el siguiente ejemplo simplificado:program tpsysv_testuse tpsysv_moduleimplicit nonedouble precision, dimension(100) :: t, x, binteger :: nb = 20logical :: pivoting = .true.call random_number( t )call random_number( b )call tpsysv( t, x, b, nb, pivoting )end program tpsysv_test<strong>La</strong> rutina tpsysv obtiene la solución x <strong>de</strong>l sistemalineal Tx = b dada la primera columna (fila) t <strong>de</strong><strong>JP2011</strong>-83


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 1. Installation instructionsT y el vector <strong>de</strong> la parte <strong>de</strong>recha <strong>de</strong> la igualdad b.<strong>La</strong> aplicación se obtiene enlazando con la bibliotecastructpack.a proporcionada por el paquete.Para su uso en una aplicación escrita en C,el paquete proporciona el fichero <strong>de</strong> cabeceratpsysv_module.h que <strong>de</strong>be ser incluido, y el módulo<strong>de</strong> Fortran 90 ctpsysv_module.F90 con el quela aplicación <strong>de</strong>be ser enlazada. Cada módulo <strong>de</strong>StructPack que resuelve un problema dado tienesu contrapartida en el módulo correspondiente cuyonombre posee como prefijo la letra c. Este módulo hace<strong>de</strong> interfaz con C para que sea posible llamar a unarutina ó módulo <strong>de</strong> Fortran 90 <strong>de</strong>s<strong>de</strong> la aplicaciónescrita en C. Utiliza el módulo iso_c_binding queproporciona interoperatividad entre C y Fortran. Porejemplo, la rutina ctpsysv pue<strong>de</strong> ser llamada <strong>de</strong>s<strong>de</strong>código fuente escrito en C manteniendo el nombre,número y tipos <strong>de</strong> argumentos <strong>de</strong> la rutina driver allamar y <strong>de</strong>scrita en el módulo, como sigue:subroutine ctpsysv(n, t, x, b, nb, piv ) bind(c)integer(kind=c_int), value, intent(in) :: nreal(c_double), dimension(n), intent(in) :: treal(c_double), dimension(n), intent(out) :: xreal(c_double), dimension(n), intent(inout) :: binteger(kind=c_int), value, intent(in) :: nbinteger(kind=c_int), value, intent(in) :: piv. . .end subroutine ctpsysvEn la actualidad, el paquete proporciona dos comandosque permiten al usuario resolver cada uno<strong>de</strong> los problemas abordados: tpsysv y tpsytrid. Unejemplo <strong>de</strong> llamada podría ser: tpsysv -n 100 -p.En este ejemplo, el comando resuelve el problemacon una matriz Toeplitz simétrica <strong>de</strong> or<strong>de</strong>n 100 generadaaleatoriamente. El comando retorna el tiempo<strong>de</strong> ejecución. <strong>La</strong> opción --help muestra las opcionesdisponibles que permiten especificar al comando, porejemplo, los datos <strong>de</strong> entrada, guardar la solución enun fichero, etc. Otra información útil que pue<strong>de</strong> retornarel comando es relativa a la precisión <strong>de</strong> losresultados. Por ejemplo, la siguiente llamada:tpsysv -n 100 -p --raw-results --raw-hea<strong>de</strong>rs \--random-seed=123retorna algunas estadísticas sobre la precisión <strong>de</strong> losresultados:# n Time (sec.) Forward error Backward error#===================================================100 0.19 1.16e-13 3.02e-16V. El futuro <strong>de</strong> StructPackUno <strong>de</strong> los objetivos <strong>de</strong> los autores <strong>de</strong> este paquetees la difusión <strong>de</strong> su existencia <strong>de</strong>ntro <strong>de</strong> la comunidadcientífica, así como su mantenimiento. Enel futuro, el equipo <strong>de</strong> trabajo irá consolidando losmétodos existentes, resolviendo problemas que pue<strong>de</strong>nsurgir <strong>de</strong> su uso por parte <strong>de</strong> otros investigadores.Respecto a la solución <strong>de</strong> sistemas lineales,estamos actualmente trabajando en sistemas linealesHermíticos complejos no simétricos <strong>de</strong> matricesToeplitz. <strong>La</strong> base matemática, que se utiliza parala implementación eficiente <strong>de</strong> la rutina que solucionael problema simétrico en sistemas multinúcleos,pue<strong>de</strong> exten<strong>de</strong>rse para la solución <strong>de</strong> un amplio rango<strong>de</strong> problemas <strong>de</strong> tipo Toeplitz, como problemascon estructura Toeplitz a bloques, bloques Toeplitz,Toeplitz+Hankel, etc. Más aún, el problema lineal<strong>de</strong> mínimos cuadrados con matrices <strong>de</strong> tipo Toeplitztambién se pue<strong>de</strong> resolver con técnicas similares, porlo que serán parte <strong>de</strong> nuestro software. <strong>La</strong> extensióna otras clases <strong>de</strong> matrices estructuradas (no <strong>de</strong> tipoToeplitz) como Van<strong>de</strong>rmon<strong>de</strong> también son parte <strong>de</strong>nuestros objetivos.<strong>La</strong> solución <strong>de</strong>l problema <strong>de</strong> valores y vectores propiosy <strong>de</strong>l problema <strong>de</strong> valores singulares involucran-<strong>JP2011</strong>-84


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011do matrices estructuradas, también es un objetivoimportante <strong>de</strong> nuestro proyecto. Algunas propuestasestán basadas en la solución <strong>de</strong> sistemas lineales comolos mencionados anteriormente, por lo que sóloresta incorporarlos a nuestro paquete.Agra<strong>de</strong>cimientosEste trabajo ha sido financiado por el Ministerioespañol <strong>de</strong> Ciencia e Innovación y por FEDER(proyectos TIN2010-14971, TIN2008-06570-C04-02,TEC2009-13741 y CAPAP-H3 TIN2010-12011-E),Universitat Politècnica <strong>de</strong> València mediante el “Programa<strong>de</strong> Apoyo a la Investigación y Desarrollo(PAID-05-10)” y la Generalitat Valenciana medianteel proyecto PROMETEO/2009/013.Referencias[1] “<strong>La</strong>pack,” http://www.netlib.org/lapack/.[2] “Scalapack,” http://www.netlib.org/scalapack/.[3] “Petsc,” http://www.mcs.anl.gov/petsc/petsc-as/.[4] “SuperLU,” http://crd.lbl.gov/~xiaoye/SuperLU/.[5] “Arpack,” http://www.caam.rice.edu/software/ARPACK/.[6] “Matlab,” http://www.mathworks.com/products/matlab/.[7] “Mathematica,” http://www.wolfram.com/mathematica/.[8] J.R. Bunch., “Stability of methods for solving Toeplitzsystems of equations,” SIAM J. on Scientific and StatisticalComputing, vol. 6, no. 2, pp. 349–364, April 1985.[9] T.Kailath and A.H.Sayed, “Displacement structure:Theory and applications,” SIAM Review, vol. 37, no.3, pp. 297–386, September 1995.[10] T.Kailath and A.H.Sayed, Eds., Fast Reliable Algorithmsfor Matrices with Structure, SIAM, Phila<strong>de</strong>lphia, PA,1999.[11] Dario Bini, “Toeplitz matrices, algorithms and applications,”ERCIM News, , no. 22, July 1995.[12] V.Olshevsky, Ed., Fast Algoritmhs for Structured Matrices:Theory and Applications, SIAM, Phila<strong>de</strong>lphia, 2003.[13] “Netlib,” http://www.netlib.no/netlib/toeplitz/.[14] “Slicot,” http://www.slicot.org/.[15] L. Graciá, P. Alonso, and A.M. Vidal, “Solution of symmetricToeplitz linear systems in GPUs,” in CMMSE’09International Conference on Computational and MathematicalMethods in Science and Engineering, Gijón (Asturias),España, June 2009.[16] A.M. Vidal, V.M. García, P. Alonso, and M.O. Bernabeu,“Parallel computation of the eigenvalues of symmetricToeplitz matrices through iterative methods,” Journalof Parallel and Distributed Computing, vol. 68, pp. 1113–1121, August 2008.[17] M.O. Bernabeu, P. Alonso, and A.M. Vidal, “A multilevelparallel algorithm to solve symmetric Toeplitz linearsystems,” The Journal of Supercomputing, vol. 44, pp.237–256, June 2008.[18] P. Alonso and A.M. Vidal, “Cauchy-like system solutionon multicore platforms,” in PARA 2008 9th InternationalWorkshop on State-of-the-Art in Scientific andParallel Computing, Trondheim, Noruega, May 13 2008,Proceedings of PARA 2008, NTNU.[19] P. Alonso, J.M. Badía, and A.M. Vidal, “Solving theblock-Toeplitz least squares problem in parallel,” Concurrencyand Computation: Practice and Experience, vol.17, pp. 49–67, January 2005.[20] “Blas,” http://www.netlib.org/blas/.[21] “Intel MKL,” http://software.intel.com/en-us/articles/intel-mkl/.[22] “FFTPack,” http://www.netlib.org/fftpack/.[23] “GNU gcc,” http://gcc.gnu.org/.[24] “StructPack,” http://www.inco2.upv.es/structpack.php.[25] Alonso-Jordá P., P. Martínez-Naredo, F.J. Martínez-Zaldívar, J. Ranilla, and Vidal A.M., “Building a libraryfor solving structured matrix problemas,” in Proceedingsof the International Conference CMMSE, Benidorm,Spain, June 26–29 2011.<strong>JP2011</strong>-85


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-86


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011A translator framework for DynamicProgramming problemsAlejandro Acosta 1 , Francisco Almeida 2 and Ignacio Peláez 3Abstract— The advent of multicore systems, joinedto the potential acceleration of the graphics processingunits, has given us a low cost computation capabilityunprece<strong>de</strong>nted. The new systems alleviatesome well known important architectural problems atthe expense of a consi<strong>de</strong>rable increment of the programmabilitywall. The heterogeneity, both at architecturaland programming level at the same time,raises the programming difficulties. As a contributionin this context, we propose a <strong>de</strong>velopment methodologyfor the automatic source-to-source transformationon specific domains. This methodology is successfullyinstantiated as a framework to solve DynamicProgramming problems. As a result of applying ourframework, the end user (a physicist, a mathematicianor a biologist) can express her problem through alatex equation and automatically <strong>de</strong>rive efficient parallelco<strong>de</strong>s for current homogeneous or heterogeneousarchitectures. The approach allows an easy portabilityto new potential emergent architectures.Keywords— Dynamic Programming problems,Source to source transformation.I. IntroductionCurrent generation of computers is based on architecturesbased on multiple i<strong>de</strong>ntical processing unitscomposed of several cores (multicores) and it is expectedthat the number of cores per processor beincremented every year. It is also a well know factthat the current generation of compilers is not beingable to transfer automatically the capacity of the newprocessing units to the applications. The situationis further complicated given that current architecturesare of heterogeneous nature, where this multicoresystems can be combined, for example, withthe capabilities of using GPU system as general purposeprocessing architectures. This fact constitutesa severe difficulty that is appearing in the form of abarrier to the programmability.Many are the proposals to tackle with this problem.Leaving asi<strong>de</strong> the proposals based on the <strong>de</strong>velopmentof new programming languages, due toinconvenience caused to the user (new learning effortand co<strong>de</strong> reusability), many of the approachesare based in the source-to-source transformation ofsequential co<strong>de</strong> into parallel co<strong>de</strong> or in the transformationof parallel co<strong>de</strong> <strong>de</strong>signed for one architectureinto parallel co<strong>de</strong> for a different one [1], [2],[3]. Another different approach is based in the use ofskeletons. The programmer is provi<strong>de</strong>d with a set ofpatterns already parallelized that constitute a frameto <strong>de</strong>velop parallel co<strong>de</strong>, just by supplying sequentialco<strong>de</strong> [4], [5]. It worth also to mention the reasearch1 e-mail: aacostad@ull.es.2 e-mail: falmeida@ull.es.3 e-mail: ignacio.pelaez@gmail.com.on frameworks <strong>de</strong>voted to build the former sourceto-sourcetransformers [6], [7].Although technologically impressive, none oftheprojects based in skeletal parallel programming haveachieved significant popularity in the wi<strong>de</strong>r parallelprogramming community. However, we claim thatmany of the <strong>de</strong>velopments ma<strong>de</strong> in the context ofskeletal programming may play an important rolein the automatic co<strong>de</strong> generation based in sourceto-sourcetransformations. An important difficultyin the source-to-source transformation process is totransform sequential co<strong>de</strong> sections into their parallelequivalent sections. That implies that the transformermust know in advance the sections to be parallelized,and how they should be translated, typicallythe user annotates the sections to be transformed.An interesting feature of parallel skeletons is thatthe parallelism is hid<strong>de</strong>n to the end user and is encapsulatedinto parallel patterns. Usually, the user fillsgaps in the skeleton by providing sequential co<strong>de</strong>s.New parallelizations (for new architectures for example)can be <strong>de</strong>veloped without any modificationof the sequential co<strong>de</strong> supplied by the user.We have <strong>de</strong>veloped a source-to-source translatorbased in skeletons that generates co<strong>de</strong> for many parallelarchitectures. The main goal is that the enduser may obtain parallel co<strong>de</strong>, without any knowledgein programming, just by <strong>de</strong>fining her problemusing a more natural language as the mathematics.An advantage of our approach is that, in general, asource-to-souce transformation from sequential co<strong>de</strong>to sequential co<strong>de</strong> is semantically easier to <strong>de</strong>velopthat a transformation from sequential to parallelco<strong>de</strong>. That is one of the fundamentals of our project,we automatically fill the sequential gaps in a parallelskeleton starting from a very user friendly specification.The parallelism is automatically provi<strong>de</strong>d bythe skeleton and can be very easily exten<strong>de</strong>d. Sincemany parallel skeletons have been already <strong>de</strong>velopedand they work efficiently in current architectures,once the transformers have been <strong>de</strong>veloped, the levelof productivity in terms of parallel co<strong>de</strong> generated ishighly increased.As a proof of concept we apply the methodologyto the dynamic programming technique. As a resultof this research it raises an specification languagefor Dynamic Programming problems that also constitutesa contribution of this work.This remaining of the paper has been structuredas follows: in section II we present the methodologythat we propose to broach the problem, in sectionIII we raise the framework <strong>de</strong>veloped in the context<strong>JP2011</strong>-87


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011of Dynamic Programming problems and in sectionIV we inclu<strong>de</strong> some computational results obtainedfrom our tool and point out the high productivityachieved by the approach while keeping the efficiencyat the same time. Finally we end the paper withsome concluding remarks and future lines of work.II. The methodologyUsually, source-to-source translators are used tomake easier the work of <strong>de</strong>velopers. The source languageuse to have a higher abstraction level than thetarget language. Many translator have been <strong>de</strong>velopedand they typically follow the common structurethat operates in two different phases, the Front-endand the Back-end. In the skeletal based translationwe propose to follow the same structure but introducingnew layers and providing an increased generalabstraction view (Figure 1). The proposal is close tothat presented in [7]. In this case, the co<strong>de</strong> generatedby the Back-ends is the input co<strong>de</strong> for a parallelskeleton. The input co<strong>de</strong> in a parallel skeleton useto be a sequential co<strong>de</strong> that is guarantied to be executedin parallel through the parallel patterns encapsulatedinto the skeleton. This patterns are adaptedto several platforms. New parallel patterns can be<strong>de</strong>veloped for new architectures and also the skeletonsare suitable for static and dynamic optimizations.Note that we separate the source to sourcetransformation from the parallelization. The transformationsare only of sequential co<strong>de</strong>s to sequentialco<strong>de</strong>s, while the parallelizations are abstracted intothe skeletons. The parallel co<strong>de</strong> generated by ourBack-end is suitable to be executed in many parallelarchitectures in terms of the parallel skeleton to becombined for the execution.Using this mo<strong>de</strong>l, we propose a <strong>de</strong>sign structurewhere each of the phases can be overviewed as sourceto-sourcetranslators (Figure 1). The Front-end maybe seen as a source-to-source translator that generatesan intermediate co<strong>de</strong>, and the Back-end receivesas input this source intermediate co<strong>de</strong> and generatethe output. By adding the skeletons the mo<strong>de</strong>l allowsto <strong>de</strong>velop a source translator, that generates intermediateco<strong>de</strong> in<strong>de</strong>pen<strong>de</strong>nt from the architecture,and also a second target translator in<strong>de</strong>pen<strong>de</strong>nt fromthe input intermediate language that generates anoutput co<strong>de</strong> adapted and optimized for different architectures.This mo<strong>de</strong>l is quite flexible since allows the use thesame target translator, and different source translators,to generate parallel co<strong>de</strong> starting from variousinput languages. Or, at the same time, the use or thesame source translator, and different target translators,to produce output co<strong>de</strong> for different skeletalsoftware platforms. The target co<strong>de</strong> generated bythe target translator can be used in many differentparallel architectures just by combining the skeleton.New adapted skeletons can be <strong>de</strong>veloped fornew emergent architectures without any change nornew <strong>de</strong>velopments in the whole translation process.As a proof of concept we have implemented asource-to-source translator that follows this mo<strong>de</strong>l(Figure 2). The translator is directed to solve DynamicProgramming problems on parallel architectures.Of course, although the specific <strong>de</strong>velopmentof this paper is oriented to the Dynamic Programmingtechnique, the same <strong>de</strong>velopment mo<strong>de</strong>l canbe applied to many other contexts.III. The dynamic programming technique: aproof of conceptDynamic Programming (DP) is an importantproblem-solving technique that has been wi<strong>de</strong>ly usedin various fields such as control theory, operationsresearch, economy, biology and computer science [8],[9]. In DP an optimal sequence of <strong>de</strong>cisions is arrivedat by making explicit appeal to the principle ofoptimality.For example [10], however most of the parallelizationspresented are for specific DP problems (see[11], [12]) or are restricted to limited classes of recurrences.A unified parallel general approach waspresented in [13] as an extension to the work of [14]but the strong theoretical effort introduced in somecases dissua<strong>de</strong>s us from using it as a mo<strong>de</strong>l for <strong>de</strong>velopingparallel tools.In conclusion, generic parallel approaches for DPare limited to classes of problems or they are notsuitable to be assumed by a software component. Itis worth mentioning that another source of difficultiesis the fact that the notation used changes substantiallyfrom one formalization to the other. Inmost of the cases, how to obtain the optimal policyproviding the optimal solution is left outsi<strong>de</strong> of theformalizations, and usually remains expressed as anon-formalized, sometimes intuitive, procedure.Analyzing the software approaches for DP, wefound a group of general libraries for combinatorialoptimization problems such as [15], [16]. They areused to supply interfaces for sequential and parallelexecutions but in most of the cases DP is not consi<strong>de</strong>redat all. Next, we can find specific DP sequentiallibraries such as [17], and interesting software approaches<strong>de</strong>rived from laboratories that apply solverssuch as LINGO [18] to DP problems, following particularmethodologies. In [19] we contributed withDPSKEL, a parallel skeleton where many efficientparallelizations for DP on different architectures areoffered to the end user. The end user fills gaps ona C++ sequential co<strong>de</strong> and the parallelism is automaticallyprovi<strong>de</strong>d. In [20] we presented DPSPEC,a XML specification for DP problems that could beused as an alternative instead of the C++ interfacefor the DP parallel skeletons. Although for a scientist(a biologist, a physician, or an economist) XMLis easier to manage, it still remains as a non naturalapproach. By other si<strong>de</strong>, the problem of finding theoptimal policy after the optimal value is computedremained unsolved at that moment.As a contribution of this paper, we propose a newspecification language for DP problems that integratesall the elements of the DP technique, includ-<strong>JP2011</strong>-88


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011… … ...IntermediateCo<strong>de</strong>OutputCo<strong>de</strong>InputCo<strong>de</strong>SourceTranslatorTargetTranslatorSkeleton<strong>La</strong>nguage Depen<strong>de</strong>ntFig. 1.PlatformDepen<strong>de</strong>ntMo<strong>de</strong>l for the proposed architectureArchitectureDepen<strong>de</strong>nting how to compute the optimal policy. DP problemsusing this specification can be transformed automaticallyinto our parallel skeletons through our intermediatelanguage DPSPEC. To achieve it, DPSPECand the parallel skeletons have been conveniently exten<strong>de</strong>d.The input <strong>de</strong>fines a structure where the user can<strong>de</strong>fine the DP problem without any knowledge ofprogramming, using a more natural language as themathematics. The co<strong>de</strong> for this structure is <strong>de</strong>finedusing the L A TEX processor, wi<strong>de</strong>ly used by thescientific community. The use of <strong>La</strong>TeX is just aproof of concept, however from the methodologicalpoint of view, any other language can be translateto the intermediate DPSPEC co<strong>de</strong>, such as Mat<strong>La</strong>b.We <strong>de</strong>fine a template where the user can <strong>de</strong>fine theproblem to be solved and its parameters. We illustratethis specification using the well known DP approachfor the Knapsack Problem(Table I). As wecan see the input data and solution or a problem are<strong>de</strong>scribed at the InputData and OutputData sectionsrespectively, the DP recurrence in the sectionDP Recurrence. Note that when this section is <strong>de</strong>fined,the <strong>de</strong>cisions d k,c are inclu<strong>de</strong>d so that the optimalpolicy can be obtained from the specificationpresented in section F ormerDecision.This L A TEX co<strong>de</strong> will be transformed using thetransformer Tex2DPS to DPSPEC. These <strong>de</strong>sign issuesmake the subsequent parsing easier and allowfor a better semantic analysis to <strong>de</strong>tect data <strong>de</strong>pen<strong>de</strong>ncies,all while adhering as closely as possibleto the user <strong>de</strong>fined equation. The semantic analysis<strong>de</strong>termines the traversing mo<strong>de</strong> of the DP table.DPSPEC brings together the elements to <strong>de</strong>scribepiecewise <strong>de</strong>fined functions, simple variablesand vectors, arithmetic, logical, relational and maxminoperators, and iterators. DPSPEC is the inputof a second translator (XML2Cpp), which isthe responsible for translating the XML specificationto C++ co<strong>de</strong>. This co<strong>de</strong> supplies the structureof a state and its evaluation through the functionalequations and the DP table is abstracted as a tableof states. DPSKEL provi<strong>de</strong>s the table and severalmethods to traverse it during the evaluation ofthe states. These methods allow different traversingmo<strong>de</strong>s (by rows, by columns, by diagonals) andthe user picks the best that doesn’t violate the <strong>de</strong>pen<strong>de</strong>ncesof the functional equations. Some recurrencesadmit several traversing mo<strong>de</strong>s in terms of<strong>de</strong>pen<strong>de</strong>nces, but the running time may vary fromone mo<strong>de</strong> to the other. In the sequential case, thetraversing mo<strong>de</strong> indicates that the states of the row(column or diagonal respectively) will be processedin sequence, while in the parallel case, the semanticappeals to the evaluation of the row (column ordiagonal respectively) using the whole set of processorssimultaneously. This approach allows to introduceany of the parallelization strategies <strong>de</strong>signed forDP algorithms. The dimensions of the DP table are<strong>de</strong>pen<strong>de</strong>nt of the instance and should be given atrunning time. DPSKEL skeleton follows the mo<strong>de</strong>lof classes <strong>de</strong>scribed in the Mallba library and addsthose particular elements related to DP, while keepingthe features of efficiency and easiness of use atthe same time. The concepts of State and Decisionare abstracted into C++ classes required (Requiredsections in Figure 2) to the user. The user <strong>de</strong>scribesthe problem and the solution, and the methods toevaluate a state (the functional equation) and to getthe optimal solution. These classes are generated bythe translator XML2Cpp. The classes provi<strong>de</strong>d (Provi<strong>de</strong>dsections in Figure 2) by DPSKEL will allocateand evaluate the DP table supplying the necessarymethods to return the solution. Implementation <strong>de</strong>tailsare hid<strong>de</strong>n to the user. The flexibility in our approachallows to <strong>de</strong>velop new translators from XMLto another library of skeletons providing new or differentfunctionalities.Since skeletons are <strong>de</strong>fined for different architectures,shared memory, message passing, hybridshared memory/message passing (see Figure 2), themethodology provi<strong>de</strong>s a huge portability, specially if<strong>JP2011</strong>-89


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLE I<strong>La</strong>tex specification for the Knapsack Problem⎧n ∈ N ⎪⎨C ∈ NInputData ≡p k ∈ N; k ∈ {0 . . . n − 1}⎪⎩w k ∈ N; k ∈ {0 . . . n − 1}# T he number of objects# T he capacity of the Knapsack# T he profit of object k# T he weight of object k{xk ∈ {0, 1}; k ∈ {0 · · · n − 1} # T he solution vectorOutputData ≡n − 1, C# T he in<strong>de</strong>x solutionDecisionDef ≡ { d k,c ∈ {0, 1}; k ∈ {0 · · · n − 1}; c ∈ {0 · · · C}# T he <strong>de</strong>cisionsDP Recurrence ⎧ ≡⎨ 0 ⇒ d k,c = 0 if c < w kf k,c = p k ⇒ d k,c = 1 if k = 0 and c ≥ w k⎩max{f k−1,c ⇒ d k,c = 0, f k−1,c−wk + p k ⇒ d k,c = 1} if k ≠ 0 and c ≥ w k⎧# Assign solution k⎪⎨xF ormerDecision ≡ k = d k,c if k ≥ 0 and c ≥ 0# Next <strong>de</strong>cision to assign⎪⎩k − 1; c − (w k ∗ x k ); if k > 0 and c ≥ (w k ∗ x k )SeqOpenMP<strong>La</strong>texInputCo<strong>de</strong>Tex2DPSSourceTranslatorXMLIntermediateCo<strong>de</strong>Xml2CppTargetTranslatorOpenCL...MPIHybridRequired Provi<strong>de</strong>dSkeletonOutputCo<strong>de</strong><strong>La</strong>nguage Depen<strong>de</strong>nt Platform Depen<strong>de</strong>nt Architecture Depen<strong>de</strong>ntFig. 2.The proposed software architectureone consi<strong>de</strong>r that extending the approach to a newemergent platform, just means to inclu<strong>de</strong> a new parallelskeleton.IV. Computational ResultsTo validate our methodology and the frameworkthat we have <strong>de</strong>veloped, we tested with several DynamicProgramming problems (Table II). Five differentDP recurrences have been consi<strong>de</strong>red that arequite representative of wi<strong>de</strong> class of problems. Notethat the data <strong>de</strong>pen<strong>de</strong>nces are different in most of theformula consi<strong>de</strong>red. That means that different paralleltraverses of the DP table can be required. We justrepresented the DP problems using our L A TEX specificationlanguage and automatically generated theparallel co<strong>de</strong>s. Four parallel skeletons have been consi<strong>de</strong>red,the sequential one and parallel versions onOpenMP, MPI and MPI/ULL CALIBRATE. Thislast version is a distributed memory MPI versioncombined with the ULL CALIBRATE library [21]to optimize in run time through dynamic load balancing.The parallel platform used to execute our experimentsis an AMD Opteron 6128 no<strong>de</strong> (4 processors,each processor composed of 8 cores), with 32 coressharing the memory. We have used only 20 of them inour tests. To simplify the experience, the tests havebeen <strong>de</strong>veloped using squared matrices of sizes 1000,2000 and 5000. Note that according to the <strong>de</strong>pen<strong>de</strong>ncesof problems on Table II, that are graphicallyrepresented in Figure IV, several traversing parallelapproaches can be used to obtain the solution. Theparallel skeletons used compute rows in parallel inthe case of the RAP and KP, the MPP and TCPare processed by computing the diagonals down-topin parallel and in the case of GCP the diagonals arecomputed in parallel top-down.Table III shows the running times of the sequentialexecutions for all the proposed problems. This tableprovi<strong>de</strong>s a general view on the granularity of each<strong>JP2011</strong>-90


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLE IIDynamic Programming test problemsProblemRecurrence0/1 KnapsackKP f i,j = max{f i−1,j , f i−1,j−wi + p i }Resource Allocation f i,j = p 1,j if i = 1 and j > 0RAP f i,j = max 0≤k 1) and (j > 0)Matrix ParentizationMPP f i,j = min i≤k


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLE IVRunning times of the RAP for several SkeletonsSkeleton OpenMP MPI MPI+ULL CALIBRATESize# cores # cores # cores2 4 8 16 20 2 4 8 16 20 2 4 8 16 201000 15 9 4 2.4 2 14 9 4 2.4 2 11 5 3 1.7 1.52000 126 73 39 20 16 119 70 37 19 16 81 44 23 12 105000 1993 1153 616 311 257 1882 1093 591 311 255 1304 700 399 180 141TABLE VRunning times for MPP, TCP, KP and GCPProblem MPP TCPSize# cores # cores2 4 8 16 20 2 4 8 16 201000 17 8 3.9 1.9 1.6 18 9 3.7 1.9 1.52000 146 73 41 22 21 143 72 36 22 205000 2659 1358 669 349 386 2596 1344 669 349 373Problem KP GCPSize# cores # cores2 4 8 16 20 2 4 8 16 201000 0.22 0.11 0.06 0.08 0.07 57 32 17 7.3 7.52000 0.86 0.44 0.23 0.24 0.24 480 271 193 74 695000 5.7 2.7 1.4 1.3 1.1 8772 4858 2559 1309 1517References[1] Isaac Dooley, “Automated source-to-source translationsto assist parallel programmers,” M.S. thesis,Dept. of Computer Science, University of Illinois, 2006,http://charm.cs.uiuc.edu/papers/DooleyMSThesis06.shtml.[2] Sain zee Ueng, Melvin <strong>La</strong>thara, Sara S. Baghsorkhi, andWen mei W. Hwu, “W.m.w.: Cuda-lite: Reducing gpuprogramming complexity,” in In: LCPC08. Volume 5335of LNCS. 2008, pp. 1–15, Springer.[3] Fred V. Lionetti, Andrew D. McCulloch, and Scott B.Ba<strong>de</strong>n, “Source-to-source optimization of cuda c for gpuaccelerated cardiac cell mo<strong>de</strong>ling,” in Proceedings of the16th international Euro-Par conference on Parallel processing:Part I, Berlin, Hei<strong>de</strong>lberg, 2010, EuroPar’10,pp. 38–49, Springer-Verlag.[4] Kiminori Matsuzaki and Hi<strong>de</strong>ya Iwasaki, “A library ofconstructive skeletons for sequential style of parallel programming,”in In InfoScale 06: Proceedings of the 1st internationalconference on Scalable information systems,volume 152 of ACM International Conference ProceedingSeries. 2006, p. 13, ACM Press.[5] Horacio González-Vélez and Mario Leyton, “A survey ofalgorithmic skeleton frameworks: high-level structuredparallel programming enablers,” Softw. Pract. Exper.,vol. 40, pp. 1135–1160, November 2010.[6] ROSE, “www.rosecompiler.org,” .[7] Siegfried Benkner, Eduard Mehofer, and Sabri Pllana,“Towards an intelligent environment for programmingmulti-core computing systems,” in Proceedings of the2nd Workshop on Highly Parallel Processing on a Chip(HPPC 2008), in conjunction with Euro-Par 2008, August2008.[8] Juliana Nascimento and Warren Powell, “Dynamic programmingmo<strong>de</strong>ls and algorithms for the mutual fundcash balance problem,” Manage. Sci., vol. 56, pp. 801–815, May 2010.[9] Alexan<strong>de</strong>r Er<strong>de</strong>lyi and Huseyin Topaloglu, “A dynamicprogramming <strong>de</strong>composition method for making overbooking<strong>de</strong>cisions over an airline network,” INFORMSJ. on Computing, vol. 22, pp. 443–456, July 2010.[10] O. <strong>de</strong> Moor, “Dynamic programming as a software component,”in Proc. 3rd WSEAS Int. Conf. Circuits, Systems,Communications and Computers, N. Mastorakis,Ed., 1999.<strong>JP2011</strong>-92[11] R. Andonov, S. Balev, S. Rajopadhye, and N. Yanev,“Otimal semi-oblique tiling and its application to sequencecomparison,” in 13th ACM Symposium on ParallelAlgorithms and Architectures (SPAA), 2001.[12] R. Andonov and S. Rajopadhye, “Optimal OrthogonalTiling of 2-D Iterations,” Journal of Parallel andDistributed Computing, vol. 45, pp. 159–165, September1997.[13] Morales D., ALmeida F., Rodríguez C., Roda J., andDelgado A. Coloma I., “Parallel dynamic programmingand automata theory,” Parallel Computing, 2000.[14] T. Ibaraki, Enumerative Approaches to CombinatorialOptimization, Part II, Annals of Operations Research.Volume 11, 1-4, 1988.[15] J. Eckstein, C. A. Phillips, and W. E. Hart, “PICO:An object-oriented framework for parallel branch andbound,” Tech. Rep., RUTCOR, 2000.[16] B. Le Cun, “Bob++ library illustrated by VRP,” in EuropeanOperational Research Conference (EURO’2001),Rotterdam, 2001, p. 157.[17] B. C. Lubow, “SDP: Generalized software for solvingstochastic dynamic optimization problems.,” Wildlife SocietyBulletin, vol. 23, pp. 738–742, September 1997.[18] P. Lohman<strong>de</strong>r, “Deterministic andstochastic dynamic programming.,”www.sekon.slu.se/ PLO/diskreto/dynp.htm.[19] I. Peláez, F. Almeida, and F. Suárez, “Dpskel: A skeletonbased tool for parallel dynamic programming,” inSeventh International Conference on Parallel Processingand Applied Mathematics, PPAM2007, 2007.[20] Ignacio Peláez, Francisco Almeida, and Daniel González,“An xml specification for automatic parallel dynamicprogramming,” in International Conference on ComputationalScience (1), 2006, pp. 872–875.[21] I. Galindo, F. Almeida, V. Blanco, and J.M. Badía, “Dynamicload balancing on <strong>de</strong>dicated heterogeneous systems,”in Recent Advances in Parallel Virtual Machineand Message Passing Interface. EuroPVM/MPI 2009,Alexey <strong>La</strong>stovetsky, Tahar Kechadi, and Jack Dongarra,Eds., Dublin, Ireland, Sept. 2008, vol. 5205 of LectureNotes in Computer Science, pp. 64–74, Springer Verlag.


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Aplicaciones <strong>de</strong> la computación <strong>de</strong> altas prestaciones<strong>JP2011</strong>-93


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-94


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Resolviendo el Diseño <strong>de</strong> Re<strong>de</strong>s para Mo<strong>de</strong>los<strong>de</strong> Tráfico Reales <strong>de</strong> Internet MedianteOptimización Multiobjetivo enMultiprocesadoresJosé M. <strong>La</strong>nza-Gutiérrez 1 , Juan A. Gómez-Pulido 1 , Miguel A. Vega-Rodríguez,Juan M. Sánchez-Pérez 1Resumen—El diseño y optimización <strong>de</strong> una red <strong>de</strong>comunicaciones es una tarea compleja que involucra unagran cantidad <strong>de</strong> factores que son necesarios evaluar,habiéndose <strong>de</strong>mostrado que es un problema NP-complejo.En este artículo se propone su resolución utilizando dosalgoritmos evolutivos: NSGA-II y SPEA-II y enfocando eltrabajo hacia un problema <strong>de</strong> optimización bi-objetivo(coste, retardo) ejecutado sobre datos reales. <strong>La</strong>experimentación se ha realizado sobre un clúster <strong>de</strong>procesadores paralelos utilizando MPI como herramienta<strong>de</strong> comunicación, con el objetivo <strong>de</strong> aumentar la velocidad<strong>de</strong> ejecución <strong>de</strong> las pruebas. Con los datos obtenidos se hapodido <strong>de</strong>terminar, mediante test estadísticos, cómo elalgoritmo SPEA-II ofrece un comportamiento superior alNSGA-II para este <strong>de</strong>terminado problema.Palabras clave—Re<strong>de</strong>s <strong>de</strong> comunicaciones, optimizaciónmultiobjetivo, algoritmos evolutivos, multiprocesadores.EI. INTRODUCCIÓNL diseño y optimización <strong>de</strong> una red <strong>de</strong>comunicaciones es una tarea compleja, puesinvolucra una gran cantidad <strong>de</strong> factores que sonnecesarios evaluar para obtener una solución queconvenza tanto a usuarios finales (calidad <strong>de</strong> servicio <strong>de</strong>la red), como a las entida<strong>de</strong>s que llevan a cabo suimplantación (costes <strong>de</strong> <strong>de</strong>spliegue / mantenimiento) [1].Entre los factores <strong>de</strong> optimización más habituales suelentomarse aquellos que afecten al coste y a la calidad <strong>de</strong> lared (retardo, confiabilidad, disponibilidad…). Ambosfactores influyen entre sí, puesto que la variación encualquiera <strong>de</strong> ellos hace que el otro se vea afectado. Porejemplo, para reducir el retardo <strong>de</strong> una red es posibleaumentar la capacidad <strong>de</strong> algunos <strong>de</strong> sus enlaces; sinembargo, esto produciría un aumento en el coste total <strong>de</strong>la red. Por este motivo se hace necesario recorrer todo elespacio posible <strong>de</strong> soluciones en busca <strong>de</strong> la soluciónóptima. Al ser un problema <strong>de</strong> diseño NP-complejo, lasbúsquedas exhaustivas son <strong>de</strong>scartadas, siendo necesarioutilizar otras técnicas que faciliten su resolución [2].Des<strong>de</strong> que este problema fue <strong>de</strong>finido como unproblema NP-complejo, se han publicado muchostrabajos que tratan <strong>de</strong> solucionarlo. Comenzando por lasheurísticas, po<strong>de</strong>mos citar los trabajos <strong>de</strong> Jan et al. [3]1 Dep. Tecnología <strong>de</strong> Computadores y Comunicaciones. EscuelaPolitécnica. Campus Universitario s/n, 10003 Cáceres.{jmlanza,jangomez, mavega,sanperez}@unex.es(<strong>de</strong>sarrollaron una técnica basada en “branch andbound” para optimizar el coste <strong>de</strong> la red sobre unosvalores <strong>de</strong> confiabilidad concretos) y <strong>de</strong> Ersoy et al. [4](usaron una técnica <strong>de</strong> optimización sobre el retardomedio para el diseño <strong>de</strong> re<strong>de</strong>s LAN y MANinterconectadas). Sin embargo, todas estas heurísticas noaseguran que las soluciones obtenidas sean las óptimas;a<strong>de</strong>más, la mayoría <strong>de</strong> ellas optimizan únicamente unobjetivo, por lo que se <strong>de</strong>be partir el problema en dos.A<strong>de</strong>más <strong>de</strong> las heurísticas, otros muchos trabajos usanalgoritmos genéticos para optimización mono-objetivo.Así, Abuali et al. [5] minimizan el coste <strong>de</strong> la red a lavez que consi<strong>de</strong>ran los valores máximos <strong>de</strong> capacidad;Ko et al. [6] optimizan el coste <strong>de</strong> la red a la vez quemantienen valores constantes <strong>de</strong> retardo; y Kumar et al.[7] usan estos algoritmos para la expansión <strong>de</strong> re<strong>de</strong>s <strong>de</strong>computadores a la vez que optimizan su disponibilidad.También han sido utilizados los algoritmos genéticosmulti-objetivo, puesto que son los que mejor se adaptana este tipo <strong>de</strong> problemáticas [8]. Así, Barnerjee et al. [9]estudiaron el diseño <strong>de</strong> re<strong>de</strong>s basadas en mo<strong>de</strong>los <strong>de</strong>trafico habituales (self-similiar y Poisson), mediante laoptimización <strong>de</strong> coste y retardo utilizando el PCGA(Pareto Converging Genetic Algorithm), y R. Kumar etal. [10] trataron la optimización sobre el coste y elretardo usando este mismo algoritmo.Pese a ser la solución más utilizada, existe una grancantidad <strong>de</strong> algoritmos evolutivos multiobjetivo que aúnno se han usado para solucionar el problema, como porejemplo los conocidos NSGA2 [11] y SPEA2 [12]. Espor ello por lo que se utilizarán para resolver esteproblema <strong>de</strong> optimización bi-objetivo (coste y retardo).Aunque pudiera parecer extraño (<strong>de</strong>bido al elevadonúmero <strong>de</strong> publicaciones en este problema),prácticamente no existen instancias públicas (datos que<strong>de</strong>finan el problema) que se puedan utilizar a la hora <strong>de</strong>validar los resultados, exceptuando una bien conocida:la <strong>de</strong> las diez ciuda<strong>de</strong>s chinas más pobladas [6], siendoésta la instancia utilizada en nuestro trabajo.El resto <strong>de</strong>l artículo se estructura como sigue: la segundasección <strong>de</strong>fine el problema y las funciones <strong>de</strong> fitnessutilizadas. <strong>La</strong> tercera sección muestra la implementación<strong>de</strong>l problema mediante los dos algoritmos mencionados.<strong>La</strong> cuarta sección expone los resultados obtenidos. En laquinta sección se discute la comparativa con otrostrabajos y, finalmente, en la quinta sección se <strong>de</strong>tallanlas conclusiones y trabajos futuros.<strong>JP2011</strong>-95


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011II. DISEÑO DE UNA RED DE COMUNICACIONESA la hora <strong>de</strong> diseñar una red <strong>de</strong> comunicaciones, existeuna serie <strong>de</strong> factores que hay que evaluar para obteneruna red a<strong>de</strong>cuada a cada necesidad, como por ejemplo:coste <strong>de</strong> la red, retardo <strong>de</strong> las comunicaciones, volumen<strong>de</strong> tráfico, posibilida<strong>de</strong>s <strong>de</strong> expansión, seguridad, etc.[1]. En este artículo se propone la optimización <strong>de</strong> la redbasada en los dos factores más importantes: el coste <strong>de</strong>instalación (no <strong>de</strong>l mantenimiento) <strong>de</strong> la red y el retardo<strong>de</strong> las comunicaciones.A. Definición <strong>de</strong> una instancia <strong>de</strong>l problemaUna instancia particular <strong>de</strong>l problema vendrá <strong>de</strong>finidapor el número <strong>de</strong> nodos <strong>de</strong> la red (N), la distancia entrelos nodos (D, una matriz <strong>de</strong> NxN elementos), el traficoestimado entre los nodos (T, una matriz <strong>de</strong> NxNelementos), el número <strong>de</strong> tipos <strong>de</strong> nodos disponibles (K,con sus características <strong>de</strong> coste y capacidad), el número<strong>de</strong> tipos <strong>de</strong> enlaces existentes (M, con sus respectivosvalores <strong>de</strong> coste y capacidad), el coste <strong>de</strong> losamplificadores <strong>de</strong> señal (A) y la máxima distancia que laseñal pue<strong>de</strong> viajar a través <strong>de</strong> la red sin necesidad <strong>de</strong>amplificación (L). Estos dos últimos parámetros (A y L)son <strong>de</strong>bidos a que se trata <strong>de</strong> una red <strong>de</strong> fibra óptica.B. Política <strong>de</strong> enrutamiento<strong>La</strong> matriz <strong>de</strong> tráfico (T) proporciona la cantidad <strong>de</strong>tráfico estimado entre cada una <strong>de</strong> las ciuda<strong>de</strong>s <strong>de</strong> lainstancia, consi<strong>de</strong>rando que existe una topologíacompletamente conexa.En el caso real, una topología está compuesta por unsubconjunto <strong>de</strong> todos los posibles enlaces <strong>de</strong> la red, porlo que se hace necesario re<strong>de</strong>finir esta matriz <strong>de</strong> tráficoinicial con las nuevas necesida<strong>de</strong>s surgidas al encaminarla información a través <strong>de</strong> los enlaces existentes. Estanueva matriz se <strong>de</strong>nomina T_acu. Para esta tarea seutiliza el algoritmo <strong>de</strong> camino mínimo <strong>de</strong> Dijsktra [14].<strong>La</strong> métrica utilizada es la longitud <strong>de</strong>l enlace.C. Funciones objetivoEl coste <strong>de</strong> <strong>de</strong>spliege <strong>de</strong> la red y 1 es <strong>de</strong>finido mediante elcoste <strong>de</strong> los nodos, el coste <strong>de</strong> los amplificadores <strong>de</strong>señal y el coste <strong>de</strong> los enlaces.El retardo y 2 se establece en base al mo<strong>de</strong>lo <strong>de</strong> tráficoutilizado; en este caso se ha <strong>de</strong>cidido utilizar Poisson, unmo<strong>de</strong>lo para re<strong>de</strong>s convencionales. De este modo, elretardo se mi<strong>de</strong> en base al tamaño <strong>de</strong> las colas <strong>de</strong> tráficogenerado en los nodos intermedios <strong>de</strong> la red [13], puestoque se consi<strong>de</strong>ra que el retardo generado por los enlacesen la transmisión tiene un valor <strong>de</strong>spreciable. Nótese quecon Co NEi se quiere hacer referencia al coste <strong>de</strong> un<strong>de</strong>terminado nodo llamado i, con Co Linki,j al coste <strong>de</strong> elenlace entre los nodos i y j, y con Cp Linki,j a la capacidad<strong>de</strong> el enlace entre los nodos i y j.Dijy Co(NECo )1Link A1ij ii j i j L T _ acuij T_ acuiji j CpLinkijy2CpLinkijAmbas funciones objetivo han sido utilizadas en otraspublicaciones [9] [10].ijD. LimitacionesPara que una <strong>de</strong>terminada topología-solución pueda serconsi<strong>de</strong>rada válida <strong>de</strong>be cumplir una serie <strong>de</strong>restricciones:• El flujo que atraviesa un enlace no pue<strong>de</strong> sersuperior a la capacidad <strong>de</strong> dicho enlace. Paraello es necesario tener en cuenta todo el tráficoque atravesará dicho enlace <strong>de</strong>bido al resto <strong>de</strong>nodos <strong>de</strong> la red.• <strong>La</strong> red obtenida <strong>de</strong>be ser confiable. Por ello esnecesario que al menos sea bi-conexa, es <strong>de</strong>cir,que todos los nodos <strong>de</strong>ben ser accesiblesmediante dos rutas alternativas.III. IMPLEMENTACIÓNA. Codificación utilizadaComo es habitual en los algoritmos genéticos, cadaindividuo se <strong>de</strong>finido mediante un cromosoma. Cadaindividuo representa una <strong>de</strong>terminada topología. Elcromosoma, <strong>de</strong> longitud fija, se divi<strong>de</strong> en dos partes, taly como pue<strong>de</strong> observarse en la figura 1:• <strong>La</strong> primera parte es la responsable <strong>de</strong> <strong>de</strong>finir eltipo <strong>de</strong> cada uno <strong>de</strong> los nodos <strong>de</strong> la red (verapartado II-A).• <strong>La</strong> segunda representa los enlaces existentesentre los nodos, don<strong>de</strong> uno indica la existencia<strong>de</strong> un enlace y cero lo opuesto. A la hora <strong>de</strong>representar la topología se ha consi<strong>de</strong>rado quelas comunicaciones son bidireccionales, por loque la matriz <strong>de</strong> adyacencia que <strong>de</strong>fine la red essimétrica, permitiendo reducir la cantidad <strong>de</strong>bits a almacenar <strong>de</strong> NxX a N(N-1)/2.En total se necesitan Nlog 2 K+N(N-1)/2 bits paraalmacenar un individuo.Fig. 1. Cromosoma <strong>de</strong> longitud fija que representa a los individuos <strong>de</strong>lproblema.B. Población inicial<strong>La</strong> población inicial es generada mediante una mezcla<strong>de</strong> procesos aleatorios y <strong>de</strong>terministas. En primer lugar,se asignan <strong>de</strong> forma aleatoria el tipo a cada uno <strong>de</strong> losnodos. A continuación, se obtiene el árbol mínimo <strong>de</strong>distancias entre todos los nodos, utilizando el algoritmo<strong>de</strong> Prim [14]. Finalmente se aña<strong>de</strong>n <strong>de</strong> forma aleatorianuevos enlaces al árbol generado.Una vez generado, el individuo se evalúa paracomprobar si es una topología válida; en caso afirmativose inserta, en caso negativo se <strong>de</strong>scartaría y se volvería arepetir el proceso. A<strong>de</strong>más, se verifica que el individuo<strong>JP2011</strong>-96


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011no se encuentre duplicado. Estas comprobaciones serealizan con el objetivo <strong>de</strong> aumentar la velocidad <strong>de</strong>convergencia <strong>de</strong> los algoritmos.C. Evaluación <strong>de</strong> los individuosCada individuo <strong>de</strong> la población es sometido a un proceso<strong>de</strong> evaluación en el que, a<strong>de</strong>más <strong>de</strong> <strong>de</strong>terminar el valor<strong>de</strong> las correspondientes funciones objetivo, se evalúa siel individuo cumple con las limitaciones (Apartado II-D<strong>de</strong> este artículo) impuestas al problema.Para ello, primero se comprueba la biconexidad <strong>de</strong> lared, para que cada nodo sea accesible <strong>de</strong>s<strong>de</strong> dos rutasalternativas. A continuación se calcula la nueva matriz<strong>de</strong> tráfico estimado mediante la política <strong>de</strong> enrutamientoya expuesta (Apartado II-B). Se comprueba que los tipos<strong>de</strong> nodos asignados a la topología (primera parte <strong>de</strong>lcromosoma) existan y no sean producto <strong>de</strong> unamodificación producida por una mutación.A continuación se calcula el coste y retardo <strong>de</strong> la red.Para ello hay que tener en cuenta que la capacidad <strong>de</strong> un<strong>de</strong>terminado enlace es la <strong>de</strong> la menor capacidad <strong>de</strong> losnodos que une. De este modo, si la capacidad es inferiora la requerida por la matriz <strong>de</strong> tráfico estimado (T_acu)la solución será inválida. Con esta capacidad seselecciona como enlace el que sea inmediatamentesuperior a este valor; en caso <strong>de</strong> que no exista, lasolución será consi<strong>de</strong>rada una vez más inválida.A las soluciones consi<strong>de</strong>radas inválidas se les asignanvalores infinitos, tanto al coste como al retardo, por loque serán <strong>de</strong>sechadas en iteraciones sucesivas.D. Cruce<strong>La</strong> recombinación <strong>de</strong> dos individuos permite laformación <strong>de</strong> nuevos individuos partiendo <strong>de</strong>l materialgenético <strong>de</strong> estos progenitores.Puesto que los cromosomas están compuestos por dospartes bien diferenciadas, se ha <strong>de</strong>cidido realizar larecombinación atendiendo a estos criterios:• Cruce en la primera parte. El punto <strong>de</strong> crucepodría seleccionarse <strong>de</strong> forma completamentealeatoria, pero entonces se produciría un grannúmero <strong>de</strong> individuos con tipos <strong>de</strong> nodosinexistentes que posteriormente serían<strong>de</strong>scartados. Por ello se ha <strong>de</strong>cidido situar elpunto <strong>de</strong> corte <strong>de</strong> forma que no se modifique lacodificación <strong>de</strong> los individuos. De este modo,la recombinación <strong>de</strong> dos individuos dará lugar aun tercer individuo en el que los tipos <strong>de</strong> nodosposibles serán únicamente los <strong>de</strong> sus padres.• Cruce en la segunda parte: El punto <strong>de</strong> cruce sesitúa <strong>de</strong> forma completamente aleatoria.E. Mutación<strong>La</strong> mutación permite facilitar una amplia exploración <strong>de</strong>lespacio <strong>de</strong> soluciones, evitando que los algoritmosentren en mínimos locales.Al igual que en el cruce, la mutación se realizaatendiendo a la división <strong>de</strong>l cromosoma, realizando unnúmero aleatorio <strong>de</strong> mutaciones que va <strong>de</strong>s<strong>de</strong> cero hastael número <strong>de</strong> bits totales <strong>de</strong>l cromosoma.• Mutación en la primera parte: Si la mutación serealiza sobre la primera parte <strong>de</strong>l cromosoma,no se muta un único bit, puesto que podría darlugar a individuos con tipos <strong>de</strong> nodosinexistentes que serían <strong>de</strong>scartados. Por ello seha <strong>de</strong>cidido mutar el tipo <strong>de</strong> nodo porcompleto, generando un número aleatorio entretodos los tipos <strong>de</strong> nodos existentes.• Mutación en la segunda parte: <strong>La</strong> mutación escompletamente aleatoria.F. Algoritmos utilizadosPara la resolución <strong>de</strong>l problema aquí propuesto se hanimplementado dos algoritmos evolutivos bienconocidos: NSGA-II y SPEA-II.El algoritmo NSGA-II (Non-dominated Sorting GeneticAlgorithm) se basa en la clasificación <strong>de</strong> individuos envarias capas o frentes. <strong>La</strong> clasificación consiste enagrupar a todos los individuos no dominados en unfrente, con un valor <strong>de</strong> fitness (o adaptabilidad) igualpara todos los individuos. Este valor es proporcional altamaño <strong>de</strong> la población, para así proporcionar unpotencial reproductivo igual para todos los individuos <strong>de</strong>este frente. De esta forma el grupo <strong>de</strong> individuosclasificados es ignorado y otro frente <strong>de</strong> individuos nodominados es consi<strong>de</strong>rado. El proceso continúa hastaque se clasifican todos los individuos en la población.Esta <strong>de</strong>finición es similar a la <strong>de</strong>l algoritmo NSGA,puesto que el NSGA-II no es más que una evolución <strong>de</strong>lprimero, siendo computacionalmente más eficiente yutilizando un mecanismo elitista consistente enseleccionar los mejores individuos <strong>de</strong> la unión <strong>de</strong> laspoblaciones <strong>de</strong> padre e hijo. El pseudocódigo es elmostrado en la figura 2; para más <strong>de</strong>talles consultar lareferencia [11].Algoritmo 1 Pseudocódigo NSGA-II1: Inicializar población, P2: Or<strong>de</strong>nar P, consi<strong>de</strong>rando dominancia3: Evaluar individuos <strong>de</strong> P.4: Aplicar operadores genéticos a P, para tener Q5: para i=0 a MAX_GENERACIONES hacer6: R = P U Q7: Or<strong>de</strong>nar R, consi<strong>de</strong>rando dominancia y obtener frentes, F I8: I = 19: mientras |P i+1 | < N entonces //N, número <strong>de</strong> individuos en P10: Calcular adaptabilidad <strong>de</strong> cada individuo en F I11: P t+1 = P t+1 U F I12: I = I + 113: fin mientras14: Or<strong>de</strong>nar P i+1 , consi<strong>de</strong>rando dominancia15: Elegir los primeros N elementos <strong>de</strong> P i+116: Aplicar operadores genéticos a P i+1 , para tener Q i+117: fin paraEl algoritmo SPEA-II (Strength Pareto EvolutionaryAlgorithm) se caracteriza por la utilización <strong>de</strong> unamemoria externa (un fichero <strong>de</strong> texto), a diferencia <strong>de</strong>lanterior, que contiene las soluciones no dominadasencontradas (población externa <strong>de</strong> no dominados P nd ).En cada generación, se copian los individuos nodominados <strong>de</strong> P en P nd y se borra <strong>de</strong> éste las solucionesdominadas. Para cada individuo en el sistema externo, secomputa su valor <strong>de</strong> fitness mediante una estrategia <strong>de</strong>asignación fina: consi<strong>de</strong>ra, para cada individuo, elnúmero <strong>de</strong> individuos que lo dominan y el número <strong>de</strong>individuos por los cuales es dominado. Otra aspectorelevante <strong>de</strong>l algoritmo es la utilización <strong>de</strong> la técnica <strong>de</strong>l“vecino más cercano” para valorar la <strong>de</strong>nsidad,dirigiendo la búsqueda <strong>de</strong> forma más eficiente. En el<strong>JP2011</strong>-97


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011algoritmo 2 pue<strong>de</strong> verse el pseudocódigo <strong>de</strong>l SPEA-II;para más <strong>de</strong>talles consultar la referencia [12].Algoritmo 2 Pseudocódigo SPEA-II1: Inicializar población, P2: para i=0 a MAX_GENERACIONES hacer3: Evaluar individuos <strong>de</strong> P4: Marcar soluciones no dominadas <strong>de</strong> P5: Actualizar el conjunto <strong>de</strong> soluciones no dominadas: P N6: Calcular la adaptabilidad <strong>de</strong> los individuos <strong>de</strong> P y P N7: Seleccionar individuos <strong>de</strong>l conjunto P V P N8: Aplicar los operadores <strong>de</strong> cruzamiento y mutación9: fin paraIV. RESULTADOSEn este artículo se ha resuelto el problema <strong>de</strong>comunicación entre las diez ciuda<strong>de</strong>s chinas máspobladas [6], mediante la utilización <strong>de</strong> dos algoritmosevolutivos: NSGA-II y SPEA-II.Todos los experimentos han sido realizadas en un clúster<strong>de</strong> procesadores paralelos compuesto por 5 nodos, cadauno <strong>de</strong> ellos con cuatro procesadores Intel® Xeon a3.0Ghz y 1 <strong>de</strong> GB memoria RAM. Para aprovechar estacapacidad <strong>de</strong> procesamiento se ha <strong>de</strong>sarrollado unsistema paralelo basado en MPI [22] que permite laejecución <strong>de</strong> múltiples instancias <strong>de</strong>l problemasimultáneamente. De esta forma, si se <strong>de</strong>sea llevar acabo 20 ejecuciones <strong>de</strong> una misma configuración, selanzan 4 ejecuciones en cada nodo (una por procesador)recogiendo los resultados <strong>de</strong> cada una a su finalización.Con esta sencilla operación se consigue reducir eltiempo <strong>de</strong> ejecución casi 20 veces, puesto que el tiempo<strong>de</strong> CPU <strong>de</strong> una ejecución es muy elevado encomparación con el tiempo <strong>de</strong> comunicación necesario.A la hora <strong>de</strong> realizar la experimentación se ha utilizadouna sencilla estrategia: en primer lugar, se han<strong>de</strong>terminado las configuraciones con las que se obtienenlos mejores resultados para cada algoritmo. Una vezobtenidos, se trata <strong>de</strong> estudiar estadísticamente si alguno<strong>de</strong> los dos ofrece un comportamiento superior al otro.Como se ha dicho, el primer paso <strong>de</strong> la experimentaciónconsiste en ajustar los parámetros más habituales para<strong>de</strong>terminar con qué configuración se obtienen losmejores resultados. Estos parámetros son: número <strong>de</strong>generaciones, tamaño <strong>de</strong> la población, probabilidad <strong>de</strong>cruce y probabilidad <strong>de</strong> mutación. Esta metodología essimilar a la <strong>de</strong> A. Rubio-<strong>La</strong>rgo et al. [15], en la que,partiendo <strong>de</strong> una configuración por <strong>de</strong>fecto, se vanfijando los valores <strong>de</strong> los parámetros uno a uno en suvalor óptimo, hasta que se han ajustado todos.A la hora <strong>de</strong> establecer el grado <strong>de</strong> bondad que tienenlos frentes obtenidos para cada configuración, esnecesario utilizar algún tipo <strong>de</strong> medida. En este caso, seha <strong>de</strong>cidido utilizar una medida habitual como es elhipervolumen [16]: a mayor valor, mejor es la solución.Para cada configuración probada se han realizado untotal <strong>de</strong> veinte repeticiones con el fin <strong>de</strong> dar vali<strong>de</strong>zestadística, obteniendo para cada una <strong>de</strong> ellas un<strong>de</strong>terminado frente y por consiguiente un hipervolumen.El valor <strong>de</strong>l campo hipervolumen en las tablas I-II-III-IV no es más que el valor promedio <strong>de</strong> todos estoshipervolúmenes para una <strong>de</strong>terminada configuración.A la hora <strong>de</strong> calcular un hipervolumen es necesario<strong>de</strong>finir los puntos <strong>de</strong> referencia máximo y mínimo [16].De forma experimental, se <strong>de</strong>terminó que es suficientecon los puntos {1.000.000, 0.9} como máximo y {0, 0}como mínimo, para las tuplas {coste, retardo}, pues asíse envuelven todos los frentes obtenidos.El procedimiento <strong>de</strong> ajuste es como sigue:• En primer lugar, se trata <strong>de</strong> obtener el número<strong>de</strong> generaciones idóneo, partiendo <strong>de</strong> unosvalores por <strong>de</strong>fecto <strong>de</strong>: población igual a 100,probabilidad <strong>de</strong> cruce <strong>de</strong>l 50% y <strong>de</strong> mutación<strong>de</strong>l 50%. Este parámetro <strong>de</strong>be ser el primero enser ajustado, pues tiene una influencia clara enel tiempo <strong>de</strong> ejecución. En la tabla I pue<strong>de</strong>observarse cómo con un valor <strong>de</strong> 800 es másque suficiente, pues su aumento no supondríauna clara mejoría <strong>de</strong>l hipervolumen obtenido ysí <strong>de</strong>l tiempo <strong>de</strong> ejecución <strong>de</strong>l experimento. Portanto, se busca balancear el tiempo <strong>de</strong> ejecucióny la calidad <strong>de</strong> los resultados.• Una vez ajustado el número <strong>de</strong> generaciones, elsiguiente parámetro a ajustar es el tamaño <strong>de</strong> lapoblación (ver tabla II). Este parámetro es elúltimo <strong>de</strong> los ajustados que inci<strong>de</strong> en el tiempo<strong>de</strong> ejecución. Como pue<strong>de</strong> observarse, paraambos se obtiene el mejor comportamiento conun total <strong>de</strong> 250 individuos.• A continuación se ajusta la probabilidad <strong>de</strong>cruce, que <strong>de</strong>terminará la probabilidad con laque los individuos serán cruzados. Los mejoresvalores para el NSGA-II y el SPEA-II seobtienen con una probabilidad <strong>de</strong>l 80% y <strong>de</strong>l60% respectivamente (ver tabla III).• Finalmente, se ajusta la probabilidad <strong>de</strong>mutación, que <strong>de</strong>termina la probabilidad con laque los nuevos individuos recibirán mutacionesen sus cromosomas. Ambos algoritmosobtienen sus mejores resultados con un valor<strong>de</strong>l 50% (ver tabla IV).Mediante el procedimiento <strong>de</strong>scrito se han podido<strong>de</strong>terminar las configuraciones óptimas para cada uno <strong>de</strong>los algoritmos (tabla V).Se podría haber incorporado una figura ilustrativa sobrelos frentes <strong>de</strong> Pareto obtenidos para ambasconfiguraciones, pero la cercanía <strong>de</strong> ambos frentesrequiere una gran resolución para una visualizaciónaceptable y el tamaño <strong>de</strong> este documento lo impi<strong>de</strong>.A partir <strong>de</strong> estas dos configuraciones obtenidas, elsiguiente paso es <strong>de</strong>terminar si, como parece ser, elalgoritmo SPEA-II obtiene mejores resultados que elNSGA-II. Para ello es necesario realizar un estudioestadístico que compruebe si la mejoría lograda por elSPEA-II es significativa.El modo <strong>de</strong> proce<strong>de</strong>r a la hora <strong>de</strong> realizar el estudioestadístico es el mostrado en la figura 3 [17]. Para ello,el primer paso consiste en <strong>de</strong>terminar si los datosproce<strong>de</strong>ntes <strong>de</strong> las treinta ejecuciones, para ambasconfiguraciones, siguen una distribución normal. Paraello utilizamos los test <strong>de</strong> Shapiro-Wilk [18] yKolmogorov-Smirnov-Lilliefors(K-S) [19]. En ambostest se contrastan las siguientes hipótesis:H 0 : El mo<strong>de</strong>lo subyacente a los datos es normal.H 1 : El mo<strong>de</strong>lo subyacente a los datos no es normal.<strong>JP2011</strong>-98


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA IAJUSTE DE PARÁMETROS PARA LA OBTENCIÓN DEL NÚMERO DEGENERACIONES IDÓNEOHipervolumen Generaciones Población Prob. Prob.NSGA SPEACruce MutacionII II0.94176 0.93698 100 100 0.5 0.50.94542 0.94674 200 100 0.5 0.50.95160 0.95382 300 100 0.5 0.50.95737 0.95403 400 100 0.5 0.50.95757 0.95493 600 100 0.5 0.50.95753 0.95965 700 100 0.5 0.50.95853 0.96005 800 100 0.5 0.50.95871 0.96028 900 100 0.5 0.50.95871 0.96028 1000 100 0.5 0.5Fig. 3. Modo <strong>de</strong> proce<strong>de</strong>r a la hora <strong>de</strong> seleccionar el test estadísticoa<strong>de</strong>cuado a la naturaleza <strong>de</strong> las muestras.TABLA IIAJUSTE DE PARÁMETROS PARA LA OBTENCIÓN DEL TAMAÑO DE LAPOBLACIÓN IDÓNEOHipervolumen Generaciones Población Prob. Prob.NSGA SPEACruce MutaciónII II0.94728 0.96114 800 50 0.5 0.50.95853 0.96005 800 100 0.5 0.50.96408 0.96067 800 150 0.5 0.50.96081 0.95914 800 200 0.5 0.50.97345 0.97443 800 250 0.5 0.50.96692 0.96822 800 300 0.5 0.50.97047 0.97217 800 350 0.5 0.5TABLA IIIAJUSTE DE PARÁMETROS PARA LA OBTENCIÓN DE LA PROBABILIDADDE CRUCE IDÓNEAHipervolumen Generaciones Población Prob. Prob.NSGA SPEACruce MutaciónII II0.97169 0.97299 800 250 0.01 0.50.97506 0.96807 800 250 0.1 0.50.96985 0.97323 800 250 0.2 0.50.97362 0.96402 800 250 0.3 0.50.97410 0.96645 800 250 0.4 0.50.97345 0.97443 800 250 0.5 0.50.97363 0.97594 800 250 0.6 0.50.97213 0.97434 800 250 0.7 0.50.97516 0.97289 800 250 0.8 0.50.96762 0.96517 800 250 0.9 0.5TABLA IVAJUSTE DE PARÁMETROS PARA LA OBTENCIÓN DE LA PROBABILIDADDE MUTACIÓN IDÓNEAHipervolumen Generacio Población Prob. Prob.NSGA SPEA nesCruce MutaciónII IINSGA-II/ SPEA-II0.96722 0.96802 800 250 0.8 /0.6 0.010.96367 0.96447 800 250 0.8 /0.6 0.030.95990 0.96909 800 250 0.8 /0.6 0.060.96753 0.96593 800 250 0.8 /0.6 0.080.96684 0.97065 800 250 0.8 /0.6 0.10.97060 0.96892 800 250 0.8 /0.6 0.20.96281 0.97299 800 250 0.8 /0.6 0.30.97230 0.96555 800 250 0.8 /0.6 0.40.97516 0.97594 800 250 0.8 /0.6 0.50.97196 0.97027 800 250 0.8 /0.6 0.60.97133 0.97380 800 250 0.8 /0.6 0.70.96669 0.97115 800 250 0.8 /0.6 0.80.97095 0.97513 800 250 0.8 /0.6 0.9TABLA VCONFIGURACIONES IDÓNEAS OBTENIDAS PARA CADA UNO DE LOSALGORITMOSAlgoritmos Generaciones Población Prob. Prob. MutaciónCruceNSGA-II 800 250 0.8 0.5SPEA-II 800 250 0.6 0.5Fig. 4. Gráfico <strong>de</strong> cajas proce<strong>de</strong>ntes <strong>de</strong>l estudio estadístico <strong>de</strong> lasmuestras proce<strong>de</strong>ntes <strong>de</strong> los algoritmos NSGA-II y SPEA-II.Para ambas pruebas se obtiene un valor-p inferior a 0.05,por lo que hay una fuerte evi<strong>de</strong>ncia en contra <strong>de</strong> lahipótesis nula. Por ello, no po<strong>de</strong>mos asumir que losdatos procedan <strong>de</strong> un mo<strong>de</strong>lo normal.Si se observa el gráfico <strong>de</strong> cajas expuesto en la figura 4,pue<strong>de</strong> comprobarse cómo existen diferencias entre lasmedianas (marcadas en negro) <strong>de</strong> ambos algoritmos,siendo superior el SPEA-II al NSGA-II. Pero, ¿es estadiferencia significativa? Para comprobarlo, y dado queno se pue<strong>de</strong> asumir una distribución normal en ningúncaso, como se ha comprobado anteriormente, se utilizaráuna prueba no paramétrica. En este caso se aplica el Test<strong>de</strong> Wilcoxon [20] puesto que se dispone <strong>de</strong> dos muestrasrelacionadas (figura 3), en el que se contrastan lassiguientes hipótesis:H 0 : <strong>La</strong>s dos muestras proce<strong>de</strong>n <strong>de</strong> poblaciones con lamisma distribución (igual mediana).H 1 : <strong>La</strong>s dos muestras proce<strong>de</strong>n <strong>de</strong> poblaciones <strong>de</strong>distribuciones diferentes en la ten<strong>de</strong>ncia central(diferente mediana).El resultado <strong>de</strong>l Test es un valor-p <strong>de</strong> 0.001, inferior a0.05, por lo que hay una fuerte evi<strong>de</strong>ncia en los datos encontra <strong>de</strong> la hipótesis nula. Es <strong>de</strong>cir, las dos muestras noproce<strong>de</strong>n <strong>de</strong> poblaciones con igual mediana, o lo que eslo mismo, existen diferencias significativas entre las dosmuestras.Concluido lo anterior, se hace necesaria la utilización <strong>de</strong>un test unilateral, que permita concluir cuál <strong>de</strong> los dosalgoritmos tiene un mejor comportamiento. Para ello seintentará <strong>de</strong>mostrar si el algoritmo NSGA-II es superioral SPEA-II, contrastando las siguientes hipótesis:H 0 : <strong>La</strong>s muestras proce<strong>de</strong>ntes <strong>de</strong>l algoritmo NSGA-II tienen una media superior o igual a la <strong>de</strong>lalgoritmo SPEA-II.<strong>JP2011</strong>-99


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011H 1 : <strong>La</strong>s muestras proce<strong>de</strong>ntes <strong>de</strong>l algoritmo NSGA-II tienen una media inferior a la <strong>de</strong>l SPEA-II.El resultado <strong>de</strong>l Test es un valor-p <strong>de</strong> 0.001; al sermenor que 0.05 hay evi<strong>de</strong>ncias para rechazar la hipótesisnula. Es <strong>de</strong>cir, se pue<strong>de</strong> concluir con relevanciaestadística que el algoritmo NSGA-II tiene uncomportamiento inferior, en media, al SPEA-II, o lo quees lo mismo, el SPEA-II produce los mejores resultados.V. COMPARATIVAS CON OTROS AUTORESComo ya se ha comentado en la primera sección, elnúmero <strong>de</strong> instancias públicas para este problema es casiinexistente; tan solo existe una que se encuentre bien<strong>de</strong>scrita, por lo que ha sido la utilizada en este trabajo.<strong>La</strong> escasez <strong>de</strong> instancias reales supone un problema a lahora <strong>de</strong> po<strong>de</strong>r validar nuestras metodologías al compararlos resultados obtenidos con los <strong>de</strong> otros autores.A<strong>de</strong>más, hay algunos autores que utilizan otrasinstancias no documentadas o bien topologías generadasaleatoriamente. No obstante existen otros trabajos queutilizan la misma instancia que la que hemos adoptado.Así, Ko et al. [6] proporcionan un único valor <strong>de</strong>l par{coste, retardo} como resultado, (obteniéndose mejoresresultados en este artículo). Barnerjee et al [9] y R.Kumar et al [10] ofrecen como resultados unos frentes<strong>de</strong> Pareto sin especificar ningún tipo <strong>de</strong> medida <strong>de</strong>calidad, como el hipervolumen utilizado en por nosotros.VI. CONCLUSIONES Y TRABAJO FUTUROEn este artículo se ha resuelto el problema <strong>de</strong>l diseño <strong>de</strong>re<strong>de</strong>s para mo<strong>de</strong>los <strong>de</strong> tráfico <strong>de</strong> Internet entre las diezciuda<strong>de</strong>s chinas más pobladas, utilizando dos conocidosalgoritmos evolutivos: el NSGA-II y el SPEA-II. A suvez, se ha realizado un completo estudio estadístico queha permitido <strong>de</strong>terminar la superioridad <strong>de</strong>l algoritmoSPEA-II sobre el NSGA-II, para esta <strong>de</strong>finición <strong>de</strong>lproblema e instancia concreta. A<strong>de</strong>más, se ha utilizadoeficientemente una estrategia paralela basada en MPI,que permite acelerar la ejecución <strong>de</strong> las pruebas.Como trabajo futuro planteamos la utilización <strong>de</strong> unamayor cantidad <strong>de</strong> instancias, otros mo<strong>de</strong>los <strong>de</strong> traficoactuales (como Self-Similar[21]) así como otrosalgoritmos evolutivos (como por ejemplo DEPT,Differential Evolution with Pareto Tournaments [15]).VII. AGRADECIMIENTOSEl presente trabajo ha sido parcialmente financiado porel Ministerio <strong>de</strong> Ciencia e Innovación y el FEDER(Fondo Europeo <strong>de</strong> Desarrollo Regional), bajo elproyecto TIN2008-06491-C04-04 (proyecto MSTAR), ypor la Junta <strong>de</strong> Extremadura, a través <strong>de</strong> la ayudaGR10025 al grupo TIC015.reliability constraint, IEEE Transactions on Reliability, vol. 42, 1993,págs. 63-70.[4] Cem Ersoy and Shivendra S. Panwar, Topological <strong>de</strong>sign ofinterconnected LAN/MAN networks, IEEE Journal on Selected Areasin Communications, vol. 11, 1993, pág. 1172--1182.[5] F.N. Abuali, D.A. Schoenefeld, y R.L. Wainwright,Designing telecommunications networks using genetic algorithms andprobabilistic minimum spanning trees, Proceedings of the 1994 ACMsymposium on Applied computing - SAC ’94, Phoenix, Arizona,United States: 1994, págs. 242-246.[6] King-Tim Ko, Kit-Sang Tang y Cheung-Yau Chan y Kim-Fung Man, , y , Sam Kwong, Using genetic algorithms to <strong>de</strong>sign meshnetworks, Computer, vol. 30, Ago. 1997, págs. 56-61.[7] A. Kumar, R.M. Pathak, y Y.P. Gupta, Genetic-algorithmbasedreliability optimization for computer network expansion, IEEETransactions on Reliability, vol. 44, 1995, págs. 63-72.[8] C. Coello Coello, Evolutionary algorithms for solvingmulti-objective problems, New York: Springer, 2007.[9] N. Banerjee y R. Kumar, Multiobjective network <strong>de</strong>sign forrealistic traffic mo<strong>de</strong>ls, Proceedings of the 9th annual conference onGenetic and evolutionary computation - GECCO ’07, London,England: 2007, pág. 1904.[10] R. Kumar, P.P. Parida, y M. Gupta, Topological <strong>de</strong>sign ofcommunication networks using multiobjective genetic optimization,Proceedings of the 2002 Congress on Evolutionary Computation.CEC’02 (Cat. No.02TH8600), Honolulu, HI, USA: , págs. 425-430.[11] Kalyanmoy Deb, Samir Agrawal y Amrit Pratap y TMeyarivan, A Fast Elitist Non-dominated Sorting Genetic Algorithmfor Multi-objective Optimization: NSGA-II, Parallel Problem Solvingfrom Nature PPSN VI, 2000.[12] E. Zitzler, M. <strong>La</strong>umanns y L. Thiele, SPEA2: Improvingthe strength Pareto evolutionary algorithm, EUROGEN 2001.[13] Mohsen Guizani, Ammar Rayes, Bilal Khan and Ala Al-Fuqaha.,Network Mo<strong>de</strong>ling and Simulation: A Practical Perspective,Wiley-Interscience, 2010.[14] T. Cormen, Introduction to algorithms, Cambridge Mass.:The MIT Press, 2001.[15] A. Rubio-<strong>La</strong>rgo, M.A. Vega-Rodriguez, J.A. Gomez-Pulido, y J.M. Sanchez-Perez, A Differential Evolution with ParetoTournaments for solving the Routing and Wavelength Assignmentproblem in WDM networks, IEEE Congress on EvolutionaryComputation, Barcelona, Spain: 2010, págs. 1-8.[16] Fonseca, C., Knowles, J., Thiele, L., Zitzler, E. , A Tutorialon the Performance Assessment of Stochastic MultiobjectiveOptimizers, EMO 2005.[17] José Otero, Luciano Sánchez Diseños Experimentales yTests Estadísticos, Ten<strong>de</strong>ncias Actuales en Machine Learning VCongreso Español sobre Metaheurísticas, Algoritmos Evolutivos yBioinspirados, MAEB 07 Tenerife, Spain 2007[18] Shapiro, S. S. and Wilk, M. B, An analysis of variance testfor normality (complete samples), Biometrika, 52, 3 and 4, (1965) 591-611[19] Chakravarti, <strong>La</strong>ha, and Roy, Handbook of Methods ofApplied Statistics, Volume I, John Wiley and Sons, (1967). 392-394.[20] Wilcoxon, F. Individual Comparisons by RankingMethods. Bio-metrics 1, (1945) 80-83[21] Sahinoglu Z, Tekinay S, On multimedia networks: selfsimilartraffic and network performance", IEEE CommunicationsMagazine, vol.37, no.1, Jan. 1999, pp.48-52. Publisher: IEEE, USA.[22] W. Gropp, Using MPI : portable parallel programming withthe message-passing interface, Cambridge Mass.: MIT Press, 1999.VIII. REFERENCIAS[1] Andrew S. Tanenbaum, Computer Networks, Prentice Hall,2003.[2] B. Dengiz, F. Altiparmak, y A.E. Smith, Local searchgenetic algorithm for optimal <strong>de</strong>sign of reliable networks, IEEETransactions on Evolutionary Computation, vol. 1, Sep. 1997, págs.179-188.[3] Rong-Hong Jan, Fung-Jen Hwang, , y , Sheng-Tzong Chen,Topological optimization of a communication network subject to a<strong>JP2011</strong>-100


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011A New Tool for Classification of SatelliteImages Available from Google Maps: EfficientImplementation in Graphics Processing UnitsSergio Bernabé a and Antonio Plaza aAbstract—In this work, we <strong>de</strong>velop a new parallelimplementation of the k-means unsupervised clusteringalgorithm for commodity graphic processing units (GPUs),and further evaluate the performance of this newly<strong>de</strong>veloped algorithm in the task of classifying (inunsupervised fashion) satellite imagery available fromGoogle Maps engine. With the ultimate goal of evaluatingthe classification precision of the newly <strong>de</strong>velopedalgorithm, we have analyzed the consensus or agreement inthe classification achieved by our implementation and analternative implementation of the algorithm available incommercial software. Our experimental results, conductedusing satellite images obtained from Google Maps engineover different locations around the Earth, indicate that theclassification agreement between our parallel version andthe k-means algorithm available in commercial software isvery high. In addition, the GPU version (<strong>de</strong>veloped usingthe CUDA language available from NVidia TM ) is muchfaster that the serial one (speedup above 30), thusindicating that our proposed implementation allows forlarger scale processing of high-dimensional imagedatabases such as those available in the Google Mapsengine.Keywords—K-means clustering, satellite imagery, GoogleMaps, GPUs, CUDA.TI. INTRODUCTIONHE wealth of satellite imagery [1] available inweb mapping service applications such as GoogleMaps 1 , which now provi<strong>de</strong>s high-resolutionsatellite images from many locations around the Earth,has opened the appealing perspective of performingclassification and retrieval tasks via programminglibraries such as SwingX-WS 2 . In fact, the introductionof Google’s mapping engine prompted a worldwi<strong>de</strong>interest in satellite imagery exploitation [2-4]. Thecombination of an easily pannable and searchablemapping and satellite imagery tool such as Google Mapswith advanced image classification and retrieval featureshas the potential to significantly expand thefunctionalities of the tool and also to allow end-users toextract relevant information from a massive and wi<strong>de</strong>lyavailable database of satellite images (the Google Mapsservice is free for non-commercial use).In this paper, we <strong>de</strong>scribe a new tool [5] which allowsan unexperienced user to perform unsupervisedclassification of satellite images obtained via Googlea Hyperspectral Computing <strong>La</strong>boratoryDepartment of Technology of Computers and CommunicationsUniversity of Extremadura, Avda. <strong>de</strong> la <strong>Universidad</strong> s/n, E-10071 Cáceres, Spaine-mail: {sergiobenabe,aplaza}@unex.es.1 http://maps.google.com2 https://swingx-ws.<strong>de</strong>v.java.netMaps by means of the well-known k-means clusteringalgorithm [6], which can be followed by spatial postprocessingbased on majority voting. The classificationstage has been implemented in parallel using commoditygraphic processing units (GPUs) [7-8], which arespecialized hardware cards that are nowadays wi<strong>de</strong>lyavailable in standard PCs. It is important to emphasizethat GPUs offer important advantages in the context ofremote sensing image processing applications. Forinstance, while the price of a next-generation GPUstands at around 400€ (∼600 USD), the price of a clustercan be much higher. At the same time, using a clusterresults in a series of unfavorable conditions from thepoint of view of its implementation as a processingmodule onboard the remote sensing instruments, withcritical issues that can negatively affect the missionpayload (weight, power consumption, heating,maintenance, etc.). In turn, GPUs offer a much morecompact solution, although it is also important to bear inmind the conditions of tolerance of GPUs to extremerequirements in terms of consumption and sensitivity toradiation in space. However, we believe that the GPUsolutions offered in this work will soon exhibit thepotential to be incorporated into remote sensingmissions for onboard processing.Specifically, the GPU implementations reported in thiswork inclu<strong>de</strong> analyses of consensus or agreement in theclassification achieved by our GPU implementation withregards to an alternative implementation of the k-meansclustering algorithm available in commercial software(ITT Visual Information Solutions ENVI 3 ). In addition,our parallel version of the k-means algorithm–implemented in NVidia TM GPUs using the computeunified <strong>de</strong>vice architecture (CUDA) 4 – is shown to bemore than 30 times faster than the serial version. Thisopens the way for exciting new <strong>de</strong>velopments andpotentials in efficient processing of large databases ofsatellite images, such as those available from GoogleMaps engine and used in this work for <strong>de</strong>monstration.The remain<strong>de</strong>r of the paper is organized as follows.Section II <strong>de</strong>scribes the classification system that wehave <strong>de</strong>veloped for satellite images available in GoogleMaps engine. Section III <strong>de</strong>scribes the GPUimplementation. Section IV provi<strong>de</strong>s experimentalresults from the viewpoint of classification agreementand parallel performance on an NVidia Tesla C1060GPU. Finally, Section V conclu<strong>de</strong>s with some remarksand hints at plausible future research lines.3 http://www.ittvis.com/ProductServices/ENVI.aspx4 http://www.nvidia.com/object/cuda home new.html<strong>JP2011</strong>-101


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011II.CLASSIFICATION SYSTEM FOR SATELLITE IMAGESIN GOOGLE MAPS ENGINEOur classification system for Google Maps imagesconsists of the integration of the different softwaremodules <strong>de</strong>veloped (unsupervised classifiers) with thefunctionalities provi<strong>de</strong>d by the SwingX-WS libraries, inthe form of a general-purpose <strong>de</strong>sktop application [2].For this purpose, we have resorted to the Javaprogramming language (see Fig. 1), which is a multiplatformenvironment that simplifies porting of our toolto different environments. Specifically, we have resortedto the NetBeans platform 5 , which allows applications tobe <strong>de</strong>veloped from a set of modular softwarecomponents called modules. In this framework,applications can install modules dynamically and anyapplication can inclu<strong>de</strong> the update center module toallow users of the application to download digitallysignedupgra<strong>de</strong>s and new features directly into therunning application. Reinstalling an upgra<strong>de</strong> or a newrelease does not force users to download the entireapplication again. The platform offers reusable servicescommon to <strong>de</strong>sktop applications, allowing <strong>de</strong>velopers tofocus on the logic specific to their application.With the above i<strong>de</strong>as in mind, Fig. 2 shows differentviews of the <strong>de</strong>veloped tool. As shown by Fig. 2, thetool allows selecting an area to be classified, obtainingclassification results in unsupervised fashion, retainingthe classified area at different zoom levels (although theclassification is obtained at the maximum zoom level),and other functionalities such as spatial post-processingof obtained results for increased spatial consistency,managing of the resulting classification and extractedsatellite images, loading/storing of results via file logswhich can be saved in a database, automatic positioningin any latitu<strong>de</strong> and longitu<strong>de</strong> coordinates in the entireGoogle Maps database, overlaying of classificationresults with different views (satellite, map, hybrid), etc.Overall, we feel that the <strong>de</strong>veloped tool incorporatesinteresting additional functionalities to the Google Mapsengine (particularly in the possibility of better exploitingthe satellite images available from this tool in differentapplication domains).III.GPU IMPLEMENTATIONGPUs can be abstracted in terms of a stream mo<strong>de</strong>l,un<strong>de</strong>r which all data sets are represented as streams (i.e.,or<strong>de</strong>red data sets) [4]. Algorithms are constructed bychaining so-called kernels, which operate on entirestreams, taking one or more streams as inputs andproducing one or more streams as outputs. Thereby,data-level parallelism is exposed to hardware, andkernels can be concurrently applied without any sort ofsynchronization.Fig. 2. Different views of the <strong>de</strong>veloped tool. Selection of an area to beclassified in New York City (top). Unsupervised classificationresult provi<strong>de</strong>d by our implementation of k-means superimposedon the tool (middle). Zoom reduction retaining the classified area(bottom).Fig. 1. Different software modules used for the <strong>de</strong>velopment of ourapplication.5 http://netbeans.orgThe kernels can perform a kind of batch processingarranged in the form of a grid of blocks, as displayed inFig. 3(a), where each block is composed by a group ofthreads which share data efficiently through the sharedlocal memory and synchronize their execution forcoordinating accesses to memory. This figure alsodisplays how each kernel is executed as a grid of blocks<strong>JP2011</strong>-102


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011of threads. On the other hand, Fig. 3(b) shows theexecution mo<strong>de</strong>l in the GPU, which can be seen as a setof multiprocessors. In each clock cycle each processorof the multiprocessor executes the same instruction butoperating on multiple data streams. Each processor hasaccess to a local shared memory and also to local cachememories in the multiprocessor, while themultiprocessors have access to the global GPU (<strong>de</strong>vice)memory.In the following we <strong>de</strong>scribe the different steps that wefollowed for the <strong>de</strong>velopment of the GPU version of thek-means algorithm. In our implementation, pixels aredistributed in the form of vectors which store the valuesof the red, green, blue and saturation components. In thefollowing, we assume that images fit in the global GPUmemory. The k-means algorithm calculates theeucli<strong>de</strong>an distance from each pixel vector to the closestcluster center (centers are initialized randomly). In ourCUDA implementation, we assigned the calculation ofthe distance of each pixel of the image to an in<strong>de</strong>pen<strong>de</strong>ntprocessing thread. This way, each thread calculates ofthe distance between the values of each pixel and thenearest cluster center. Fig. 4 illustrates the kernel thatperforms this operation. Next, we recalculate the centersof each cluster and reassign new pixels to each of theclusters until convergence. This part has not beenparallelized in the GPU, mainly because for a smallnumber of clusters this computation can be performed inthe CPU without representing a dominant factor in theoverall time of the solution.k-means has been conducted by comparing the resultsprovi<strong>de</strong>d by our GPU implementation with thoseavailable in a well-known commercial softwarepackage: the ENVI package distributed by ITT VisualInformation Solutions. In our tests, we adopt exactly thesame parameters when running our implementation andthe one available in ENVI software, comparing theresults in terms of the agreement between both solutionsand their computational performance.(a)(b)Fig. 3. Schematic overview of a GPU architecture. (a) Threads, blocksand grids. b) Execution mo<strong>de</strong>l in the GPU.(c)Fig. 5. (a) Satellite image over the World Tra<strong>de</strong> Center area. (b)Unsupervised classification result provi<strong>de</strong>d by our GPUimplementation of k-means. (c) Unsupervised classification resultprovi<strong>de</strong>d by ENVI’s implementation of k-means.Fig. 4. Main CUDA kernel <strong>de</strong>veloped for the implementation ofk-means algorithm in GPUs.IV.EXPERIMENTAL RESULTSIn this section, we perform an experimental validationof our <strong>de</strong>veloped system using satellite images obtainedfrom Google Maps. The experimental validation ofIn the following, we present the obtained results in aspecific case study focused on classification of satelliteimages available from the World Tra<strong>de</strong> Center (WTC)area in New York City. Fig 5(a) shows a satellite imageextracted from Google Maps engine. The resolution ofthe image is quite high, with approximately 5 meters perpixel. Fig. 5(b) shows the unsupervised classificationresult provi<strong>de</strong>d by our GPU implementation as<strong>JP2011</strong>-103


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011compared to the result provi<strong>de</strong>d by ENVI’s k-means inFig. 5(c). As shown by Fig. 5, the color labels for ourimplementation and the one available in ENVI aredifferent, but the classification maps are very similar. Inboth cases, the parameters for both algorithms have beenset to exactly the same values, with the number ofclusters set empirically to five. Table I reports theclassification agreement (in percentage) measured aftercomparing our k-means classification map with the oneobtained by ENVI (assuming the latter as the reference).As shown by Table I, the agreement between both mapsis quite high.TABLE IClassification agreement (in percentage) after comparing theclassification map provi<strong>de</strong>d by our GPU implementation of k-meanswith the classification map obtained by ENVI’s k-means for the imagein Fig. 5(a).Shadows #1[blue inFig. 5(b)]Shadows#2 [red inFig. 5(b)]Urbanareas #1[yellow inFig. 5(b)]Urbanareas #1[green inFig. 5(b)]Urbanareas #2[orange inFig. 5(b)]Overallagreement78.26 95.49 85.56 90.65 97.39 89.47In a second experiment, we have selected a specificcase study focused on classification of satellite imagesavailable from the Nile river in the north of Cairo(Egypt) (see Fig. 6). The resolution of the image is quitehigh, with approximately 5 meters per pixel. As show byFig. 6, the color labels for our implementation and theone available in ENVI are different, but theclassification maps are very similar. In both cases, theparameters for both algorithms have been set to exactlythe same values, with the number of clusters set to five.Table II reports the classification agreement (inpercentage) measured after comparing our k-meansclassification map with the one obtained by ENVI(assuming the latter as the reference). As shown byTable II, the agreement between both maps is quite high.TABLE IIClassification agreement (in percentage) after comparing theclassification map provi<strong>de</strong>d by our GPU implementation of k-meanswith the classification map obtained by ENVI’s k-means for the imagein Fig. 6(a).Soil #1[blue inFig. 6(b)]Water #1[green inFig. 6(b)]Urbanareas #1[orange inFig. 6(b)]Water #2[red in Fig.6(b)]Soil #2[yellow inFig. 6(b)]Overallagreement63.89 96.98 99.74 89.01 94.59 88.47TABLE IIIProcessing times (in seconds) and speedups achieved with regards tothe corresponding CPU for different GPU implementations of thek-means algorithm (using different image sizes and number ofclusters), in Fig. 5(a).(a)Parameters consi<strong>de</strong>redGeForce 9400MGPUTesla C1060 GPUImage sizeNumber ofclustersTime Speedup Time Speedup512 x 512 5 0.252 3.26x 0.145 5.67x512 x 512 64 0.496 7.60x 0.210 17.95x512 x 512 128 0.764 10.29x 0.268 29.33x1024 x 1024 64 3.582 6.18x 0.715 30.97x1024 x 1024 128 4.376 8.76x 1.044 36.69x(b)(c)Fig. 6. (a) Satellite image collected over a stretch of the Nilo river inEgypt (the image is available online through Google Mapsengine). (b) Unsupervised classification result provi<strong>de</strong>d by ourGPU implementation of k-means. (c) Unsupervised classificationresult provi<strong>de</strong>d by ENVI’s implementation of k-means.TABLE IVProcessing times (in seconds) and speedups achieved with regards tothe corresponding CPU for different GPU implementations of thek-means algorithm (using different image sizes and number ofclusters), in Fig. 6(a).Parameters consi<strong>de</strong>redGeForce 9400MGPUTesla C1060 GPUImage sizeNumber ofclustersTime Speedup Time Speedup512 x 512 5 0.140 3.84x 0.118 4.55x512 x 512 64 0.458 4.79x 0.210 10.46x512 x 512 128 0.592 6.28x 0.223 16.67x1024 x 1024 64 5.153 3.59x 1.046 17.68x1024 x 1024 128 6.467 4.01x 1.254 20.66x<strong>JP2011</strong>-104


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Finally, we analyze the computational performance ofthe <strong>de</strong>veloped GPU implementation with regards to itsCPU (serial) version. In this work, we have used twodifferent CPU-GPU configurations. In the first one, weuse an Intel Core i7 920 CPU with the Ubuntu 9.04Linux operating system and the NVidia Tesla C1060GPU 6 . In the second one, we use an Intel Core 2 DuoP8700 2.53Ghz CPU with the Windows 7 operatingsystem and an NVidia GeForce 9400MGPU 7 . Table IIIand Table IV show the execution times achieved foreach of the CPU-GPU configurations used, as well asthe speedups achieved for different image sizes andnumber of clusters. An important observation is that, aswe increase the image size and number of clusters, thespeedup achieved by the GPUs tends to be moresignificant. For instance, the implementation in the TeslaC1060 GPU achieves a speedup of about 37x withregards to the CPU version for 1024 × 1024 image sizeand 128 clusters in the best case. However, theimplementation in the GeForce 9400M GPU saturatesfor certain image sizes, achieving a speedup of about10x in the best case.V. CONCLUSIONS AND FUTURE RESEARCHIn this work, we have <strong>de</strong>veloped a new parallelimplementation of the k-means clustering algorithm inthe context of satellite image processing usingNVIDIA TM GPUs. The algorithm has been implementedusing CUDA, and tested using a recently <strong>de</strong>velopedsystem for information extraction and analysis of imagedata sets from Google Maps engine. The algorithm hasbeen evaluated in terms of its agreement withcommercial software in the same context, and alsoanalyzing the speedup with regards to the (optimized)serial implementation of the same co<strong>de</strong>.The main contributions of this study can besummarized as follows:• The proposed method succee<strong>de</strong>d in obtaining agood agreement in classification with regards tocommercial software.• The GPU implementation obtained a significantspeedup over the optimized serial version, thussupporting large scale tests in the Google Mapsengine.In future work, we will <strong>de</strong>velop other parallelimplementations of the consi<strong>de</strong>red algorithm and alsoimprove the clustering procedure by including otherclassifiers such as support vector machines (SVMs),which allow a user to train the classifier by selectingtraining samples from the image to be processed insemi-supervised fashion. Implementations of theproposed methods in OpenCL also represent aninteresting future research line.project, reference AYA2008-05965-C04-02). Fundingfrom Junta <strong>de</strong> Extremadura (local government) un<strong>de</strong>rproject PRI09A110 is also gratefully acknowledged.REFERENCES[1] D. A. <strong>La</strong>ndgrebe, Signal theory methods in multispectral remotesensing, John Wiley and Sons, Hoboken, NJ, 2003.[2] P. Soille, Morphological image analysis: principles andapplications, Springer-Verlag, Berlin, 2003.[3] J. A. Benediktsson, J. A. Palmason, and J. R. Sveinsson,“Classification of hyperspectral data from urban areas based onexten<strong>de</strong>d morphological profiles”, IEEE Trans. Geoscience andRemote Sensing 42, pp. 480 - 491, 2005.[4] L. Bruzzone, M. Chi, and M. Marconcini, “A novel transductivesvm for the semisupervised classification of remote sensingimages” IEEE Trans. Geoscience and Remote Sensing 44, pp.3363 - 3373, 2006.[5] S. Bernabe and A. Plaza, “A new system to performunsupervised and supervised classification of satellite imagesfrom google maps,” Proc. SPIE Conference on Satellite DataCompression, Communications, and Processing, vol. 7810, pp.1–10, 2010.[6] J. A. Hartigan and M. A. Wong, “Algorithm as 136: A k-meansclustering algorithm,” Journal of the Royal Statistical Society,Series C (Applied Statistics), vol. 28, pp. 100–108, 1979.[7] J. Setoain, M. Prieto, C. Tenllado, A. Plaza, and F. Tirado,“Parallel morphological endmember extraction using commoditygraphics hardware”, IEEE Geoscience and Remote SensingLetters, vol. 43, pp. 441–445, 2007.[8] J. Setoain, M. Prieto, C. Tenllado, and F. Tirado, “GPU forparallel on-board hyperspectral image processing," InternationalJournal of High Performance Computing Applications 22 (4), pp.424-437, 2008.ACKNOWLEDGEMENTThis work has been supported by the Spanish Ministryof Science and Innovation (HYPERCOMP/EODIX6 http://www.nvidia.com/object/product tesla c1060 us.html7 http://www.nvidia.com/object/product geforce 9400m g us.html<strong>JP2011</strong>-105


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-106


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Visibility Map Computation at all Points of aTerrainL. F. Romero, 1 S. Tabik, 2 E.L. Zapata 3Abstract— The knowledge of visibility informationon a terrain is essential for a large number of currentapplications. There exist several algorithms in theliterature for building visibility maps (VM) but onlyfor one single viewpoint or at most for a very smallnumber of observers. This limitation is due to thehigh computational complexity of the used methods(which is greater than O(N 2 ), where N is the numberof the terrain points) and also to the fact thatsingle-point algorithms cannot efficiently be scaled toall points. We present a novel fast algorithm ableto compute the complete VM where, given a terrainT represented by its regular digital elevation mo<strong>de</strong>l(DEM), our method produces a continuous VM foreach point of T. In fact, the proposed algorithm combinestwo algorithms, i) a visible heights computationalgorithm that divi<strong>de</strong>s the terrain into sectors andcalculated the end of all the visible ring sectors, andii) an algorithm that finds out the start of the visiblering sectors using a low cost calculation. To ease thetheoretical and experimental comparisons with previousworks, we consi<strong>de</strong>red the VM for one single observer.The results show that our algorithm is moreaccurate and faster by many or<strong>de</strong>rs of magnitu<strong>de</strong> thanthe wi<strong>de</strong>ly used ArcGis visibility tools.I. IntroductionIN the last <strong>de</strong>ca<strong>de</strong>, new larger DEMs (Digital ElevationMo<strong>de</strong>ls) of higher precision are being created,for example, a global DEM of the earth’s landsurface of size 15.1015 pixels and precision 3 arc seconds(approximately 90 x 90 m2 at the equator) isnow available in [1]; in addition to a large numberof DEMs of many regions of resolution higher than 1arc second (30 x 30 m2). Moreover, in the next threeyears new global products of higher resolution are expected;TanDEM-X Satellite, launched the 21st June2010, will allow the generation of global DEMs of resolutionhigher than 10 x 10 m2. This advances areproducing a huge need to new fast and efficient GIS(Geographic Information Systems) processing algorithms.An important number of GIS applications on terrainsrepresented by DEMs is concerned with visibility.There exists a wi<strong>de</strong> range of actual applications.Examples inclu<strong>de</strong> the computation of the minimumnumber of locations that have the largest coverageof a terrain [2], [16] i) for placing radio, TV, Internet,wireless or mobile phones transmitters and receiversin telecommunications, ii) for situating forestfire watchtowers in environmental planning, iii) for<strong>de</strong>termining routes for hiking trails in tourism. Recently,visibility analysis is also used for visual impactassessment, such as the impact of aquiculture1 Dpto. Arquitectura <strong>de</strong> Computadores, <strong>Universidad</strong> <strong>de</strong>Malaga, e-mail: felipe@uma.es2 stabik@uma.es3 ezapata@uma.esprojects [4] and wind turbines farms installations [6].It is also used to improve wildlife population size estimationtechniques [5], and in the field of archeology,it is used for the reconstruction of views to and fromhistorical objects and sites [7].Most visibility software, such as the well knownvisibility analysis tools implemented un<strong>de</strong>r the commercialArcGIS 9.0 [8], r.los implemented un<strong>de</strong>rGRASS 6.2.2 [9] and, many algorithms provi<strong>de</strong>d inthe literature [12], [18], [13], [17], [20], [21] computethe parts of a terrain that are visible from a singleviewpoint or at most from a reduced number of observers.However none of these implementations iscapable of computing the VM at all the points of theterrain. The reason behind this limitation is thatthe calculation of VM even for a single point is tooexpensive and has a complexity greater than O(N),where N is the total number of points of the DEM.This means that computing the complete VM at allthe points of the terrain has a complexity greaterthan O(N 2 ).This paper presents a novel algorithm able to computethe VM on the entire terrain with a low cost. Incontrast to most previous algorithms which processall the N points of the DEM in or<strong>de</strong>r to produce theVM of one single point, our method finds out the visiblepoints by regions. That is, it looks for the visiblepoints only among a selected set of points, called sector.As the size of the selected set is O(log(N/S)),finding the visible regions over all the terrain has acomplexity of only O(S.N.log(N)), where S is thetotal number of sectors. As far as we know, thisalgorithm is the first in computing the VM for theentire terrain. To make our algorithm comparablewith one of the most used visibility algorithms, ArcGis,we compared the runtimes of computing VM atone single viewpoint. The experimental results showthat our algorithm is largely faster than the visibilityanalysis tool of ArcGis.This paper is organized as follows. A brief <strong>de</strong>scriptionof related works is given in section 2. A <strong>de</strong>tailed<strong>de</strong>scription of all the algorithmic strategies, necessaryfor carrying out both stages of the algorithm, isprovi<strong>de</strong>d in section 3. Numerical and computationalresults are given in section 4 and, finally conclusionsin section 5.II. Related WorksThe problem of computing continuous visibilitymaps with respect to a single viewpoint has beenextensively studied in the literature. Nagy and, Florianiand Magillo provi<strong>de</strong> complete surveys of visibilityalgorithms in [10] and [11] respectively. In this<strong>JP2011</strong>-107


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011section we will discuss only those papers more relatedto our own work.Atallah [12] uses a divi<strong>de</strong>-and-conquer algorithmto compute the upper envelope of N segments in theplane with a time complexity of O(Nα(N)logN)),where α is the inverse Ackermann function, a slowgrowing function, nearly constant. This algorithmrecursively divi<strong>de</strong>s the line segments into halves, andpairwise merges the resultant upper envelopes viaa sweep line technique. Hershberger [13] improvesAtallah’s algorithm, reaching an optimal complexityof O(NlogN). De Floriani et al. [17] computesthe visibility map on TINs (Triangulated IrregularNetworks) using the front-to-back or<strong>de</strong>r intime O(N 2 α(N)).Alternatively, the visibility problem can also besolved using horizon calculation. The approximativemethod of Cabral et al. [20] divi<strong>de</strong>s the horizon intoS sectors, and in each sector it <strong>de</strong>termines the elevationof the horizon, consi<strong>de</strong>ring solely the pointsof the terrain that are in the central line of the sectorwith a computational cost O(S(N 1.5 )). Stewart[21] proposed a more precise and faster algorithmthat computes the approximate horizon for all thepoints of the DEM in the whole sector with a totalcost O(SN(log 2 N +S)) and space O(N(log N)). Finally,Tabik et al. [22] proposed a three-level horizonapproach more than three times faster than Stewartsalgorithm while maintaining the same accuracy.Nevertheless, none of these works produces the visibilitymap at all the points of a terrain.III. Our AlgorithmOur algorithm works in two main phases. Actually,it solves the visibility problem by finding thelimits where the visible regions start and end. In thefirst phase, it searches for the visible heights amongthe points that form the horizon or the profile of theterrain. In particular, it finds the end limits of thevisible regions, of ring sector shapes, in each directionaround the points of the terrain. In the nextphase, it uses a very fast algorithm to calculate thestart limits of those visible ring sectors.A. Visible Heights ComputationIn this section we <strong>de</strong>scribe all the algorithmic basisof this stage and the optimizations that makes thewhole algorithm faster.A.1 Profile ComputationThe DEM of a terrain T can be <strong>de</strong>scribed as aset of N points P i (i = 0, ..., N) of coordinates(x i , y i , z i ), where z i is the height of the point. The algorithmdivi<strong>de</strong>s the space around the points P i of theDEM into S sector of azimuth angle 2π Sradians eachone. Each point P i has an associated data structureD Pi which store all points that lie in region s, wheres = 1, ..., S. The profile of a given point is consi<strong>de</strong>redas the sequence of points that have the maximum elevationsin s; together they form a boundary that coversall the points of D Pi . These upper convex hullsFig. 1. Point P i has three visible ring sectors (in light grey) inthe region <strong>de</strong>limited by sector s. These visible ring sectorsare <strong>de</strong>termined by the set of Start-of-Ring-Sector pointsSRS.s.p and the End-of-Ring-Sector points ERS.s.p.Fig. 2. In direction s, P i and P i+1 belong to the set of Endof-visible-Ring-Sectorspoints of P 0 (i.e., ERS.s. P0 ={P i , P i+1 } ). While in the opposite sector, s ′ , with ŝ ′ =−ŝ, P i and P 0 belong to the End-of-visible-Ring-Sectorsof the point labeled as ”?” (i.e., ERS.s’.? = {P i , P 0 }. Thepoint labeled as ”?” belongs to the set of Start-of-visible-Ring-Sectors of P 0 and it is found in the second stage ofthe algorithm.are calculated by projecting all the points stored inD Pi onto the vertical plane that passes from z-axis.The points that have the maximum tangent (calculatedbetween the projection of P i and each point inD Pi ) are maximum elevations. Moreover, a binarytree, HT , of N leaves is used to store all the profilesof all the points of the DEM during the S iterations.The algorithm processes the points in a previously<strong>de</strong>termined or<strong>de</strong>r in such a way that each point findsits profile in HT and simultaneously it is incorporatedas a candidate profile point for the points thatwill be processed in next iterations.A.2 Notion of Visible Ring SectorWe formulate VM computation into <strong>de</strong>terminingwhere the continuous visible regions start and end.Once the space is partitioned into sectors, we proceedto compute the visible areas, of ring sector shapes,in each sector s. A visible ring sector from a givenpoint P is <strong>de</strong>limited by the set of points where thering sector starts, which we call Start of Ring SectorSRS.s.P , and the set of points where the ring sectorends, which we call End of visible Ring SectorERS.s.P . See Figure 1 for illustration.A.3 Opposite Sector Based OptimizationIn each sector s and for each point P of the terrain,the set SRS.s.P and ERS.s.P must be found.Suppose the algorithm has already calculated theSRS.s.P and ERS.s.P of a specific point P in sec-<strong>JP2011</strong>-108


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011tor s. In future iterations, particularly in the oppositesector s ′ such as ŝ ′ = −ŝ (i.e., ŝ ′ = ŝ + π), thealgorithm will analyze again the point P as possibleSRS.s’ or ERS.s’, in sector s ′ , of its own SRS.s.P andERS.s.P points. For simplicity consi<strong>de</strong>r the easy exampledrawn in Figure 2. If the point labeled as ”?”belongs to SRS.s.P 0 , in direction s, thus P 0 may belongto ERS.s’.? in the opposite sector s ′ . Therefore,calculating both SSR and ERS of all the points ofthe DEM is redundant and requires twice as muchcalculation and storage capacity. To eliminate thisredundancy, we first compute and store only the ERSof all the points of the terrain and then in a secondstage use a very fast postprocessing to obtain theSRS points. This approach reduces the storage requirementsand calculation by half.A.4 ERS points ComputationOur algorithm searches for the ERS.s.P i amongthe profile points based on the following assumption.The ERS and SSR points of P belong to the set ofpoints that form P ’s own profile (or hulls) in s. Thiscan be <strong>de</strong>monstrated mathematically as follows:Lemma:∀Q ∈ D P , if Q ∈ ERS.s.P ⇒ Q ∈ some hull.Proof:suppose Q ∈ ERS.s.P and Q /∈ any hull.this means that ∃!Q ′ such as Q ′ elevation islarger than P elevationwhich implies that Q /∈ ERS.s.PTo <strong>de</strong>termine the ERS.s.P points among the profilepoints, the algorithm processes the profile pointsin the increasing distance or<strong>de</strong>r from P . If the tangentbetween the projection of the last profile pointand the current profile point is greater than themaximum angle, the current point is ad<strong>de</strong>d to theERS.s.P set.A.5 ERS Computation Algorithm SummaryIn summary, our visibility algorithm can be <strong>de</strong>scribedas follows:For each sector s in S– We sort all the points of the DEM by a ⊥and b ⊥ in the new system (a ⊥ , b ⊥ , z), wherea ⊥ and b ⊥ are two vectors perpendicular tovectors a and b that <strong>de</strong>limit sector s. Sincethe target DEMs are regular grids, the sortingoperation can be carried out by counting thenumber of points behind the sweep line usingvery simple trigonometric operations, i.e., theposition number is directly computed. In practicethe time spent in this phase is negligible.We reuse the or<strong>de</strong>ring by b ⊥ in sector i to reor<strong>de</strong>rby a ⊥ in sector i + 1. The new indicesj and k are <strong>de</strong>termined for each point.– For each point P j,k in or<strong>de</strong>r of increasing in<strong>de</strong>xj :∗ Add all the points that fall in s to D P∗ Compute the profile points using the Hulltree of P j,k . The structure and processingor<strong>de</strong>r of the tree ensure a highly efficientcomputation since the profile points elevationis always found among the O(logN)leaf-to-root no<strong>de</strong>s in the tree.∗ Add to tree new candidate as possible profilefor next points. The tree is updated byinserting the heights of the new point P j,k .In<strong>de</strong>x k is used to insert the point in thestructure.∗ Find ERS points among profile points andstore them in the ERS structure.– The points are reor<strong>de</strong>red from their indices jto recover the original or<strong>de</strong>ring.A.6 Start-of-Ring-Sector CalculationOnce all the ERS points are calculated for all thepoints of the terrain, the algorithm proceed to computethe SRS points by sector and by point. In thisstage, each point P looks for the points whose it isend of ring sector and stores them into a data structurethat we call reverse list. In principle, all thepoints that belong to this list are candidates for SRSof P . For illustration consi<strong>de</strong>r point P 0 in Figure 2.Among the set of points limited by two consecutiveERS points, P i and P i+1 , the points that have P 0as ERS in the opposite sector and belong to the interval[P i , P i+1 ] are candidates for SSR.s.P 0 . Onlythe point that verifies the following criteria is SRS ofP 0 . It is further than P i and nearer than P i+1 andobviously it is a candidate in the reverse list.This stage is very slight from a computationalpoint of view. For instance, for the terrain shownin Figure 3(a) of size 2000 × 2000 points, the secondstage takes only 33 minutes on a Desktop basedon Intel core2 duo that runs at 3.16 GHz with 3,25GB of main memory. Actually, computing the reverselist takes 3 minutes and calculating SRS takes30 minutes.Due to the discrete nature of the problem, thereverse search method explained above doesn’t ensurethat every ERS matches with its SRS. Alternatively,missed SRSs can be found using a binarysearch among candidates in the current sector, whichis also very fast because, in Stewart’s method, DEMpoints have been already sorted in the required or<strong>de</strong>r.IV. Numerical and Computational ResultsSome numerical results of our approach are shownin Figure 3. In particular, Figure 3(b) shows thevisibility map computed on the terrain of the cityof Malaga, Spain, whose DEM is shown in Figure3. The value at each pixel in Figure 4 shows thenumber of visible Km 2 . Dark red color correspondsto points with very high visibility, about 100 visibleKm 2 . Dark blue color corresponds to points withvery low visibility. From this figure, one can observethat higher points don’t necessarily have higher visibility.Actually, some points at the sea level havenotably more visibility than higher interior points.One of the main advantages of the visibility mapsthat our algorithm is able to produce is allowing a<strong>JP2011</strong>-109


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 3. Elevation map of the city of Malaga, Spain; darkerred and lighter green correspond to points with higher andlower elevations respectively.Fig. 5. The light grey regions indicate the ring sectors visiblefrom a point selected at the sea level in the 2000 × 2000points DEM of the city of Malaga, Spain.Fig. 4. The visibility map of the city of Malaga; darker redand darker blue show higher and lower numbers of visibleKm 2 respectively.global visibility comparison over all the points of theterrain.The precision of the VM calculated by our algorithmonly <strong>de</strong>pends on the resolution of the usedDEM and the consi<strong>de</strong>red number of sectors. It can beincreased or <strong>de</strong>creased <strong>de</strong>pending on the needs of theconsi<strong>de</strong>red application. Notice that the azimuthalsectorization of the viewshed involves a slight linearloss of precision in very distant locations. Thisfact can be appreciated in Figure 5, which showsthe farthest End-of-Ring-Sectors seen at a point selectedfrom the lower right corner (at the sea level) ofthe DEM of the city of Malaga. However, this kindof precision losses is irrelevant in most applicationssince signals intensity is inversely proportional to thesquare of the distance (I = P/4πd 2 , where P is thepower of the signal).The co<strong>de</strong> was implemented in C++ and compiledwith -O3. For performance evaluations, we comparedthe runtime of our algorithm with the runtime of ArcGis[8], one of the fastest and wi<strong>de</strong>ly used softwarefor viewshed calculation. We performed all experimentson a PC based on Intel core2 duo running at3.16 GHz with 3.25 GB of main memory. Comput-ing the ERS points of all the points of a 2000 × 2000points DEM (of size 8 MB), consi<strong>de</strong>ring 360 sectors,takes about 6.5 hours. Building the reverse list takes3 minutes and finding the SRS points takes about30 minutes. Storing the ERS points by sector in filestakes 10 minutes resulting in a set of 360 files of a totalsize of about 42 GB. This means that the storagerequirements per point per sector is about 30 bytes.In VM of the city of Mlaga shown is Figure 3(b), theaverage number of ring sectors per point per sectoris equal to 3.1 ring sectors.Taking into account all these measurements, computingthe VM at a single point on a terrain of size2000 × 2000 points using the algorithm we proposedin this work takes only 0.0063 seconds, while ArcGistakes about 10 seconds to compute VM in the sameconditions.V. ConclusionsWe presented a new and fast algorithm that computesthe visibility map on the entire terrain. Theproposed algorithm can be very useful for acceleratinga wi<strong>de</strong> range of visibility based applications.For example it can be used to accelerate siting multipleobservers so as to jointly cover as much terrainas possible <strong>de</strong>scribed in [15] and for extending thevisibility in<strong>de</strong>x calculation, cited in [15], [2], to verylarge radius. The presented algorithm has a timecomplexity O(S.N.log(N)) substantially better thanprevious single-point-visibility algorithms and scalesO(N.log(N)) versus O(N 2 ) for previous algorithms.Moreover, experimental results <strong>de</strong>monstrate that ourmethod is faster by many or<strong>de</strong>r of magnitu<strong>de</strong> thanmost used visibility tools inclu<strong>de</strong>d in ArcGis.AcknowledgementsThis work was supported by the Spanish Ministryof Education and Science throughout Juan <strong>de</strong>la Cierva Grant and the project TIN2006-01078.References[1] CGIAR-Consortium for Spatial Information ShuttleRadar Topography Mission (SRTM) Database [online].<strong>JP2011</strong>-110


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Available from: http://srtm.csi.cgiar.org/. 2007.[2] Franklin R. and Ray C. K. Advances in GIS Research:Sixth International symposium on spatial Data handlinghigher isn’t necessarily better: Visibility Algorithms andExperiments. 1994.[3] Floriani, L.D., Magillo, P. Algorithms for visibilitycomputation on digital terrain mo<strong>de</strong>ls. Proceedings ofthe ACM/SIGAPP Symposium on Applied Computing.ACM, New York. 1993.[4] Perez O. M., Telfer T. C. and Ross L. G. Use of GISbasedmo<strong>de</strong>ls for integrating and <strong>de</strong>veloping marine fishcages within the tourism industry in Tenerife (CanaryIslands) Coastal Management 31(4), 355-366. 2003.[5] Maichak E. J. and Schuler K. L. Applicability of viewshedanalysis to wildlife population estimation AmericanMidland Naturalist 152, 277-285. 2004.[6] Kidner D. B., Rallings P. J., Ware J. A. Parallel processingfor terrain analysis in GIS: Visibility as a case study,Geoinformatica, 1(2), 183–207. 1997.[7] Ogburn D. E. Assessing the level of visibility of culturalobjects in past landscapes Journal of Archaeological Science33, 405-413. 2006.[8] ESRI(Environmental Systems Research Institute) AR-CGIS Software. Version 9.3. 2010.[9] GRASS Development Team Geographic Resources AnalysisSupport System (GRASS) Software, available inhttp://grass.itc.it. 2007.[10] Nagy G. Terrain visibility Computers and Graphycs,8(1), 763–773. 1994.[11] De Floriani L. and Magillo P. Algorithms for visibilitycomputation on terrains: A survey, Environment andPlanning B: Planning and Design 30, 709-728. 2003.[12] Atallah M. Dynamic computational geometry Proceedingof the 24th IEEE Symposium on the Foundations ofComputer science, 92-99. 1983.[13] Hershberger J. Finding the upper envelope of n line segmentsin O(n log n) time, Information Processing Letters,33(4), 169174. 1989.[14] Stewart A.J. Fast Horizon Computation at All Points of aTerrain With Visibility and Shading Applications IEEETransactions on Visualization and Computer Graphics,4(1), 82–93. 1998.[15] Franklin R. Sitting observers on terrain. Symposium onSpatial Data Han<strong>de</strong>ling. 2002.[16] Ben-Shimo Y., Ben-Moshe B., Ben-Yehezkel Y., Dvir A.and Segal M. Automated antenna positioning algorithmsfor wireless fixed-access networks. Journal of Heuristics,13(3), 243–263. 2007.[17] De Floriani L., Falcidieno B. , Nagy G. and PienoviC. Polyhedral Terrain Description Using Visibility Criterianstitute for Applied Mathematics, National ResemvhCouncil, Technical Report (17). 1989.[18] De Floriani L., and Magillo P. Visibility Algorithms onTriangulated Terrain Mo<strong>de</strong>ls International Journal of GeographicInformation Systems, 8(1), 13–41. 1994.[19] Katz M. J. , Overmars M. H., Shairr M. Efficient hid<strong>de</strong>nsurface removal for objects with small union size Proceedingsof the seventh annual symposium on Computationalgeometry, 31–40, New Hampshire, United States 1991.[20] Cabral B., Max N., and Springmeyer R. Bidirectionalreflection functions from surface bump maps ACM SIG-GRAPH Computer Graphics 21, 273–281. 1987.[21] Stewart A.J. Fast Horizon Computation at All Points of aTerrain With Visibility and Shading Applications IEEETransactions on Visualization and Computer Graphics,4(1), 82–93. 1998.[22] S. Tabik, L. F. Romero and E. L. Zapata High PerformanceThree-horizon Composition Algorithm for largescale terrains International Journal of Geographical InformationScience. 25(4), 541–555 2011.<strong>JP2011</strong>-111


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-112


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Un método <strong>de</strong> acceso aproximado para muyalta dimensionalidad y su paralelizaciónFernando Artigas Fuentes 1 José Manuel Badía Contelles 2 y Reynaldo Gil García 3Resumen— En este trabajo, proponemos un nuevométodo <strong>de</strong> acceso aproximado para espacios <strong>de</strong> muyalta dimensionalidad y especialmente aquellos conmuy alta dispersión <strong>de</strong> los datos. Está basado enel uso <strong>de</strong> múltiples grafos como estructura <strong>de</strong> in<strong>de</strong>xadoy un algoritmo <strong>de</strong> búsqueda para obtener <strong>de</strong> unrepositorio <strong>de</strong> objetos, representados como vectores,aquellos más relacionados a otros objetos usados comoconsultas. Aunque este método es aproximado, muestraun nivel bajo <strong>de</strong> error. Tiene a<strong>de</strong>más un costetemporal muy bajo durante las consultas y está especialmentediseñado para ser ejecutado en paralelo <strong>de</strong>forma simple y eficiente. Mostramos versiones paralelastanto para la generación <strong>de</strong> la estructura <strong>de</strong> in<strong>de</strong>xadocomo para el algoritmo <strong>de</strong> búsqueda. Se ha paralelizadousando la interfaz OpenMP. Hemos evaluadonuestra propuesta sobre espacios <strong>de</strong> representación <strong>de</strong>miles dimensiones obteniendo prestaciones paralelascercanas al óptimo.Palabras clave— métodos <strong>de</strong> acceso, computaciónparalela, búsqueda aproximada, grafos.I. IntroducciónPARA recuperar información, es muy común quese utilice un método <strong>de</strong> acceso. Este tiene elobjetivo <strong>de</strong> organizar los objetos <strong>de</strong> un repositorio <strong>de</strong>forma tal que durante las consultas solo sea necesarioacce<strong>de</strong>r a una porción <strong>de</strong>l mismo. Cuanto menor seala porción visitada para cada consulta, más eficienteresulta el método <strong>de</strong> acceso.<strong>La</strong> mayoría <strong>de</strong> los datos que se manejan en la actualidadson <strong>de</strong>scritos mediante un gran número <strong>de</strong> características,que para los métodos <strong>de</strong> acceso se conviertenen dimensiones <strong>de</strong>l espacio <strong>de</strong> representación<strong>de</strong> los datos.Existe en la literatura un conjunto amplio <strong>de</strong>métodos <strong>de</strong> acceso capaces <strong>de</strong> in<strong>de</strong>xar espacios multidimensionales,pero la mayoría sufre un problemaconocido como ”Maldición <strong>de</strong> la dimensionalidad”[1]. Este provoca que a medida que aumenta ladimensionalidad <strong>de</strong>l espacio <strong>de</strong> representación <strong>de</strong>los datos los resultados <strong>de</strong> la búsqueda se van<strong>de</strong>gradando hasta convertirse en iguales o peores quepara el caso <strong>de</strong> búsqueda exhaustiva.Debido a que todos los métodos exactos sufren elproblema antes <strong>de</strong>scrito, para el caso <strong>de</strong> espacios <strong>de</strong>muy alta dimensionalidad, se han presentado en laliteratura nuevos métodos que obtienen solucionesaproximadas. Estos métodos utilizan varias técnicasque consisten en relajar las condiciones tanto <strong>de</strong> laconstrucción <strong>de</strong> las estructuras <strong>de</strong> in<strong>de</strong>xado como <strong>de</strong>1 CERPAMID, Univ. Oriente, Cuba, e-mail:artigas@cerpamid.co.cu.2 Dpto. <strong>de</strong> Ingeniería y Ciencias <strong>de</strong> los Computadores, Univ.Jaume I, e-mail: badia@icc.uji.es.3 CERPAMID, Univ. Oriente, Cuba, e-mail:gil@cerpamid.co.cu.las estrategias <strong>de</strong> búsqueda. Algunas <strong>de</strong> las técnicasusadas son la reducción <strong>de</strong> la dimensionalidad <strong>de</strong>lespacio <strong>de</strong> búsqueda, seleccionando un subconjunto<strong>de</strong> características más representativas <strong>de</strong> los objetos,hasta valores más manejables por los métodos ya existentes[2], y la sustitución <strong>de</strong> los objetos originalespor otros menos complejos que mantengan aproximadamentelas mismas relaciones <strong>de</strong> vecindad quelos originales [6].Otras propuestas son eficientes manejando un grannúmero <strong>de</strong> dimensiones, como es el caso <strong>de</strong>l VA-filey los <strong>de</strong>rivados <strong>de</strong> este [3], [4], [5]. Sin embargo,estos métodos se vuelven ineficientes cuando a la altadimensionalidad <strong>de</strong> los datos tratados se suma unaalta dispersión <strong>de</strong> los mismos.En este trabajo proponemos un nuevo método<strong>de</strong> acceso que es poco afectado por ambos problemas:la alta dimensionalidad y la alta dispersión<strong>de</strong> los datos. El mismo está basado en el uso <strong>de</strong>múltiples grafos como estructura <strong>de</strong> in<strong>de</strong>xado y unalgoritmo <strong>de</strong> búsqueda que, aunque aproximado, permiteobtener un elevado porcentaje <strong>de</strong> soluciones exactascon un coste temporal muy bajo.A<strong>de</strong>más, la estructura <strong>de</strong> datos se ha diseñado conel fin <strong>de</strong> po<strong>de</strong>r construirla y utilizarla en paralelo <strong>de</strong>forma sencilla y eficiente. Presentamos a<strong>de</strong>más unaversión paralela <strong>de</strong> este método, mediante el uso <strong>de</strong>memoria compartida y la interfaz OpenMP.El resto <strong>de</strong>l trabajo está organizado como sigue: enla sección 2 se trata con más <strong>de</strong>talles las propieda<strong>de</strong>s<strong>de</strong> los métodos <strong>de</strong> acceso, en la sección 3 explicamosnuestra propuesta y su paralelización, en la sección 4<strong>de</strong>scribimos los experimentos realizados y los resultadosobtenidos. Finalmente en la sección 5 mostramoslas conclusiones <strong>de</strong> este trabajo.II. Métodos <strong>de</strong> accesoUn método <strong>de</strong> acceso está formado por una estructura<strong>de</strong> in<strong>de</strong>xado, que organiza <strong>de</strong> alguna maneralos objetos <strong>de</strong> un repositorio, y una estrategia <strong>de</strong>búsqueda que <strong>de</strong>be recorrer los objetos in<strong>de</strong>xados <strong>de</strong>la manera más eficiente.Un método <strong>de</strong> acceso necesita a<strong>de</strong>más <strong>de</strong> una medida<strong>de</strong> comparación entre los objetos que exprese laproximidad entre estos. Esta pue<strong>de</strong> ser una semejanza,que da una medida <strong>de</strong> en cuanto se parecendos objetos entre sí; o una diferencia, que <strong>de</strong>terminaen cuanto se distinguen. Por lo general como medida<strong>de</strong> comparación se usa una función <strong>de</strong> distancia, quea<strong>de</strong>más <strong>de</strong> expresar lo cercano que están los objetosentre sí, <strong>de</strong>fine un espacio métrico.Una función distancia pue<strong>de</strong> expresarse como:dist : Ω d xΩ d → R +<strong>JP2011</strong>-113


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011don<strong>de</strong> Ω d es el espacio <strong>de</strong> representación <strong>de</strong> los datosy d la dimensionalidad <strong>de</strong>l mismo.Una distancia <strong>de</strong>be cumplir los siguientes requisitos:Reflexividad: ∀x ∈ Ω d , dist(x, x) = 0Simetría: ∀x, y ∈ Ω d , dist(x, y) = dist(y, x)Desigualdad triangular: ∀x, y, z ∈ Ω d , dist(x, y) ≤dist(x, z) + dist(z, y)Si el espacio <strong>de</strong> representación usado no es un espaciométrico, entonces es suficiente con que la medida<strong>de</strong> comparación cumpla con los dos primeros.Debido a que las medidas pue<strong>de</strong>n ser diversas,cuando comparemos dos objetos, nos referiremossimplemente a proximidad, y la <strong>de</strong>notaremos por Ψ,por lo que se cumple que:∀x, y, z ∈ Ω d , Ψ(x, y) < Ψ(x, z) → sem(x, y) >sem(x, z)∀x, y, z ∈ Ω d , Ψ(x, y) < Ψ(x, z) → dif(x, y)


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Algoritmo 1 GenerarGrafo(O p , θ)Entrada: O p : subconjunto <strong>de</strong> vectores a in<strong>de</strong>xar, θ:número mínimo <strong>de</strong> vecinos directos <strong>de</strong> cada vérticeen el grafo final.Salida: G p : grafo que in<strong>de</strong>xa a los vectores <strong>de</strong> entrada.Etapa1. Cálculo <strong>de</strong>l centroi<strong>de</strong> <strong>de</strong>l subconjunto.Se obtiene un nuevo vector como resultado <strong>de</strong>sumar todos los vectores <strong>de</strong>l conjunto dimensiónpor dimensión. El vector resultante tiene valormayor que cero en todas las dimensiones <strong>de</strong>l espacio<strong>de</strong> representación <strong>de</strong> este subconjunto.Etapa 2. Descomposición <strong>de</strong>l subconjuntoen una lista or<strong>de</strong>nada <strong>de</strong> subconjuntos porsu proximidad con el centroi<strong>de</strong>.A partir <strong>de</strong> los elementos <strong>de</strong>l subconjunto se obtieneuna lista or<strong>de</strong>nada en or<strong>de</strong>n <strong>de</strong>creciente <strong>de</strong>proximidad con el centroi<strong>de</strong> <strong>de</strong>l subconjunto.Esta lista es dividida en un número pre<strong>de</strong>finido <strong>de</strong>sublistas, que quedarán or<strong>de</strong>nadas por la proximidad<strong>de</strong> sus elementos con el centroi<strong>de</strong>.Etapa 3. Construcción <strong>de</strong>l grafo conexo.De los elementos <strong>de</strong> la primera sublista, se calculael par <strong>de</strong> elementos más próximos entre sí. Estoselementos forman la primera arista <strong>de</strong>l grafo.Del resto <strong>de</strong> los elementos <strong>de</strong> la sublista se calculael elemento que al ser conectado a un par <strong>de</strong>vértices <strong>de</strong> cualquier arista <strong>de</strong>l grafo provoca elmenor crecimiento en área <strong>de</strong> esta.Este proceso se repite hasta que todos los elementos<strong>de</strong> la sublista son conectados al grafo.Los dos pasos anteriores son repetidos para el resto<strong>de</strong> las sublistas, hasta que todos los elementos <strong>de</strong>la lista original estén conectados en el grafo.Etapa 4. Completar el grafo hasta que cadavértice tenga θ vecinos.En esta etapa se verifica que cada vértice formeparte como mínimo <strong>de</strong> una cantidad pre<strong>de</strong>finida <strong>de</strong>aristas. En caso que se <strong>de</strong>tecte un vértice que nocumpla esta condición el mismo es conectado connuevos vecinos más próximos hasta que se cumplala condición.Etapa 5. Calcular los vértices <strong>de</strong> entrada algrafo.Se <strong>de</strong>terminan aquellos vértices que cumplen quetodos los vértices con los que conforman aristasestán más próximos que estos al centroi<strong>de</strong> <strong>de</strong>l subconjunto,y aquellos vértices que cumplen que todoslos vértices con los que conforman aristas estánmenos próximos que estos al centroi<strong>de</strong> <strong>de</strong>l subconjunto.Finalmente se genera una estructura que contieneal conjunto <strong>de</strong> vértices (O p ), al conjunto <strong>de</strong> aristas(A p ) y al conjunto <strong>de</strong> los vértices i<strong>de</strong>ntificadoscomo <strong>de</strong> entrada al grafo (E p ).return G p = (O p , A p , E p ).Algoritmo 2 BuscarKPróximos(R, G, q, k)Entrada: R, el repositorio <strong>de</strong> objetos iniciales; G =G 1 , G 2 , ..., G N , la lista <strong>de</strong> los grafos obtenidos medianteel Algoritmo 1; q, el objeto <strong>de</strong> consulta; yk, el número <strong>de</strong> soluciones requeridas.Salida: Los k objetos <strong>de</strong> R más próximos a q segúnΨ.Sea −→ v = ζ(q) la representación vectorial <strong>de</strong> q.Sean G i = G[i], O i = G i [1],A i = G i [2] y E i =G i [3].Sean S ′= ∅ y N = |G|.for i = 1 → N doSea S i = {( −→ o j,p , ψ j,v )/ −→ o j,p ∈ O i , ψ j,v =Ψ( −→ o j,p , −→ v )}, obtenido mediante kNN(G[i], −→ v ,k)(Algoritmo 3).= S ′ ∪ S iend forSea S ′′ la lista <strong>de</strong> los elementos <strong>de</strong> S ′ or<strong>de</strong>nada<strong>de</strong> mayor a menor según el valor <strong>de</strong> ψ j,v <strong>de</strong> cadaelemento.Sea S = {S ′′ [1], S ′′ [2], ..., S ′′ [k]} las k solucionesmás próximas al objeto <strong>de</strong> consulta.return {r j /r j ∈ R, r j = ˜ζ(o i,p ), (o i,p , ψ i,v ) ∈ S}.S ′altamente dispersos, con un número suficientementegran<strong>de</strong> <strong>de</strong> estos la carga <strong>de</strong> trabajo <strong>de</strong> los procesadorestien<strong>de</strong> a equilibrarse ”<strong>de</strong> manera natural”.D. Paralelización <strong>de</strong> las consultasEl proceso <strong>de</strong> buscar las soluciones parciales queaporta cada grafo al resultado <strong>de</strong> una consulta escompletamente in<strong>de</strong>pendiente para cada uno <strong>de</strong> ellos.Posteriormente es necesario combinar estas solucionesparciales para obtener la solución final, procesoque sigue siendo <strong>de</strong> naturaleza secuencial y essimilar al <strong>de</strong>scrito para la versión secuencial.Los cambios con respecto al Algoritmo 2 sonmostrados en el Algoritmo 4. Notese que el buclefor se ejecuta en paralelo por todos los procesadoresinvolucrados. Se ha incluido a<strong>de</strong>más una seccióncrítica para evitar que más <strong>de</strong> un proceso actualice elconjunto S ′en el mismo instante, lo que provocaríainconsistencias en el mismo.IV. Análisis experimentalA. Entorno experimentalPara realizar nuestros experimentos usamos unrepositorio <strong>de</strong> la agencia Reuters con los textos <strong>de</strong>un gran número <strong>de</strong> noticias cortas en prensa: lacolección Reuters corpus versión 1 (RCV1-v2) [7].El vector <strong>de</strong> características −→ o i <strong>de</strong> cada documentor i fue producido mediante la concatenación <strong>de</strong> lostextos en los elementos y <strong>de</strong> losXML originales. El texto fue reducido a caracteresen minúsculas, <strong>de</strong>spués <strong>de</strong> lo cual se realizó sobre losmismos un proceso <strong>de</strong> tokenización, eliminación <strong>de</strong>puntuaciones y estemizado. Se eliminaron las palabras<strong>de</strong> parada, se sopesaron los términos y finalmentelos pesos fueron normalizados, tras realizaruna selección <strong>de</strong> características.<strong>JP2011</strong>-115


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Algoritmo 3 Función kNNEntrada: G i , estructura <strong>de</strong> in<strong>de</strong>xado; −→ v , el vector<strong>de</strong> consulta; k, la cantidad <strong>de</strong> soluciones requerida.Salida: KNN, los k objetos más próximos a −→ v .{Determinando los vértices <strong>de</strong> entrada}.Sean G i = G[i], O i = G i [1],A i = G i [2] y E i =G i [3].Sea S ′= −−→ o k1 ,i, −−→ o k2 ,i, ..., −−−→ o k|S| ,i la lista <strong>de</strong> elementos<strong>de</strong> E i , or<strong>de</strong>nada en or<strong>de</strong>n <strong>de</strong>creciente <strong>de</strong> su proximidada −→ v .Sea α ∈ {1, ..., |S|} una constante pre<strong>de</strong>finidaque <strong>de</strong>termina <strong>de</strong>l conjunto S el número real <strong>de</strong>vértices que serán usados como puntos <strong>de</strong> entradaa la estructura <strong>de</strong> in<strong>de</strong>xado.{Búsqueda <strong>de</strong>l vecino más próximo a −→ v }.Sea NN = [] una lista vacía.for e = 1 → α do−→ s0 = S ′ [e].repeatSea L la lista or<strong>de</strong>nada <strong>de</strong> los elementos <strong>de</strong>{ −→ o j,i / −→ o j,i ∈ G i , ( −→ s 0 , −→ s j,i ) ∈ A i } en or<strong>de</strong>n <strong>de</strong>creciente<strong>de</strong> su proximidad a −→ v .if Ψ(L[1], −→ v ) > Ψ( −→ s 0 , −→ v ) then−→ s0 = L[1].end ifuntil Ψ(L[1], −→ v ) ≤ Ψ( −→ s 0 , −→ v )NN[e] = −→ s 0 .end forOr<strong>de</strong>nar los elementos <strong>de</strong> NN en or<strong>de</strong>n <strong>de</strong>creciente<strong>de</strong> su proximidad a −→ v .kNN = NN[1].{Búsqueda <strong>de</strong> los siguientes (k − 1) vecinosmás próximos a −→ v }if k > 1 thenkNN = kNN ∪ { −→ o j,i / −→ o j,i ∈ G i , ( −→ s 0 , −→ o j,i ) ∈ A i }.repeatSea L la lista or<strong>de</strong>nada <strong>de</strong> los elementos <strong>de</strong>kNN en or<strong>de</strong>n <strong>de</strong>creciente <strong>de</strong> su proximidada −→ v .Sea L ′ = L[1], L[2], ..., L[t] tal que t =min(k − 1, |L|).kNN = { −→ o j,i / −→ o j,i ∈ L ′ }.Sea ρ = Ψ(L[t], −→ v ) la mínima proximidad entrelos elementos <strong>de</strong> L ′ y −→ v .for p = 1 → t doSea H p = { −→ o j,i / −→ o j,iA i , Ψ( −→ o j,i , −→ v ) ≥ ρ)}Sea kNN ′ = kNN ∪ H p .end forkNN = kNN ′ .∣until ( ∣kNN ′∣ ∣ ′ ≥ k) ∧ (kNN = kNN)end ifreturn kNN.∈ G i , (L ′ [p], −→ o j,i ) ∈Algoritmo 4 BuscarKPróximosPar(R, G, q, k){...}for i = 1 → N do {en paralelo}Sea S i = {( −→ o j,p , ψ j,v )/ −→ o j,p ∈ O i , ψ j,v =Ψ( −→ o j,p , −→ v )}, obtenido mediante kNN(G[i], −→ v ,k)(Algoritmo 3).Sección crítica: S ′= S ′ ∪ S iend for{...}Se usó <strong>de</strong> la partición LYRL2004 su conjunto <strong>de</strong>entrenamiento que contiene 23.149 vectores. El espacio<strong>de</strong> representación <strong>de</strong> este conjunto tiene 47.152dimensiones. <strong>La</strong> matriz <strong>de</strong> representación <strong>de</strong> este espaciocontiene una gran número <strong>de</strong> ceros, <strong>de</strong>bidos ala alta dispersión <strong>de</strong> los vectores.Todos los experimentos fueron realizados sobre unmultiprocesador SGI Altix 350 con memoria compartida.Esta máquina tiene 8 nodos, cada uno <strong>de</strong>los cuales tiene 2 procesadores Intel Itanium2, a 1.5GHz. Cada nodo cuenta con 4Gb <strong>de</strong> memoria localconectadas mediante una red SGI NUMAlink, llegandoa 32 GBytes <strong>de</strong> memoria compartida.Todos los algoritmos fueron implementadosusando lenguaje C, y fueron compilados con ICC9.0 sobre el sistema operativo Linux. <strong>La</strong>s versionesparalelas fueron implementas usando la interfazOpenMP.B. Resultados experimentalesPara estudiar el comportamiento <strong>de</strong> nuestra propuestase generó, para los esquemas secuencial y paralelo,un gran número <strong>de</strong> estructuras <strong>de</strong> in<strong>de</strong>xadocon diferentes números <strong>de</strong> grafos. Para seleccionar elvalor <strong>de</strong> θ se generaron grafos usando valores entre 10y 90. Finalmente seleccionamos el valor <strong>de</strong> 50 por serel que garantizó un mejor equilibrio entre la calidad<strong>de</strong> los resultados y la selectividad <strong>de</strong>l método.Los resultados fueron obtenidos mediante latécnica <strong>de</strong> validación cruzada 10-fold-cross validation,por lo que se procesaron 10 repositorios distintos.Los valores experimentales mostrados son lospromedios <strong>de</strong> los obtenidos para cada repositorio.Por cada experimento medimos el coste temporal<strong>de</strong> la generación <strong>de</strong> la estructura <strong>de</strong> in<strong>de</strong>xado para20.000 objetos, el coste temporal <strong>de</strong> 2.300 consultas,el consumo <strong>de</strong> memoria principal, la selectividad y ladimensionalidad <strong>de</strong> cada espacio <strong>de</strong> representación.<strong>La</strong> asignación <strong>de</strong> objetos a los subconjuntos <strong>de</strong>datos fue realizada <strong>de</strong> manera aleatoria.C. Precisión <strong>de</strong> los resultadosEl primer primer aspecto estudiado fue la calidad<strong>de</strong> los resultados obtenidos durante las consultas.Los comparamos con los obtenidos con el métodoexhaustivo, que garantiza las soluciones exactas.<strong>La</strong> Figura 1 muestra que la exactitud <strong>de</strong> los resultadosse incrementa con el número <strong>de</strong> grafos usados.El incremento fue <strong>de</strong>s<strong>de</strong> el 92% <strong>de</strong> soluciones exactaspara un grafo hasta casi el 97% para 16.<strong>JP2011</strong>-116


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 1. Precisión <strong>de</strong> los resultados comparados contra losobtenidos mediante el método exhaustivo.D. Selectividadtra, a medida que se usan más grafos para in<strong>de</strong>xarel repositorio, el tamaño máximo <strong>de</strong> los espacios <strong>de</strong>representación disminuye. Esto se <strong>de</strong>be a que cuantosmás grafos son usados, los subconjuntos <strong>de</strong> datoscontienen menos elementos, y <strong>de</strong>bido a la dispersión<strong>de</strong> los datos, van a contener en conjunto menos dimensiones.Esto es así porque aumenta la probabilidad<strong>de</strong> que en cada submatriz <strong>de</strong> representación, quecontiene <strong>de</strong> la matriz original solamente aquellas filas<strong>de</strong> los vectores que le pertenecen, exista una grancantidad <strong>de</strong> columnas con todos los valores a 0, encuyo caso esa dimensión <strong>de</strong>l espacio original no setiene en cuenta.<strong>La</strong> Figura 3 muestra que la máxima dimensionalidad<strong>de</strong>l espacio <strong>de</strong> representación disminuye<strong>de</strong>s<strong>de</strong> aproximadamente 50.000 dimensiones hastacasi 14.000, cuando se varía el número <strong>de</strong> grafos<strong>de</strong>s<strong>de</strong> 1 hasta 16. Es necesario notar que el problemageneral mantiene siempre la misma dimensionalidad,pero las dimensiones son repartidas <strong>de</strong> maneraaleatoria entre los grafos. Una misma dimensiónpue<strong>de</strong> aparecer en más <strong>de</strong> un grafo.F. Coste temporal <strong>de</strong> la generación <strong>de</strong> los grafosFig. 2. Número <strong>de</strong> objetos evaluados como promedio durantelas consultas, variando el tamaño <strong>de</strong>l repositorio.Como se aprecia en la Figura 2, el número promedio<strong>de</strong> objetos comparados durante las consultasse va estabilizando a medida que se incrementa eltamaño <strong>de</strong>l repositorio, por lo que la selectividad <strong>de</strong>lmétodo crece en igual medida.E. Dimensionalidad <strong>de</strong>l espacio <strong>de</strong> representaciónFig. 4. Coste temporal para generar los grafos en la variantesecuencial.<strong>La</strong> Figura 4 muestra el coste temporal cuando losgrafos son generados <strong>de</strong> manera secuencial, variandoel número <strong>de</strong> grafos <strong>de</strong>s<strong>de</strong> 1 hasta 16. Para la versiónparalela usamos, <strong>de</strong> modo natural, la misma cantidad<strong>de</strong> procesadores que <strong>de</strong> grafos generados.Fig. 3. Dimensionalidad máxima obtenida para los espacios<strong>de</strong> representación, variando el número <strong>de</strong> grafos usados.Para analizar la dimensionalidad <strong>de</strong>l espacio <strong>de</strong>representación <strong>de</strong> cada problema usamos el tamaño<strong>de</strong> los centroi<strong>de</strong>s <strong>de</strong> cada grafo, y tomamos en cadacaso el mayor valor. Por ejemplo, cuando usamosun solo grafo tomamos el tamaño <strong>de</strong> su centroi<strong>de</strong>,pero cuando generamos más <strong>de</strong> un grafo medimos eltamaño <strong>de</strong>l centroi<strong>de</strong> <strong>de</strong> cada grafo y mostramos elmayor valor.<strong>La</strong> ten<strong>de</strong>ncia seguida por la dimensionalidad <strong>de</strong>lespacio es mostrada en la Figura 3. Como se mues-Fig. 5.Aceleración optenida con la versión paralela.<strong>La</strong> Figura 5 muestra la aceleración optenida conla versión paralela <strong>de</strong> generación <strong>de</strong> los grafos. Estamuestra a<strong>de</strong>más que se han obtenido superaceleracionesen casi todos los casos. Esto se <strong>de</strong>be al mejor<strong>JP2011</strong>-117


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011uso <strong>de</strong> la estructura <strong>de</strong> la memoria cuando se usanvarios procesadores que cuando se usa uno solo.G. Consumo <strong>de</strong> memoria por los grafosFig. 6. Consumo <strong>de</strong> memoria principal, variando el número<strong>de</strong> grafos.<strong>La</strong> Figura 6 muestra la cantidad <strong>de</strong> memoria necesariapara almacenar los grafos. Los valores son losmismos tanto para la versión secuencial como parala paralela.Los resultados <strong>de</strong>muestran que el consumo <strong>de</strong>memoria se incrementa poco a medida que son usadosmás grafos para in<strong>de</strong>xar el repositorio. Esteincremento lento se <strong>de</strong>be a que cuantos más grafosson usados cada uno <strong>de</strong> estos contiene menos objetos,pero cada grafo aporta un consumo adicional <strong>de</strong>bidoa que al mantener la cantidad <strong>de</strong> vecinos <strong>de</strong> cadaobjeto igual a θ en cada grafo, el número global <strong>de</strong>enlaces se incrementa. A<strong>de</strong>más, para cada grafo sealmacena un conjunto <strong>de</strong> objetos <strong>de</strong> entrada.H. Coste temporal <strong>de</strong> las búsquedasFig. 7. Coste temporal para generar los grafos en la variantesecuencial.<strong>La</strong> Figura 7 muestra el promedio <strong>de</strong>l coste temporalnecesario para evaluar una consulta, variandoel número <strong>de</strong> grafos, tanto para la versión secuencialcomo para la paralela.Se pue<strong>de</strong> observar que este coste se incrementaa medida que crece el número <strong>de</strong> grafos. Estoes <strong>de</strong>bido a que se necesita, entre otros aspectos,evaluar un número mayor <strong>de</strong> vértices <strong>de</strong> entrada.También se observa que este incremento disminuyedrásticamente en la versión paralela, <strong>de</strong>bido a que sinimportar el número <strong>de</strong> grafos usados, las consultas acada grafo se solapan en el tiempo. En este caso,el incremento <strong>de</strong>l coste temporal se <strong>de</strong>be fundamentalmentea la pequeña sección secuencial remanente,en la que se obtiene el resultado final a partir <strong>de</strong> losparciales obtenidos para cada grafo.V. Conclusiones y trabajo futuroHemos presentado un método <strong>de</strong> acceso para espacios<strong>de</strong> muy alta dimensionalidad basado en el uso<strong>de</strong> multiples grafos como estructura <strong>de</strong> in<strong>de</strong>xado. <strong>La</strong>estrategia <strong>de</strong> búsqueda que utiliza, aunque da lugara soluciones aproximadas, lo hace con un nivel <strong>de</strong> errorbajo y con una alta selectividad. Esto provocabajos costes temporales durante las consultas.Como hemos observado a medida que se usan másgrafos en la estructura <strong>de</strong> in<strong>de</strong>xado la precisión <strong>de</strong>lmétodo se incrementa, aunque el coste temporal <strong>de</strong>las consultas se incrementa un poco.<strong>La</strong> estructura <strong>de</strong> in<strong>de</strong>xado se ha elegido a<strong>de</strong>más,porque permite su construcción y utilización en paralelo<strong>de</strong> forma sencilla y eficiente. Los resultados experimentales<strong>de</strong>muestran que se obtienen muy buenasprestaciones con la versión paralela <strong>de</strong> ambosprocesos.Como trabajo futuro explotaremos las características<strong>de</strong> arquitecturas híbridas, con la combinación<strong>de</strong>l uso <strong>de</strong> memoria compartida y distribuida.Agra<strong>de</strong>cimientosEl presente trabajo ha sido financiado por el DepartamentoIngeniería y Ciencia <strong>de</strong> los Computadores<strong>de</strong> la <strong>Universidad</strong> Jaume I, Castellón.Referencias[1] H. Samet, Foundations of Multidimensional and MetricData Structures. Morgan Kaufman, ISBN 0123694469,2006.[2] Cortizo, J.C., Girál<strong>de</strong>z, J.I., Multi criteria wrapper improvementsto naive bayes learning. LCNS, Vol. 4224,2006.[3] Berchtold, S. et al., In<strong>de</strong>pen<strong>de</strong>d quantization: an in<strong>de</strong>xcompression technique for high-dimensional data spaces.ICDE’00, pp. 577–588, 2000.[4] Zhenjie Zhang and Beng Chin and Ooi Srinivasan andParthasarathy Anthony and K. H. Tung, Similarity searchon bregman divergence: Towards non-metric in<strong>de</strong>xing, InVLDB, 2009.[5] Ro J. S. Dutra and William A. Pearlman and Eduardo A.B. Da Silva and Senior Member, Successive ApproximationWavelet Coding of 1 AVIRIS Hyperspectral Images, 2010.[6] Edgar Chavez, Karina Figueroa y Gonzalo Navarro, EffectiveProximity Retrieval by Or<strong>de</strong>ring Permutations. IEEETransactions on Pattern Analysis and Machine Intelligence(TPAMI). Vol. 30 No. 9. pp 1647-1658, 2007.[7] Lewis, D. D. et al., RCV1: A new benchmark collection fortext categorization research, Journal of machine learningresearch, num. 5, pp. 361-397, 2004.<strong>JP2011</strong>-118


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Perceptually enhanced INTRA vi<strong>de</strong>o enco<strong>de</strong>rfor high <strong>de</strong>finition/quality servicesM. Martínez-Rach, O. López, P. Piñol, M. Perez Malumbres 1 andJ. Oliver 2Resumen— Although inter vi<strong>de</strong>o coding gets thehighest R/D for general vi<strong>de</strong>o coding, intra enco<strong>de</strong>rsare of particular interest for some applications. Wepropose a simple perceptually enhanced intra-mo<strong>de</strong>vi<strong>de</strong>o enco<strong>de</strong>r (PM-LTW) based on the ContrastSensitivity Function (CSF) that gets good performanceby allowing a gracefully quality <strong>de</strong>gradationas compression rate increases. We evaluated theperformance in terms of perceptual quality, memoryconsumption and complexity with H.264/AVC intra,Motion-JPEG2000 and Motion-SPIHT. We employedthe Visual Information Fi<strong>de</strong>lity (VIF) image QualityAssessment Metric (QAM) as vi<strong>de</strong>o quality metric.The results show that the proposed enco<strong>de</strong>r is competitivewith respect to H.264/AVC at low to mediumcompression rates, and as vi<strong>de</strong>o resolution increases,it outperforms H.264/AVC. In addition it requiresmuch less memory and exhibits fast encoding rates.Palabras clave— High Definition Vi<strong>de</strong>o Coding, PerceptualCoding, Contrast Sensitivity FunctionI. IntroductionALTHOUG the use of motion-estimation (interframecoding) achieves much better R/D whencompared to intra-frame coding, there are severalapplications that requires a intra-frame coding approach.Most of the television content productionsrequire recordings in HD to maintain high qualityof picture even though the final transmission is inSD (standard <strong>de</strong>finition) format and after professionalvi<strong>de</strong>o editing processes, where random and frequentframe access and edition is performed. Intraframecoding is <strong>de</strong>sirable as well in many other applicationslike vi<strong>de</strong>o archiving, high-quality highresolutionmedical and satellite vi<strong>de</strong>o sequences, applicationsrequiring simple real-time encoding likevi<strong>de</strong>o-conference systems where very low <strong>de</strong>lay is <strong>de</strong>sirableor even for professional or home vi<strong>de</strong>o surveillancesystems [1] and Digital Vi<strong>de</strong>o Recording systems(DVR), where the user equipment is usually notas powerful as the hea<strong>de</strong>nd equipment. So, for theseapplications, computing capability, limited memoryresources and real-time constraints need to be takeninto account. Many wireless applications often useintra coding technologies which exhibits an excellenterror resilience behavior at the price of higher bitrates.The strength of an intra-vi<strong>de</strong>o coding systemrelies on the ability to efficiently exploit the spatialredundancies of each vi<strong>de</strong>o sequence frame avoidingcomplexity in the <strong>de</strong>sign of the encoding/<strong>de</strong>codingengines.1 Departament of Physics and Computer Engineering,Miguel Hernan<strong>de</strong>z University - Elche - Spain, e-mail:{mmrach,otoniel,pablop,mels}@umh.es.2 Departament of Computer Engineering, Polytechnic Universityof Valencia - Spain, e-mail: joliver@upv.esIn the context of image and vi<strong>de</strong>o compression, themost reliable way of measuring the perceived qualityis by performing subjective quality tests. Such subjectivetests were standardized by the Vi<strong>de</strong>o QualityExperts Group (VQEG) [2]. The Mean OpinionScore (MOS) is a subjective quality metric obtainedfrom a number of human observers, has beenregar<strong>de</strong>d for many years as the most reliable formof quality measurement, and the procedure for doingsuch experiments has been standardized [3]. However,the MOS method is too cumbersome, slow an<strong>de</strong>xpensive for most applications.Many research has been done in or<strong>de</strong>r to obtainobjective image and vi<strong>de</strong>o image QAM based on theknowledge of how our Human Visual System (HVS)perceives quality. QAM are valuable because theyprovi<strong>de</strong> vi<strong>de</strong>o enco<strong>de</strong>r <strong>de</strong>signers and standard organizationswith means for making meaningful qualityevaluations without convening viewer panels. Themost commonly used quality metric is the PSNRsince it is simple and fast to calculate. HoweverPSNR does not always capture the distortion perceivedby the HVS. In terms of correlation to humanperception it would be preferable to use the MOSvalue as QAM when performing R/D comparisonsbut it would be too cumbersome. Some studies beginto present their results by means of quality assessmentmetrics like MSSIM [4] and VIF [5].Image and vi<strong>de</strong>o enco<strong>de</strong>rs have inclu<strong>de</strong>d much ofthe knowledge of our HVS in the way they processin or<strong>de</strong>r to obtain a better perceptual quality of thecompressed sequences. The most wi<strong>de</strong>ly used characteristicis the contrast adaptability of the HVS.HVS is more sensitive to contrast than to absoluteluminance. The Contrast Sensitivity Function (CSF)relates the spatial frequency with the contrast sensitivity.We propose a intra perceptual vi<strong>de</strong>o enco<strong>de</strong>r, PM-LTW, based on LTW image co<strong>de</strong>c [6] with the inclusionof CSF in the wavelet transform stage, optimizedand tuned to work at mo<strong>de</strong>rate to good vi<strong>de</strong>o qualitylevels. We propose the use of a CSF weighting matrixapplied to wavelet subbands that preservers a verygood balance between bit-rate and perceptual qualityin all the quantization range. As quality metricfor R/D comparisons, we propose to use the VIF (VisualInformation Fi<strong>de</strong>lity) QAM [7] which has beenproven [8] [9] to have a better correlation with subjectiveperception than other metrics that are usuallyused for this types of comparisons [10] [4]. Weperform a comparison of the PM-LTW perceptualperformance with other intra tuned coding proposals<strong>JP2011</strong>-119


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011like H264/AVC, Motion-JPEG2000, Motion-SPIHTand x264.The rest of the paper is organized as follows. Insection II we introduce some advantages of intra coding,in section III we <strong>de</strong>scribe how to inclu<strong>de</strong> the CSFin the encoding process and in section IV we discussabout the convenience of using quality assessmentmetrics. In Section V we <strong>de</strong>scribe the co<strong>de</strong>c versionsinclu<strong>de</strong>d in the comparison against PM-LTW and weexplain the methods followed to perform the comparisonas well as the results presented, and finally insection VI some conclusions are drawn.II. Advantages of Intra-CodingInter-frame coding uses temporal correlation ofpictures to generate lower bit-rates than intra codingschemes, assuming that the content of successiveframes is similar. When this assumption fails,for example in vi<strong>de</strong>os of “still-camera” strobes, fastmotion sport sequences, quick zooms and pans, specialeffects or sequences with short duration eventsand high motion, then the bit-rate savings would bereduced, approaching to bit-rates produced by theintra coding option. Furthermore, the compression<strong>de</strong>lay coding in intra mo<strong>de</strong> is much lower than theone produced in inter coding, what should be takeninto account for interactive IPTV applications.In vi<strong>de</strong>o content editing applications, accessingrandom frames would be natural for intra codingschemes, while inter coding would require <strong>de</strong>codingseveral frames. Moreover, the quality of reconstructedframes <strong>de</strong>pends only of the frame itselfavoiding error propagation between frames thatwould be consi<strong>de</strong>rable when previous frames or partof them are lost or with errors. This also leads to alower <strong>de</strong>gradation of the edited vi<strong>de</strong>o when multipleeditions of the same sequence are done.Parallel processing is another field where intra codingcan take advantage, since inter coding <strong>de</strong>finesmore data <strong>de</strong>pen<strong>de</strong>ncies that causes parallel programmingto be complex and less efficient. Intra onlycompression is very suitable with parallel processingarchitectures, i.e. multi core CPUs, or GPUs.In [11] an experimental study was performed withH.264/AVC and JPEG2000 in or<strong>de</strong>r to <strong>de</strong>termine thebenefits of the use of inter frame encoding versus intraframe encoding for Digital Cinema applications.Their results draw that the coding efficiency advantagesof inter frame coding are significantly reducedfor film content at the data rates and quality levelsassociated with digital cinema. This indicatesthat the benefit of inter frame coding is questionable,because it is computationally much more complex,creates data access complications due to the <strong>de</strong>pen<strong>de</strong>nciesamong frames and in general <strong>de</strong>mands moreresources. For lower resolutions their experimentsconfirms that inter frame coding was more efficientthan intra frame coding. These results provi<strong>de</strong> a justificationfor using JPEG2000, or other intra framecoding methods, for coding digital cinema content.Fig. 1.Contrast Sensitivity FunctionIII. Contrast Sensitivity FunctionHVS research offers mathematical mo<strong>de</strong>ls of humanperception. A comprehensive review of HVSmo<strong>de</strong>lsfor quality assessment/image compression isfound in [12]. Most of these mo<strong>de</strong>ls account for thevarying sensitivity over spatial frequency, color, andthe inhibiting effects of strong local contrasts or activity,called masking. Complex HVS-mo<strong>de</strong>ls implementeach of these low level visual effects as a separatestage. Then the overall mo<strong>de</strong>l consists of thesuccessive processing of each stage. One of the initialHVS stages is the visual sensitivity as a function ofspatial frequency that is <strong>de</strong>scribed by the CSF.A closed form mo<strong>de</strong>l of the CSF for luminanceimages [13] is given by:H(f) = 2.6(0.0192 + 0.114f)e −(0.114f)1.1 (1)where spatial frequency is f = (fx 2 + f y 2)1/2withunits of cycles/<strong>de</strong>gree (f x and f y , are the horizontaland vertical spatial frequencies). The frequency isusually measured in cycles per optical <strong>de</strong>gree (cpd),which makes the CSF in<strong>de</strong>pen<strong>de</strong>nt of the viewingdistance.Figure 1 <strong>de</strong>picts the CSF curve obtained withequation 1, it characterizes luminance sensitivity asa function of normalized spatial frequency. CSF isa bandpass filter, which is most sensitive to normalizedspatial frequencies between 0.025 and 0.125 andless sensitive to very low and very high frequencies.The reason why we can not distinguish patterns withhigh frequencies is the limited number of photoreceptorsin our eye. CSF curves exist for chrominanceas well. However, unlike luminance stimuli, humansensitivity to chrominance stimuli is relatively uniformacross spatial frequency. The work of [13] wasone of the first where it was <strong>de</strong>monstrated that theMSE cannot reliably predict the difference of the perceivedquality of two images. They propose, by theway of psychovisual experiments, the aforementionedmo<strong>de</strong>l of the CSF, that is well suited and wi<strong>de</strong>ly used([14][15][16][17]) for wavelet based co<strong>de</strong>cs, thereforewe adopt this mo<strong>de</strong>l.<strong>JP2011</strong>-120


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA I50Proposed CSF Weighting matrix48LL LH HH LHL1 1.0 1.1795 1.0000 1.7873L2 1.0 3.4678 2.4457 4.8524L3 1.0 6.2038 5.5841 6.4957L4 1.0 6.4177 6.4964 6.1187L5 1.0 5.1014 5.5254 4.5678L6 1.0 3.5546 3.9300 3.1580PSNR4644424038363432PM_LTWMJASPERMSPHITX264H2643028The granularity of the correspon<strong>de</strong>nce between frequencyand weighting value is a key issue. As waveletbased co<strong>de</strong>cs obtain a multiresolution signal <strong>de</strong>compositionthe easiest association is to find a uniqueweighting value for each wavelet frequency subband.If further <strong>de</strong>compositions of the frequency domainare done, for example by the use of packet waveletsa finer association could be done between frequencyand weights [18]. The most common way of implementthe CSF curve in wavelet based co<strong>de</strong>cs is by theuse of an Invariant Scaling Factor Weighting [19].In [20], subjective experiments were performed obtaininga mo<strong>de</strong>l to express the threshold DWT noiseas a function of spatial frequency. Using this mo<strong>de</strong>lauthors obtain a perceptually lossless quantizationmatrix for the linear-phase 9/7 DWT. By the use ofthis quantization matrix each subband is quantizedby a value that adjust the overall resulting quantizedimage at the threshold of artifacts visibility.For supra-threshold quantization a uniform quantizationstage is afterwards performed.In [21] authors argued that fixing the quantizationmatrix for at-threshold visibility and then performa uniform quantization to reach a <strong>de</strong>sired bit-ratein the supra-threshold range does not guarantee topreserve the best perceptual quality for the resultingimage. They propose an iterative rate/distortionprocess based on the relationship among contrastof resulting image and the MSE. Again subjectivesupra-threshold experiments were performed for establishinghow the overall contrast sensibility is affectedby supra-threshold quantization impairmentsin each individual wavelet subband.We perform an ISFW implementation of the CSFbased on [14] but increasing the granularity at thesubband level. So we scale the wavelet coefficientsbefore a uniform quantization stage. We obtain theweighting matrix of Table I directly from the CSFcurve (unlike [20] and [21]), by normalizing the correspondingvalues so that the most perceptually importantfrequencies are scaled with higher values,while the less important are preserved. This scalingprocess augment the value of all wavelet coefficients(except LL subband) and therefore the overall bitratenee<strong>de</strong>d for the transmission of the scaled versionof the image. Our tests reveal that thanks tothe weighting process, the oncoming uniform quantizationstage preserves a very good balance betweenbit-rate and perceptual quality in all the quantizationrange.VIF261.000.950.900.850.800.750.700.650.600.550.500.450.400.350.300.2550010001500200025003000350040004500Bitrate Kb/s500055006000PM_LTWMJASPERMSPIHTX264H264Fig. 2. R/D comparative PSNR and VIF results for ContainerCIF sequenceIV. The use of Quality Assessment MetricsUpper panel of Figure 2 show the PSNR R/D resultsfor the Container CIF sequence of all evaluatedco<strong>de</strong>cs. While looking at these results, a first conclusioncould be that the algorithms or improvementsinclu<strong>de</strong>d in the PM-LTW enco<strong>de</strong>r do not performwell and should be discar<strong>de</strong>d because the quality differencesare too high for any rate. For example, focusingat 3458.15 Kb/s (1.13 bpp) the difference betweenH.264/AVC and PM-LTW is up to 3.32 dB. Infigure 3 the frame number 20 of the Container CIFsequence is presented at this rate for H.264/AVC andPM-LTW. After having a look at these two framesthe difference of 3.32 dB seems too high, that is, oneexpects more visual difference for a numeric distanceof 3.32 dB.Therefore we can not trust how PNSR ranks quality.We need a quality metric on which rely. Lowerpanel of figure 2 the quality is measured in termsof the VIF QAM, the previous conclusion that discar<strong>de</strong>dthe PM-LTW enco<strong>de</strong>r is compromised. Althoughquality assessment metrics are not foolproof,the objective quality values for both enco<strong>de</strong>rs are notas distant as before, being this distance closer to theperceived one. Assuming that a quality assessmentmetric is based on a fitting process over a set of MOSvalues, it is worth to use such a metric for comparisonsof different enco<strong>de</strong>r proposals.6500V. Performance AnalysisAll the evaluated enco<strong>de</strong>rs working in intra codingmo<strong>de</strong> have been tested on an Intel Pentium Core2 CPU at 1.8 GHz with 6GB of RAM memory.We have selected H.264/AVC (High-10, JM16.1),700075008000<strong>JP2011</strong>-121


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011(a) PSNR=37.49 dB Bit-rate=3458.15 Kb/s(b) PSNR=41.19 dB Bit-rate=3690.42 Kb/sFig. 3. Frame 20 of the container sequence enco<strong>de</strong>d with a)PM-LTW and b) H.264/AVC INTRATABLA IIQuality levels lower thresholdsLower Thresholds CIF & QCIF ITU & HDVisually lossless 0.93 0.90Excellent 0.87 0.85Good 0.80 0.75Acceptable 0.70 0.60Motion-JPEG2000 (Jasper 1.701.0), Motion-SPIHT(Spiht 8.01), x264 (FFmpeg version SVN-r25117,profile High, level 4.0) and our PM-LTW.The main parameters used for the H264/AVCJM16.1 are: Profile ID: 110; Level ID: 4.1 (forQCIF and CIF) and 5.1 for (ITU and HD1080);IntraProfile: 1; IntraPeriod: 1; IDRPeriod: 1;GrayScale: 1; RateControlEnable: 1; RCUpdate-Mo<strong>de</strong>: 1; CABAC.The main parameters used for the X264 Softwareare: -intra; -pix fmt yuv420p; -vf ”format=gray”; -fpre ”libx264-hq.ffpreset”The test vi<strong>de</strong>o sequences used in the evaluationare: Foreman, Hall, Container, News, Mobile andPe<strong>de</strong>strian area. Resolutions were QCIF, CIF, ITU576 and HD 1024.The rates, timing and the distortion values(PSNR) were obtained from the corresponding co<strong>de</strong>clog file. For getting the memory consumption values,we used the VMMap Sysinternals tool. The frameVIF value was obtained with the matlab VIF sourceco<strong>de</strong> that can be downloa<strong>de</strong>d from authors web page[22].While comparing enco<strong>de</strong>r proposals it is commonto work within a bit-rates and quality workingranges. As we will focus in perceptual qualitiesstated by users as good and above, first we have to establishthe quality working ranges by means of VIFvalues. We did a simple subjective test with fourobservers in or<strong>de</strong>r to <strong>de</strong>fine five quality levels, “Visuallylossless”, “Excellent”, “Good”, “Acceptable”and “Bad”. For each sequence, the uncompressed sequenceis present as reference to the viewer togetherwith a sequence compressed at a different bit-rateeach time. Viewers had no knowledge of the bitratebeing evaluated but they know which one is theuncompressed image. They set for each sequence avalue ranging from 0 to 4 with steps of 0.2 points. Avalue of 0.0 is given when the viewer does not <strong>de</strong>tectany differences between the two sequences. A valueof 1 is the lower threshold for the “Excellent” level,being 2 and 3 the corresponding lower thresholds for“Good” and “Acceptable”. When users rank a sequencewith a value higher than 3, this means thatthis sequence is in the “Bad” level. Our study willfocus only on the first four levels, from “Visuallylossless” to “Acceptable”.The subjective test to <strong>de</strong>termine the five qualitylevels was run using different vi<strong>de</strong>o sequences withdifferent formats and the vi<strong>de</strong>o co<strong>de</strong>cs <strong>de</strong>fined above.In or<strong>de</strong>r to properly choose the vi<strong>de</strong>o sequences forthe test, we used the enco<strong>de</strong>r that offers the bestR/D behavior, in terms of the VIF quality metric,for each sequence. After analyzing the resultingdata, the VIF value thresholds are obtained foreach level. From the raw data, we <strong>de</strong>tected that observersset the thresholds for each level around differentVIF values <strong>de</strong>pending on the picture size. Forexample, when picture size was CIF or QCIF thelower threshold for the “Good” level was set around0.80 VIF units, but at higher picture sizes it was setaround 0.75 VIF units. In the same way, for smallsize sequences the lower threshold for the “Acceptable”level was set around 0.70 VIF units while forlarger sequences it was set around 0.60 VIF units.Table II resume these values.Figure 4 shows the VIF R/D curve for the HD1080“Pe<strong>de</strong>strian area” sequence. Regardless of the co<strong>de</strong>c,points of curves with quality values over 0.90 VIFunits could be consi<strong>de</strong>red perceptually the same. Focusingon the “Visually lossless” level (above 0.90VIF units) in figure 4, the key issue is then, at whichbit-rate one co<strong>de</strong>c reaches this level and if a bit-ratesaving is obtained by using one co<strong>de</strong>c or another.As previously mentioned, for the “Visually lossless”level all the sequences seem to be the same. The rawvalues told that there is a bit-rate saving (around an8.9%) when using PM-LTW at 56 Mb/s (0.93 VIF)instead of using X264, because for getting the sameVIF quality it needs 61.7 Mb/s. But this, althoughmatematically correct, is not from a perceptual pointof view. In this case, if we reduce the bit-rate for theX264 co<strong>de</strong>c up to 56 Mb/s we get a VIF value of91.6 units, which falls in the same level, being there-<strong>JP2011</strong>-122


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA IIIAverage bit-rate savings while comparing the use ofPM-LTW with studied co<strong>de</strong>cs for each quality levelPM-LTW vs QCIF CIF ITU-D1 HDM-JPEG2000Vis. Lossless 7.32% 9.26% 11.88% -Excellent 6.59% 4.03% 10.33% 42.48%Good 7.58% 2.93% 9.05% 17.59%Acceptable 9.08% 4.38% 9.02% 4.51%M-SPIHTVis. Lossless 12.13% 13.76% 19.84% 37.59%Excellent 12.04% 12.82% 18.28% 36.63%Good 12.70% 12.58% 16.32% 31.34%Acceptable 13.15% 12.77% 14.94% 22.87%x264Vis. Lossless -1.68% -1.96% 16.11% 12.11%Excellent -2.51% -2.32% 15.41% 14.09%Good -3.61% -2.63% 14.48% 17.02%Acceptable -5.04% -2.94% 13.98% 19.42%H.264Vis. Lossless -3.04% -2.05% 12.80% 17.86%Excellent -4.97% -4.05% 6.50% 16.68%Good -7.63% -6.72% -2.31% 11.23%Acceptable -10.59% -9.27% -9.06% 2.92%VIF0,980,960,940,920,900,880,860,840,820,800,780,760,740,720,700,680,660,640,620,60PM_LTWMJASPERMSPIHTX264H2641013161922252831343740434649525558616467707376798285Bitrate in Mb/sFig. 4. R/D by means of VIF for the Pe<strong>de</strong>strian Area HD1080sequencefore indistinguishable form the PM-LTW enco<strong>de</strong>d sequence.So, in this case, no advantage of the use ofPM-LTW is obtained, because the same saving couldbe obtained with the x264 enco<strong>de</strong>r. For getting areal bit rate saving in this level by the use of one enco<strong>de</strong>rinstead of another, both enco<strong>de</strong>rs must reachthe “Visually lossless” quality level lower thresholdat different rates.For the rest of levels, the curves corresponding tothe different co<strong>de</strong>cs can not be assumed to be perceptuallythe same, because there were viewers thatperceived some differences between values insi<strong>de</strong> thesame interval. Table III shows the relative bit-ratesavings that in average can be achieved for each ofthe <strong>de</strong>fined quality levels. When comparing our proposalwith Motion-JPEG2000 or Motion-SPIHT andregardless of the frame size and quality level, bit-ratesavings are always achieved. The trend is that thesaving increases with frame size. When focusing inx264 and H.264 and at QCIF and CIF sizes, theiraveraged values for all sequences give a better performancefor all the <strong>de</strong>fined quality levels, being thisTABLA IVTiming differences between PM-LTW & M-LTW due toPerceptual Enhancement (Average frame time inmilliseconds)D Wavelet Coding TotalPM-LTWCIF 3091.9 Kb/s 3.35 12.41 15.76ITU 9113.8 Kb/s 12.24 37.03 49.27HD 45471.3 Kb/s 92.38 231.00 323.37M-LTWCIF 3091.9 Kb/s 3.05 13.36 16.41ITU 9113.8 Kb/s 11.05 41.96 53.01HD 45471.3 Kb/s 85.64 264.64 350.28DifferencesCIF 3091.9 Kb/s 0.30 -0.95 -0.65ITITU 9113.8 Kb/s 1.19 -4.93 -3.74HD 45471.3 Kb/s 6.74 -33.64 -26.910)(log10ames/sec Fra10001001010QCIF(30Hz)at25.6Kb/frameCIF(30Hz)at103.0Kb/frameITU(640X512)(30Hz)at303.7Kb/framePM-LTWM-LTWM-SPIHTM-JPEG 2000X264H264/AVCHD(1920X1024)(25Hz)at1818.8Kb/frameFig. 5. Maximum frame rates in log scale for the differentframe sizessavings greater for H.264 than for x264 in all levels.Looking at ITU vi<strong>de</strong>o size the PM-LTW performanceincreases as the quality level becomes higher. Whencomparing with x264, PM-LTW achieve lower bitratein all quality levels. However, the improvements withrespect H.264 are only achieved at “Excellent” and“visually Lossless” quality levels.Figure 5 shows the frame rate obtained by the differentenco<strong>de</strong>rs being evaluated. As shown, the PM-LTW outperforms the rest of the enco<strong>de</strong>rs for anysequence frame size. Regarding memory usage, inFigure 6 we can see the maximum amount in MBytesof the private memory working set nee<strong>de</strong>d for eachenco<strong>de</strong>r and sequence size. The bit-rate used for eachresolution are 769.9 Kb/s, 3091.9 Kb/s, 9113.8 Kb/sand 45471.3 Kb/s for QCIF, CIF, ITU and HD respectively.PM-LTW is by far the one which lessmemory needs for all frame sizes. As frame size increasesthese differences are more important. Thismakes the PM-LTW very suitable to enco<strong>de</strong> at highvi<strong>de</strong>o resolutions.VI. ConclusionPM-LTW intra mo<strong>de</strong> vi<strong>de</strong>o co<strong>de</strong>c is very competitivein terms of perceptual quality and outperformingthe rest of the evaluated enco<strong>de</strong>rs for high vi<strong>de</strong>oresolutions sequences. Since intra frame encodinghas some advantages over inter frame encoding fora set of applications the proposed enco<strong>de</strong>r is a verygood option for these applications. The use of theVIF QAM instead PSNR in Rate/Distortion com-<strong>JP2011</strong>-123


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011MBytes (log2 scale)5122561286432168421Fig. 6.1,78PM-LTWM_SPIHTM-JASPERX264H2642,302,615,128,022,073,713,956,5820,982,948,347,0710,4662,049,2139,2731,3231,63QCIF CIF ITU HD375,17Memory consumption comparison in MBparisons, reveals that our proposal performs perceptuallyvery good. This, in turn, verify the fact thatusing PNSR while comparing encoding proposals interms of R/D is not recommen<strong>de</strong>d, because it couldinduce to wrong conclusions. Our proposal inclu<strong>de</strong>sthe well known Contrast Sensitivity Function afterthe wavelet transform stage of our enco<strong>de</strong>r performinga perceptual weighting of the obtained waveletcoefficients. We proposed a weighting matrix thatgives a very good R/D behavior in all the bit-raterange. PM-LTW achieves important bit-rate savingsfor the same perceptual quality when comparedwith M-SPIHT or M-JPEG2000 for all the evaluatedsequence resolutions and quality levels. Whencomparing with X264 these savings occurs for theITU resolution but only in the Excellent and Visuallylossless quality levels. As resolution increasesup to HD our proposal achieves bit-rate savings forall the evaluated quality levels being the highest valuesfor the Visually lossless quality level. PM-LTWrequires much less memory than any other enco<strong>de</strong>rbeing the differences higher as resolution increase.For HD resolution requires near 4 times less memorythan M-SPIHT, M-JPEG2000 and X264, and up to40 times less memory than H.264. In addition PM-LTW is also the fastest of the evaluated enco<strong>de</strong>rsbeing up to 2.3 times as fast as x264 and 28 times asfast as H.264/AVC intra.This makes PM-LTW a good choice for intra framecoding at high <strong>de</strong>finition/resolution applications.AcknowledgmentThanks to Spanish Ministry of education and Scienceun<strong>de</strong>r grant DPI2007-66796-C03-03 for fundingReferencias[1] Jang-Seon Ryu and Eung-Tea Kim, “Fast intra codingmethod of h.264 for vi<strong>de</strong>o surveillance system,” IJCSNSInternational Journal of Computer Science and NetworkSecurity, vol. 7, no. 10, October 2007.[2] VQEG, “Final report from the vi<strong>de</strong>o quality expertsgroup on the validation of objective mo<strong>de</strong>ls of vi<strong>de</strong>o qualityassessment. phase II,” August 2003.[3] Recommendations of the ITU, Telecommunication StandardizationSector, “Objective perceptual vi<strong>de</strong>o qualitymeasurement techniques for digital cable television in thepresence of a full reference,” Draft Revised RecommendationJ.144.[4] Z. Wang, A. Bovik, H. Sheikh, and E. P. Simoncelli, “Imagequality assessment: From error visibility to structuralsimilarity,” IEEE Transactions on Image Processing, vol.13, no. 4, 2004.[5] Hamid Rahim Sheikh, Alan Conrad Bovik, and Gustavo<strong>de</strong> Veciana, “An information fi<strong>de</strong>lity criterion forimage quality assessment using natural scene statistics,”IEEE Transactions on Image Processing, vol. 14, no. 12,2005.[6] J. Oliver and M.P. Malumbres, “Low-complexitymultiresolution image compression using wavelet lowertrees,” IEEE Transactions on CSVT, vol. 16, no. 11, pp.1437–1444, November 2006.[7] H. R. Sheikh and A. C. Bovik, “Image information andvisual quality,” Image Processing, IEEE Transactionson, vol. 15, no. 2, pp. 430–444, 2006.[8] M. Martinez-Rach, O. Lopez, P. Piñol, J. Oliver, andM.P. Malumbres, “A study of objective quality assessmentmetrics for vi<strong>de</strong>o co<strong>de</strong>c <strong>de</strong>sign and evaluation,”in Eight IEEE International Symposium on Multimedia,San Diego, California, Dec 2006, vol. 1, ISBN 0-7695-2746-9, pp. 517–524, IEEE Computer Society.[9] H. R. Sheikh, M. F. Sabir, and A. C. Bovik, “A statisticalevaluation of recent full reference image qualityassessment algorithms,” IEEE Transactions on ImageProcessing, vol. 15, no. 11, pp. 3440– 3451, 2006.[10] Francesca De Simone, Mourad Ouaret, Fre<strong>de</strong>ric Dufaux,Andrew G. Tescher, and Touradj Ebrahimi, “A comparativestudy of jpeg2000, avc/h.264 and hdphoto,” inProc. of Applications of Digital Image Processing XXX,San Diego, August 2007.[11] Michael Smith and John Villasenor, “Intra-frame jpeg-2000 vs. inter-frame compression comparison: The benefitsand tra<strong>de</strong>-offs for very high quality, high resolutionsequences,” SMPTE Technical Conference and Exhibition,Pasa<strong>de</strong>na, California, October 20-23 2004.[12] Marcus J. Na<strong>de</strong>nau, Stefan Winkler, David Alleysson,and Murat Kunt, “Human vision mo<strong>de</strong>ls for perceptuallyoptimized image processing – a review,” in PROC. OFTHE IEEE, 2000.[13] J. Mannos and D. Sakrison, “The effects of a visual fi<strong>de</strong>litycriterion of the encoding of images,” InformationTheory, IEEE Transactions on, vol. 20, no. 4, pp. 525 –536, July 1974.[14] A.P. Beegan, L.R. Iyer, A.E. Bell, V.R. Maher, and M.A.Ross, “Design and evaluation of perceptual masks forwavelet image compression,” in Digital Signal ProcessingWorkshop, 2002 and the 2nd Signal Processing EducationWorkshop. Proceedings of 2002 IEEE 10th, Oct.2002, pp. 88 – 93.[15] A. Gaddipati, R. Machiraju, and R. Yagel, “Steeringimage generation with wawelet based perceptual metric,”in Eurographics, 1997.[16] H. Rushmeier, G. Ward, C. Piatko, P. San<strong>de</strong>rs, andB. Rust, “Comparing real and synthetic images: Somei<strong>de</strong>as about metrics,” in In Proc. 6th Eurographics Workshopon Ren<strong>de</strong>ring, Dublin, Ireland,, 1995, pp. 82–91.[17] Noureddine Moumkine, Ahmed Tamtaoui, and Ab<strong>de</strong>llahAit Ouahman, “Integration of the contrast sensitivityfunction into wavelet co<strong>de</strong>c,” in In Proc. Second InternationalSymposium on Comunications, Control and SignalProcessing ISCCSP, Marrakech, Morocco, March 2006.[18] Xinbo Gao, Wen Lu, Dacheng Tao, and Xuelong Li,“Image quality assessment based on multiscale geometricanalysis,” IEEE TRANSACTIONS ON IMAGE PRO-CESSING, vol. 18, no. 7, pp. 1409–1423, 2009.[19] Marcus J. Na<strong>de</strong>nau, Julien Reichel, and Murat Kunt,“Wavelet-based color image compression: Exploiting thecontrast sensitivity function,” IEEE TRANSACTIONSON IMAGE PROCESSING, vol. 12, no. 1, 2003.[20] Andrew B. Watson, Gloria Y. Yang, Joshua A. Solomon,and John Villasenor, “Visibility of wavelet quantizationnoise,” IEEE TRANSACTIONS ON IMAGE PRO-CESSING, vol. 6, no. 8, pp. 1164–1175, 1997.[21] D. M. Chandler and S. S. Hemami, “Dynamic contrastbasedquantization for lossy wavelet image compression,”IEEE Transactions on Image Processing, vol. 14, no. 4,April 2005.[22] Hamid R. Sheikh and Alan C. Bovik,“Image information and visual quality,”http://live.ece.utexas.edu/research/quality/VIF.htm.<strong>JP2011</strong>-124


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Equipo paralelo <strong>de</strong> metaheurísticas para laresolución <strong>de</strong> un problema real <strong>de</strong>telecomunicacionesJosé M. Chaves González 1 , Miguel A. Vega Rodríguez 1 ,Juan A. Gómez Pulido 1 y Juan M. Sánchez Pérez 1Resumen— En este artículo se presenta un estudio llevadoa cabo con una eficiente estrategia paralela aplicada a laresolución <strong>de</strong> un importante problema real <strong>de</strong>ntro <strong>de</strong>ldominio <strong>de</strong> las telecomunicaciones: el problema <strong>de</strong> laasignación automática <strong>de</strong> frecuencias (FAP –FrequencyAssignment Problem). <strong>La</strong> obtención <strong>de</strong> planificaciones <strong>de</strong>frecuencia eficientes es una tarea compleja y crucial paralos operadores <strong>de</strong> telefonía actuales. <strong>La</strong> razón es el númerolimitado <strong>de</strong> frecuencias con que cuentan dichos operadorespara dar soporte al gran número <strong>de</strong> comunicaciones que seproducen en la red. El uso <strong>de</strong> estrategias metaheurísticasen combinación con técnicas basadas en paralelismo ha<strong>de</strong>mostrado ser una <strong>de</strong> las mejores maneras <strong>de</strong> conseguirresultados <strong>de</strong> alta calidad en tiempos competitivos. Elequipo paralelo <strong>de</strong>scrito en este trabajo está compuesto porun conjunto <strong>de</strong> siete metaheurísticas que presentandiferentes comportamientos. Así, algunas son estrategiasbasadas en trayectoria y otras basadas en población, unasson estrategias clásicas y otras muy recientes, o algunaspresentan diseños bio-inspirados y otras están basadas enmo<strong>de</strong>los probabilísticos. El equipo paralelo está controladopor una hiperheurística (HH) que orquesta el eficientefuncionamiento <strong>de</strong> todo el sistema. El análisis <strong>de</strong> losresultados obtenidos <strong>de</strong>muestra que la utilización <strong>de</strong> unequipo heterogéneo <strong>de</strong> estrategias <strong>de</strong>bidamenteconfiguradas obtiene resultados <strong>de</strong> muy alta calidad en laresolución <strong>de</strong>l problema abordado. De hecho, lasplanificaciones <strong>de</strong> frecuencia conseguidas por el sistemapropuesto mejoran los resultados <strong>de</strong> otras publicacionesrelevantes.Palabras clave— Equipo heterogéneo <strong>de</strong> metaheurísticas,Hiperheurística Paralela, Problema Real <strong>de</strong> AsignaciónAutomática <strong>de</strong> Frecuencias, FAP, MPI.EI. INTRODUCCIÓNL problema <strong>de</strong> la asignación automática <strong>de</strong>frecuencias (FAP –Frequency Assignment Problem)es una <strong>de</strong> las tareas más importantes llevadas a cabo enel diseño <strong>de</strong> re<strong>de</strong>s reales <strong>de</strong> comunicaciones. De hecho,resulta un trabajo fundamental tanto para los operadores<strong>de</strong> telefonía actuales como para los futuros, ya que<strong>de</strong>bido a las restricciones <strong>de</strong> ancho <strong>de</strong> banda quepresenta cada compañía <strong>de</strong> telefonía, es bien sabido quesólo con una planificación <strong>de</strong> frecuencias <strong>de</strong> alta calidadse pue<strong>de</strong> conseguir el máximo partido <strong>de</strong>l reducidorango <strong>de</strong> frecuencias disponible. Por tanto, <strong>de</strong>bido a surelevancia, el problema FAP ha sido muy estudiado enlas últimas décadas, por lo que en la bibliografía se1 Dpto. Tecnología <strong>de</strong> los Computadores y <strong>de</strong> las Comunicaciones,<strong>Universidad</strong> <strong>de</strong> Extremadura, Escuela Politécnica <strong>de</strong> Cáceres, e-mail:{jm, mavega, jangomez, sanperez}@unex.es.pue<strong>de</strong>n encontrar numerosos trabajos don<strong>de</strong> se utilizandiferentes aproximaciones y una gran variedad <strong>de</strong>mo<strong>de</strong>los matemáticos para su resolución [1, 2]. Sinembargo, la mayoría <strong>de</strong> estas publicaciones resuelvenproblemas FAP <strong>de</strong> tipo benchmark [2], los cuales tienenuna complejidad menor que los problemas basados enre<strong>de</strong>s reales, don<strong>de</strong> se consi<strong>de</strong>ran requisitos y conceptosque son inherentes a dichas re<strong>de</strong>s [3], como son elelevado número <strong>de</strong> transmisores que se utilizan comosoporte <strong>de</strong> las comunicaciones o las restricciones en lasque se basan las interferencias producidas en la red.El problema <strong>de</strong> optimización que surge con el FAP seexplica porque las re<strong>de</strong>s <strong>de</strong> telefonía actuales disponen<strong>de</strong> un rango <strong>de</strong> frecuencias muy limitado con el que<strong>de</strong>ben dar servicio al cada vez mayor número <strong>de</strong>usuarios que utilizan los servicios <strong>de</strong> dicha red. Estehecho causa que las frecuencias <strong>de</strong>ban ser utilizadas <strong>de</strong>manera simultánea en distintos puntos <strong>de</strong> la red para quesea posible llevar a cabo todas las comunicaciones quese producen. Sin embargo, el solapamiento <strong>de</strong>frecuencias lleva acarreado interferencias que dificultan,e incluso pue<strong>de</strong>n llegar a anular, dichas comunicaciones.Por esta razón se hace necesario realizar unaplanificación <strong>de</strong> frecuencias <strong>de</strong> alta calidad con la que seconsiga maximizar la cobertura en toda la redmanteniendo a la vez unos mínimos aceptables en lacalidad <strong>de</strong> servicio que ésta ofrece.El FAP es un problema NP-completo, por lo queutilizar algoritmos exactos para resolver instanciasreales <strong>de</strong>l mismo no es factible. Por el contrario, abordareste tipo <strong>de</strong> instancias con técnicas basadas enbúsquedas heurísticas o estrategias metaheurísticas es, sino obligatorio, una <strong>de</strong> las mejores opciones paraconseguir planificaciones <strong>de</strong> frecuencia <strong>de</strong> alta calidad[4]. Sin embargo, el problema abordado también tieneunas fuertes restricciones temporales, y el uso <strong>de</strong> estetipo <strong>de</strong> algoritmos conlleva muchas veces una <strong>de</strong>mora<strong>de</strong>masiado amplia para los requisitos <strong>de</strong>l mismo. Portanto, el uso <strong>de</strong> estrategias paralelas que aceleren laobtención <strong>de</strong> resultados <strong>de</strong> alta calidad también resultafundamental cuando se trabaja con instancias reales <strong>de</strong>gran<strong>de</strong>s dimensiones.De esta manera, en este artículo se <strong>de</strong>scribe lautilización <strong>de</strong> un equipo paralelo que hace uso <strong>de</strong> variasestrategias metaheurísticas para conseguir resultados <strong>de</strong>alta calidad que resuelvan instancias reales <strong>de</strong>l problema<strong>de</strong> la asignación automática <strong>de</strong> frecuencias. A<strong>de</strong>más, seha hecho un estudio <strong>de</strong> cómo la heterogeneidad <strong>de</strong> lasestrategias que participan en el equipo redunda en unamejora significativa <strong>de</strong> los resultados, concluyendo que<strong>JP2011</strong>-125


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011una configuración a<strong>de</strong>cuada <strong>de</strong> esta aproximaciónconsigue resultados altamente satisfactorios para elproblema abordado.El resto <strong>de</strong>l artículo se estructura <strong>de</strong> la siguientemanera: en la Sección II se explican los conocimientosbásicos y la <strong>de</strong>finición formal utilizada para mo<strong>de</strong>lar elproblema FAP manejado en nuestro estudio. Acontinuación, en la Sección III, se <strong>de</strong>scribe el equipoheterogéneo <strong>de</strong> metaheurísticas propuesto para resolverel problema. Después se resumen los experimentosrealizados y los resultados obtenidos mediante losmismos en la Sección IV. Finalmente, las conclusiones ylíneas futuras se discuten en la Sección V.II. LA PLANIFICACIÓN DE FRECUENCIAS EN REDES GSM<strong>La</strong> planificación <strong>de</strong> frecuencias es el último paso en eldiseño <strong>de</strong> una red GSM [5]. Antes <strong>de</strong> afrontar esteproblema, el diseñador <strong>de</strong> la red tiene que tratar concuestiones previas, como por ejemplo la localización yconfiguración <strong>de</strong> las antenas que darán cobertura a la redo configurar el número y orientación <strong>de</strong> los sectores quetendrá cada antena y la distribución <strong>de</strong> TRXs(transmisores-receptores) <strong>de</strong>ntro <strong>de</strong> éstos [6], que sonlos elementos encargados <strong>de</strong> realizar la comunicación.El número <strong>de</strong> TRXs que se instalarán en cada sector<strong>de</strong>pen<strong>de</strong>rá <strong>de</strong> la <strong>de</strong>manda <strong>de</strong> tráfico que éste <strong>de</strong>basoportar. <strong>La</strong> planificación <strong>de</strong> frecuencias consiste enasignar un canal (o frecuencia) a cada TRX [3]. Noexiste una única versión <strong>de</strong>l problema <strong>de</strong> la asignaciónautomática <strong>de</strong> frecuencias. De hecho, tanto el mo<strong>de</strong>lomatemático utilizado para representar el problema [1, 3]como la técnica <strong>de</strong> resolución aplicada para resolverlovariarán <strong>de</strong>pendiendo <strong>de</strong>l escenario abordado y <strong>de</strong>lobjetivo concreto que se persiga. En este artículo seresuelven dos instancias reales <strong>de</strong> gran tamaño. Por unalado se aborda la instancia Denver, que incluye 2612TRXs distribuidos en 334 BTSs y únicamente tienedisponibles 18 frecuencias para asignar a todos y cadauno <strong>de</strong> los TRX <strong>de</strong> la red. Por otro lado se maneja lainstancia Seattle, que incluye 970 TRXs instalados en503 antenas y únicamente 15 frecuencias diferentes pararealizar la planificación <strong>de</strong> frecuencias en toda la red. Ala vista <strong>de</strong> las cifras que se manejan, queda claro queconseguir planificaciones <strong>de</strong> frecuencias <strong>de</strong> alta calida<strong>de</strong>s una tarea tan importante como compleja.Por tanto, el problema <strong>de</strong> optimización surge <strong>de</strong>bido aluso <strong>de</strong> la misma frecuencia por varios transmisores. Estehecho suele provocar interferencias que pue<strong>de</strong>n llegar areducir la calidad <strong>de</strong> servicio (QoS) hasta nivelesinsatisfactorios para una red comercial, y esto ha <strong>de</strong> ser,si no evitado (porque no es posible evitarlo), sí reducidotodo lo posible.Hay varias formas <strong>de</strong> cuantificar las interferencias quese producen en una red <strong>de</strong> telecomunicaciones, aunquela más extendida (y la que nosotros utilizamos) es usarlo que se llama la matriz <strong>de</strong> interferencias, M, <strong>de</strong> la red[3]. Cada elemento M(i,j) <strong>de</strong> esta matriz contienebásicamente dos tipos <strong>de</strong> interferencia: la interferenciaco-canal, que representa la <strong>de</strong>gradación <strong>de</strong> la calidad <strong>de</strong>señal en la red si las celdas i y j operan con la mismafrecuencia; y la interferencia <strong>de</strong> canal adyacente, que seproduce cuando dos TRXs operan en canales adyacentes(por ejemplo, un TRX opera en el canal f y otro en elcanal f+1 o f-1). Es muy importante que la matriz <strong>de</strong>interferencias esté bien ajustada, ya que el objetivo <strong>de</strong>cualquier algoritmo que resuelva el FAP será minimizarla suma <strong>de</strong> las interferencias expresadas en la matriz M.En la siguiente subsección se explica el mo<strong>de</strong>lomatemático que se ha utilizado para mo<strong>de</strong>lar elproblema. Dicho mo<strong>de</strong>lo fue propuesto en un trabajoprevio, por lo que el usuario que quiera una explicaciónmás completa que la dada en este artículo pue<strong>de</strong>consultar la referencia [7].A. Descripción formal <strong>de</strong>l problemaSea T = {t 1 , t 2 ,…, t n } un conjunto <strong>de</strong> n TRXs, y sea F i= {f i1 ,…, f ik } ⊂ N el conjunto <strong>de</strong> frecuencias validas quepue<strong>de</strong>n ser asignadas a un TRX t i ∈ T, i = 1,…, n.Nótese que k, que representa la cardinalidad <strong>de</strong> F i , notiene que ser necesariamente la misma para todos losTRXs. A<strong>de</strong>más, sea S = {s 1 , s 2 ,…, s m } el conjunto <strong>de</strong> lossectores (o celdas) don<strong>de</strong> los TRXs están instalados, <strong>de</strong>cardinalidad m. Cada TRX t i ∈ T está instaladoexactamente en uno <strong>de</strong> los m sectores. A<strong>de</strong>más,llamamos al sector don<strong>de</strong> un TRX t i concreto estáinstalado como s(t i ) ∈ S. Finalmente, sea la matriz M ={(μ ij , σ ij )} mxm , llamada matriz <strong>de</strong> interferencias, don<strong>de</strong>las dos entradas μ ij y σ ij <strong>de</strong> la matriz M(i,j) = (μ ij , σ ij )son valores numéricos mayores o iguales que 0. Dehecho, μ ij representa la media, y σ ij es la <strong>de</strong>sviaciónestándar <strong>de</strong> una distribución <strong>de</strong> probabilidad gausianaque <strong>de</strong>scribe la proporción señal/interferencia (C/I,carrier-to-interference) <strong>de</strong>ntro <strong>de</strong> la red [8] cuando lossectores i y j operan con la misma frecuencia. Cuantomás alto es el valor <strong>de</strong> la media, más baja será lainterferencia, y <strong>de</strong> esta manera mejor la calidad en lacomunicación. A<strong>de</strong>más, es importante señalar que lamatriz <strong>de</strong> interferencias se <strong>de</strong>fine a nivel <strong>de</strong> sector(celda), porque todos los transmisores instalados en cadasector dan cobertura a la misma área. De esta forma,po<strong>de</strong>mos establecer que una solución al problema FAPse obtiene asignando a cada TRX t i ∈ T una <strong>de</strong> lasfrecuencias <strong>de</strong> F i . Diremos que una solución al problema(o una planificación <strong>de</strong> frecuencias) se <strong>de</strong>fine como: p ∈F 1 × F 2 × … × F n , don<strong>de</strong> p(t i ) ∈ F i es la frecuenciaasignada al TRX t i . El objetivo <strong>de</strong>l algoritmo, y <strong>de</strong> laplanificación misma, es encontrar una solución p queminimice la siguiente función <strong>de</strong> coste:C(p)=∑ ∑Csigt∈Tu∈T, u≠t( p,t,u)Para <strong>de</strong>finir la función C sig (p,t,u), vamos a establecerque s t y s u son los sectores en los que los TRXs t y uestán instalados, que son s t =s(t) y s u =s(u). A<strong>de</strong>más, seaμs t s u y σs t s u los dos elementos correspondientes <strong>de</strong>ntro<strong>de</strong> la matriz <strong>de</strong> interferencias M(s t ,s u ) con respecto a lossectores s t y s u . De esta forma, C sig (p,t,u) es igual a laexpresión <strong>de</strong>scrita en la ecuación 2.⎧ K⎪Cco( μsts, σu⎨⎪Cadj( μsts, σu⎪⎩ 0stsustsu))si s = s ,si s ≠ s , μtstsusi s ≠ s , μttuuustsup(t)− p(u)< 2> 0, p(t)− p(u)= 0> 0, p(t)− p(u)= 1en otro caso(1)(2)Don<strong>de</strong> K >> 0 es una constante con un valor muy altoque está <strong>de</strong>finida por el diseñador <strong>de</strong> la red para hacer<strong>JP2011</strong>-126


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011in<strong>de</strong>seable la asignación <strong>de</strong> la misma o frecuenciasadyacentes a transmisores que sirven <strong>de</strong>ntro <strong>de</strong>l mismoárea (instalados en el mismo sector). A<strong>de</strong>más, <strong>de</strong>ntro <strong>de</strong>la ecuación 2, C co (μ,σ) representa el coste <strong>de</strong>bido a lasinterferencias co-canal (ecuación 3) mientras queC adj (μ,σ) es el coste en caso <strong>de</strong> las interferencias <strong>de</strong>canal adyacente (ecuación 4).CSH− μCco(μ,σ ) = 100(1.0 − Q())(3)σCSH− CACR− μCadj( μ,σ ) = 100(1.0 − Q()) (4)σDon<strong>de</strong> C SH es un umbral <strong>de</strong> calidad mínima <strong>de</strong> la señaly C ACR (rechazo <strong>de</strong> canal adyacente) mi<strong>de</strong> la habilidad<strong>de</strong>l receptor a la hora <strong>de</strong> recibir la señal requerida enpresencia <strong>de</strong> una señal que no es la requerida en un canaladyacente. Finalmente, Q(z) se <strong>de</strong>fine como:Q(z)=∞∫z12πe x 2−2Para una explicación más <strong>de</strong>tallada sobre los costesC co (μ,σ) y C adj (μ,σ) y el mo<strong>de</strong>lo matemático utilizado,el lector interesado pue<strong>de</strong> consultar las referencias [1,3], don<strong>de</strong> se da una explicación más profunda sobre laformulación utilizada.dxIII. EQUIPO PARALELO DE METAHEURÍSTICASEn este artículo se presenta un equipo heterogéneocompuesto por un conjunto <strong>de</strong> siete metaheurísticas ycontrolado por una hiperheurística (HH) paralela. Elobjetivo <strong>de</strong> la HH no consiste en solucionar el problema<strong>de</strong> manera directa, sino en seleccionar el método mása<strong>de</strong>cuado que <strong>de</strong>be aplicarse ante una <strong>de</strong>terminadasituación. Este método, una metaheurística en nuestrocaso, será el encargado <strong>de</strong> trabajar con el problema. Enla Fig. 1 se pue<strong>de</strong> observar un diagrama que <strong>de</strong>scribe elfuncionamiento general <strong>de</strong>l sistema propuesto.Fig. 1. Diseño <strong>de</strong>l equipo heterogéneo <strong>de</strong> metaheurísticas.Como se pue<strong>de</strong> observar, tanto las especificaciones <strong>de</strong>lproblema como las instancias que <strong>de</strong>ben manejarse songestionadas por un conjunto <strong>de</strong> metaheurísticas que han(5)sido especialmente ajustadas para trabajar con el FAP.<strong>La</strong> tarea <strong>de</strong> la que se encarga la HH consiste en controlarla salida proporcionada por dichas estrategias paradistribuir <strong>de</strong> manera a<strong>de</strong>cuada la carga <strong>de</strong> trabajo <strong>de</strong>acuerdo con la calidad <strong>de</strong> los resultados obtenidos porcada algoritmo. <strong>La</strong> comunicación entre la HH y lasmetaheurísticas no <strong>de</strong>pen<strong>de</strong> <strong>de</strong> las especificaciones <strong>de</strong>lproblema, ya que la HH únicamente recibe en cadasincronización la mejor solución conseguida por cadametaheurística hasta ese momento, su coste asociado yel i<strong>de</strong>ntificador <strong>de</strong>l algoritmo que aportó la citadasolución. De acuerdo con dicha información la HHdistribuye la carga <strong>de</strong> trabajo que cada algoritmo <strong>de</strong>beráprocesar hasta la siguiente sincronización. Al final <strong>de</strong>lproceso, la mejor solución conseguida por una <strong>de</strong> lasmetaheurísticas será la solución que <strong>de</strong>vuelva el sistema.Una <strong>de</strong> las características más interesantes <strong>de</strong> la HH esque ésta hace que las metaheurísticas realicen subúsqueda en paralelo. Como se expondrá en la siguientesección, los experimentos se han realizado en un clúster<strong>de</strong> 128 núcleos, por lo que el diseño <strong>de</strong> la hiperheurísticaparalela saca el máximo partido <strong>de</strong> los recursosdisponibles. Uno <strong>de</strong> los núcleos <strong>de</strong>l clúster ejecutará elproceso maestro <strong>de</strong>l sistema (Algoritmo 1), mientras queel resto <strong>de</strong> núcleos ejecutarán las metaheurísticas<strong>de</strong>stinadas a resolver el problema propiamente dicho.Por tanto, la HH forma parte <strong>de</strong> un sistema síncronodon<strong>de</strong> su tarea es sincronizar y gestionar un equipo <strong>de</strong>algoritmos metaheurísticos con el fin <strong>de</strong> resolver unproblema FAP real.Algoritmo 1 – Pseudocódigo para el proceso maestro <strong>de</strong> la HH1: vectorProbHH ← inicializar_vectorProbHH2: vectorCores ← asignar_metaheurística_a_cada_core (vectorProbHH)3: lanzar_ejecuciones_esclavos (vectorCores)4: mientras (! condición_<strong>de</strong>_parada) hacer5: /* El proceso maestro espera a que cada core ejecute su algoritmo */6: /* Cada sincronización → los cores envían la mejor solución al maestro */7: para (j = 0) hasta (j = número_<strong>de</strong>_cores_configurados) hacer8: vectorSoluciones ← recibir_soluciones_cores (j)9: fin para10: vectorSoluciones ← or<strong>de</strong>nar_soluciones_fitness (vectorSoluciones)11: vectorProbHH ← actualizar_vectorProbHH (vectorSoluciones)12: vectorCores ← actualizar_vectorCores (vectorProbHH)13: mejorSolucion ← seleccionar_mejor_solucion (vectorSoluciones)14: relanzar_ejecuciones_esclavos (vectorCores, mejorSolucion)15: fin mientras16: <strong>de</strong>volver seleccionar_mejor_solucion_recibida (vectorSoluciones)El proceso comienza con la distribución homogénea <strong>de</strong>todas las metaheurísticas incluidas en el sistema, <strong>de</strong>acuerdo con un vector <strong>de</strong> probabilidad inicializado parael efecto (líneas 1 y 2). Este vector <strong>de</strong> probabilidad tienela función <strong>de</strong> <strong>de</strong>cidir el número <strong>de</strong> núcleos queejecutarán cada una <strong>de</strong> las metaheurísticas incluidas enel sistema. Como se pue<strong>de</strong> observar en la Fig. 1 se haseleccionado un conjunto heterogéneo <strong>de</strong> sietemetaheurísticas que se han consi<strong>de</strong>rado representativas.Así, se han seleccionado algunas basadas en población(el algoritmo genético –GA [9], la búsqueda dispersa –SS [10], el algoritmo basado en colonia <strong>de</strong> abejas –ABC[11] y el aprendizaje incremental basado en población –PBIL [12]) y otras basadas en trayectoria (elprocedimiento <strong>de</strong> búsqueda adaptativa, aleatoria yavariciosa –GRASP [13], la búsqueda local iterativa –ILS [14] y la búsqueda <strong>de</strong> entorno variable –VNS [15]).Algunas <strong>de</strong> ellas son estrategias clásicas, como el GA, yotras son muy novedosas, como el ABC. Otras se<strong>JP2011</strong>-127


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011caracterizan por una evolución muy rápida (ILS, VNS) obien por una búsqueda bastante intensivas (ABC, GA).En <strong>de</strong>finitiva, tienen diferentes características que lashacen estrategias complementarias en la búsqueda <strong>de</strong>lvalor óptimo <strong>de</strong>l problema con el que se trabaja.En cualquier caso, una vez que todos los algoritmoshan sido repartidos entre los cores, empezarán suejecución (línea 3) hasta que su condición <strong>de</strong> parada (unlímite temporal) se satisfaga. Por cuestiones <strong>de</strong> espacio,no se explicará en este artículo el esquema <strong>de</strong> cadaalgoritmo, si bien es importante indicar que cada uno hasido sometido a un completo ajuste paramétrico para quese ajuste al problema con el que <strong>de</strong>be trabajar. Elproceso maestro espera hasta que las metaheurísticasterminan su ejecución, en cuyo momento le enviarán lamejor solución encontrada hasta ese momento (línea 8).Cuando todas las soluciones se han recibido, la HH lasor<strong>de</strong>na <strong>de</strong> acuerdo con su calidad y actualiza el vector <strong>de</strong>probabilidad siguiendo un proceso <strong>de</strong> presión selectiva(líneas 10 y 11). A continuación la hiperheurísticareasigna los algoritmos a los núcleos <strong>de</strong>l clúster <strong>de</strong>acuerdo con el nuevo vector <strong>de</strong> probabilidad calculado(línea 12) teniendo en cuenta que ninguna <strong>de</strong>be<strong>de</strong>saparecer por completo <strong>de</strong>l sistema. A<strong>de</strong>más, seenviará a cada núcleo la mejor solución conseguidahasta ese momento (líneas 13 y 14) para que losalgoritmos basados en trayectoria (ILS, VNS y GRASP)continúen su ejecución partiendo <strong>de</strong> dicha solución y losbasados en población (GA, SS, ABC y PBIL) laincluyan a la primera población <strong>de</strong> soluciones generada.Finalmente, cuando la condición <strong>de</strong> parada <strong>de</strong>l sistemase satisfaga (línea 4), que como se verá en la siguientesección es un cierto número <strong>de</strong> sincronizaciones, lahiperheurística <strong>de</strong>volverá la mejor solución conseguidaal final <strong>de</strong> proceso (línea 16), que será una planificación<strong>de</strong> frecuencias <strong>de</strong> alta calidad que <strong>de</strong> solución alproblema FAP abordado en nuestro estudio.IV. EXPERIMENTOS Y RESULTADOSTodos los experimentos se han llevado a cabo en unclúster homogéneo compuesto por 16 nodos multinúcleo.Cada nodo cuenta con 8 núcleos, lo cual hace untotal <strong>de</strong> 128 nodos <strong>de</strong> procesamiento. A<strong>de</strong>más, tal ycomo se especificó en la Sección II <strong>de</strong> este artículo, sehan utilizado dos instancias reales para realizar losexperimentos (Denver y Seattle), cuya topología pue<strong>de</strong>observarse en la Fig. 2. En dicha figura cada triángulorepresenta una antena sectorizada en la que operanvarios TRXs. Denver cuenta con 2616 TRXs yúnicamente 18 frecuencias disponibles, mientras queSeattle consta <strong>de</strong> 970 TRXs y sólo 15 frecuencias.Debido a la naturaleza estocástica <strong>de</strong> lasmetaheurísticas, todos los experimentos realizados ennuestro estudio han sido repetidos <strong>de</strong> manerain<strong>de</strong>pendiente 30 veces, con el fin <strong>de</strong> validarestadísticamente los resultados obtenidos <strong>de</strong> maneraempírica. Por otro lado, para <strong>de</strong>tectar diferencias en laejecución <strong>de</strong> los algoritmos en diferentes periodos <strong>de</strong>tiempo y para po<strong>de</strong>r realizar una comparativa con otrosestudios que resuelven el mismo problema (Tabla I), sehan consi<strong>de</strong>rado tres límites temporales: 120, 600, 1800.En este sentido, no se han tenido en cuenta tiemposinferiores a dos minutos porque, <strong>de</strong>bido a la complejidad<strong>de</strong>l problema, en dichos casos las metaheurísticastendrían <strong>de</strong>masiado poco tiempo para hacer evolucionarlas soluciones, por lo que los resultados no seríansignificativos. Tampoco se han consi<strong>de</strong>rado tiempos queen la mayoría <strong>de</strong> los casos superaran los treinta minutos,ya que éstos serían excesivos para un problema real<strong>de</strong>ntro <strong>de</strong>l dominio abordado.Fig. 2. Topología <strong>de</strong> las instancias GSM utilizadas.Los dos experimentos más relevantes realizados con elequipo <strong>de</strong> metaheurísticas fueron los relevantes alnúmero <strong>de</strong> sincronizaciones que éste <strong>de</strong>bía realizar y a lacomposición <strong>de</strong> las metaheurísticas sobre las que seapoyaba. En el primer caso, si el número <strong>de</strong>sincronizaciones es <strong>de</strong>masiado alto, el sistema gastará<strong>de</strong>masiado tiempo en esta tarea, <strong>de</strong>jando a lasmetaheurísticas sin tiempo suficiente para hacerevolucionar las soluciones. Por el contrario, si serealizan menos sincronizaciones <strong>de</strong> las <strong>de</strong>bidas, lasmetaheurísticas trabajarán <strong>de</strong>masiado tiempo <strong>de</strong> maneraaislada, como islas in<strong>de</strong>pendientes, por lo que losresultados tampoco serán <strong>de</strong> tanta calidad como<strong>de</strong>berían. Por tanto, para llevar a cabo el ajuste <strong>de</strong> lassincronizaciones, se llevó a cabo una serie <strong>de</strong> pruebasutilizando las instancias Denver y Seattle anteriormentemencionadas con el objetivo <strong>de</strong> <strong>de</strong>terminar la frecuenciaóptima <strong>de</strong> sincronizaciones que <strong>de</strong>be realizar la HH paraobtener planificaciones <strong>de</strong> frecuencia <strong>de</strong> la mayorcalidad posible. <strong>La</strong>s Figs. 3 y 4 resumen los resultadosobtenidos con dichos experimentos. Se han realizadopruebas sincronizando el sistema cada minuto, cada 2minutos, cada 5, 10 y 15 minutos. Teniendo en cuentaque la duración total <strong>de</strong>l experimento es <strong>de</strong> 30 minutossignifica que se han hecho pruebas realizando 29, 14, 5,2 y 1 sincronizaciones respectivamente.Fig. 3. Evolución en los resultados obtenidos para la instancia Seattleutilizando diferentes sincronizaciones.<strong>JP2011</strong>-128


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Como se pue<strong>de</strong> observar en la Fig.3, los mejoresresultados cuando se aborda la instancia Seattle seobtienen cuando la HH sincroniza las metaheurísticascada 5 minutos, ya que con esta configuración lasplanificaciones <strong>de</strong> frecuencia generadas tienen un costemenor que los resultados sincronizando cada 2 y cada 10minutos. Sincronizar cada 10 minutos nunca es másprovechoso que cada 5, mientras que un periodo <strong>de</strong>sincronización <strong>de</strong> 2 minutos sólo es ligeramente mejordurante los 8 primeros minutos <strong>de</strong> ejecución (don<strong>de</strong> elsistema sólo se ha sincronizado una vez con laconfiguración <strong>de</strong> realizar sincronizaciones cada 5minutos). Si se configura al sistema con un númeromayor <strong>de</strong> sincronizaciones los resultados son tambiénmuy buenos en los primeros minutos <strong>de</strong> ejecución <strong>de</strong>lalgoritmo (Fig. 3), sin embargo, empeoran mucho trasestos primeros instantes, ya que se invierte <strong>de</strong>masiadotiempo en la operación <strong>de</strong> sincronización, por lo que lasmetaheurísticas no tienen tiempo suficiente para hacerque las soluciones evolucionen a<strong>de</strong>cuadamente.número <strong>de</strong> cores y <strong>de</strong> metaheurísticas trabajando a lavez), pero que únicamente utilizaba uno <strong>de</strong> losalgoritmos. <strong>La</strong> Fig. 5 muestra el resultado <strong>de</strong> esteestudio comparativo para la instancia Seattle. Como sepue<strong>de</strong> observar, el equipo heterogéneo mejorasignificativamente los resultados <strong>de</strong> cualquier equipohomogéneo para cualquier rodaja <strong>de</strong> tiempo estudiada(entre los 2 y los 30 minutos).Fig. 5. Comparativa <strong>de</strong> resultados sobre la instancia Seattle entre lahiperheurística paralela (PHH, equipo heterogéneo) y sieteequipos homogéneos formados por la misma metaheurística.Fig. 4. Evolución en los resultados obtenidos para la instancia Denverutilizando diferentes sincronizaciones.Por otro lado, si se analizan los datos para la instanciaDenver (Fig. 4), se pue<strong>de</strong> observar que los mejoresresultados a corto plazo son alcanzados porconfiguraciones que realizan sincronizaciones cada muypoco tiempo (1 o 2 minutos), sin embargo, a partir <strong>de</strong> los10 minutos, las mejores planificaciones son obtenidas siel sistema se sincroniza cada 5, 10 o incluso 15 minutos.De hecho, si se consi<strong>de</strong>ra la mejor configuración <strong>de</strong>Denver para los 30 minutos completos <strong>de</strong> ejecución, seestablece que la mejor configuración es sincronizar cada10 minutos, sin embargo, si se establece sincronizarcada 5 minutos, el sistema consigue mejores resultadosmedios en muchos más periodos <strong>de</strong> tiempo, tal y comose pue<strong>de</strong> observar en la Fig. 4, don<strong>de</strong> la línea <strong>de</strong> los 5minutos representa la mejor configuración consi<strong>de</strong>rando<strong>de</strong> manera global los 30 minutos <strong>de</strong> ejecución.Otro aspecto importante con el equipo es <strong>de</strong>terminarlas metaheurísticas que formarán parte <strong>de</strong> él. Por estarazón se realizó un estudio comparativo para <strong>de</strong>terminarcómo influía en los resultados la heterogeneidad <strong>de</strong> lasmetaheurísticas incluidas en el equipo. Se realizaronexperimentos comparativos entre un equipo heterogéneo<strong>de</strong> metaheurísticas (que se apoyaba en los sietealgoritmos indicados anteriormente: GA, SS, PBIL,ABC, ILS, VNS y GRASP) con un equipo homogéneoque poseía la misma capacidad <strong>de</strong> cómputo (mismoEn cuanto a la instancia Denver (Fig. 6), también seproduce una mejora bastante significativa en cualquierperiodo <strong>de</strong> tiempo si el equipo se encuentra configurado<strong>de</strong> manera heterogénea, por lo que queda <strong>de</strong> manifiestola importancia <strong>de</strong> este parámetro para el funcionamientoóptimo <strong>de</strong>l equipo.Fig. 6. Comparativa <strong>de</strong> resultados sobre la instancia Denver entre lahiperheurística paralela (PHH, equipo heterogéneo) y sieteequipos homogéneos formados por la misma metaheurística.A. Comparativa con otros autoresEn esta subsección se comparan los resultadosconseguidos por el equipo paralelo diseñado con otrasaproximaciones. <strong>La</strong> Tabla I resume dicha comparativa,don<strong>de</strong> se muestran los resultados medios (y <strong>de</strong>sviacionesestándar) <strong>de</strong> 30 ejecuciones en tres periodos <strong>de</strong> tiempocuando se aborda la resolución <strong>de</strong> la instancia Denvercon diversas técnicas. Los trabajos con los que se<strong>JP2011</strong>-129


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011compara están sujetos a los mismos requerimientos yconsi<strong>de</strong>raciones que el presentado en este documento,por lo que sus resultados representan una fuente <strong>de</strong>comparación excepcional. Los resultados finalesconseguidos por el equipo paralelo explicado en esteartículo aparecen en la primera línea. <strong>La</strong>s siguientes filascontienen los datos arrojados por otros estudiosrelevantes (se incluye su referencia correspondiente).Únicamente el trabajo que aparece en la última fila <strong>de</strong> latabla (GridEA [16]) utiliza un límite temporal diferenteal <strong>de</strong>l resto <strong>de</strong> estudios, ya que el algoritmo <strong>de</strong>sarrolladoen ese estudio fue limitado por iteraciones en lugar <strong>de</strong>por un límite temporal. Sin embargo, el estudio se haincluido en la tabla comparativa porque, hasta don<strong>de</strong>nosotros sabemos, representaba el mejor resultadopublicado en la bibliografía en la resolución <strong>de</strong> lainstancia Denver hasta que fue superado por losresultados obtenidos con la hiperheurística paralela.Como se pue<strong>de</strong> observar en la Tabla I incluso esosresultados (GridEA [16]), que fueron obtenidos <strong>de</strong>spués<strong>de</strong> 1,5 horas <strong>de</strong> ejecución, han sido superados por losresultados conseguidos por la PHH <strong>de</strong>sarrollada, pero enun tercio <strong>de</strong>l tiempo invertido por el sistema grid (30minutos), y utilizando menos recursos hardware.Como se pue<strong>de</strong> observar, el problema FAP ha sidoabordado por diferentes técnicas metaheurísticas yaproximaciones paralelas en los últimos años, sinembargo, hasta don<strong>de</strong> sabemos, el equipo paralelopresentado en este artículo mejora los resultadosobtenidos por otros diseños publicados.TABLA ICOMPARATIVA ENTRE LOS RESULTADOS OBTENIDOS POR LAESTRATEGIA DISEÑADA Y OTROS TRABAJOS RELEVANTES120 segundos 600 segundos 1800 segundosx± σ x± σ x± σEquipo paralelo 87100.2±381.2 85167.9±382.9 84527.4±404.7ACO [7] 93978.2±1165.9 91726.4±1002.9 90382.5±935.3EA [7] 108071.9±1723.4 103535.9±1939.7 99862.3±1553.1GRASP [17] 91225.7±1197.2 89369.6±1185.1 88850.6±1075.2GridGRASP [17] 87256.9±2309.2 86772.1±1701.0 85855.3±686.9ACO [18] 93439.5±1318.9 92325.4±1092.8 90649.9±727.5ssGA [18] 89540.4±991.1 87850.8±573.6 86908.9±379.8SS [18] 94199.6±1172.3 93953.9±1178.6 93820.4±1192.3(1+2)EA [18] 92294.0±1407.6 89669.8±1164.8 88574.3±1100.3LSHR [18] 92061.7±585.3 89430.9±704.2 88550.3±497.0Grid EA [16] Resultados obtenidos en 1,5 horas: 84936.3±375.8V. CONCLUSIONES Y TRABAJO FUTUROEn este artículo se presenta un equipo heterogéneo <strong>de</strong>metaheurísticas para resolver un problema real <strong>de</strong>telecomunicaciones. En concreto se han abordado dosinstancias reales <strong>de</strong> gran tamaño <strong>de</strong>l problema <strong>de</strong> laasignación automática <strong>de</strong> frecuencias. El análisis <strong>de</strong> losresultados arroja una doble conclusión. <strong>La</strong> primeraresalta la importancia <strong>de</strong> configurar el equipo con unconjunto heterogéneo y equilibrado <strong>de</strong> metaheurísticas,ya que aunque algunas funcionen <strong>de</strong> manera máseficiente en algunas circunstancias, otras obtendránmejores resultados en otras (por ejemplo, con distintasmetaheurísticas o diferentes rodajas <strong>de</strong> tiempo, Figs. 5 y6). En este sentido, el análisis <strong>de</strong> los resultados nos llevaa concluir que todas las metaheurísticas incluidas ennuestro equipo contribuyen a la evolución global <strong>de</strong>lsistema. A<strong>de</strong>más, ha quedado <strong>de</strong> manifiesto que la mejorconfiguración en cuanto a sincronizaciones es realizarlascada 5 minutos (Figs. 3 y 4). Finalmente, se ha realizadouna comparación con otros estudios presentes en labibliografía (Tabla I) <strong>de</strong> la que se pue<strong>de</strong> extraer que losresultados conseguidos por el sistema propuesto mejoranlos resultados <strong>de</strong> otras publicaciones relevantes.Como trabajo futuro, tenemos la intención <strong>de</strong> aplicar elequipo diseñado a instancias <strong>de</strong>l problema FAP aúnmayores así como el <strong>de</strong> abordar otros problemasrelevantes <strong>de</strong>ntro <strong>de</strong>l dominio <strong>de</strong> las comunicaciones,como el RWA (Routing and Wavelength Assignment,enrutamiento y asignación <strong>de</strong> longitu<strong>de</strong>s <strong>de</strong> onda [19]).AGRADECIMIENTOSEl presente trabajo ha sido parcialmente financiado porel Ministerio <strong>de</strong> Ciencia e Innovación y el FEDER(Fondo Europeo <strong>de</strong> Desarrollo Regional), bajo elproyecto TIN2008-06491-C04-04 (proyecto M*).REFERENCIAS[1] K. I. Aardal, S. P. M. van Hoesel, et al., “Mo<strong>de</strong>ls and solutiontechniques for frequency assignment problems”, Annals ofOperations Research, 153 (1), 79-129, 2007.[2] FAP Web: http://fap.zib.<strong>de</strong>/, 2010.[3] A. Eisenblätter, “Frequency Assignment in GSM Networks:Mo<strong>de</strong>ls, Heuristics, and Lower Bounds”, PhD thesis, TechnischeUniversität Berlin, 2001.[4] C. Blum, y A. Roli, “Metaheuristics in CombinatorialOptimization: Overview and Conceptual Comparison”, ACMComputing Surveys, 35, pp: 268-308, 2003.[5] M. Mouly, y M.B. Paulet, “The GSM System for MobileCommunications”. Telecom Publishing, 1992.[6] A.R. Mishra, Fundamentals of Cellular Network Planning andOptimisation: 2G/2.5G/3G... Evolution to 4G, chapter: “RadioNetwork Planning and Optimization”, pp: 21-54, Wiley, 2004.[7] F. Luna, C. Blum, E. Alba, A.J. Nebro, “ACO vs EAs forSolving a Real World Frequency Assignment Problem in GSMNetworks”, GECCO’07, pp: 94-101, 2007.[8] B.H. Walke, “Mobile Radio Networks: Networking, Protocolsand Traffic Performance”, Wiley, 2002.[9] D. E. Goldberg, “Genetic Algorithms in Search, Optimization,and Machine Learning”, Addison-Wesley, 1989.[10] R. Martí, M. <strong>La</strong>guna, F. Glover. “Principles of scatter search”,European Journal of Operational Research, 169 (2), 359-372,2006.[11] D. Karaboga, B. Basturk, “A powerful and efficient algorithm fornumerical function optimization: artificial bee colony (ABC)algorithm”, Journal of Global Optimization, Springer, 39, 459-471, 2007.[12] S. Baluja, “Population-based Incremental Learning: A Methodfor Integrating Genetic Search based Function Optimization andCompetitive Learning”. Technical Report CMU-CS-94-163,Carnegie Mellon University, Junio 1994.[13] T.A. Feo, M.G. Resen<strong>de</strong>, “Greedy Randomized Adaptive SearchProcedures”, Journal of Global Optimization, 6, 109-133, 1995.[14] H.R. Lourenço, O. Martin, T. Stützle, Handbook ofMetaheuristics, chapter “Iterated local search”, KluwerAca<strong>de</strong>mic Publishers, 321-353, 2002.[15] N. Mla<strong>de</strong>novic, P. Hansen, “Variable neighborhood search”,Computers and Operations Research, 24 (11), 1097-1100, 1997.[16] F. Luna, A. J. Nebro, et al., “Solving large-scale real-worldtelecommunication problems using a grid-based geneticalgorithm”, Engineering Optimization, 40 (11), 1067-1084, 2008.[17] J. M. Chaves-González, R. Hernando-Carnicero, et al., “Solvinga Realistic FAP Using GRASP and Grid Computing”. Advancesin Grid and Pervasive Computing (GPC 2009), pp. 79-90, 2009.[18] F. Luna, C. Estébanez, et al., “Metaheuristics for Solving a Real-World Frequency Assignment Problem in GSM Networks”,GECCO’08, pp. 1579-1586, 2008.[19] A. Rubio-<strong>La</strong>rgo, M. A. Vega-Rodríguez, et al., “A DifferentialEvolution with Pareto Torunaments for solving the Routing andWavelength Assignment Problem in WDM Networks”, CEC2010, pp. 129-136, 2010.<strong>JP2011</strong>-130


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Determination of traffic control tables by HPCEligius M.T. Hendrix, Siham Tabik 1 and Rene Haijema 2Resumen— The concept of traffic control tables(TCT) for an intersection is sketched and a StochasticDynamic Programming mo<strong>de</strong>l is outlined. The <strong>de</strong>terminationof a TCT by dynamic programming becomesmore cumbersome if more traffic flows and combinationof lights are taken into account. This paper explainshow High Performance Computing (HPC) canbe essential to do this job and sketches the challengesof this research question.Palabras clave— Stochastic Dynamic Programming,traffic control, parallel implementation, Markov chainTABLA ITCT for F2C2 when lights show all-redq 1 q 2 0 1 2 3 4 50 2 2 2 2 2 21 1 2 2 2 2 22 1 1 2 2 2 23 1 1 1 2 2 24 1 1 1 1 2 25 1 1 1 1 1 2Fig. 1.I. IntroducciónSituation F2C2; at most one of two flows gets priorityTraffic lights are introduced at the beginning of theprevious century to make road traffic safer, at placeswhere traffic from different directions cross the sameroad segment, called the intersection or crossing. Bygiving right of way to traffic in some direction(s),cars approaching from other directions need to waitbefore they get priority. By controlling the trafficlights, the overall <strong>de</strong>lay or waiting time of the carscan be kept to a minimum. In literature, the problemis studied by queueing theorist as well as engineers(see [5], [6], [9],[8], [10]). An optimal dynamic policyis not reported except in [4].The basis of optimal traffic control on a singleintersection is what we call a traffic control table(TCT) that prescribes which combination of flowsshould be given the right of way given the amountof cars waiting in every queue. For illustration consi<strong>de</strong>rthe simple situation in Figure 1, called in [3]the F2C2 case for having 2-Flows in 2-Combinations.Either the left, or right flow has a green light, or alllights are red to clear the intersection. For the ease ofreasoning, we abstract here from using amber lights.Table I illustrates the concept of a TCT. It marksthe <strong>de</strong>cision of which light to set on green, given thequeue length of both queues, when the light is in theall-red state. In this example λ 2 > λ 1 , such that onequal queue length, it is convenient to give flow 2the right of way. [4] mo<strong>de</strong>l the generation of such atable as a Stochastic Dynamic Programming (SDP)1 Dpto. Arquitectura <strong>de</strong> Computadores, Univ. De Málaga,e-mail: eligius, stabik @uma.es.2 Operations Research and Logistics group, Wageningen University,e-mail: rene.haijema@wur.nl.problem in or<strong>de</strong>r to find that TCT that minimizesthe expected total waiting time in the system.In Section II, the SDP mo<strong>de</strong>l is outlined and theiterative process to obtain traffic control tables fromthat. Section III <strong>de</strong>scribes the parallel programmingapproach used to exploit multicore systems. SectionIV provi<strong>de</strong>s the experimental set up where a computationalillustration is given in Section V. Finally,Section VI conclu<strong>de</strong>s.II. TCT by Stochastic DynamicProgrammingThere are numerous ways to mo<strong>de</strong>l traffic flows.We focus here on a Markov chain view with timeslots are thought of as to be that big that one carcan pass by on a green light, usually taken as twoseconds. The state is <strong>de</strong>scribed by the vector (q, l),where the vector q tracks the number of cars in eachqueue and l ∈ {0, . . . , ncomb} indicates the state ofthe light, i.e. which of the ncomb combination hasright of way (l = 0 represents the all-red state).The probabilities of going from one state to theother <strong>de</strong>pend on the TCT as well as on the probabilitiesλ j of a car arriving at the queues j (for allj ∈ {1, . . . , nflow}. In or<strong>de</strong>r to get a finite statespace to allow numerical computations the queuelength is truncated to a maximum size Q, such thatq j ∈ {0, . . . , Q}.For the F2C2 case of Figure 1, this means that thestate space is 3-dimensional: (q 1 , q 2 , l). The numberof possible states is ns = (ncomb+1)×(Q+1) nflow =3(Q + 1) nflow . Consi<strong>de</strong>r the F4C2 case of Figure 2.The state space is 5 dimensional and the number ofstates is ns = 3(Q + 1) 4 . We observe that the numberof states grows exponentially fast in the numberof queues; this called the curse of dimensionalityin solving an SDP problem. Nevertheless up to theF4C2 case, Haijema conclu<strong>de</strong>s that an optimal policycan relatively easily be computed on a PC witha single processor. Although the curse of dimensionalityis not resolved by HPC, HPC may stretch thecomputational limit beyond the F4C2 case.To find a TCT that minimizes the expected wait-<strong>JP2011</strong>-131


| m0<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 3.Value function <strong>de</strong>terminationFig. 2.Situation with 4 flows and 2 symmetric combinationsing time we apply the so-called value iteration (VA)algorithm (for <strong>de</strong>tails see [7] and [3]). First a costnflow∑function C(q, l) = q j is <strong>de</strong>fined that capturesj=1the waiting time during the coming time slot forthe current state (q, l). Note that by Little’s lawminimizing the expected number of cars waiting alsominimizes the overall expected waiting time. Next aso-called value vector V n (q, l) that gives a valuationfor each state over the next n time slots, is to becomputed for n = 1, 2, 3, . . .. Clearly the cost over0 periods is zero, hence we start the value iterationalgorithm with n = 0 and V n (q, l) = 0 for all states(q, l). Then one <strong>de</strong>termines iteratively optimum <strong>de</strong>cisionsa such thatV n+1 (q, l) = C(q, l) + min E e|a V n (T (q, l, a, e))awhere T is a transformation function that gives thestate at which to arrive when at the current state,the <strong>de</strong>cision a is taken and arrival event e happens.The whole is sketched in Figure 3. Notice thatthe number of possible events is 2 nflow , as at eachqueue, a car may arrive or not. The probabilitiesare <strong>de</strong>termined from the vector of traffic intensities(λ 1 , . . . , λ nflow ). If l = 0, i.e. all lights are red, the<strong>de</strong>cision a ∈ {1, . . . , ncomb}, i.e. one of the combinationscan be given a green light. In the other cases,there are 2 possibilities; either the light stays as it is,or is put in the all-red state to clear the intersection.Fig. 4.in |max20 30 40 5010Convergence of the span for the F4C2 instance, calculatedby the parallel co<strong>de</strong> on a quad-socket eight-coreIntel X7550 (Beckton).Convergence100 150 200 #iterations 50 0III. Coding Value iterationThe value iteration process requires running the iterationsup to convergence. At each iteration all valuesfor the ns states of V n+1 have to be <strong>de</strong>termined.If l = 0, this requires looking up ncomb × 2 nflow valuesin V n . As we have seen, this is less if one of thecombinations is green. We should look up 2 nflow+1and take the minimum over the two <strong>de</strong>cisions.V n(ns)V n+1(ns)(2,ncomb) {0,…,2 nflow }iFig. 5. Each V n+1 (i) is <strong>de</strong>termined using 2 or ncomb ×Q nflowelements of V n, <strong>de</strong>pending on the state of light.In summary, the iterative process of value iterationfor the TCT generation can be sketched as follows:……The converging part in the process is the differenceV n+1 −V n converging to a constant vector whichrepresents the average waiting time in the system.Practical implementations require the translation ofthe state (q, l) to a state number i and vice versa,such that one works with two arrays with elementsV n+1 (i) and V n (i). The convergence is measured bykeeping hold of the so-called span <strong>de</strong>fined as span =max i (V n+1 (i) − V n (i)) − min i (V n+1 (i) − V n (i)). Thisis illustrated in Figure 4.for(i=0;i < nflows;i++)q[i]=1;while(1){for(i=0;i


0<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011if (max-min


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA IIArchitecural summary of the multi-core platform used in the experimentsIntel X7550 4 socketscores/socket SMT L1D cache L2 cache L3 cache memory8 yes 8×32KB 8×256KB 1×18MB 128GBexploit the potential of multi-socket multi-core architectures.Preliminary speedups of the data-sharingimplementation have been measured for a mediumsized instance called F4C2.Currently, we are exploring new techniques suchas software prefetching and cache blocking to furtherimprove the performance of the data-sharingimplementation at one Socket level. In addition,we are working on optimizing the communicationsin the data-privatizing implementation to improvethe performance among multiple Sockets. The intentionis to apply the techniques to the F12C4 casegiven in Figure 8. for which no optimum TCT hasbeen <strong>de</strong>rived yet. Updating one value of the valuefunction requires the evaluation of several times 2 12states due to the possible events. Moreover, using aminimum queue length of Q = 2, this has to be donefor 5 × 3 12 = 2.7 mln states. Future investigationwill look at using interpolation to keep the numberof states limited to that number.[3] R. Haijema, Solving large structured markov <strong>de</strong>cisionproblems for perishable inventory management and trafficcontrol, Ph.D. thesis, Univeristy of Amsterdam - TinbergenInstitute - Amsterdam School of Economics, 122008.[4] R. Haijema and J. van <strong>de</strong>r Wal, An MDP <strong>de</strong>compositionapproach for traffic control at isolated signalized intersections,Probability in the Engineering and InformationalSciences 22 (2008), no. 4, 587–602.[5] G. F. Newell, Approximation methods for queues withapplications to the fixed-cycle traffic light, SIAM Review7 (1965), no. 2, 223–240.[6] M. Papageorgiou, C. Diakaki, V. Dinopoulou, A. Kotsialos,and Y. Wang, Review of road traffic control strategies,Proc. of the IEEE, vol. 91, IEEE, 2003, pp. 2043–2067.[7] M. L. Puterman, Markov <strong>de</strong>cision processes: Discretestochastic dynamic programming, Wiley Series in Probabilityand Mathematical Statistics, 1994.[8] M. S. van <strong>de</strong>n Broek, J. S. H. van Leeuwaar<strong>de</strong>n, I. J. B. F.Adan, and O. J. Boxma, Bounds and approximations forthe fixed-cycle traffic-light queue, Transportation Science40 (2006), 484–496.[9] J. S. H. van Leeuwaar<strong>de</strong>n, Delay analysis for the fixed cycletraffic light queue, Transportation Science 40 (2006),no. 2, 189–199.[10] M. Wiering, J. van Veenen, J. Vreeken, and A. Koopman,Intelligent traffic light control, technical report UU-CS-2004-029, Institute of information and computing sciences,Utrecht University, 2004.Fig. 8.Instance of intersection with 12 flows, 4 combinationsAgra<strong>de</strong>cimientosThis work is supported by grants from the SpanishMinistry of Science and Innovation (TIN2008-01117, TIN2006-01078), Junta <strong>de</strong> Andalucía (P08-TIC-3518), in part financed by the European RegionalDevelopment Fund (ERDF). Eligius Hendrixis fellow of the Spanish “Ramon y Cajal” contractprogram and Siham Tabik of the “Juan <strong>de</strong> la Cierva”program, co-financed by the European Social Fund.Referencias[1] The OpenMP API specification for parallel programming,http://openmp.org/wp/openmp-specifications/.[2] Intel Compilers for Linux, http://software.intel.com/enus/articles/intel-c-compiler-professional-edition-forlinux-documentation/(2009).<strong>JP2011</strong>-134


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Evaluación <strong>de</strong>l método <strong>de</strong>l GradienteBiconjugado para matrices dispersas en GPUs.G. Ortega 1 , E. M. Garzón 1 , F. Vázquez 1 , I. García 2Resumen— En una gran variedad <strong>de</strong> aplicaciones<strong>de</strong> diferentes disciplinas científicas y relacionadas conla ingeniería, se requiere la resolución <strong>de</strong> sistemas<strong>de</strong> ecuaciones no simétricos y complejos. Para resolvereste tipo <strong>de</strong> sistemas <strong>de</strong> ecuaciones lineales, elMétodo <strong>de</strong>l Gradiente Biconjugado se consi<strong>de</strong>ra especialmenterelevante, ya que es capaz <strong>de</strong> resolver sistemas<strong>de</strong> ecuaciones complejos y no simétricos. Sinembargo, <strong>de</strong>s<strong>de</strong> el punto <strong>de</strong> vista computacional, elmétodo BCG es muy costoso <strong>de</strong>bido a los productosmatriz vector (SpMV) involucrados en dicho algoritmo.Por lo tanto, para acelerar dicho métodoes necesaria la explotación <strong>de</strong> Computación <strong>de</strong> AltasPrestaciones (HPC). <strong>La</strong> computación GPU haemergido como una nueva técnica <strong>de</strong> HPC que ofreceun paralelismo masivo y, por tanto, pue<strong>de</strong> ser consi<strong>de</strong>radacomo una valiosa herramienta para acelerareste tipo <strong>de</strong> algoritmos. En este trabajo se muestraque el método BCG pue<strong>de</strong> ser acelerado <strong>de</strong> una formaeficiente si las operaciones SpMV se computan en laGPU. Hemos consi<strong>de</strong>rado dos implementaciones distintas<strong>de</strong>l método BCG en la GPU: CuBCG SP (basadoen la librería CUSPARSE) y CuBCG ET (basado enla rutina ELLR-T). Ambos <strong>de</strong>sarrollos han sido evaluadospara dos conjuntos <strong>de</strong> matrices <strong>de</strong> testeo <strong>de</strong>tipo complejo y real, ambos en simple precisión. Losresultados experimentales han mostrado que ambosmétodos, CuBCG SP y CuBCG ET , obtienen rendimientossuperiores a la implementación con múltiples cores<strong>de</strong>l BCG. Sin embargo, CuBCG ET alcanza el mejorrendimiento, especialmente para el conjunto <strong>de</strong> matrices<strong>de</strong> tipo complejo.Palabras clave—Método <strong>de</strong>l Gradiente Biconjugado,computacion GPU, computación paralela, sistemas <strong>de</strong>ecuaciones lineales.I. IntroducciónEL algoritmo <strong>de</strong>l Gradiente Conjugado (CG) esuno <strong>de</strong> los métodos iterativos más utilizadospara la resolución <strong>de</strong> sistemas simétricos positivos<strong>de</strong>finidos [1], [2]. Dicho método es especialmenteapropiado para resolver sistemas <strong>de</strong> ecuaciones linealesen los que intervienen matrices dispersas <strong>de</strong>dimensiones consi<strong>de</strong>rables. Sin embargo, el métodoCG no es a<strong>de</strong>cuado para sistemas no simétricos. Así,el Método <strong>de</strong>l Gradiente Biconjugado (BCG), unageneralización <strong>de</strong>l CG, es capaz <strong>de</strong> resolver sistemas<strong>de</strong> ecuaciones lineales simétricos y complejos con suficienteprecisión. Sin embargo, el método BCGrequiere operaciones con un alto coste computacionalen cada iteración. Esto significa un esfuerzoadicional: la utilización <strong>de</strong> Computación <strong>de</strong> AltasPrestaciones (HPC) para acelerar la computación <strong>de</strong>lmétodo BCG.Actualmente, las Unida<strong>de</strong>s <strong>de</strong> Proceso Gráfico1 Dpt. Arquitectura y Electrónica, <strong>Universidad</strong> <strong>de</strong>Almería, e-mail: glortega@ual.es, gmartin@ual.es,f.vazquez@ual.es2 Dpt. Arquitectura, <strong>Universidad</strong> <strong>de</strong> Málaga, e-mail:igarcia@ac.uma.es(GPU) son plataformas que ofrecen un paralelismomasivo y, por tanto, pue<strong>de</strong>n resultar <strong>de</strong> utilidad paraacelerar este tipo <strong>de</strong> algoritmos. En la literatura sehan implementado y evaluado diversos <strong>de</strong>sarrollos <strong>de</strong>los métodos CG y BCG [3], [4], [5]. Sin embargo,en este estudio se obtienen mejores rendimientos enel <strong>de</strong>sarrollo <strong>de</strong> implementaciones HPC <strong>de</strong>l métodoBCG basadas en computaciones GPU.<strong>La</strong>s arquitecturas GPU pue<strong>de</strong>n trabajar como eficientescoprocesadores <strong>de</strong> supercomputación y supo<strong>de</strong>r pue<strong>de</strong> ser aplicado a una gran variedad <strong>de</strong> aplicaciones,en particular en aquellas relacionadas conoperaciones matriciales. <strong>La</strong>s GPUs constan <strong>de</strong> cientos<strong>de</strong> cores que pue<strong>de</strong>n ejecutar <strong>de</strong> forma colectivamiles <strong>de</strong> threads <strong>de</strong> computación. Cada core, llamadoProcesador Escalar (SP), pertenece a un conjunto<strong>de</strong> unida<strong>de</strong>s multiprocesadoras llamadas MultiprocesadoresStreaming (SM) que componen el dispositivo.Por lo tanto, los últimos avances en latecnología GPU se han centrado en el <strong>de</strong>sarrollo <strong>de</strong>Interfaces <strong>de</strong> Programación <strong>de</strong> aplicaciones (APIs),tales como la Arquitectura Unificada <strong>de</strong> Dispositivos<strong>de</strong> Cómputo (CUDA) <strong>de</strong> NVIDIA, que claramentefacilitan la programación <strong>de</strong> aplicaciones sobreGPUs. En los últimos años, el uso <strong>de</strong> las GPUs paraaplicaciones <strong>de</strong> propósito general ha crecido estrepitosamente<strong>de</strong>bido a la evolución tanto <strong>de</strong> las fuentes<strong>de</strong> programación GPU como <strong>de</strong> las tecnologías semiconductoras.De este modo, las GPUs han emergidocomo nuevas plataformas <strong>de</strong> computación que ofrecenun paralelismo masivo y proporcionan un altoratio <strong>de</strong> rendimiento para la computación científica.Una aproximación para facilitar la programaciónGPU es el uso tanto <strong>de</strong> rutinas básicas como <strong>de</strong> librerías,ya que: (1) tienen optimizadas las operacionesmás utilizadas en diversas aplicaciones y (2)pue<strong>de</strong>n ser aceleradas <strong>de</strong> forma óptima a través <strong>de</strong> lasGPUs. En esta línea, NVIDIA suministra un amplioconjunto <strong>de</strong> rutinas relacionadas con diversos tipos<strong>de</strong> aplicaciones tales como CuBLAS, CuFFT o CUS-PARSE [6].Centrándonos en este estudio, las plataformasGPU nos permiten exten<strong>de</strong>r el método BCG parapo<strong>de</strong>r resolver sistemas <strong>de</strong> ecuaciones lineales <strong>de</strong>mayor dimensión. Esto es <strong>de</strong>bido al hecho <strong>de</strong> que lacomputación GPU acelera las dos operaciones SpMVrequeridas por el método BCG. Dicha operación esla que tiene un mayor coste computacional en dichoalgoritmo, por lo tanto, pue<strong>de</strong> ser consi<strong>de</strong>radacomo la clave en el <strong>de</strong>sarrollo <strong>de</strong>l método BCG sobreplataformas GPUs. En la literatura es posibleencontrar varias implementaciones <strong>de</strong> la operaciónSpMV basadas en la computación CUDA [6], [7], [8],<strong>JP2011</strong>-135


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011[9], [10]. Particularmente, nuestro trabajo se ha centradoen dos kernels <strong>de</strong> CUDA para computar lasoperaciones SpMV involucradas en el método BCG:(1) el kernel SpMV <strong>de</strong> la librería CUSPARSE [6] y (2)el kernel ELLR-T, basado en el formato ELLPACK-R [10], [11]. Para realizar una intensa evaluación<strong>de</strong>l rendimiento <strong>de</strong> ambas aproximaciones, hemosutilizado dos conjuntos representativos <strong>de</strong> matrices(reales y complejas). El estudio comparativo hallegado a la conclusión <strong>de</strong> que la aproximación <strong>de</strong>lmétodo BCG basada en la rutina ELLR-T alcanzalos mejores rendimientos.<strong>La</strong> Sección II revisa el método BCG. <strong>La</strong> Sección IIIintroduce las dos implementaciones <strong>de</strong>l método BCGque se han <strong>de</strong>sarrollado: CuBCG CS , basada en elkernel CUSPARSE, y CuBCG ET , basada en el kernelELLR-T. <strong>La</strong> Sección IV evalúa ambas aproximacionesen una arquitectura GPU GTX 480. Para ello,se utilizan dos conjuntos representativos <strong>de</strong> matrices<strong>de</strong> testeo <strong>de</strong> tipo real y complejo que tienen distintospatrones <strong>de</strong> regularidad. Los resultados claramentemuestran que el método BCG basado en la rutinaELLR-T obtiene los mejores rendimientos para todaslas matrices <strong>de</strong> testeo consi<strong>de</strong>radas. Finalmente,la Sección V resume las principales conclusiones.II. Método <strong>de</strong>l Gradiente BiconjugadoEl Método <strong>de</strong>l Gradiente Biconjugado (BCG) proporcionauna generalización <strong>de</strong>l CG, ya que se reemplazanlas secuencias ortogonales <strong>de</strong> residuos por dossecuencias mutuamente ortogonales, al coste <strong>de</strong> proporcionaruna minimización [12], [13].El método BCG (propuesto por <strong>La</strong>nczos [14], [15]y discutido por Fletcher [16] y Jacobs [17]) es unmétodo iterativo no estacionario capaz <strong>de</strong> solucionarsistemas <strong>de</strong> ecuaciones lineales Ax = b, don<strong>de</strong> lamatriz A ∈ C N×N pue<strong>de</strong> ser no simétrica. Para elsistema <strong>de</strong> ecuaciones dado, A <strong>de</strong>nota el coeficiente(disperso) la matriz, b indica el término in<strong>de</strong>pendientey x es la solución vector.El Algoritmo 1 muestra el pseudocódigo para elMétodo <strong>de</strong> Gradiente Biconjugado. A<strong>de</strong>más, en dichoalgoritmo también se muestran los ór<strong>de</strong>nes <strong>de</strong>complejidad <strong>de</strong> las operaciones más costosas computacionalmente.Destaquemos que nz <strong>de</strong>nota elnúmero los elementos no nulos <strong>de</strong> A y N el número <strong>de</strong>filas. El coste computacional asociado a la operaciónSpMV es el mayor, ya que el resto <strong>de</strong> las operacionesson productos escalares. Es importante resaltar quecada iteración implica el cómputo <strong>de</strong> la operaciónSpMV utilizando las matrices A y A T (líneas 9 y13 <strong>de</strong> Algoritmo 1), don<strong>de</strong> la operación SpMV sobreA T representa una penalización en el rendimiento <strong>de</strong>lmétodo BCG.III. Implementación <strong>de</strong>l Método <strong>de</strong>lGradiente Biconjugado sobre GPUsEn el algoritmo 1 las operaciones más costosascomputacionalmente son los productos matriz vector(SpMV), especialmente cuando las matrices involucradastienen un número elevado <strong>de</strong> elementos no nu-Algoritmo 1 Método <strong>de</strong>l Gradiente BiconjugadoEntrada: Definir EP S = Umbral <strong>de</strong> precisiónSalida: El valor <strong>de</strong> x (i) .1: Computar r (0) = b − Ax (0) para un inicial x (0)2: Elegir r ′(0) = r (0) ; p ′(0) = 0; p (0) = p ′(0) ; ρ ′(0) = 13: Calcular ∆ (0) = norm2(r (0) ) O(4N)4: for i = 1, 2, ... do5: ρ (i) = (r ′(i−1) , r (i−1) ) O(8N)6: β (i) = ρ (i) /ρ ′(i−1)7: p (i) = r (i−1) + β (i) p (i−1) O(8N)8: p ′(i) = r ′(i−1) + β (i) p ′(i−1) O(8N)9: v (i) = Ap (i) O(8nz)10: α (i) = ρ (i) /(p ′(i) , v (i) ) O(8N)11: x (i) = x (i−1) + p (i) α (i) O(8N)12: r (i) = r (i−1) − v (i) α (i) O(8N)13: r ′(i) = r ′(i−1) − α (i) (A T p ′(i) ) O(8nz + 8N)14: ∆ (i) = norm2(r (i) ) O(4N)15: if ∆ (i) < ∆ (0) EP S then16: return x (i)17: else18: ρ ′(i) = ρ (i)19: end if20: end forlos, nz (ver el coste computacional <strong>de</strong> cada operaciónen el Algoritmo 1). En cada iteración <strong>de</strong>l métodoBCG, se computan dos operaciones SpMV con lasmatrices A y A T . Como se comentó anteriormente,cuando la operación SpMV utiliza la traspuesta <strong>de</strong>la matriz el tiempo consumido es mayor. Esto es <strong>de</strong>bidoa las penalizaciones relacionadas con la pérdida<strong>de</strong> localidad en el acceso a los elementos <strong>de</strong> A T . Porlo tanto, para superar esta pérdida en el rendimiento,nuestras implementaciones almacenan ambas matrices,A y A T , como dos matrices dispersas distintas.De este modo, se mantiene la localidad en el acceso alos elementos <strong>de</strong> ambas matrices en todas las operacionesSpMV. Para matrices A <strong>de</strong> gran dimensión, laalta complejidad computacional <strong>de</strong>l SpMV requiere<strong>de</strong> la explotación <strong>de</strong> técnicas <strong>de</strong> Computación <strong>de</strong> AltoRendimiento. Por lo tanto, nuestro interés se centraen acelerar tanto las operaciones SpMVs como elresto <strong>de</strong> operaciones con vectores, para así mejorar elrendimiento <strong>de</strong> todo el método BCG. <strong>La</strong>s aproximacionesutilizadas para acelerar este algoritmo estánbasadas en la computación GPU, ya que las plataformasGPUs pue<strong>de</strong>n ser utilizadas como un acelerador<strong>de</strong>l SpMV [6], [11], [18].CUDA es la Interfaz <strong>de</strong> Programación <strong>de</strong> Aplicaciones(API) <strong>de</strong>sarrollada por NVIDIA para facilitarla programación <strong>de</strong> las GPUs. Utilizando la interfazCUDA, la GPU es consi<strong>de</strong>rada por el programadorcomo un conjunto <strong>de</strong> multiprocesadores coninstrucciones SIMT (Simple Instrucción, MúltiplesHilos) [19]. Cada kernel (código paralelo) se ejecutacomo un grupo <strong>de</strong> hilos organizado como un grid <strong>de</strong>bloques <strong>de</strong> hilos cuya configuración es <strong>de</strong>finida porel programador, al establecer ciertos parámetros específicos.Uno <strong>de</strong> estos parámetros es el tamaño <strong>de</strong>lbloque <strong>de</strong> hilos, a partir <strong>de</strong> aquí <strong>de</strong>nominado BS.En tiempo <strong>de</strong> ejecución, los bloques son mapeados<strong>de</strong> forma cíclica en los SMs. Los bloques, en turnos,son divididos en conjuntos <strong>de</strong> hilos llamados warps,el tamaño <strong>de</strong> warp (ws = 32) está <strong>de</strong>finido por la ar-<strong>JP2011</strong>-136


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011quitectura. Actualmente, los SMs están compuestospor treinta y dos SPs en las arquitecturas Fermi másextendidas [19], [20].Para optimizar la explotación <strong>de</strong> la arquitecturaGPU <strong>de</strong> NVIDIA, el programador tien<strong>de</strong> a maximizar:(1) el ratio entre el número <strong>de</strong> warps activospor multiprocesador y el número máximo <strong>de</strong> (posibles)warps activos; este propósito se pue<strong>de</strong> lograr:eligiendo el valor óptimo <strong>de</strong> BS, balanceando la carga<strong>de</strong> trabajo <strong>de</strong> los hilos y evitando las instrucciones <strong>de</strong>control <strong>de</strong> flujo que podrían causar la divergencia <strong>de</strong>los hilos, (por ejemplo, manteniendo los multiprocesadoresen el dispositivo tan ocupados como sea posible);y (2) el ancho <strong>de</strong> banda <strong>de</strong> memoria; el manejo<strong>de</strong> la memoria se optimiza cuando el patrón <strong>de</strong> acceso<strong>de</strong> los diferentes hilos pertenecientes a cada halfwarp(16 hilos) verifica las condiciones <strong>de</strong> coalescenciay alineamiento. Los accesos a memoria pue<strong>de</strong>nllevarse a cabo en paralelo y la latencia <strong>de</strong> memoriasería la misma que para un solo acceso. A<strong>de</strong>más, elhecho <strong>de</strong> utilizar la cache <strong>de</strong> texturas como memoriacache mejora el rendimiento [19].Aparte <strong>de</strong> CUDA, NVIDIA proporciona un conjunto<strong>de</strong> rutinas básicas o librerías (CuBLAS yCuFFT) que aceleran <strong>de</strong> forma óptima una ampliavariedad <strong>de</strong> operaciones con matrices sobre GPUs.Se han <strong>de</strong>sarrollado múltiples implementaciones <strong>de</strong>lSpMV basadas en CUDA [6], [7], [8], [9], [10] ya quela operación SpMV es, en realidad, la clave en el <strong>de</strong>sarrollo<strong>de</strong>l método BCG utilizando GPUs.Nosotros hemos seleccionado dos implementacionesCUDA para computar el SpMV con el fin<strong>de</strong> implementar el método BCG sobre GPUs: (1)el kernel incluido en la librería CUSPARSE [6] y(2) el kernel ELLR-T que está basado en el formatoELLPACK-R [10], [11]. <strong>La</strong> evaluación comparativa<strong>de</strong>scrita en [10] muestra que ELLR-T alcanza unrendimiento mejor que otras aproximaciones para laoperación SpMV sobre GPUs. Sin embargo, la rutinapara computar el SpMV <strong>de</strong> la librería CUSPARSEno está incluida en el mencionado estudio. En nuestrotrabajo, hemos seleccionado ambos kernels paracomputar la operación SpMV y po<strong>de</strong>r <strong>de</strong>sarrollar elmétodo BCG sobre GPUs.<strong>La</strong> clave <strong>de</strong> este artículo es el <strong>de</strong>sarrollo y evaluación<strong>de</strong> las implementaciones <strong>de</strong>l BCG basadasen ambos kernels. En a<strong>de</strong>lante, la implementaciónbasada en la librería CUSPARSE será referenciadacomo CuBCG CS , y la implementación basada en larutina ELLR-T se <strong>de</strong>nominará CuBCG ET . A continuaciónse <strong>de</strong>scriben ambas aproximaciones con <strong>de</strong>talle:• CuBCG CS se basa en la librería CUSPARSEla cual proporciona un conjunto <strong>de</strong> subrutinasbásicas <strong>de</strong> álgebra lineal para el manejo <strong>de</strong> matricesdispersas. El formato utilizado para compactarlas matrices es el <strong>de</strong> almacenamientocomprimido por fila (CRS). El paradigma <strong>de</strong>la librería CUSPARSE es el siguiente: se <strong>de</strong>finenmúltiples bloques, B i , en función <strong>de</strong> la dimensión<strong>de</strong> A, don<strong>de</strong> cada bloque está encargado<strong>de</strong> procesar un grupo <strong>de</strong> filas, (G j ). Y acada fila se le asignada un grupo <strong>de</strong> hilos, T k .A<strong>de</strong>más, se han tenido en cuenta una serie <strong>de</strong>consi<strong>de</strong>raciones adicionales para incrementar elrendimiento: (1) ajustar el número <strong>de</strong> hilos porfila para evitar el <strong>de</strong>sequilibrio entre hilos; (2)alinear hilos por fila para favorecer la coalescenciay (3) utilizar tanto la memoria compartidacomo la memoria <strong>de</strong> texturas [6].• CuBCG ET se basa en la rutina <strong>de</strong> ELLR-T cuyoformato es el ELLPACK-R, el cual permite almacenarla matriz dispersa <strong>de</strong> una forma regular.Para el formato ELLR-T, cada conjunto<strong>de</strong> T hilos calcula un elemento <strong>de</strong>l vector <strong>de</strong>salida. El acceso <strong>de</strong> la matriz a la memoriaglobal es coalescente y alineado. Según el mapeado<strong>de</strong> los hilos en la computación <strong>de</strong> cada fila,se pue<strong>de</strong>n ejecutar múltiples configuraciones <strong>de</strong>lformato ELLR-T. Para optimizar el rendimiento<strong>de</strong>l método, los valores <strong>de</strong> dos parámetros. elnúmero <strong>de</strong> hilos (T ) y el tamaño <strong>de</strong> bloque <strong>de</strong>los hilos (BS), <strong>de</strong>ben modificarse para cada tipo<strong>de</strong> matrices dispersasEn la siguiente sección se muestran los rendimientosobtenidos al evaluar la operación SpMV sobrelos formatos CUSPARSE y ELLR-T, así comopara nuestras implementaciones <strong>de</strong>l método BCG:CuBCG CU y CuBCG ET .IV. EvaluaciónPara evaluar los tiempos <strong>de</strong> ejecución <strong>de</strong> nuestros<strong>de</strong>sarrollos, hemos empleado dos conjuntos distintos<strong>de</strong> matrices dispersas sobre la plataforma GPUGeForce GTX 480. Estas matrices <strong>de</strong> testeo proce<strong>de</strong>n<strong>de</strong> un amplio espectro <strong>de</strong> disciplinas relacionadascon la ciencia y la ingeniería. Por lo tanto, po<strong>de</strong>mosencontrar tanto matrices regulares y bien estructuras,como matrices con una gran irregularidady <strong>de</strong>sequilibrio en el número <strong>de</strong> elementos no nulospor fila. <strong>La</strong> Tabla I ilustra los principales parámetros<strong>de</strong> estas matrices: número <strong>de</strong> filas (N), número total<strong>de</strong> elementos no nulos (nz) y promedio <strong>de</strong> entradaspor fila (Av). Resulta <strong>de</strong> interés <strong>de</strong>stacar que la dimensión<strong>de</strong> todas las matrices es N x N.En los experimentos realizados para evaluar elrendimiento <strong>de</strong> los kernels CUSPARSE y ELLR-T, para cada matriz <strong>de</strong> prueba, se ha consi<strong>de</strong>radola configuración óptima <strong>de</strong> los parámetros T yBS. A<strong>de</strong>más, los productos escalares se han aceleradogracias a la librería CUBLAS. En cuanto alos conjuntos <strong>de</strong> matrices <strong>de</strong> tipo real y complejo,los elementos han sido almacenados como uno o dosnúmeros reales, respectivamente.<strong>La</strong> figura 1 muestra el rendimiento (GFLOPs)<strong>de</strong> la operación SpMV sobre la plataforma GPUGeForce GTX 480, utilizando los kernels CUS-PARSE y ELLR-T (para tipos <strong>de</strong> datos reales y complejos).Cada prueba ha consistido en 1000 ejecuciones<strong>de</strong> la rutina SpMV, obteniendo así tiempos <strong>de</strong>ejecución fiables. Los lenguajes <strong>de</strong> programación utilizadospara diseñar los códigos han sido C y CUDA.<strong>JP2011</strong>-137


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA ICaracterísticas <strong>de</strong> las matrices <strong>de</strong> testeo.Matriz real N nz Avwbp 16384 3933097 240cant 62451 4007384 64pdb1HYS 36417 4344766 119consph 83334 6010481 72shipsec1 140874 7813404 55pwtk 217918 11634425 53wbp256 65536 31413934 479Matriz compleja N nz Avkim1 38415 933195 24femfilter 74062 1731206 23NN70 729000 5086618 7NN80 1000000 6979798 7NN90 1331000 9292578 7kim2 456976 11330020 24femhifreqcircuit 491100 20239237 41Los resultados <strong>de</strong> la Figura 1 muestran que losmejores rendimientos para todas las matrices consi<strong>de</strong>radasson alcanzados por ELLR-T. Esto es <strong>de</strong>bidoa que dicho kernel es capaz <strong>de</strong> adaptarse al patrón<strong>de</strong> las matrices dispersas involucradas en el sistema,utilizando para ello el parámetro T . El kernel CUS-PARSE, sin embargo, presenta una pobre flexibilidadya que dicho parámetro no pue<strong>de</strong> ser modificado.Es importante resaltar que el rendimiento <strong>de</strong>ambos formatos normalmente incrementa al aumentarel número <strong>de</strong> elementos no nulos <strong>de</strong> la matriz.<strong>La</strong>s mejoras <strong>de</strong> rendimiento <strong>de</strong> la operación SpMValcanzadas por los kernels ELLR-T y CUSPARSE<strong>de</strong>notan que las implementaciones <strong>de</strong>l método BCGbasado en SpMV ELLR-T y SpMV CUSPARSEpue<strong>de</strong>n obtener buenos rendimientos. Por lotanto, hemos realizado un análisis comparativo <strong>de</strong>lrendimiento <strong>de</strong> las dos aproximaciones para resolverel método BCG: el método CuBCG CS (basado en elkernel CUSPARSE) y el método CuBCG ET (basadoen el kernel ELLR-T).<strong>La</strong> Figura 2 muestra el rendimiento (GFLOPs) alcanzadopor los métodos CuBCG CS y CuBCG ETpara la resolución <strong>de</strong> sistemas <strong>de</strong> ecuaciones lineales,reales y complejos, respectivamente. Para el objetivo<strong>de</strong> estimar el rendimiento proporcionado por GPUSpara estos métodos, hemos consi<strong>de</strong>rado los mismosvalores <strong>de</strong> los parámetros <strong>de</strong> la mejor configuraciónpara las operaciones SpMV, cuyo rendimiento se ilustraen la Figura 1.Los resultados mostrados en la Figura 2 ilustranlas siguientes consi<strong>de</strong>raciones: (1) el rendimientoobtenido por ambos métodos aumenta al incrementarseel número <strong>de</strong> entradas no nulas en la matriz.Este comportamiento sugiere que, en general,conforme la dimensión <strong>de</strong> las matrices aumente, elrendimiento será mejor (sobre todo para el conjunto<strong>de</strong> matrices complejas). (2) Para ambos conjuntos<strong>de</strong> matrices consi<strong>de</strong>radas, los mejores rendimientosson alcanzados por el método CuBCG ET .Fig. 1Rendimiento <strong>de</strong> la operación SpMV basada en loskernels CUSPARSE y ELLR-T sobre GPU GeForceGTX 480 con dos conjuntos <strong>de</strong> matrices <strong>de</strong> testeo(reales y complejas).Para estimar las mejoras proporcionadas por laGPU en las dos implementaciones <strong>de</strong>l método BCG,hemos consi<strong>de</strong>rado la versión optimizada <strong>de</strong>l SpMVpara un procesador mo<strong>de</strong>rno. Esta implementación<strong>de</strong>l método BCG está basada en la librería MKL [21]para el cómputo <strong>de</strong> las operaciones SpMV sobre unprocesador superescalar actual (Intel Xeon Westmerecon 8 procesadores). <strong>La</strong> Tabla II muestra los factores<strong>de</strong> ganancia obtenidos por los métodos CuBCG CS yCuBCG ET sobre la GPU GTX 480 frente a la ejecución<strong>de</strong>l método BCG sobre un procesador <strong>de</strong> ochonúcleos, consi<strong>de</strong>rando los dos conjuntos <strong>de</strong> matrices<strong>de</strong> testeo. Los resultados muestran que los factores<strong>de</strong> ganancia en ambos <strong>de</strong>sarrollos GPU son mejoresque la implementación multicore. Así, CuBCG CSCuBCG ET toman ventaja <strong>de</strong>l paradigma <strong>de</strong> programación<strong>de</strong> las GPUs.Para las matrices <strong>de</strong> testeo consi<strong>de</strong>radas, los speedup alcanzan valores entre 1,95× y 11,60× para elmétodo CuBCG ET y entre 1,03× y 5,07× para elmétodo CuBCG CS . <strong>La</strong> Tabla II ilustra que el speedup alcanzado por CuBCG ET es siempre mayor queel <strong>de</strong> CuBCG CS para todas las matrices. Merece lapena <strong>de</strong>stacar que este hecho es más relevante cuandolas matrices son <strong>de</strong> tipo complejo.<strong>JP2011</strong>-138


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA IISpeed Up para los métodos CuBCG CS y CuBCG ETfrente a la versión multicore (8 cores) <strong>de</strong>l BCGutilizando la librería MKL.Matriz real CuBCG CS CuBCG ETwbp128 3,48 4,44cant 1,76 2,40pdb1HYS 3,43 4,78consph 1,89 2,29shipsec1 3,12 3,99pwtk 1,68 2,62wbp256 4,09 4,41Matriz compleja CuBCG CS CuBCG ETkim1 1,03 1,95femfilter 1,38 3,16NN70 4,94 8,88NN80 5,07 9,27NN90 3,52 11,60kim2 1,90 6,92femhifreqcircuit 2,93 7,25Fig. 2Rendimiento <strong>de</strong> las aproximaciones BCG (CuBCG CS yCuBCG ET ) sobre GPU GeForce GTX 480 con dosconjuntos <strong>de</strong> matrices <strong>de</strong> testeo (reales andcomplejas).V. ConclusiónSe han <strong>de</strong>sarrollado dos implementaciones <strong>de</strong>lmétodo BCG (CuBCG CS y CuBCG ET ) con el objetivo<strong>de</strong> resolver sistemas <strong>de</strong> ecuaciones lineales nosimétricos y complejos utilizando GPUs. Tanto losproductos escalares como las operaciones SpMV involucradosen las iteraciones <strong>de</strong>l método BCG hansido acelerados utilizando GPUs. Para ello, se han<strong>de</strong>sarrollado dos métodos, CuBCG CS y CuBCG ET ,basados en los kernels CUSPARSE y ELLR-T, capaces<strong>de</strong> computar la operación SpMV en la GPU,respectivamente. Los resultados <strong>de</strong> evaluación muestranque el rendimiento para ambas implementaciones<strong>de</strong>pen<strong>de</strong> fuertemente <strong>de</strong>l patrón <strong>de</strong> la matriz<strong>de</strong> coeficientes. Sin embargo, <strong>de</strong>spués <strong>de</strong> un extensoestudio utilizando dos conjuntos <strong>de</strong> matrices<strong>de</strong> testeo, se pue<strong>de</strong> concluir que la implementaciónCuBCG ET claramente alcanza el mejor rendimientogracias al hecho <strong>de</strong> que el kernel ELLR-T en el quese basa, pue<strong>de</strong> ser mejor adaptado a los diferentespatrones <strong>de</strong> las matrices dispersas. Este hecho esespecialmente relevante para matrices <strong>de</strong> tipo complejoya que la consi<strong>de</strong>ración <strong>de</strong>l espacio complejoenvuelve un mayor número <strong>de</strong> operaciones en puntoflotante.A<strong>de</strong>más, la evaluación <strong>de</strong>l método CuBCG ET enuna GPU GeForce GTX 480 ha revelado que los factores<strong>de</strong> aceleración tienen un rango entre 2× y 12×en comparación con la versión optimizada <strong>de</strong>l métodoBCG que explota el estado <strong>de</strong>l arte <strong>de</strong> un procesadorsuperescalar con 8 núcleos.Por último, resaltar que nuestra implementaciónCuBCG ET basada en la computación GPU permiteexten<strong>de</strong>r la dimensión <strong>de</strong>l sistema <strong>de</strong> ecuaciones linealesa resolver para así po<strong>de</strong>r tratar con un rangomayor <strong>de</strong> aplicaciones.Agra<strong>de</strong>cimientosEste trabajo ha sido parcialmente financiado porsubvenciones <strong>de</strong> la Junta <strong>de</strong> Andalucía (P08-TIC-3518, P10-TIC-6002) y el Ministerio <strong>de</strong> Ciencia e Innovación(TIN2008-01117), en parte financiado porel Fondo Europeo <strong>de</strong> Desarrollo Regional (FEDER).Referencias[1] Gene H. Golub and Charles F. van Van Loan, MatrixComputations (Johns Hopkins Studies in MathematicalSciences)(3rd Edition), The Johns Hopkins UniversityPress, Oct. 1996.[2] Yousef Saad, Iterative Methods for Sparse Linear Systems,Second Edition, Society for Industrial and AppliedMathematics, Apr. 2003.[3] Abhijeet Gaikwad and Ioane Muni Toke, “Parallel iterativelinear solvers on gpu: A financial engineering case,”in Proceedings of the 2010 18th Euromicro Conferenceon Parallel, Distributed and Network-based Processing,Washington, DC, USA, 2010, PDP ’10, pp. 607–614,IEEE Computer Society.[4] Norberto Garcia, “Parallel power flow solutions using abiconjugate gradient algorithm and a newton method: Agpu-based approach,” July 2010, pp. 1–4.<strong>JP2011</strong>-139


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011[5] Marcin Wozniak, Tomasz Olas, and RomanWyrzykowski, “Parallel implementation of conjugategradient method on graphics processors,” inParallel Processing and Applied Mathematics, RomanWyrzykowski, Jack Dongarra, Konrad Karczewski, andJerzy Wasniewski, Eds., vol. 6067 of Lecture Notesin Computer Science, pp. 125–135. Springer Berlin /Hei<strong>de</strong>lberg, 2010.[6] NVIDIA, “Cuda cusparse library,” Tech. Rep., September2010.[7] M M Baskaran and R Bordawekar, “Optimizing sparsematrix-vector multiplication on GPUs,” Tech. Rep. ResearchReport RC24704, IBM, April 2009.[8] J W Choi, A Singh, and RW Vuduc, “Mo<strong>de</strong>l-driven autotuningof sparse matrix-vector multiply on GPUs,” inPPoPP ’10: Proceedings of the 15th ACM SIGPLANsymposium on Principles and practice of parallel programming,New York, NY, USA, 2010, pp. 115–126,ACM.[9] NVIDIA, “Cusp library,” Tech. Rep., October 2010.[10] F Vázquez, G Ortega, J J Fernán<strong>de</strong>z, and E M Garzón,“Improving the performance of the sparse matrix vectorproduct with GPUs,” in 10th IEEE International Conferenceon Computer and Information Technology. CIT2010. 2010, pp. 1146–1151, IEEE Computer Society.[11] F. Vázquez, J. J. Fernán<strong>de</strong>z, and E. M. Garzón, “A newapproach for sparse matrix vector product on NVIDIAGPUs,” Concurr. Comput. : Pract. Exper., vol. 23, pp.815–826, June 2011.[12] R. Barrett, M. Berry, T. F. Chan, J. Demmel, J. Donato,J. Dongarra, V. Eijkhout, R. Pozo, C. Romine,and H. Van <strong>de</strong>r Vorst, Templates for the Solution ofLinear Systems: Building Blocks for Iterative Methods,2nd Edition, SIAM, Phila<strong>de</strong>lphia, PA, 1994.[13] William H. Press, Saul A. Teukolsky, William T. Vetterling,and Brian P. Flannery, “Numerical recipes in c: Theart of scientific computing. second edition,” 1992.[14] C. <strong>La</strong>nczos, “An iteration method for the solution ofthe eigenvalue problem of linear differential and integraloperators,” J . Res. Nat. Bur. Stand., vol. 45, pp. 255–282, 1950.[15] Cornelius <strong>La</strong>nczos, “Solution of systems of linear equationsby minimized iterations,” J. Res. Natl. Bur. Stand,vol. 49, pp. 33–53, 1952.[16] R. Fletcher, “Conjugate gradient methods for in<strong>de</strong>finitesystems,” vol. 506, pp. 73–89. Springer Berlin / Hei<strong>de</strong>lberg,1976.[17] D. A. H. Jacobs, “The exploitation of sparsity by iterativemethods in sparse matrices and their uses,” I. S. Duff.,pp. 191–222, 1981.[18] Nathan Bell and Michael Garland, “Implementing sparsematrix-vector multiplication on throughput-oriented processors,”in Proceedings of the Conference on High PerformanceComputing Networking, Storage and Analysis,New York, NY, USA, 2009, SC ’09, pp. 18:1–18:11, ACM.[19] NVIDIA, “Cuda programming gui<strong>de</strong>. version 2.3,” 2009.[20] NVIDIA, “Next generation CUDA architecture. FermiArchitecture,” 2010.[21] INTEL, “Math kernel library. reference manual,” 2009.<strong>JP2011</strong>-140


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Paralelización <strong>de</strong>l cálculo <strong>de</strong> coeficientes <strong>de</strong>lMétodo <strong>de</strong> Elementos <strong>de</strong> Contorno en laresolución <strong>de</strong> problemas <strong>de</strong> contactotermoelástico 3DRaquel González 1 , Lidia Sánchez 2 y José Vallepuga 3Resumen— Este artículo propone varios algoritmosparalelos para la optimización <strong>de</strong> una aplicación <strong>de</strong>sarrolladaen Fortran para la resolución <strong>de</strong> problemas<strong>de</strong> contacto entre sólidos tridimensionales mediante elmétodo <strong>de</strong> los elementos <strong>de</strong> contorno (MEC). El uso<strong>de</strong> librerías <strong>de</strong> funciones paralelas como MPI permitela consecución <strong>de</strong> gran<strong>de</strong>s mejoras en cuanto a tiempo<strong>de</strong> cálculo <strong>de</strong> forma sencilla. Los experimentos realizadosen un cluster <strong>de</strong> memoria distribuida muestranla efectividad <strong>de</strong> este tipo <strong>de</strong> programación.Palabras clave— Problemas <strong>de</strong> contacto termoelástico,Método <strong>de</strong> los Elementos <strong>de</strong> Contorno, MPI,paralelización.I. IntroducciónEN los últimos tiempos, se han <strong>de</strong>sarrollado diversasaplicaciones que implementan el Método <strong>de</strong>los Elementos <strong>de</strong> Contorno (MEC) aplicado a distintoscampos, como pue<strong>de</strong>n ser la obtención <strong>de</strong> imágenes<strong>de</strong> origen electromagnético [1], la resolución<strong>de</strong> problemas <strong>de</strong> dispersión acústica [2], o, como ennuestro caso, la resolución <strong>de</strong> problemas <strong>de</strong> contacto,tanto para el caso bidimensional [3], [4], como para eltridimensional [5]. En [6] se propone un método iterativopara resolver problemas <strong>de</strong> contacto termoelásticoentre sólidos tridimensionales usando MEC. Apesar <strong>de</strong> que el MEC hace uso <strong>de</strong> una cantidad muchomenor <strong>de</strong> datos y <strong>de</strong> cálculo que otros métodosnuméricos como el MEF (Método <strong>de</strong> los ElementosFinitos), sigue requiriendo <strong>de</strong> gran<strong>de</strong>s cantida<strong>de</strong>s <strong>de</strong>tiempo y <strong>de</strong> memoria para su ejecución. Por estarazón, se pue<strong>de</strong>n encontrar diversos trabajos queversan sobre la optimización <strong>de</strong> los cálculos, minimizandoel espacio y tiempo requeridos mediante eluso <strong>de</strong> sistemas <strong>de</strong> memoria distribuida, clusters <strong>de</strong>computadores, etc.Por ejemplo, para el caso bidimensional, Kreinmeyery Stein [7] realizan una comparativa entre dosimplementaciones paralelas <strong>de</strong>l MEC: una para la resolucióndirecta <strong>de</strong>l sistema <strong>de</strong> ecuaciones linealesmediante <strong>de</strong>scomposición LU, y otra para la resolución<strong>de</strong> dicho sistema <strong>de</strong> forma iterativa. Para elcaso tridimensional, Natarajan y Krinshnaswamy [8]implementan MEC <strong>de</strong> forma paralela para un sistema<strong>de</strong> memoria distribuida. Para la paralelización,1 Dpto. <strong>de</strong> Ingenierías Mecánica, Informática y Aeroespacial,Univ. <strong>de</strong> León2 Dpto. <strong>de</strong> Ingenierías Mecánica, Informática y Aeroespacial,Univ. <strong>de</strong> León, e-mail: lidia.sanchez@unileon.es3 Dpto. <strong>de</strong> Tecnología Minera, Topografía y <strong>de</strong> Estructuras,Univ. <strong>de</strong> Leónrealizan el particionamiento <strong>de</strong> datos mediante eluso <strong>de</strong> una topología <strong>de</strong> procesadores (taurus 2D).Bucheau et al. [9] aplican distintas estrategias<strong>de</strong> paralelización sobre una matriz comprimida medianteFMM (Fast Multipole Method), como son lavectorización, la programación multihilo en sistemas<strong>de</strong> memoria compartida, y la programación multiprocesoen sistemas <strong>de</strong> memoria distribuida. Cunha etal. [10], [11], [12] presentan en sus distintos trabajosla utilización <strong>de</strong> librerías <strong>de</strong> programación paralela,<strong>La</strong>pack y Sca<strong>La</strong>pack, para la paralelización <strong>de</strong> códigosque implementan el MEC tanto en sistemas <strong>de</strong>memoria compartida, como en sistemas <strong>de</strong> memoriadistribuida. En ambos casos hacen uso <strong>de</strong> unatopología <strong>de</strong> procesadores para el particionamiento<strong>de</strong> datos.En este artículo se <strong>de</strong>tallan un conjunto <strong>de</strong> implementacionesparalelas <strong>de</strong>l MEC, realizadas medianteel uso <strong>de</strong> la librería MPI, en un sistema <strong>de</strong> memoriadistribuida.II. MétodosA. Introducción al problema<strong>La</strong> paralelización se ha realizado sobre un código<strong>de</strong>sarrollado en Fortran en [6] para la resolución <strong>de</strong>problemas termoelásticos <strong>de</strong> contacto entre sólidostridimensionales mediante el método <strong>de</strong> los elementos<strong>de</strong> contorno. El código está dividido en 3 partesperfectamente diferenciadas:1. <strong>La</strong> discretización <strong>de</strong> los sólidos, que en nuestrocaso consiste en generar un malla <strong>de</strong> elementostriangulares constantes sobre el contorno <strong>de</strong> dichossólidos.2. El cálculo <strong>de</strong> los coeficientes, el cual necesita <strong>de</strong>lcálculo <strong>de</strong> una integral <strong>de</strong> contorno que se realiza<strong>de</strong>s<strong>de</strong> cada uno <strong>de</strong> los nodos sobre cada uno<strong>de</strong> los elementos que forman el contorno. Comoen este caso el método utilizado consi<strong>de</strong>ra tansólo un nodo por elemento, es necesario resolverN 2 integrales, siendo N el número <strong>de</strong> elementosque forman el mallado. Este número pue<strong>de</strong>aumentar en función <strong>de</strong>:• <strong>La</strong>s subdivisiones: cuando un nodo se integrasobre un elemento próximo, este elemento sesubdivi<strong>de</strong> con el fin <strong>de</strong> generar una malla másfina. Esto permite una mejor precisión, perotambién incrementa el número <strong>de</strong> integrales aresolver.<strong>JP2011</strong>-141


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011• <strong>La</strong>s simetrías: cuando un problema presentasimetría, los elementos simétricos no se almacenanen memoria, pero hay que tenerlos encuenta a la hora <strong>de</strong> realizar los cálculos, yaque no es necesario integrar <strong>de</strong>s<strong>de</strong> los nodos<strong>de</strong> estos elementos, pero sí hay que integrarsobre ellos.3. El montaje y resolución <strong>de</strong>l sistema <strong>de</strong> ecuacioneslineales generado a partir <strong>de</strong> los coeficientescalculados en el paso anterior. Se trata<strong>de</strong> un sistema <strong>de</strong> N × N ecuaciones para el problematérmico <strong>de</strong> potencial, y <strong>de</strong> un sistema <strong>de</strong>3N × 3N ecuaciones para el problema elástico.Cuando se trata <strong>de</strong> un problema termoelástico,se <strong>de</strong>ben resolver ambos sistemas.B. Cálculo <strong>de</strong> coeficientesEn este artículo, presentamos una primera aproximaciónpara la paralelización <strong>de</strong>l cálculo <strong>de</strong> los coeficientes.Este paso es relativamente fácil <strong>de</strong> abordar,ya que cada una <strong>de</strong> las integrales <strong>de</strong> contorno es in<strong>de</strong>pendiente<strong>de</strong>l resto.Como se ha indicado anteriormente (sección II-A), han <strong>de</strong> integrarse todos los nodos sobre todoslos elementos, incluido el elemento al que pertenece.Cuando un nodo se integra sobre sí mismo se resuelveuna integral analítica, mientras que si se integra sobreotro diferente, se resuelve una integral numérica.De esta forma, el algoritmo secuencial utilizado seríael <strong>de</strong>tallado en el Algorimo 1.Algoritmo 1 Algoritmo secuencial para el cálculo<strong>de</strong> coeficientes.for i = 1 → N do {<strong>de</strong>s<strong>de</strong> cada elemento}for j = 1 → N do {sobre cada nodo}if i = j thenIntegralAnalitica(e i )elseIntegralNumerica(e i ,e j )end ifend forend forA partir <strong>de</strong> éste, se han implementado dos algoritmosdiferentes <strong>de</strong> distribución <strong>de</strong>l trabajo entre losdistintos procesadores.B.1 Distribución directaEn este primer algoritmo, se distribuye el trabajo<strong>de</strong> uno <strong>de</strong> los bucles <strong>de</strong> foma equitativa entre losdistintos procesadores.Si distribuimos el bucle interior, es <strong>de</strong>cir, los elementos,en cada iteración <strong>de</strong>l bucle exterior, se integrael elemento e i sobre N/p nodos, y se envíanlos resultados al procesador maestro (ver Algoritmo2). En este caso el envío y recepción <strong>de</strong> datos seproduce <strong>de</strong>l or<strong>de</strong>n <strong>de</strong> N × nEsclavos veces, perola cantidad <strong>de</strong> datos a enviar es relativamente pequeña(N/nEsclavos) siendo nEsclavos el número<strong>de</strong> procesadores esclavos.Algoritmo 2 Algoritmo paralelo. Distribución <strong>de</strong>lbucle interior.for i = 1 → N doif rank ≥ 0 then {si es procesador esclavo}for j = 1 → N/nEsclavos doif i = j thenIntegralAnalitica(e i )elseIntegralNumerica(e i ,e j )end ifPack() {empaqueta los datos para su envío}end forSend(datos,0) {enviamos datos empaquetadosal maestro}else {si es procesador maestro}for j = 1 → nEsclavos doRecv(datos,j) {recibimos datos empaquetados<strong>de</strong>s<strong>de</strong> cada esclavo}Unpack() {<strong>de</strong>sempaquetamos los datos recibidos}end forend ifend forSi distribuimos el bucle exterior, es <strong>de</strong>cir, los nodos,se integran grupos <strong>de</strong> N/nEsclavos elementossobre N nodos en cada procesador esclavo, y se envíanlos resultados al maestro (ver Algoritmo 3). Eneste caso el envío y recepción <strong>de</strong> datos se producetan sólo nEsclavos veces, pero la cantidad <strong>de</strong> datosa enviar es mucho mayor (N/nEsclavos × N).Algoritmo 3 Algoritmo paralelo. Distribución <strong>de</strong>lbucle exterior.if rank ≥ 0 then {si es procesador esclavo}for i = 1 → N/nEsclavos dofor j = 1 → N doif i = j thenIntegralAnalitica(e i )elseIntegralNumerica(e i ,e j )end ifPack() {empaqueta los datos para su envío}end forend forSend(datos,0) {enviamos datos empaquetados almaestro}else {si es procesador maestro}for i = 1 → nEsclavos doRecv(datos,i) {recibimos datos empaquetados<strong>de</strong>s<strong>de</strong> cada esclavo}Unpack() {<strong>de</strong>sempaquetamos los datos recibidos}end forend ifUna comparativa entre estas dos distribuciones semuestra en la figura 1 y en la tabla I. En ella sepue<strong>de</strong> apreciar que las diferencias entre los tiemposno son muy significativas, pero son algo menores losobtenidos mediante la distribución <strong>de</strong>l bucle interior,<strong>JP2011</strong>-142


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011a pesar <strong>de</strong> ser la que mayor comunicación conlleva.Fig. 1. Comparativa <strong>de</strong> tiempos en función <strong>de</strong>l bucle distribuido.En ambos casos, cuando se emplean 1 ó 2 esclavos,el tiempo <strong>de</strong> ejecución no mejora respecto al casosecuencial <strong>de</strong>bido a la penalización <strong>de</strong> tiempo existente enla comunicación con el maestro. A partir <strong>de</strong> 4 esclavosla mejora es significativa. Con 8 esclavos conseguimos eltiempo mínimo. A partir <strong>de</strong> 8, la penalización <strong>de</strong> tiempoen la comunicación vuelve a ser mayor que la mejora quesupone añadir un procesador más para el cálculo.TABLA IComparativa <strong>de</strong> tiempos <strong>de</strong> ejecución y porcentajes<strong>de</strong> reducción en función <strong>de</strong>l bucle distribuidoBucle InteriorBucle ExteriorTiempo % tiempo Tiempo % tiempo0 46,96 100,00 46,96 100,002 56,33 119,97 60,68 129,234 28,75 61,23 31,56 67,216 18,92 40,29 22,57 48,068 4,54 9,68 6,57 13,9910 9,27 19,75 11,60 24,7015 6,45 13,74 11,98 25,5220 6,71 14,29 10,18 21,67B.2 Creación <strong>de</strong> una topología <strong>de</strong> procesadoresAlgunos autores proponen la creación <strong>de</strong> unatopología <strong>de</strong> procesadores para la distribución <strong>de</strong>lcálculo <strong>de</strong> coeficientes. Como el objetivo <strong>de</strong>l cálculo<strong>de</strong> estas integrales es el montaje <strong>de</strong> la matriz<strong>de</strong>l sistema <strong>de</strong> ecuaciones lineal, Geng et al. [2] proponendistribuir el montaje <strong>de</strong> esta matriz, ya seaasignando a cada procesador un bloque <strong>de</strong> matriz arellenar (para lo cual cada procesador necesita losdatos <strong>de</strong> todos los elementos), o asignando a cadaprocesador la información <strong>de</strong> un subconjunto <strong>de</strong> elementosque colaboran en la formación <strong>de</strong> la matrizglobal (para lo cual cada procesador necesita teneracceso a toda la matriz).Nuestro programa usa un algoritmo iterativo parala resolución <strong>de</strong>l sistema <strong>de</strong> ecuaciones lineales, <strong>de</strong>forma que en cada iteración se monta la matriz <strong>de</strong>lsistema a partir <strong>de</strong> los resultados <strong>de</strong> las integrales <strong>de</strong>contorno, y se resuelve, repitiendo el proceso hastaque la solución converja. Es por esto que, en nuestrocaso, primero realizamos todas las integrales <strong>de</strong>contorno y guardamos los resultados. A pesar <strong>de</strong>que esto supone un gasto consi<strong>de</strong>rable <strong>de</strong> memoria,supone también un ahorro consi<strong>de</strong>rable en tiempo <strong>de</strong>cómputo, ya que a la hora <strong>de</strong> realizar el montaje noes necesario volver a resolver las integrales.Para almacenar los resultados, lo que buscamos esrellenar una matriz <strong>de</strong> coeficientes <strong>de</strong> la forma⎛⎞A 1,1 · · · A 1,N⎜A =⎝..⎟. ⎠A N,1 · · · A N,Ndon<strong>de</strong> A i,j es el resultado <strong>de</strong> la integración <strong>de</strong>l elementoi sobre el nodo j.Para ello, creamos una topología <strong>de</strong> procesadores⎛P =⎜⎝⎞P 1,1 · · · P 1,C..⎟. ⎠P R,1 · · · P R,Csiendo R el número <strong>de</strong> filas y C el <strong>de</strong> columnas.P i,j es cada uno <strong>de</strong> los procesadores <strong>de</strong> quedisponemos, y se encargará <strong>de</strong> integrar N/R elementossobre N/C nodos, o lo que es lo mismo, rellenaruna submatriz <strong>de</strong> A <strong>de</strong> N/R × N/C elementos.III. Resultados experimentalesLos experimentos se han realizado en el clusterMPI <strong>de</strong>l supercomputador Caléndula <strong>de</strong> la Fundación<strong>de</strong>l Centro <strong>de</strong> Supercomputación <strong>de</strong> Castilla yLeón. El código paralelo se ha programado medianteel uso <strong>de</strong> funciones <strong>de</strong> la librería MPI para Fortran.El problema sobre el que se han realizado los experimentosse trata <strong>de</strong> un problema termoelásticocon simetría respecto al plano YZ, que ha sido discretizadoen un total <strong>de</strong> 5120 elementos, lo que significaque han <strong>de</strong> resolverse 5120 × (2 × 5120) integrales<strong>de</strong> contorno, es <strong>de</strong>cir, cada nodo <strong>de</strong>be integrarsesobre todos los elementos y sobre sus simétricos.Hasta ahora sólo se ha programado la resolución<strong>de</strong>l problema para topologías <strong>de</strong> procesadorescuadradas, es <strong>de</strong>cir, en las que R = C.<strong>La</strong> figura 2 y la tabla II muestran una comparativa<strong>de</strong> tiempos entre los dos algoritmos <strong>de</strong> paralelizaciónprobados.TABLA IIComparativa <strong>de</strong> tiempos <strong>de</strong> ejecución y porcentajes<strong>de</strong> reducción entre la distribución directa y el uso<strong>de</strong> una topología <strong>de</strong> procesadores (5120 elementos)Distribución directaTopologíaTiempo % tiempo Tiempo % tiempo1x1 46,96 100,00 46,26 100,002x2 37,32 79,48 46,01 99,453x3 5,63 11,98 18,08 39,094x4 5,65 12,04 11,54 24,945x5 4,53 9,65 9,14 19,75<strong>JP2011</strong>-143


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 2. Comparativa entre la distribución directa y el uso<strong>de</strong> una topología <strong>de</strong> procesadores para 5120 elementos.Des<strong>de</strong> la topología cuadrada más pequeña, y en relaciónal caso secuencial (1x1), los tiempos <strong>de</strong> ejecución mejoranprogresivamente, aunque en menor medida que en el caso<strong>de</strong> la distribución directa, don<strong>de</strong> el balanceo <strong>de</strong> carga esmejor.Como se pue<strong>de</strong> observar, para un número elevado<strong>de</strong> procesadores, presenta mejores tiempos el algoritmo<strong>de</strong> distribución directa. Esto se <strong>de</strong>be a que,como se mencionó en el apartado II-B, cuando se integra<strong>de</strong>s<strong>de</strong> un elemento sobre sí mismo, la integral esanalítica, y en otro caso numérica. Esto provoca quepara el caso <strong>de</strong> distribución directa la carga <strong>de</strong> trabajoesté mejor distribuida, ya que cada procesador<strong>de</strong>be integrar los nodos que se le envían sobre el total<strong>de</strong> elementos, incluidos ellos mismos, mientras que enel caso <strong>de</strong> utilizar la topología <strong>de</strong> procesadores, aquellosque no están situados sobre la diagonal principalen la matriz <strong>de</strong> procesadores, no realizarán ningunaintegral analítica.A<strong>de</strong>más, para el caso en que la ejecución se realizaen 9 procesadores es mucho mejor el algoritmo <strong>de</strong>distribución directa. Esto es resultado <strong>de</strong> que 2560,que es el número total <strong>de</strong> elementos, es divisible entre8, que son los esclavos entre los que se reparte lacarga <strong>de</strong> trabajo en el algoritmo <strong>de</strong> distribución directa;sin embargo, 2560 no es divisible entre 3, quees el número <strong>de</strong> procesadores en cada fila y en cadacolumna en el caso <strong>de</strong> utilizar una topología.<strong>La</strong> figura 3 y la tabla III muestran una comparativapara un segundo problema, en este caso un problemaelástico sin simetría, en que el número <strong>de</strong> elementos<strong>de</strong>l mallado es 4704, por lo que, al no habersimetría, el número <strong>de</strong> integrales a calcular es 4704 2 .El hecho <strong>de</strong> que no exista ningún tipo <strong>de</strong> simetríahace que el número <strong>de</strong> integrales numéricas a realizarsea menor, lo que a su vez provoca que se acentúenmás las diferencias entre el primer algoritmo, don<strong>de</strong>el balanceo <strong>de</strong> carga es mejor, y el segundo.IV. ConclusionesEn este trabajo se han estudiado distintas implementacionesparalelas <strong>de</strong>l Método <strong>de</strong> los Elementos<strong>de</strong> Contorno. Todas ellas presentan mejoras temporalesrespecto al código secuencial, pero, en función<strong>de</strong>l tipo <strong>de</strong> problema a resolver, pue<strong>de</strong> resultar másinteresante una u otra estrategia. Los experimentosrealizados muestran mejoras <strong>de</strong> hasta un 90,32% enla paralelización directa <strong>de</strong>l bucle interior, y <strong>de</strong> unFig. 3. Comparativa entre la distribución directa y el uso <strong>de</strong>una topología <strong>de</strong> procesadores para 4704 elementos. <strong>La</strong>reducción <strong>de</strong>l tiempo <strong>de</strong> ejecución es significativa <strong>de</strong>s<strong>de</strong>la topología más pequeña. <strong>La</strong>s diferencias respecto a ladistribución directa son gran<strong>de</strong>s ya que la ausencia <strong>de</strong>simetría produce un mayor <strong>de</strong>sequilibrio en la carga.TABLA IIIComparativa <strong>de</strong> tiempos <strong>de</strong> ejecución y porcentajes<strong>de</strong> reducción entre la distribución directa y el uso<strong>de</strong> una topología <strong>de</strong> procesadores (4704 elementos).Distribución directaTopologíaTiempo % tiempo Tiempo % tiempo1x1 20,61 100,00 20,15 100,002x2 18,02 87,42 17,96 89,113x3 0,81 3,91 8,64 42,854x4 2,25 10,91 5,75 28,525x5 1,80 8,73 4,40 21,8186,01% en el exterior (véase tabla I). Una mayoreficiencia se gana cuando se dan condiciones i<strong>de</strong>ales<strong>de</strong> distribución <strong>de</strong> datos, es <strong>de</strong>cir, cuando el número<strong>de</strong> elementos es múltiplo <strong>de</strong>l número <strong>de</strong> procesadoresesclavos entre los que se distribuye el cálculo. El uso<strong>de</strong> una topología <strong>de</strong> procesadores para la distribución<strong>de</strong> los datos presenta mejoras menores pero tambiénsignificativas <strong>de</strong> hasta un 80,25% (ver tabla II) parael caso i<strong>de</strong>al en que el número <strong>de</strong> elementos <strong>de</strong>l malladoes múltiplo <strong>de</strong>l número <strong>de</strong> procesadores en cadafila y columna <strong>de</strong> la matriz <strong>de</strong> la topología, y a<strong>de</strong>máses un número elevado (matriz <strong>de</strong> 5×5). El primer algoritmopresenta una mejor distribución <strong>de</strong> la carga,mientras que el segundo presenta gran<strong>de</strong>s ventajas<strong>de</strong> cara a crear la matriz <strong>de</strong>l sistema directamente,eliminando el paso intermedio <strong>de</strong> almacenarlos parasu posterior utilización. Esto pue<strong>de</strong> ser ventajoso enaquellos problemas cuya convergencia se produzca enun número pequeño <strong>de</strong> iteraciones, y por tanto, nohaya que realizar el cálculo <strong>de</strong> coeficientes en muchasocasiones.Agra<strong>de</strong>cimientosEste trabajo ha sido realizado gracias al programa<strong>de</strong> becas <strong>de</strong> formación <strong>de</strong> Personal Docente e Investigador<strong>de</strong> la <strong>Universidad</strong> <strong>de</strong> León, y la colaboración<strong>de</strong> la Fundación <strong>de</strong>l Centro <strong>de</strong> Supercomputación <strong>de</strong>Castilla y León.<strong>JP2011</strong>-144


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Referencias[1] Y Ataseven, Z Akalin-Acar, C E Acar, and N G Gençer,“Parallel implementation of the accelerated bem approachfor emsi of the human brain,” Med Biol EngComput, vol. 46, pp. 671–679, 2008.[2] P Geng, J T O<strong>de</strong>n, and R A van <strong>de</strong> Geijn, “Massivelyparallel computation for acoustical scattering problemsusing boundary element methods,” Journal of Sound andVibration, vol. 191, pp. 145–165, 1996.[3] T An<strong>de</strong>rsson, B Fredriksson, and B G A Persson, “Theboundary element method applied to two-dimensionalcontact problems,” in New <strong>de</strong>velopments in boundaryelement methods. Proceedings of the Second InternationalSeminar on Recent Advances in Boundary ElementMethods. Southampton, England., 1980, pp. 247–263.[4] J A González, Estudio <strong>de</strong> problemas <strong>de</strong> contacto incluyendorodadura mediante el método <strong>de</strong> los elementos<strong>de</strong> contorno, Ph.D. thesis, <strong>Universidad</strong> <strong>de</strong> Sevilla, 2001.[5] A Foces y F París J A Garrido, “Three dimensional frictioncontact using b.e.m.,” in Advances in BoundaryElements XIII, Computational Mechanics Publications.,Springer-Verlag, Ed., 1991.[6] José Vallepuga, Análisis <strong>de</strong>l problema <strong>de</strong> contactotermoelástico tridimensional sin fricción mediante elmétodo <strong>de</strong> los elementos <strong>de</strong> contorno, aplicación enmicro-electrónica, Ph.D. thesis, <strong>Universidad</strong> <strong>de</strong> Valladolid,2010.[7] M Kreienmeyer and E Stein, “Parallel implementation ofthe boundary element method for linear elastic problemson a mimd parallel computer,” Computational Mechanics,vol. 15, pp. 342–349, 1995.[8] R Natarajan and D Krishnaswamy, “A case study in parallelscientific computing: the boundary element methodon a distributed-memory multicomputer,” EngineeringAnalysis with Boundary Element, vol. 18, pp. 183–193,1996.[9] André Buchau, Wolfgang Hafla, Frie<strong>de</strong>mann Groh, andWolfgang M Rucker, “Parallelized computation of compressedbem matrices on multiprocessor computer clusters,”The International Journal for Computation andMathematics in Electrical and Electronic Engineering,vol. 24, pp. 468–479, 2005.[10] M T F Cunha, J C F Telles, and A L G A Coutinho, “Parallelboundary elements using lapack and scalapack,” inProceedings of the 14th Symposium on Computer Architectureand High Performance Computing, 2002.[11] M T F Cunha, J C F Telles, and A L G A Coutinho, “Aportable parallel implementation of a boundary elementelastostatic co<strong>de</strong> for shared and distributed memory systems,”Advances in Engineering Software, vol. 35, pp.453–460, 2004.[12] M T F Cunha, J C F Telles, A L G A Coutinho, andJ Panetta, “On the parallelization of boundary elementco<strong>de</strong>s using standard and portable libraries,” EngineeringAnalysis with Boundary Elements, vol. 28, pp. 893–902,2004.<strong>JP2011</strong>-145


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-146


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Iterative procedure to solve thermoelasticcontact problems between 3D solids usingBEM and OOPAna M a Suárez Rivero 1 , Raquel González 2 , Lidia Sánchez 3 y J. Vallepuga Espinosa 4Resumen— This paper <strong>de</strong>scribes the resolution processin an application <strong>de</strong>veloped to solve contactproblems between three-dimensional solids using theBoundary Element Method (BEM). Consi<strong>de</strong>ring aprevious <strong>de</strong>signed application using OPP (Object OrientedProgramming) techniques, an iterative processto solve thermal, elastic and thermoelastic contactproblems has been implemented and Gauss JordanMethod is used to solve the obtained equation system.The proposed application reduces the executiontime of the previous FORTRAN program as it isshowed for several experiments of thermal, elastic andthermoelastic contact problem resolution between 3Dsolids.Palabras clave— Boundary element method, thermoelasticcontact problems, Gauss Jordan Method,OOP.I. IntroductionTHERE are a lot of researchers that have studiedthe contact problem between solids in the lastfew <strong>de</strong>ca<strong>de</strong>s. In the study of this problem, they haveused different numerical methods, as for example,Finite Element Method (FEM) used by Wilson [17],Chan and Tuba [5] o Wriggers [18], or the BoundaryElement Method (BEM) used by An<strong>de</strong>rson [4]to solve bidimensional contact problems. Gracini[6] uses the theory to solve contact problems betweensolids with axial symmetry. Working withtree-dimensional solids, Emperador [3] applies thismethod to solve elastodynamics problems and Gonzalez[10] applies this method in the resolution ofrolling contact problems. Gracini [6] uses the theoryto solve contact problems between solids with axialsymmetry.The Boundary Element Method has its origins inBetti’s reciprocal theorem and in Somigliana’s i<strong>de</strong>ntityfrom mid XIXth century. Since sixties, BEMstarted to be applied in the resolution of engineeringproblems [13], and, in 1967, the first research that<strong>de</strong>veloped a program used to solve elasticity problems[14], was published.It is remarkable to say its application is possible touse in different areas, like stress analysis, potentialflow, mechanical fracture, acoustics [9] and electromagnetism[1], [15]. Also, it is possible to be used asa CAD tool for electrical, mechanical or civil engi-1 Dpto. <strong>de</strong> Ingenierías Mecánica, Informática y Aeroespacial,Univ. <strong>de</strong> León, e-mail: amsuar@unileon.es.2 Dpto. <strong>de</strong> Ingenierías Mecánica, Informática y Aeroespacial,Univ. <strong>de</strong> León, e-mail: raquel.gonzalez@unileon.es.3 Dpto. <strong>de</strong> Ingenierías Mecánica, Informática y Aeroespacial,Univ. <strong>de</strong> León, e-mail: lidia.sanchez@unileon.es.4 Dpto. <strong>de</strong> Tecnología Minera, Topografía y <strong>de</strong> Estructuras,Univ. <strong>de</strong> León, e-mail: jvale@unileon.es.neering [2]. Moreover, this method has been used tosolve thermoelastic contact problems between threedimensionalsolids [8].BEM is a method used to solve differential partialequations, so that it can be only used when theproblem can be represented in a differential equationform. The method is <strong>de</strong>rived from the discretizationof an integral equation that is mathematicallyequivalent to the initial partial differential equation.This equation consists of an integral equation thatis <strong>de</strong>fined in the boundary domain and an integralequation that relates the boundary solution with thepoints in the domain. This integral equation is calledboundary integral equation. To solve this equation,a technique that converts this integral into a linearequation system is applied. There is a huge varietyof <strong>de</strong>rivation methods of equation systems that takesas basis the integral equation, which can be appliedto <strong>de</strong>velop a particular boundary element method.However, this new reformulation of the equationcan be only done for some specific types of partialdifferential equations. That is the reason why BEMcan not be only used as a general way, in contrastwith the finite element method or the finite differencesmethod. In spite of that, for those cases whereBEM can be applied, it offers a friendly and efficientnumerical method, more than other ones [2],[16]. BEM consists of meshing solid surfaces. Consequently,fewer no<strong>de</strong>s are consi<strong>de</strong>red, fewer amount ofunknown factors are generated and time execution isreduced [16].In [8], BEM is applied to solve contact problemsbetween three-dimensional solids. Three kinds ofproblems are consi<strong>de</strong>red: thermal, elastic and thermoelasticones. An iterative resolution method isproposed and <strong>de</strong>veloped using Fortran.The following section <strong>de</strong>scribes the problem we<strong>de</strong>al with. In section III we present the <strong>de</strong>velopedapplication. Section IV shows the experiments andobtained results. Finally, section V gathers theachieved conclusions.II. The thermoelastic contact problem in3DThe thermoelasticity <strong>de</strong>scribes solid behavioursthat un<strong>de</strong>rgo shape variations as a function of thetemperature. When two solids are contacted, thedistribution of pressures in the contact zone can varywith temperature. If temperature and thermal flowsare known, then, it is possible to <strong>de</strong>termine the realcontact zone between them [8] since generated strains<strong>JP2011</strong>-147


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011and stress on the solids can be computed.The most of materials, when their temperature isincreased, they are expan<strong>de</strong>d in a proportional wayto this increment. If it is in a non-<strong>de</strong>fine expansion,there is not generated stress on the solid. In contrast,although temperature does not create stresses, thereis a well-known phenomenon named thermal distortion[7]. Such phenomenon curves straight surfacesbecause of the temperature gradient.Those thermoelastic strains are more importantwhen those two solids are in contact, because pressuresin the contact zone are more sensitive to temperaturechanges. If both solids are ma<strong>de</strong> by thesame material, curvatures on contact surfaces will bei<strong>de</strong>ntical, and the distortion will not have any importance.However, if the distortion capacities of solidsare different, the convexity will increase in the hottersolid, and will <strong>de</strong>crease in the col<strong>de</strong>r one, causing apressure increment on some regions and a <strong>de</strong>crementon others.Depending on the distortivities and the directionof the heat flow, two types of contact appear:• Imperfect contact: when the heat flows towardsthe solid with the lesser thermoelasticity distortivity,both systems of lineal equations, thermaland thermoelastic, are coupled by the presenceof a thermal resistance that varies inverselywith the contact pressure.• If heat flows into the material with the larger distortivityis possible to obtain solutions involvinga zone of perfect contact bor<strong>de</strong>red directly byseparation zones. Then, the non linearity is dueto the unknown size of the contact zone.A. DescriptionThe problem is based on two three-dimensionalsolids in contact. Those solids are un<strong>de</strong>r a systemof static loads applied in the boundary and a thermalload that is transmitted by conduction insi<strong>de</strong> ofboth solids [8].Depending on the direction of thermal flow, somecontact conditions (perfect or imperfect) are set onthe interface. Stress, movements, temperatures andtemperature gradients on their boundaries are <strong>de</strong>terminedfor both solids.B. Assumed hypothesisThe following hypothesis are assumed to makeeach approach [8]:1. Continuous, homogeneous, elastic and isotropicsolids.2. The conductivity is consi<strong>de</strong>red constant for everyrange of temperature used in the problem.3. Short strains and movements.4. Slow temperature variations along the time(quasi-static process).5. Non friction contact.6. Heat transmission by radiation is not consi<strong>de</strong>red.C. Problem <strong>de</strong>finitionLet be A and B the two solids consi<strong>de</strong>red in eachproblem. Every point y on the boundary of eachsolid is referenced by employing a global coordinatessystem OXYZ, and it is related to a stress array t k j (y)and a displacement array u k j (y) [8]. Moreover, theyhave associated a temperature T k (y) and a thermalgradient q k (y). To solve the problem, boundary isdivi<strong>de</strong>d into two areas:1. G (A,B)C, common contact surface for bothsolids.2. G K L , non-contact region of each solid.In general, this boundary division can not beestablished previously since the contact zone canchange during the load process. Therefore, a potentialcontact zone is supposed. Such region inclu<strong>de</strong>scontact points at the beginning of resolution processand the nearest points that can be in contact in thefinal solution. Resolution process allows us to <strong>de</strong>terminein a iterative way which the actual contact zoneis [8].D. Resolution ProcessFirst we <strong>de</strong>fine the type of problem and geometryof the solids that are involved in the problem. Thenwe establish boundary conditions and type of contact.After that, the obtained equation system canbe solved by an iterative process [8]. The resolutionprocess is ma<strong>de</strong> up by the following steps:1. Assembly of matrixes equation system Ax=B.2. Resolution of equation system using Gaussmethod.3. Resolution of thermal problem (if it is necessary).4. Resolution of elastic problem (if it is necessary).5. Resolution of thermoelastic problem (if it isnecessary).6. Resolution of the iterative process.III. Application <strong>de</strong>velopmentBEMAPEC (Boundary Element Method Appliedto Problems of Elastic Contact) is a Java applicationthat offers a friendly workspace to <strong>de</strong>fine andsolve problems between three-dimensional solids usingBEM [11].A. Original BEMAPECBEMAPEC [12] provi<strong>de</strong>s an easy way to <strong>de</strong>fine thegeometry of solids that are involved in the problem.Those solids are discretized by triangular geometricalmeshes. BEMAPEC also calculates the coefficientsas a result of each element integration that makesup solids. Those coefficients are used in the problemresolution. Finally, BEMAPEC application displaysobtained results graphically using the <strong>de</strong>velopmentenvironment OpenGL.<strong>JP2011</strong>-148


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011B. Improvements on BEMAPEC functionalityUsing the previous version of BEMAPEC [12] wehave <strong>de</strong>veloped several improvements. First, we <strong>de</strong>finethe type of problem and the geometry of solidsthat are involved. Then we mesh these solids and<strong>de</strong>fine boundary conditions and type of contact. Afterthat, BEMAPEC calculates coefficients for eachmeshed element. We build the equation system fromthose coefficients. Finally, the equation system issolved and the whole problem is computed by meansof an iterative process. This last stage, equation system<strong>de</strong>finition and problem resolution, is the functionalityad<strong>de</strong>d to the program.The resolution process comprises the followingsteps:1. Assembly of matrixes equation system Ax=B:the coefficients computed by the integration of eachelement over all the rest, are used to do the assemblyof the A matrix and the B vector for the equation systemAx=B. A and B elements are <strong>de</strong>termined takingin account the solid and the region that each elementbelongs to (contact zone or free zone).2. Resolution of equation system by GaussMethod: to solve the previously obtained equationsystem, it is necessary to use Gauss Method withpivot. This choice is due to effectiveness and efficiencyreasons, so as the intrinsic characteristics ofthe problem that generates a large amount of zerosin A and B.3. Resolution of thermal problem (if it is necessary):this step is consi<strong>de</strong>red just for thermal orthermoelastic problems. The process starts with theresolution of the equation system by using the GaussMethod. So we obtain an X vector that is employedto establish boundary conditions in the contact zonefor each element that belongs to the contact surfacesof each solid. This process finishes with the writingof temperature and heat flow parameters related toeach thermal element into a file.4. Resolution of elastic problem (if it is necessary):this stage is carried out for elastic or thermoelasticproblems. First we solve the equation system byGauss Method and the resulting X vector allows usto <strong>de</strong>termine the elastic conditions for each elementof either contact or free zones. Once each element ofboth solids has its boundary condition, relative displacementscan be calculated. Next, every value foreach element of both solids is written in an outputfile. We need now to check the obtained partial results.Firstly, tension checking is ma<strong>de</strong> to <strong>de</strong>terminewhich elements are leaving the contact zone. Whenthere are no elements coming into or out from thecontact zone, we write in an output file the new elasticcondition values for every element and the thermalresistance values for those elements that belongto the contact zone.5. Resolution of thermoelastic problem (if it isnecessary): this stage is consi<strong>de</strong>red for thermoelasticproblems. In that case, firstly the thermal problemis solved. Then, it is solved the elastic problem.Subsequently, only in the case that contact betweensolids is imperfect, a comparison among thermal resistancesfor those elements that belong to the contactzone is ma<strong>de</strong>. If the result of such comparisonis higher than a certain tolerance, thermal resistancevalues will be modified, and process will be repeatedagain.6. Resolution of iterative process (if it is necessary):it could happen, when elastic or thermoelasticproblems are being solved, that some specific conditionscan appear that makes come back to point 1of the resolution, and process would have to be executedagain. Conditions that make the process startsa new iteration <strong>de</strong>pend on the type of problem thatis being solved. So, it is necessary to do the followingdistinction:• Elastic problem: once equation system is solved,results need to be checked. In this case, firstly,tension checking for every element that belongsto the contact zone is carried out. This allows usto <strong>de</strong>termine which elements come out from thecontact zone. Once tension checking is done,if the number of elements that come out fromthe contact zone is zero, interpenetrations arechecked. Interpenetration checking <strong>de</strong>termineswhich elements come into the contact zone.After tension checking is finished, if there is anyelement coming out from the contact zone, theprocess will be repeated. If no-one elementscome out from the contact zone but some elementscome into such zone, the process also willbe repeated.• Thermal problem: in case of thermoelastic problems,process can be repeated because of severalreasons. A reason is the previously explainedone for the elastic problem. Another one is dueto the thermal problem. In that case, the comparisonbetween thermal resistances is carriedout. If the result of this comparison differs fromany tolerance in amount higher than a certainvalue for any element that belongs to the contactzone, the problem will be solved again withthose new resistance values.In short, process will stop when no-one elementcomes into or out from the contact zone (elasticproblem) and thermal resistance differs in an amountlower than a certain value (thermal problem) for everyelement that belongs to the contact zone.IV. Experiments and ResultsWe have carried out several experiments to comparethe execution time for FORTRAN’s applicationversion [8] and BEMAPEC application.A. Thermal problemsProof cases used in the thermal problem are basedon two solids in contact (Fig. 1). Both solids arecubes ma<strong>de</strong> up by 640 elements. 128 elements fromeach cube belong to the contact zone. The type ofcontact between solids is perfect, the environmentis vacuum. For those no<strong>de</strong>s on the potential con-<strong>JP2011</strong>-149


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011tact zone, that remind separated in the final configuration,if it is not consi<strong>de</strong>red that energy can takeplace in these zone (vacuum). Reference temperatureis zero. Equation system is ma<strong>de</strong> up by 1280equations.1136 equations. In this case, there are not elementscoming into or out from the contact zone in tensionchecking or interpenetrations checking so the processis not repeated5. Proof Case 5: It consists of two solids in contact.Both of them are prisms; solid A is ma<strong>de</strong> up by768 elements and solid B is ma<strong>de</strong> up by 768 elements.The number of elements that belong to the contactzone is 128 for both solids. Equation system Ax=Bhas 4608 equations. The process is carried out onlyonce.Fig. 1. This figure shows solids of Proof Case 1 on theway they are represented on the BEMAPEC’s applicationgraphical environment. Points are the no<strong>de</strong>s of each elementobtained after meshing. The grey plane representsYZ symmetry plane.B. Elastic problemsDue to the higher complexity and casuistry in elasticproblems, number of proof cases is higher. Allthe experiments have the following conditions: thetype of contact between solids is perfect, the referencetemperature is zero and the environment is vacuum.For those no<strong>de</strong>s on the potential contact zone,that remind separated in the final configuration, if itis not consi<strong>de</strong>red that energy can take place in thesezone (vacuum). Particular characteristics about eachproof case are shown below:1. Proof Case 1: It consists of two solids in contact.Both of them are prisms; solid A is ma<strong>de</strong> upby 384 elements and solid B is ma<strong>de</strong> up by 752 elements.The number of elements that belong to thecontact zone is 128 in both cases. Equation systemAx=B has 3408 equations. Resolution process needs5 iterations due to the tension checking.2. Proof Case 2: It consists of two solids in contact(Fig. 2). Both of them are prisms; solid A is ma<strong>de</strong>up by 182 elements and solid B is ma<strong>de</strong> up by 218elements. The number of elements that belong to thecontact zone, is 132 for both solids. Equation systemAx=B has 1200 equations. Resolution processrequires 6 iterations due to the tension checking.3. Proof Case 3: It consists of two solids in contact.Both of them are cubes; solid A is ma<strong>de</strong> up by200 elements and solid B is ma<strong>de</strong> up by 200 elements.The number of elements that belong to the contactzone is 50 in both cases. Equation system Ax=B has1200 equations. In this case, there are not elementscoming into or out from the contact zone in tensionchecking or interpenetrations checking so the processis not repeated.4. Proof Case 4: It consists of two solids in contact.Both of them are prisms; solid A is ma<strong>de</strong> upby 656 elements and solid B is ma<strong>de</strong> up by 616 elements.The number of elements in the contact zonefor both cases is 128. Equation system Ax=B hasFig. 2. This figure shows solids from Proof Case 2 on theway they are represented on the BEMAPEC’s applicationgraphical environment. Points are the no<strong>de</strong>s of eachelement obtained after meshing. The white plane representsXZ symmetry plane and the grey one, YZ symmetryplane.C. Thermoelastic problemsAs elastic problems, the number of thermoelasticcase problems is higher. All the cases have the followingcommon conditions: the type of environmentis vacuum and for those no<strong>de</strong>s on the potential contactzone, that remind separated in the final configuration,if it is not consi<strong>de</strong>red that energy can takeplace in these zone (vacuum).1. Proof Case 1: It consists of two solids in contact.Both of them are cubes; solid A is ma<strong>de</strong> up by640 elements and solid B is ma<strong>de</strong> up by 640 elements.The number of elements of the contact zone is 128for both solids. The type of contact between solidsis imperfect and the reference temperature is zero.Equation system Ax=B has 3840 equations. Resolutionprocess needs 3 iterations due to the thermalpart of the problem.2. Proof Case 2: It consists of two solids in contact.Both of them are cubes; solid A is ma<strong>de</strong> up by640 elements and solid B is ma<strong>de</strong> up by 640 elements.The number of elements that belong to the contactzone, in both cases, is 128. The type of contact betweensolids is perfect and the reference temperatureis zero. Equation system Ax=B has 3840 equations.Resolution process requires 3 iterations due to theelastic part of the problem, specifically, to the tensionchecking.3. Proof Case 3: It consists of two solids in contact(Fig. 3). Both of them are prisms; solid A is ma<strong>de</strong>up by 384 elements and solid B is ma<strong>de</strong> up by 752 elements.The number of elements of the contact zone,in both solids, is 128. The type of contact betweensolids is imperfect and the reference temperature is<strong>JP2011</strong>-150


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 201130. Equation system Ax=B has 3408 equations. Resolutionprocess needs 6 iterations due to the thermalpart of the problem.4. Proof Case 4: It consists of two solids in contact.Both of them are prisms; solid A is ma<strong>de</strong> upby 384 elements and solid B is ma<strong>de</strong> up by 752 elements.The number of elements that belong to thecontact zone is 128 for both solids. The type of contactbetween solids is imperfect and the referencetemperature is 30. Equation system Ax=B has 3408equations. Resolution process requires 2 iterationsdue to the thermal part of the problem.Fig. 4. This figure shows the execution time comparison of thethermal problem explained. As it is showed, the executiontime in Fortran’s version is bigger than in Java’s version,so, in this case, we have managed a meaningful reductionin execution time.Fig. 3. This figure shows solids from Proof Case 3 as they arerepresented on the BEMAPEC’s application graphical environment.Points are the no<strong>de</strong>s of each element obtainedafter meshing. The white plane means XZ symmetry andthe grey plane corresponds to YZ symmetry.D. Executed time comparisonPrevious mentioned problems for FORTRAN’s applicationversion and BEMAPEC application aboutexecuted time are displayed as it is shown on thegraphics 4, 5 and 6. When we solved the thermalproblem using JAVA’s application version, we managean improvement because the execution time isreduced. If we analyze results obtained in elasticproblems, we could draw as conclusion that higherthe number of equations which ma<strong>de</strong> up the equationsystem is, more significant the reduction in executiontime is. In contrast, when the equation systemis lesser, Java’s application version increase a bit theexecution time, although the difference is not veryimportant.Finally, thermoelastic problems’ behaviour is different.In these problems, it is less important thenumber of equations than the number of iterations.For example, in cases 3 and 4, the number of equationsis the same, but in case 3 there are 4 iterationsmore than in case 2 and we obtained better timeswhen the number of iterations is higher. When thenumber of iterations is less, the execution time ispractically the same.As it is can be observed, the more elements makeup solids, the higher is the difference between times,and therefore, the amount of equations is higher. Inthose cases, Java’s application version is more efficiently.V. Conclusions and Future WorksIn this work, we have used OOP techniques tosolve contact problems between 3D solids. So that,after coefficients have been calculated using the previousversion of BEMAPEC, assembly matrixes ofequation system Ax=B is done. After that, GaussFig. 5. This figure shows the execution time comparison ofelastic problems which have been proved. We managed agreat reduction in cases 1, 4 and 5. However, slightly weget worse the execution time in case 2 and 3. This is dueto our application is more effective when the number ofequations in the equation system is large.Method with pivot is used to solve it because, actually,this is the most efficiently method on resolvingequation systems when the number of them is higher.Then, problem is solved using methods that <strong>de</strong>pendon the type of problem (thermal, elastic o thermoelastic).Process finishes with the writing of obtainedresults into an output file.When equation number that makes up systemequation is large, the execution time for the resolutionproblem is lower in Java’s version than FOR-TRAN’s one. In contrast, when equation system hasfewer equations, the FORTRAN’s version is more efficient.However, in this kind of problems is usual tohave a large number of equations.Further works inclu<strong>de</strong> to parallelize the resolutionprocess in or<strong>de</strong>r to reduce the execution time as wellas using different techniques to solve the equationsystem.VI. AcknowledgementsThis work has been partially supported by the researchgrants program from the University of León(Spain).Referencias[1] Matti Stenroos, Helsinki bem library., [Online]. Available:http://peili.hut.fi/BEM.<strong>JP2011</strong>-151


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011sis”, Advances in Engineering Software, vol. 37, pp. 248–259, 2006.[17] E. A. Wilson and B. Parsons, Finite element analysis ofelastic contact problems using differential displacements,International Journal for Numerical Methods in Engineering,vol. 2, pp. 387–395. 1969.[18] P. Wriggers, ”Finite element algorithms for contact problems”,Archives of Computational Methods in Engineering,vol. 2, pp. 1–49, 1995.Fig. 6. This figure shows the execution time comparison ofthermoelastic problems. In cases 1 and 3, we manage ameaningful reduction while in cases 2 and 4, the differenceis insignificant.[2] Stephen Kirkup, Boundary element method for laplaceproblems., [Online]. Available: http: //www.boundaryelement-method.com/laplace/manual/chap1/in<strong>de</strong>x.htm.[3] J. M. E. Alzola, ”El método <strong>de</strong> los elementos <strong>de</strong> contornoen problemas elastodinámicos con simetría <strong>de</strong> revolución”,Ph.D. dissertation, <strong>La</strong>s Palmas <strong>de</strong> Gran Canaria, 1988.[4] T. An<strong>de</strong>rsson, B. Fredriksson, and B. G. A. Persson, ”Theboundary element method applied to two-dimensional contactproblems”, in New <strong>de</strong>velopments in boundary elementmethods. Proceedings of the Second International Seminaron Recent Advances in Boundary Element Methods.,Southampton, England., 1980, pp. 247–263.[5] S. K. Chan and I. S. Tuba, ”A finite element methodfor contact problems of solid bodies - part i. theory andvalidation”, International Journal of Mechanical Sciences,vol. 13, pp. 615–625, 1971.[6] E. G. Díaz, ”Formulación e implementación <strong>de</strong>l método<strong>de</strong> los elementos <strong>de</strong> contorno para problemas axisimétricos<strong>de</strong> contacto. aplicación a la caracterización <strong>de</strong> la interfasefibra matriz en materiales compuestos”, Ph.D. dissertation,<strong>Universidad</strong> <strong>de</strong> Sevilla, 2006.[7] J. Dundurs, ”Distorsion of a body caused by free thermalexpansion”, Mechanics Research Communications, vol. 1,pp. 121–124, 1974.[8] J. V. Espinosa, ”Análisis <strong>de</strong>l problema <strong>de</strong> contacto termoelásticotridimensional sin fricción mediante el método<strong>de</strong> los elementos <strong>de</strong> contorno, aplicación en microelectrónica”,Ph.D. dissertation, <strong>Universidad</strong> <strong>de</strong> Valladolid,2010.[9] L. Gaul and W. Wenzel, ”Acoustic calculations with thehybrid boundary element method in time domain”, Engineeringanalysis with boundary elements, vol. 25, no. 4-5,pp. 259–265, 2001.[10] J. Ángel González Pérez, ”Estudio <strong>de</strong> problemas <strong>de</strong> contactoincluyendo rodadura mediante el método <strong>de</strong> los elementos<strong>de</strong> contorno”, Ph.D. dissertation, <strong>Universidad</strong> <strong>de</strong>Sevilla, 2001.[11] R. Gonzalez, J. Vallepuga, y L. Sánchez, ”Desarrollo<strong>de</strong> un entorno en C++ y OpenGL para la resolucio´n <strong>de</strong>problemas <strong>de</strong> contacto entre sólidos 3D”, Congreso <strong>de</strong>Métodos Numéricos en Ingeniería, 2009.[12] R. González, ”Optimización <strong>de</strong>l método <strong>de</strong> los elementos<strong>de</strong> contorno en la resolución <strong>de</strong> problemas <strong>de</strong> contactotermoelástico mediante técnicas <strong>de</strong> paralelismo”, <strong>Universidad</strong><strong>de</strong> León, 2010.[13] H. R. Millwater, ”Probabilistic fracture mechanics analysisusing the boundary element method”, First InternationalSymposium on Uncertainty Mo<strong>de</strong>ling and AnalysisProceedings, 1990, pp. 426–431.[14] F. J. Rizzo, ”An integral equation approach to boundaryvalue problems of classical elastostatics”, Quarterly ofApplied Mathematics, vol. 25, pp. 83–95, 1967.[15] M. Stenroos, V. Mäntynen, and J. Nenonen, ”A matlablibrary for solving quasi-static volume conduction problemsusing the boundary element method”, Computermethods and programs in biomedicine, vol. 88, pp. 256–263, 2007.[16] H. Qiao, ”Object-oriented programming for the boundaryelement method in two-dimensional heat transfer analy-<strong>JP2011</strong>-152


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Evaluación <strong>de</strong> la Paralelización <strong>de</strong> un Mo<strong>de</strong>loHidrodinámico 3DMario C. Acosta 1,3 , Mancia Anguita 1 , Francisco J. Rueda 2,3 y F. Javier Fernán<strong>de</strong>z-Baldomero 1costa, lo que resulta importante para compren<strong>de</strong>r elResumen—Se presenta la implementación paralela <strong>de</strong> un comportamiento físico y biogeoquímico <strong>de</strong> mo<strong>de</strong>losmo<strong>de</strong>lo hidrodinámico tridimensional (3D) en un pequeño naturales acuáticos <strong>de</strong> gran escala.cluster <strong>de</strong> 3 nodos multi-cores. El programa aprovecha los De igual forma, un coste excesivo <strong>de</strong> tiempo para3 nodos <strong>de</strong>l cluster usando el estándar MPI y los 4 cores <strong>de</strong> completar la simulación es inaceptable cuando elcada nodo usando el estándar OpenMP. En este trabajo semo<strong>de</strong>lo SWE forma parte <strong>de</strong> un sistema <strong>de</strong> <strong>de</strong>cisión yaanaliza la influencia en las prestaciones <strong>de</strong> diferentesque en estos casos, los resultados <strong>de</strong>ben obtenerse conconfiguraciones <strong>de</strong> la plataforma, distintas distribuciones<strong>de</strong> la carga <strong>de</strong> trabajo, diferentes métodos <strong>de</strong> suficiente antelación con el fin <strong>de</strong> que estos sistemas seimplementación y <strong>de</strong>l uso <strong>de</strong> procesamiento por bloques. puedan usar para <strong>de</strong>sarrollar y probar estrategias <strong>de</strong>Palabras clave—Procesamiento paralelo, Sistemas con gestión que puedan minimizar los efectos <strong>de</strong> <strong>de</strong>sastresmemoria compartida, Sistemas con memoria distribuida, naturales tales como inundaciones o la introducción <strong>de</strong>Hidrodinámica.alguna especie invasiva en la zona.Los mo<strong>de</strong>los usados en sistemas <strong>de</strong> <strong>de</strong>cisión suelenI. INTRODUCCIÓNejecutarse repetidamente, usando en cada ocasión unA computación <strong>de</strong> altas prestaciones sigue conjunto <strong>de</strong> parámetros distinto y/o condiciones <strong>de</strong>aumentando en la ciencia <strong>de</strong>l agua, se necesitan frontera diferentes con el objetivo <strong>de</strong> proporcionarLobtener campos <strong>de</strong> flujo en ecosistemas naturales predicciones futuras <strong>de</strong>l campo <strong>de</strong> flujo con un grado <strong>de</strong>con mayor <strong>de</strong>talle, pero sin que conlleve un coste <strong>de</strong> confiabilidad satisfactorio.tiempo <strong>de</strong>masiado elevado.<strong>La</strong> mayoría <strong>de</strong> los esfuerzos en la mo<strong>de</strong>lización <strong>de</strong>lEstas <strong>de</strong>scripciones <strong>de</strong>talladas <strong>de</strong> los campos <strong>de</strong> flujo, medio ambiente fluido <strong>de</strong>ben tener como objetivoobtenidas bien a partir <strong>de</strong> simulaciones <strong>de</strong> algoritmos <strong>de</strong> mejorar el tiempo <strong>de</strong> ejecución <strong>de</strong> los mo<strong>de</strong>lostres dimensiones que resuelven las ecuaciones <strong>de</strong> numéricos existentes, especialmente en plataformas <strong>de</strong>gobierno para el movimiento <strong>de</strong> flujo o bien a través <strong>de</strong> bajo coste, para que los estudiosos <strong>de</strong>l agua puedanobservaciones realizadas con técnicas experimentales obtener un <strong>de</strong>tallado y riguroso conocimiento y<strong>de</strong> alta resolución, han permitido que los científicos comprensión <strong>de</strong> los procesos físicos <strong>de</strong> transporte yestudiosos <strong>de</strong>l agua alcancen alguna compresión sobre mezcla que tienen lugar en las aguas <strong>de</strong> interior y quelos procesos <strong>de</strong> transporte en aguas <strong>de</strong> interior [1] [2]: los gestores <strong>de</strong>l agua puedan conseguir prediccioneslagos y <strong>de</strong>ltas. Pero esta comprensión dista aún mucho precisas <strong>de</strong>l flujo ante perturbaciones externas (por<strong>de</strong> ser completa.ejemplo, la polución) y así obtener estrategias <strong>de</strong> gestiónMuchos <strong>de</strong> los mo<strong>de</strong>los hidrodinámicos en un tiempo aceptable.tridimensionales, implementados en un computador para Este trabajo evalúa una implementación paralela <strong>de</strong> unsimulaciones físicas, se usan en la actualidad en algunos mo<strong>de</strong>lo SWE 3D que permite incluso un tiempo<strong>de</strong> los lagos investigados y están basados en la solución aceptable <strong>de</strong> ejecución en computadores paralelos <strong>de</strong><strong>de</strong> una forma simplificada <strong>de</strong> las ecuaciones <strong>de</strong> Navier- bajo coste.Stokes, las ecuaciones <strong>de</strong> aguas someras (SWE Shallow En la Sección 2 se presenta <strong>de</strong> forma sintetizada elWater Equations) [3].mo<strong>de</strong>lo hidrodinámico paralelizado. A continuación, enLos mo<strong>de</strong>los SWE forman un conjunto simplificado <strong>de</strong> la Sección 3, se resume el trabajo relacionado realizadoecuaciones con un coste computacional mo<strong>de</strong>rado que, hasta la fecha en este campo. En la Sección 4 se realizasin embargo, consumen una gran cantidad <strong>de</strong> memoria una comparación entre distintos métodos para lay tiempo <strong>de</strong> cómputo cuando se usan cuadrículas implementación paralela así como distintas formas <strong>de</strong>espaciales <strong>de</strong> alta <strong>de</strong>nsidad o cuando se usan para realizar la <strong>de</strong>scomposición <strong>de</strong>l dominio <strong>de</strong> datos. En lasimular el comportamiento <strong>de</strong> sistemas <strong>de</strong> agua naturales Sección 5 se indica las características <strong>de</strong> la plataformadurante un largo periodo <strong>de</strong> tiempo.utilizada y se resumen los resultados experimentalesEl uso <strong>de</strong> cuadrículas <strong>de</strong> alta resolución es necesario, obtenidos. Por último se resumen las conclusiones en lapor ejemplo, para obtener el flujo en <strong>de</strong>terminadas zonas Sección 6.<strong>de</strong> pequeña escala, como las corrientes cercanas a laII. MODELO HIDRODINÁMICOEl mo<strong>de</strong>lo 3D SWE a paralelizado se <strong>de</strong>nomina SI3D1 Dpto. <strong>de</strong> Arquitectura y Tecnología <strong>de</strong> Computadores, Univ. [4]. Este mo<strong>de</strong>lo, <strong>de</strong>s<strong>de</strong> su presentación, ha sidoGranada, e-mail: manguita@ugr.es javier@atc.ugr.esampliamente validado, tanto por las soluciones analíticas2 Dpto. <strong>de</strong> Ingeniería Civil, Univ. Granada, e-mail: frueda@ugr.es como por el conjunto <strong>de</strong> datos <strong>de</strong> campo recogidos en3 Instituto Del Água, Univ. Granada, e-mail: marioa@correo.ugr.es una amplia gama <strong>de</strong> lagos [5].<strong>JP2011</strong>-153


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011SI3D, está basado en la solución numérica <strong>de</strong> lasecuaciones <strong>de</strong> continuidad, Reynolds-average y lasecuaciones <strong>de</strong> Navier-Stokes para aguas someras <strong>de</strong>momentum, la ecuación <strong>de</strong> transporte para latemperatura, y una ecuación <strong>de</strong> estado que relacionatemperatura con la <strong>de</strong>nsidad <strong>de</strong>l fluido. <strong>La</strong>s ecuacionesfundamentales se integran en un mo<strong>de</strong>lo por capasdividido en la horizontal por una serie <strong>de</strong> capasseparadas por diferentes planos en niveles.Para discretizar estas ecuaciones se usa un algoritmosemi-implícito <strong>de</strong> tres niveles <strong>de</strong> diferencias finitascompuesto por pasos iterativos trapezoidal-salto <strong>de</strong> ranasobre una cuadrícula tradicional <strong>de</strong> ejes Cartesianos, queintroduce escasa difusión numérica [4]. Este enfoquesemi-implícito está basado en el tratamiento <strong>de</strong> ondas <strong>de</strong>gravedad y la difusión vertical para evitar limitacionesen el paso <strong>de</strong> tiempo <strong>de</strong>bido a las condiciones dadas porCouram-Friedrich-Levy y para garantizar la estabilidad<strong>de</strong>l método [6]. El resto <strong>de</strong> términos incluyendo laadvección se incluyen explícitamente. Los operadoreslaplacianos se usan para representar mezclas y loscoeficientes constantes <strong>de</strong> mezcla se usan paraparametrizar el efecto <strong>de</strong> turbulencias horizontales.Un sistema <strong>de</strong> dos ecuaciones para turbulenciascalcula los coeficientes <strong>de</strong> la mezcla en la vertical [7].Los cálculos en cada iteración estudian una a una cadacolumna <strong>de</strong> agua para generar una matriz pentadiagonal<strong>de</strong> las ecuaciones <strong>de</strong>l movimiento <strong>de</strong>l agua en lasuperficie libre (η), que resuelve mediante el método <strong>de</strong>lgradiente conjugado precondicionado [4]; <strong>de</strong> esta formaobtiene los valores <strong>de</strong> la velocidad horizontal mediantela actualización <strong>de</strong> los valores <strong>de</strong> η.III. TRABAJO RELACIONADOSe pue<strong>de</strong>n encontrar en la bibliografía diferentesimplementaciones paralelas <strong>de</strong> mo<strong>de</strong>los SWE queaprovechan el paralelismo <strong>de</strong> datos implícito en este tipo<strong>de</strong> aplicaciones. <strong>La</strong> mayor parte <strong>de</strong> estasimplementaciones sacan partido <strong>de</strong> este paralelismo enlas arquitecturas paralelas <strong>de</strong> memoria distribuida o <strong>de</strong>memoria compartida usando paradigmas <strong>de</strong>programación <strong>de</strong> paso <strong>de</strong> mensajes o <strong>de</strong> memoriacompartida. Recientemente se han presentadoimplementaciones que aprovechan las arquitecturasSIMD presentes en los procesadores actuales(instrucciones multimedia) y unida<strong>de</strong>s <strong>de</strong> procesamiento<strong>de</strong> gráficos o GPU.En la bibliografía reciente, hay implementaciones queutilizan el paradigma <strong>de</strong> paso <strong>de</strong> mensajes con MPI <strong>de</strong>mo<strong>de</strong>los en 2D ([8] [9] [10] [1]) y 3D ([11]). Tambiénhay alguna implementación con el paradigma <strong>de</strong>variables compartidas usando OpenMP; por ejemplo, en[10] se paraleliza el mo<strong>de</strong>lo 3D <strong>de</strong> lattice Boltzmanncon OpenMP. Tanto en las implementaciones <strong>de</strong>variables compartidas como en las <strong>de</strong> paso <strong>de</strong> mensajesse usa <strong>de</strong>scomposición <strong>de</strong> dominio para dividir la carga<strong>de</strong> trabajo entre hilos o procesos respectivamente.También, en [12] se presentan la implementación <strong>de</strong>un mo<strong>de</strong>lo SWE 2D que usa las instrucciones SSE <strong>de</strong>los procesadores <strong>de</strong> Intel, y en [13] se mejora lasprestaciones <strong>de</strong> un mo<strong>de</strong>lo SWE 2D usando lasinstrucciones multimedia <strong>de</strong> Intel a través <strong>de</strong> las libreríasIPP <strong>de</strong> Intel (Intel Performance Primitives). Hay variasimplementaciones <strong>de</strong> mo<strong>de</strong>los SWE en GPU, porejemplo en [14] se programa un mo<strong>de</strong>lo SWE 2D (doscapas) en una GPU <strong>de</strong> Nvidia usando CUDA.Los mo<strong>de</strong>los tridimensionales, como SI3D, necesitangran<strong>de</strong>s cantida<strong>de</strong>s <strong>de</strong> datos lo que exige la necesidad <strong>de</strong>recurrir a computación <strong>de</strong> alto rendimiento. A<strong>de</strong>más, eneste caso la distribución <strong>de</strong> la carga <strong>de</strong> trabajo suponeotra dificultad ya que, presenta una distribución irregularen el plano horizontal (primera y segunda dimensión), ala que se aña<strong>de</strong> una tercera dimensión, tambiénirregular, para el plano vertical, dado por la profundidad.En este trabajo se presenta diferentes formas <strong>de</strong>realizar la implementación paralela <strong>de</strong> un mo<strong>de</strong>lohidrodinámico semi-implícito 3D, en este caso SI3D. <strong>La</strong>implementación realizada combina tanto el paradigma<strong>de</strong>l paso <strong>de</strong> mensajes (con MPI) como el paradigma <strong>de</strong>memoria compartida (con OpenMP). También secomparan variantes en la implementación, en unausando operaciones redundantes (con solapamiento)frente a otra que no las incluye. El solapamientoincrementa el número <strong>de</strong> operaciones pero por elcontrario reduce el número <strong>de</strong> comunicaciones. Estetrabajo también analiza la influencia <strong>de</strong> diferentesconfiguraciones <strong>de</strong> la plataforma (tales como lastecnologías <strong>de</strong> Intel HyperThreading, SpeedStep yTurboMo<strong>de</strong>, y la precaptación <strong>de</strong> datos), así comodiferentes alternativas <strong>de</strong> <strong>de</strong>scomposición el dominio.Por último, también se han probado distintas opciones<strong>de</strong> optimización dadas por el compilador y laimplementación <strong>de</strong> un procesamiento por bloques.IV. IMPLEMENTACIÓNSe ha trabajado en varias alternativas <strong>de</strong>implementación buscando comparar el uso <strong>de</strong> cálculoredundante frente al uso <strong>de</strong> más comunicaciones ysincronizaciones (C/S). Los resultados muestran que elcálculo redundante mejora el rendimiento <strong>de</strong> laimplementación MPI <strong>de</strong> SI3D y que, sin embargo, parala implementación con OpenMP, el rendimientoaumenta cuando las operaciones redundantes se reducenpara añadir algo <strong>de</strong> sincronización extra.<strong>La</strong> figura 1 muestra el diagrama <strong>de</strong> flujo <strong>de</strong> la mejorimplementación paralela <strong>de</strong> SI3D. <strong>La</strong> etapa 2 no ha sidoparalelizada puesto que supone tan solo un 2% <strong>de</strong>cómputo con respecto a las etapas 1 y 3 juntas en laversión secuencial <strong>de</strong> SI3D.<strong>La</strong> sincronización y comunicación (C/S) ocurre tresveces por iteración. <strong>La</strong> primera se produce cuando elproceso 0 obtiene y resuelve la matriz pentadiagonalpara resolver el movimiento en la superficie libre (η).Una vez resuelta la matriz, el proceso 0 <strong>de</strong>be volver arepartir estos datos entre el resto <strong>de</strong> procesos. <strong>La</strong> terceraocurre al final <strong>de</strong> cada iteración don<strong>de</strong> se <strong>de</strong>benactualizar los valores <strong>de</strong> u, v y η para el siguiente paso<strong>de</strong> tiempo intercambiando datos <strong>de</strong> u, v y η entre losdiferentes procesos. En una implementación sinsolapamiento el número <strong>de</strong> puntos en los que se <strong>de</strong>benintercambiar datos se incrementa: habría cuatro en laetapa 1 y cinco en la 3.<strong>La</strong> implementación paralela <strong>de</strong> SI3D usa<strong>de</strong>scomposición <strong>de</strong> dominio para dividir la carga <strong>de</strong>trabajo entre procesos y hilos, como es usual enaplicaciones <strong>de</strong> dinámica <strong>de</strong> fluidos computacional. El<strong>JP2011</strong>-154


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Lectura <strong>de</strong> los datos <strong>de</strong> entradaDescomposición <strong>de</strong>l dominio paraMPITransmisión <strong>de</strong> datosSi Step = 1w1f111==2Etapa 1. Obtiene un sistema matricialpara las ecuaciones <strong>de</strong> momentumx/y, calcula la matriz <strong>de</strong> coeficientespara la superficie libreTransmisión <strong>de</strong> la matriz <strong>de</strong>coeficientesEtapa 2. Resolución <strong>de</strong>l sistema <strong>de</strong>ecuacionesTransmisión <strong>de</strong> la solución matricialEtapa 3. Resuelve el campo <strong>de</strong>velocida<strong>de</strong>s, transporte escalar y noescalar y asigna los coeficientes <strong>de</strong>difusión y viscosidad <strong>de</strong> turbulencia.Transmisión <strong>de</strong> datosSi Single = 0Single ==2Si Single = 1==2Actualización <strong>de</strong>datos antes <strong>de</strong> unsalto <strong>de</strong> ranaStartStepSi Step = 2==2Inicialización <strong>de</strong>l mo<strong>de</strong>lo eimpresión <strong>de</strong> datos para n=0Comienzo <strong>de</strong> la región paralelaOpenMPEtapa 1. Obtiene un sistema matricialpara las ecuaciones <strong>de</strong> momentumx/y, calcula la matriz <strong>de</strong> coeficientespara la superficie libreTransmisión <strong>de</strong> la matriz <strong>de</strong>coeficientesEtapa 2. Resolución <strong>de</strong>l sistema <strong>de</strong>ecuacionesTransmisión <strong>de</strong> la solución matricialEtapa 3. Resuelve el campo <strong>de</strong>velocida<strong>de</strong>s, transporte escalar y noescalar y asigna los coeficientes <strong>de</strong>difusión y viscosidad <strong>de</strong> turbulencia.Transmisión <strong>de</strong> datosActualización <strong>de</strong>Step = 2ntrap datos antes <strong>de</strong> otro==2Si ntrap > totaltrapSi ntrap paso trapezoidal totaliterTermina la región paralela OpenMPEndDescomposición <strong>de</strong>l dominio paraOpenMPniter = niter + 1Figura 1. Diagrama <strong>de</strong> flujo <strong>de</strong>l algoritmo paralelo.ntrap = ntrap + 1Si niter


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011si se reduce el número <strong>de</strong> comunicaciones usandosolapamiento entre los subdominios.El número <strong>de</strong> comunicaciones <strong>de</strong> tipo send/receive sonmayores si se corta en dos direcciones, como se muestraen la Figura 2(c); aunque el total <strong>de</strong> datosintercambiados y el número <strong>de</strong> cálculo redundantepodría ser menor que alguna <strong>de</strong> las otras dosdistribuciones <strong>de</strong>pendiendo <strong>de</strong> la geometría particular y<strong>de</strong>l número <strong>de</strong> subdominios. Con esta distribución unproceso envía y recibe <strong>de</strong> más <strong>de</strong> dos procesos. Losotros dos tipos <strong>de</strong> distribuciones, el corte estrecho yancho, presentan el mismo número <strong>de</strong> comunicaciones<strong>de</strong>l tipo send/receive. En estos dos casos un procesointercambiará datos con uno o dos procesos mientrasque en con la división <strong>de</strong> la Figura 8(c) un procesopue<strong>de</strong> intercambiar datos con más <strong>de</strong> dos procesos.En [15] se comparan las alternativas <strong>de</strong> la Figura 2(a)y 2(c) usando paso <strong>de</strong> mensajes (MPI) en un cluster <strong>de</strong>4 nodos AMD Opteron 2.2 GHz y dos cores cada unoconectados mediante Gigabit Ethernet. Los resultadospara diferentes tipos <strong>de</strong> simulaciones haciendo uso <strong>de</strong>varias cuadrículas mostraban un mejor rendimiento si la<strong>de</strong>scomposición estaba hecha usando el corte en anchoen vez <strong>de</strong>l corte <strong>de</strong> dos direcciones. [8] compara lasalternativas <strong>de</strong> la Figura 2(b) y 2(c) usando también paso<strong>de</strong> mensajes con MPI en un CC-NUMA HP/ConvexExemplar X-Class (SPP2200) con 64 procesadoresdistribuidos en cuatro híper-nodos. Los ochos nodos <strong>de</strong>un híper-nodo están conectados en red (switch) <strong>de</strong> 960MB/s <strong>de</strong> ancho <strong>de</strong> banda en cada dirección [16]. Siendoesta una red basada en el estándar SCI. Los resultadosmuestran que el corte estrecho da mejores resultados queel <strong>de</strong> dos direcciones.<strong>La</strong> alternativa <strong>de</strong> la 2(c) presenta peor localidad <strong>de</strong>datos que las otras dos alternativas. Esto afecta a lasprestaciones, especialmente en la implementación <strong>de</strong>memoria compartida. Teniendo en cuenta esto y locomentado más arriba, se ha <strong>de</strong>scartado una comparativacon esta alternativa. En el trabajo que aquí se presentase comparan el corte ancho y estrecho tanto en laimplementación <strong>de</strong> paso <strong>de</strong> mensajes como la <strong>de</strong>memoria compartida. Para mejorar la localidad <strong>de</strong> losdatos, tanto para la distribución <strong>de</strong>l corte en ancho yestrecho, los datos se almacenan en posiciones <strong>de</strong>memoria contiguas.TABLA IOPCIONES DE OPTIMIZACIÓN ( INTEL COMPILER 11.1 )O2: Expansión en línea, clonación <strong>de</strong> funciones, optimizaciones clásicas (<strong>de</strong>senrollado <strong>de</strong> bucles, copia y propagación <strong>de</strong>constantes, renombrado <strong>de</strong> variables, liberación <strong>de</strong> memoria inútil) y vectorización (en el que se intentan generar instrucciones <strong>de</strong> tipoMMX, SSE, SSE2). O2 generalmente se recomienda como opción <strong>de</strong> optimización para mejorar el tiempo <strong>de</strong> comunicación.O3: Igual que O2 pero aplicado <strong>de</strong> una forma más agresiva, con técnicas como precaptación, reemplazamiento para reducirreferencias a memoria, transformaciones <strong>de</strong> bucles o <strong>de</strong>l acceso a memoria.ipo: Multifile interprocedural optimization (esto, por ejemplo, permite la expansión y clonación <strong>de</strong> llamadas a funciones <strong>de</strong>finidasen archivos distintos).openmp: Esta opción permite al compilador generar las hilos basándose en las directivas <strong>de</strong> OpenMP incluidas en el mismocompilador.xSSE4.2 (architecture-specific optimization): Intenta generar instrucciones <strong>de</strong>l tipo MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1 ySSE4.2 (vectorización) y pue<strong>de</strong> optimizar la familia <strong>de</strong> procesadores <strong>de</strong> Intel Core i7.prof_gen and prof_use (Profile Gui<strong>de</strong>d Optimization or PGO): Permite optimizar teniendo en cuenta la referencia real <strong>de</strong> losdatos en vez <strong>de</strong> usar datos heurísticos.A. PlataformaV. RESULTADOSLos resultados han sido obtenidos en un pequeñocluster <strong>de</strong> tres nodos conectados mediante una switchGigabit Ethernet. Cada nodo tiene 6 GB <strong>de</strong> memoria yun Core i7 CPU920 (<strong>de</strong>l último cuarto <strong>de</strong>l 2008). CadaCore i7 920 se compone <strong>de</strong> cuatro cores <strong>de</strong> 2,667 GHz(2 hilos por core si está activado Hyperthreading). cacheL3 <strong>de</strong> 8 MB compartidos por todos los cores yQuickPath <strong>de</strong> 4,8 GT/s. El cluster tiene instalado unLinux Fedora 10 (kernel 2.6.27.41)<strong>La</strong>s comunicaciones <strong>de</strong>l sistema han sido evaluadasmediante un benchmark ping-pong programado conMPI. El ancho <strong>de</strong> banda <strong>de</strong> la red obtenido con el testping-pong es <strong>de</strong> 115 MB/s, cerca <strong>de</strong> los teóricos 125MB/s.El ejecutable se ha generado con el compilador Fortran<strong>de</strong> Intel (versión 11) por lo que se ha usado la versiónOpenMP <strong>de</strong> este compilador. Para paso <strong>de</strong> mensajes seha usado MPICH 1.3. El código se ha compilado usandodistintas opciones <strong>de</strong> compilación orientadas a suoptimización y vectorización.En la Tabla I se resume las opciones <strong>de</strong> optimizaciónusadas. Los tiempos <strong>de</strong> ejecución obtenidos con O2 yO3 son muy similares, a<strong>de</strong>más cuando se aña<strong>de</strong> lasopciones ipo o SSE4.2 a O2 u O3 no se presentancambios perceptibles en el rendimiento. De igual formaPGO no mejora el tiempo <strong>de</strong> ejecución con respecto auna versión que no usa PGO. Los ejecutables usados enla siguiente sección se han generado con las opciones <strong>de</strong>compilación O2 y openmp.B. Mo<strong>de</strong>lo <strong>de</strong> Prueba<strong>La</strong> aplicación <strong>de</strong> prueba escogida se trata <strong>de</strong> unasimulación <strong>de</strong>l lago Tahoe, la meta final <strong>de</strong> estasimulación es caracterizar las rutas <strong>de</strong> transporte <strong>de</strong> laslarvas <strong>de</strong> especies invasivas (el bivalve Corbiculafluminea, o almeja asiática) <strong>de</strong>s<strong>de</strong> los puntos cercanos ala costa a otras zonas en el lago, y las condiciones medioambientales a las que podrían estar expuestas durante laruta.Simular un lago <strong>de</strong>l tamaño <strong>de</strong>l lago Tahoe, cuyasdimensiones son <strong>de</strong> 20x30 km, con un tamaño <strong>de</strong> lasceldas en la horizontal <strong>de</strong> O(10) m resulta un problema<strong>de</strong>s<strong>de</strong> el punto <strong>de</strong> vista computacional que sólo pue<strong>de</strong>ser abordado mediante el uso <strong>de</strong> computadoresparalelos. Para hacerse una i<strong>de</strong>a, la relación entre eltiempo real y el tiempo <strong>de</strong> ejecución secuencial (un<strong>JP2011</strong>-156


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Figura 3. Rendimiento <strong>de</strong> diferentes configuraciones <strong>de</strong> la plataforma (Segundos por iteración).core) es aproximadamente 1/1. <strong>La</strong> simulación que sepresenta aquí utiliza una cuadrícula con 95 capas enprofundidad <strong>de</strong> espesor variable con columnascuadradas <strong>de</strong> 100mx100m y 50mx50m. A su vez cadacolumna está compuesta por un número <strong>de</strong> celdillas, entotal 3,663,501 celdillas para las 48,885 columnas <strong>de</strong>lmo<strong>de</strong>lo <strong>de</strong> baja resolución. Mientras, el mo<strong>de</strong>lo <strong>de</strong>mayor resolución tiene 14,654,639 celdillas en 197,781columnas.C. Rendimiento <strong>de</strong> diferentes configuraciones <strong>de</strong> laplataforma.En este trabajo se analiza la influencia en elrendimiento <strong>de</strong> distintas configuraciones <strong>de</strong> <strong>de</strong>l cluster<strong>de</strong> tres nodos ACII. El particular se analiza la influencia<strong>de</strong> la precaptación, el Hyperthreading y la tecnologíaSpeedStep junto con Turbomo<strong>de</strong> <strong>de</strong> Intel.El precaptador hardware lleva datos a cache conantelación a su uso cuando <strong>de</strong>tecta que un patrón <strong>de</strong>acceso a memoria se repite. <strong>La</strong> tecnologíaHyperthreading <strong>de</strong> Intel permite ejecutar dos hilos porcore. SpeedStep permite al sistema operativo controlar lavelocidad <strong>de</strong> cada core y TurboMo<strong>de</strong> permite a cadaprocesador funcionar, bajo ciertas condiciones, a mayorfrecuencia que la asignada.<strong>La</strong> Figura 3 muestra los segundos por iteraciónobtenidos para diferentes configuraciones <strong>de</strong> laplataforma y diferente número <strong>de</strong> hilos y/o procesosusados en cada ejecución. Hay que tener en cuenta queno se incluye el tiempo necesario en distribuir los datosal principio <strong>de</strong> la ejecución y la recolección <strong>de</strong> datos alfinal ya que no <strong>de</strong>pen<strong>de</strong>n <strong>de</strong>l número <strong>de</strong> iteraciones y noconsumen un tiempo <strong>de</strong>stacable. En estas pruebas se hautilizado la distribución por corte estrecho y la versiónque aña<strong>de</strong> cálculo redundante.Se asignan 4 hilos a cada nodo, un número mayor <strong>de</strong>hilos empeora el rendimiento incluso activandoHyperthreading. En la Figura 3, la columna HSTPmuestra los resultados para la configuración que se usapor <strong>de</strong>fecto, en dicha configuración la BIOS y el sistemaoperativo tienen activado Hyperthreading, SpeedStep yTurbomo<strong>de</strong> y el hardware <strong>de</strong> precaptación. <strong>La</strong>configuración por <strong>de</strong>fecto <strong>de</strong>l gestor <strong>de</strong> frecuencia <strong>de</strong> laCPU (CPUfreq) en el sistema operativo <strong>de</strong>l cluster eson<strong>de</strong>mand; por tanto, el gestor pue<strong>de</strong> variar la frecuenciaentre un mínimo <strong>de</strong> 1.6 GHz y un máximo <strong>de</strong> 2.667 GHz<strong>de</strong>pendiendo <strong>de</strong> la carga, pudiendo la frecuencia máximaincrementarse gracias a la tecnología TurboMo<strong>de</strong>.En cuanto los resultados dados por esta configuraciónen tiempo <strong>de</strong> ejecución, empeora el rendimiento <strong>de</strong>bidoa la distribución <strong>de</strong> hilos en los ocho cores lógicos <strong>de</strong> unmismo nodo. Si Hyperthreading está <strong>de</strong>sactivado mejorael tiempo, pero si a<strong>de</strong>más se <strong>de</strong>sactivanSpeedStep/Turbomo<strong>de</strong> o la precaptación el tiempo seincrementa levemente. Comparando la columna -STP y ---P se <strong>de</strong>duce que hay un incremento <strong>de</strong> la frecuencia <strong>de</strong>reloj gracias a TurboMo<strong>de</strong>. <strong>La</strong> comparación <strong>de</strong> lascolumnas -STP y -ST- sugiere que el hardware <strong>de</strong>precaptación mejora ligeramente las prestaciones. Losresultados presentados a continuación han sidoobtenidos con la configuración -STP y on<strong>de</strong>mand.Se probó una implementación <strong>de</strong>l procesamiento porbloques en SI3D con el objetivo <strong>de</strong> reducir los fallos <strong>de</strong>cache y así mejorar la localidad <strong>de</strong> los datos. En laspruebas realizadas con esta implementación usando elmo<strong>de</strong>lo con celdillas <strong>de</strong> 100m x 100m y un nodo conhasta 4 hilos se observó una reducción <strong>de</strong>l tiempo <strong>de</strong>ejecución <strong>de</strong>l 4%. Esta técnica solo mejoraba elrendimiento <strong>de</strong> la implementación marginalmente,aunque no se observó en ningún momento queempeorara el tiempo como en el caso <strong>de</strong>l procesamientopor bloques implementado en [10]. Los resultados en[10] se han obtenido en una plataforma IBM conPower5+ 1.9GHz para un grid <strong>de</strong> 1024x1024x10 con10.485.760 celdillas, en estos resultados elprocesamiento por bloques mostraba un malcomportamiento en las pruebas realizadas <strong>de</strong>s<strong>de</strong> 1 a 8procesadores, mientras que mejoraba las prestacionespara 12 y 16 procesadores, siendo este último el númeromáximo <strong>de</strong> procesadores utilizados [10].Comparaciónentre la distribución <strong>de</strong> corte ancho y corte estrecho.<strong>JP2011</strong>-157


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011D. Comparación entre la distribución <strong>de</strong> corte ancho ycorte estrecho.En ambas distribuciones el número <strong>de</strong> comunicacionesque presentan son las mismas, sin embargo son <strong>de</strong>tamaño distinto. A<strong>de</strong>más, para la versión MPI concálculo redundante, la distribución para el corte anchoconsta <strong>de</strong> un mayor número <strong>de</strong> operaciones redundantesya que el bor<strong>de</strong> <strong>de</strong>l corte ancho es mayor.En la Figura 4 se muestra el tiempo <strong>de</strong> ejecución poriteración y la ganancia en velocidad para las dosdistribuciones, corte ancho y estrecho. <strong>La</strong> ganancia en-<strong>La</strong> implementación a nivel <strong>de</strong> procesos mejora usandomás solapamiento mientras que presenta mejorestiempos a nivel <strong>de</strong> hilos cuando dichas áreas <strong>de</strong>solapamiento se reducen para añadir algo <strong>de</strong>sincronización extra.-Con la implementación paralela, una simulación <strong>de</strong> 24horas que usan celdillas cuadradas <strong>de</strong> 50m x 50mrequiere aproximadamente 6 horas si se usa unprocesador (4 hilos) y aproximadamente 2 horas y 30minutos con 3 procesadores (12 hilos). Estos tiemposcontrastan con el tiempo que tarda la simulación con unhilo: <strong>de</strong> 20 horas y 30 minutos.AGRADECIMIENTOSAl proyecto "Evaluación <strong>de</strong>l riesgo <strong>de</strong> la expansión <strong>de</strong>almeja asiática y el impacto medioambiental en el <strong>La</strong>goTahoe. Proyecto: Mo<strong>de</strong>lización <strong>de</strong>l transporte <strong>de</strong> larvas"Financiado por la Estación <strong>de</strong> Investigación <strong>de</strong>lSuroeste <strong>de</strong>l Pacífico, USDA Forest Service.Figura 4. Comparación <strong>de</strong> distribuciones en ancho y en estrecho.velocidad mejora en algunos casos en mayor medida conel corte estrecho porque esta distribución tiene un bor<strong>de</strong><strong>de</strong> menor tamaño que el dado por el corte ancho, siendoeste bor<strong>de</strong> o zona <strong>de</strong> solapamiento <strong>de</strong> un tamaño 25%menor en la distribución con corte estrecho con respectoal corte ancho.VI. CONCLUSIONESEste trabajo presenta y evalúa las prestaciones <strong>de</strong> unaimplementación paralela con hilos y procesos <strong>de</strong> unmo<strong>de</strong>lo hidrodinámico semi-implícito tridimensional.De los resultados obtenidos se pue<strong>de</strong>n extraer lassiguientes conclusiones:-<strong>La</strong> implementación hace un uso positivo <strong>de</strong> laprecaptación hardware (la precaptación reduce el tiempo<strong>de</strong> ejecución entre un 3% y un 8%) y se obtiene ciertamejora usando el procesamiento por bloques (unamejora <strong>de</strong> un 4% aproximadamente).-Intel TurboMo<strong>de</strong> reduce en cierta medida el tiempo <strong>de</strong>ejecución (entre un 2% y un 7% aproximadamente).-las prestaciones se reducen consi<strong>de</strong>rablemente si laconfiguración por <strong>de</strong>fecto <strong>de</strong> la BIOS y <strong>de</strong>l sistemaoperativo <strong>de</strong> la plataforma está activada (el tiempo <strong>de</strong>ejecución se incrementa entre un 40% y un 60%<strong>de</strong>pendiendo <strong>de</strong>l número <strong>de</strong> procesos o hilos usados).Esto se <strong>de</strong>be a la asignación <strong>de</strong> hilos que el sistemaoperativo realiza por <strong>de</strong>fecto entre los ocho coreslógicos <strong>de</strong> un nodo en el caso <strong>de</strong> que Hyperthreadingesté activado. Aunque para este caso realizar laasignación <strong>de</strong> hilos <strong>de</strong> forma explícita pue<strong>de</strong> solucionarel problema en vez <strong>de</strong> <strong>de</strong>sactivar el Hyperthreading.-El procesamiento por bloques añadido reduce eltiempo <strong>de</strong> ejecución levemente.REFERENCIAS[1] B. R. Hodges, J. Imberger, A. Saggio and K. B. Winters,"Mo<strong>de</strong>ling Basin-Scale Internal Waves in a Stratified <strong>La</strong>ke,"Limnology and Oceanography, vol. 45, pp. 1603-1620, Nov., 2000.[2] F. J. Rueda, S. G. Schladow and S. Ó. Pálmarsson, "Basin-scaleinternal wave dynamics during a winter cooling period in a large lake,"J. Geophys. Res., vol. 108, pp. 3097, 03/27. 2003.[3] Haro Ortega, Glòria, "Numerical simulation of shallow waterequations and some physical mo<strong>de</strong>ls in image processing," Open FileReport, B.40014-2005 Universitat Pompeu Fabra., Chapter 2. 2005.[4] P. E. Smith, A Semi-Implicit, Three-Dimensional Mo<strong>de</strong>l ofEstuarine Circulation. ,Open-File Report 2006-1004. USGS.ed.Sacramento, California: 2006,[5] F. J. Rueda and E. A. Cowen, "The resi<strong>de</strong>nce time of afreshwater embayment connected to a large lake," Limnol. Oceanogr.,vol. 50, pp. 1638-1653, 2005.[6] V. Casulli and R. T. Cheng, "Semi-implicit finite differencemethods for three-dimensional shallow water flow," Int. J. Numer.Methods Fluids, vol. 15, pp. 629-648, 1992.[7] L. H. Kantha and C. A. Clayson, "An improved mixed layermo<strong>de</strong>l for geophysical applications," J. Geophys. Res., vol. 99, pp.25235-25266, 1994.[8] W. von Bloh, S. Rost, D. Gerten and W. Lucht, "Efficientparallelization of a dynamic global vegetation mo<strong>de</strong>l with riverrouting," Environmental Mo<strong>de</strong>lling & Software, vol. 25, pp. 685-690,6, 2010.[9] P. Rao, "A parallel hydrodynamic mo<strong>de</strong>l for shallow waterequations," Applied Mathematics and Computation, vol. 150, 2004.[10] M. J. Castro, J. A. García-Rodríguez, J. M. González-Vida andC. Parés, "A parallel 2d finite volume scheme for solving systems ofbalance laws with nonconservative products: Application to shallowflows," Comput. Methods Appl. Mech. Eng., vol. 195, 2006.[11] K. R. Tubbs and F. T. -. Tsai, "Multilayer shallow water flowusing lattice Boltzmann method with high performance computing,"Adv. Water Resour., vol. 32, pp. 1767-1776, 12. 2009.[12] O. Nesterov, "A simple parallelization technique with MPI forocean circulation mo<strong>de</strong>ls," Journal of Parallel and DistributedComputing, vol. 70, pp. 35-44, 1. 2010.[13] D. van Dyk, M. Geveler, S. Mallach, D. Ribbrock, D. Göd<strong>de</strong>keand C. Gutwenger, "HONEI: A collection of libraries for numericalcomputations targeting multiple processor architectures," Comput.Phys. Commun., vol. 180, pp. 2534-2543, 12. 2009.[14] M. J. Castro, J. A. García-Rodríguez, J. M. González-Vida andC. Parés, "Solving shallow-water systems in 2D domains using FiniteVolume methods and multimedia SSE instructions," J. Comput. Appl.Math., vol. 221, pp. 16-32, 2008.[15] l. A. <strong>de</strong>, J. Mantas and M. Castro, "Simulation of one-layershallow water systems on multicore and CUDA architectures," TheJournal of Supercomputing, online 10 March 2010. 2010.[16] O. Nesterov, "A simple parallelization technique with MPI forocean circulation mo<strong>de</strong>ls," Journal of Parallel and DistributedComputing, vol. 70, pp. 35-44, 1. 2010.<strong>JP2011</strong>-158


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Paralelización <strong>de</strong>l Análisis <strong>de</strong> Imágenes conTensor <strong>de</strong> Difusión en Resonancia Magnéticausando GPUsMoisés Hernán<strong>de</strong>z 1 , Ginés D. Guerrero 1 , José M. Cecilia 1 , José M. García 1 y AlbertoInuggi 2 ,Resumen— Enten<strong>de</strong>r la función <strong>de</strong>l cerebro atendiendoa las conexiones existentes entre sus diferentesáreas es uno <strong>de</strong> los mayores retos <strong>de</strong> la neuroimagen.<strong>La</strong>s Imágenes con Tensor <strong>de</strong> Difusión (ITD) en resonanciamagnética proporcionan información <strong>de</strong>l cerebroque no está presente en ninguna otra modalidad<strong>de</strong> imágenes. Mucha <strong>de</strong> esta valiosa informaciónpue<strong>de</strong> ser extraída solamente con la ayuda <strong>de</strong> un postprocesamiento<strong>de</strong> los datos adquiridos al paciente. Sinembargo, la necesidad computacional <strong>de</strong> los algoritmosutilizados hace muy tediosa su práctica, llegandoa tardar el post-procesado en algunos casos más <strong>de</strong> 24horas para un sólo paciente. En este artículo discutimosla paralelización en la GPU <strong>de</strong> una herramienta<strong>de</strong> ITD propuesta en el programa FSL <strong>de</strong>l centro FM-RIB <strong>de</strong> la <strong>Universidad</strong> <strong>de</strong> Oxford. Nuestros resultados<strong>de</strong>muestran que se pue<strong>de</strong>n alcanzar gran<strong>de</strong>s aceleracionesen este tipo <strong>de</strong> aplicaciones (hasta 85x) en comparacióncon las tradicionales CPUs, pudiendo estarambas plataformas en un or<strong>de</strong>nador <strong>de</strong> sobremesa ya un coste similar.Palabras clave— GPUs, Bioinformática, ResonanciaMagnética, Imágenes con Tensor <strong>de</strong> DifusiónI. IntroducciónLAS imágenes con tensor <strong>de</strong> difusión (ITD) constituyenun método relativamente nuevo en lasimágenes por resonancia magnética (IRM), en el cualse proponen técnicas no invasivas que permiten investigarlas propieda<strong>de</strong>s locales <strong>de</strong> las fibras <strong>de</strong> lamateria blanca [1]. <strong>La</strong>s ITDs son sensibles a la difusión<strong>de</strong> las moléculas <strong>de</strong> agua, las cuales pue<strong>de</strong>nvariar a lo largo <strong>de</strong> los diferentes tejidos cerebrales,principalmente cuando se encuentran próximasa las zonas <strong>de</strong> materia blanca, don<strong>de</strong> el agua se difun<strong>de</strong>con mayor facilidad a lo largo <strong>de</strong> sus principalesconexiones. Mediante la aplicación <strong>de</strong> fuertespulsos magnéticos es posible crear un mapa con lasprincipales direcciones <strong>de</strong> difusión en cada parte <strong>de</strong>lcerebro, y con el uso <strong>de</strong>l software a<strong>de</strong>cuado conseguirel tracto entre sus diferentes áreas, es <strong>de</strong>cir, la representación<strong>de</strong> una red <strong>de</strong> interconexión tridimensional<strong>de</strong>l cerebro, llamada tractografía. Este procedimientoha sido usado para investigar cambios durante el<strong>de</strong>sarrollo humano y el envejecimiento, en estudios<strong>de</strong> enfermeda<strong>de</strong>s neuro<strong>de</strong>generativas y <strong>de</strong> pacientesque tienen ictus u otras otras patologías cerebrales.Bedpost es una aplicación perteneciente al softwareFSL (<strong>de</strong>sarrollada en el Centro <strong>de</strong> Investigación1 Grupo <strong>de</strong> Arquitectura y Computación Paralela, Dpto.<strong>de</strong> Ingeniería y Tecnología <strong>de</strong> Computadores, Univ.<strong>de</strong> Murcia, e-mail: {moises, gines.guerrero, chema,jmgarcia}@ditec.um.es.2 <strong>La</strong>boratorio <strong>de</strong> Neurociencia Cognitiva, Dpto. <strong>de</strong> Psicología,Univ. <strong>de</strong> Murcia, e-mail: inuggi@um.es.FMRIB <strong>de</strong> la <strong>Universidad</strong> <strong>de</strong> Oxford), que es capaz<strong>de</strong> realizar tractografías. A<strong>de</strong>más, este software tieneun enfoque multi-fibra que pue<strong>de</strong> incrementar <strong>de</strong>forma significativa su sensibilidad, teniendo la capacidad<strong>de</strong> reconstruir los tractos dominantes [2]. Suprincipal <strong>de</strong>sventaja es el tiempo <strong>de</strong> ejecución, don<strong>de</strong><strong>de</strong>pendiendo <strong>de</strong> los parámetros <strong>de</strong> la secuencia <strong>de</strong>resonancia magnética, el análisis <strong>de</strong> un sujeto pue<strong>de</strong>llevar más <strong>de</strong> 24 horas.Debido a que los estudios pue<strong>de</strong>n llegar a realizarsesobre un gran número <strong>de</strong> personas, proponemos laparalelización <strong>de</strong> esta aplicación en una arquitecturamasivamente paralela, como es la <strong>de</strong> las unida<strong>de</strong>sgráficas <strong>de</strong> procesamiento (GPUs). <strong>La</strong>s GPUs actualesson procesadores masivamente paralelos que soncapaces <strong>de</strong> soportar varios miles <strong>de</strong> hilos ejecutándoseen paralelo. Muchas aplicaciones <strong>de</strong> propósito generalhan sido diseñadas para estas plataformas <strong>de</strong>bidoa su alto rendimiento. El lenguaje que se usapara programar estos dispositivos es C con extensionesCUDA. <strong>La</strong>s nuevas generaciones <strong>de</strong> GPU tienenhasta 512 procesadores escalares por chip, pudiendoalcanzar un rendimiento pico teórico <strong>de</strong> hasta 1TeraFLOP.Hemos paralelizado la aplicación Bedpost en CU-DA, para así aprovechar la gran capacidad <strong>de</strong> computoque poseen las GPUs. Se han llevado a cabo unconjunto <strong>de</strong> pruebas variando sus distintos parámetros<strong>de</strong> entrada, llegando a obtener una mejora entorno a <strong>de</strong> 85X respecto al código secuencial.El resto <strong>de</strong>l documento está estructurado como sigue.En la sección II introducimos los conceptos necesariospara enten<strong>de</strong>r mejor el resto <strong>de</strong>l contenido:por un lado se <strong>de</strong>scribe el mo<strong>de</strong>lo <strong>de</strong> tensor <strong>de</strong> difusión(apartado II-A); y luego pasamos a comentarbrevemente algunos aspectos <strong>de</strong> la arquitectura <strong>de</strong> laGPU y <strong>de</strong>l mo<strong>de</strong>lo <strong>de</strong> programación CUDA (apartadoII-B). En la sección III <strong>de</strong>scribimos el algoritmoque es utilizado por Bedpost <strong>de</strong> forma secuencial.Posteriormente, se <strong>de</strong>talla la versión paralela implementadaen CUDA en la sección IV. Ambas implementacionesson analizadas mediante un conjunto <strong>de</strong>pruebas en la sección V. Finalmente la sección VImuestra las conclusiones y el trabajo futuro.II. PreliminaresA. Imágenes con Tensor <strong>de</strong> Difusión (ITD)<strong>La</strong>s moléculas <strong>de</strong> agua están en un constante movimientoaleatorio conocido como movimiento brow-<strong>JP2011</strong>-159


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011niano, que trasladado a un nivel macroscópico produceel proceso <strong>de</strong> difusión [3].El tejido cerebral humano se pue<strong>de</strong> dividir en tresclases principales: materia blanca, materia gris y fluidocerebroespinal. En la materia gris y el fluido cerebroespinal,la difusión es aleatoria porque las moléculas<strong>de</strong> agua se mueven en todas las direcciones. Estefenómeno se <strong>de</strong>nomina difusión isotrópica.Sin embargo, en la materia blanca el movimiento<strong>de</strong> las moléculas no conserva esa componente totalmentealeatoria. <strong>La</strong> materia blanca está formadaprincipalmente por axones, que estan principalmenterecubiertos <strong>de</strong> mielina. Esta sustancia es una barrerapara el movimiento <strong>de</strong> la moléculas <strong>de</strong> agua, y portanto condiciona el movimiento <strong>de</strong> las mismas. Eneste caso hablamos <strong>de</strong> difusión anisotrópica [4].El mo<strong>de</strong>lo tensor <strong>de</strong> difusión nos permite mo<strong>de</strong>larla dirección <strong>de</strong> las fibras nerviosas en cada una <strong>de</strong> laspartes <strong>de</strong>l cerebro. Gracias a la difusión anisotrópicaes posible observar las direcciones preferenciales <strong>de</strong>difusión <strong>de</strong> las moléculas <strong>de</strong> agua en la materia blancacerebral, correspondiendo estas direcciones con lasdirecciones que siguen las fibras nerviosas cerebrales,y por tanto permite mo<strong>de</strong>lar el tracto cerebral.Los datos <strong>de</strong> imagen <strong>de</strong> resonancia magnética cerebral<strong>de</strong> un sujeto estan compuestos por varias imágenes2D, cada una <strong>de</strong> las cuales se correspon<strong>de</strong> con uncorte transversal <strong>de</strong>l cerebro (o slice). Un slice, a suvez, está compuesto por pixels, que representan launidad mínima <strong>de</strong> la imagen 2D. Asimismo, un voxeles la unidad cúbica mínima que compone el objetotridimensional.El objetivo <strong>de</strong> las Imágenes con Tensor <strong>de</strong> Difusión(ITD) es mo<strong>de</strong>lar las direcciones <strong>de</strong>l tracto <strong>de</strong> variasfibras nerviosas cerebrales en cada uno <strong>de</strong> los voxels.Esto se consigue aplicando dos pulsos <strong>de</strong> gradientes<strong>de</strong> campo magnético sobre el tejido cerebral mientrasse produce el proceso <strong>de</strong> difusión, lo que genera unaseñal <strong>de</strong> campo magnético asociada a la difusión quese produce durante los dos pulsos. A partir <strong>de</strong> laseñal obtenida se genera una imagen digital (Imagen<strong>de</strong> Resonancia Magnética). Si se aplican diferentesdirecciones en los gradientes obtendremos una señalcompuesta, a partir <strong>de</strong> la cual, gracias a métodos<strong>de</strong> análisis numéricos podremos reconstruir el tensorque <strong>de</strong>scribe el proceso <strong>de</strong> difusión y por consiguientela dirección principal <strong>de</strong> las fibras en cada voxel [5].El cálculo <strong>de</strong> estas direcciones está asociado a ciertaincertidumbre, ya que la información se recoge apartir <strong>de</strong> varias direcciones en los gradientes aplicados,y a<strong>de</strong>más se produce un cierto ruido durante laadquisición <strong>de</strong> la imagen por resonancia magnética.Por tanto, el objetivo se reduce a obtener aquella direccióncon máxima probabilidad <strong>de</strong> cada una <strong>de</strong> lasfibras nerviosas que se <strong>de</strong>sea mo<strong>de</strong>lar [6].<strong>La</strong> ecuación 1 muestra el mo<strong>de</strong>lado <strong>de</strong> la señal parala medida <strong>de</strong> difusión <strong>de</strong> cada uno <strong>de</strong> los voxels,<strong>de</strong>spués <strong>de</strong> aplicar los 2 gradientes <strong>de</strong> difusión con ndirecciones [2, 6–8].S(g) =S 0[(1 −N∑f i ) exp(−bd)+i=1N∑] (1)f i exp(−bd(gv i ) 2 )i=1Don<strong>de</strong> S 0 es la señal sin difusión, f ∈ [0, 1] es lafracción <strong>de</strong> volumen <strong>de</strong> difusión anisotrópica en el voxel;b indica la magnitud y duración <strong>de</strong> los gradientes,a<strong>de</strong>más <strong>de</strong>l tiempo entre el par <strong>de</strong> gradientes aplicadospara obtener los datos (medido en s/mm 2 ); <strong>de</strong>s la difusividad; g indica la dirección <strong>de</strong> cada gradienteaplicado; finalmente v <strong>de</strong>scribe las orientaciones<strong>de</strong> una fibra ante los gradientes aplicados. Estasorientaciones viene <strong>de</strong>finidas a partir <strong>de</strong> operacionestrigonométricas (senos y cosenos).Los parámetros <strong>de</strong> cada una <strong>de</strong> las fibras mo<strong>de</strong>ladas,los cuales <strong>de</strong>scriben su orientación, <strong>de</strong>ben serestimados. Cuando adquirimos los datos <strong>de</strong> un sujetoconocemos la señal S con la medida <strong>de</strong> difusión quese ha obtenido, la cual <strong>de</strong>pen<strong>de</strong> <strong>de</strong> los parámetrosque queremos estimar. El mo<strong>de</strong>lo <strong>de</strong> la señal <strong>de</strong>scritoen la ecuación 1 <strong>de</strong>fine la máxima probabilidad<strong>de</strong> que se produzca la señal obtenida (ya que se haproducido y la conocemos) dados los parámetros que<strong>de</strong>sconocemos P (señal | parámetros). El teorema <strong>de</strong>Bayes nos permite calcular la probabilidad a posterioriP (parámetros | señal), es <strong>de</strong>cir, dada una señalsaber cual es la probabilidad <strong>de</strong> que este formadapor unos parámetros concretos. De esta manera sepue<strong>de</strong>n proponer muestras <strong>de</strong> los parámetros a partir<strong>de</strong> la distribución a posteriori conjunta utilizandoel algoritmo <strong>de</strong> Monte Carlo <strong>de</strong> ca<strong>de</strong>nas <strong>de</strong> Markov(MCMC). Para ello generamos números aleatorios querepresentan los parámetros a estimar y escogemosquellos que maximicen la probabilidad <strong>de</strong> alcanzarla señal que se ha obtenido en el tiempo <strong>de</strong> adquisición[8].Para realizar una buena estimación <strong>de</strong> los parámetrosen el algoritmo MCMC, se realiza una primeraaproximación don<strong>de</strong> se utiliza el algoritmo <strong>de</strong>Levenberg-Marquardt [9, 10].B. <strong>La</strong> unidad <strong>de</strong> procesamiento gráfico (GPU))<strong>La</strong> nuevas unida<strong>de</strong>s <strong>de</strong> procesamiento gráfico(GPU, Graphics Processing Unit) presentan una arquitecturamasivamente paralela, capaz <strong>de</strong> manejarmiles <strong>de</strong> hilos concurrentemente <strong>de</strong> manera altamenteeficiente tanto para aplicaciones gráficas, como paraaplicaciones <strong>de</strong> propósito general.En concreto, la línea Tesla <strong>de</strong> Nvidia para el mercado<strong>de</strong> altas prestaciones, y en concreto la TeslaC2050, presenta un total <strong>de</strong> 448 procesadores (oStreaming-Processors, SPs) organizados en 14 multiprocesadores(o Streaming Multiprocessor, SMs) y3GB <strong>de</strong> memoria principal GDDR5 (llamada <strong>de</strong>viceo global memory). <strong>La</strong> GPU se comunica con la CPUa través <strong>de</strong>l bus PCI Express x16 (proporcionandoun ancho <strong>de</strong> banda <strong>de</strong> 4 GB/s en cada dirección).<strong>JP2011</strong>-160


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 2. Un hilo secuencial ejecutando n ∗ m voxels <strong>de</strong> un slice.Fig. 1. Esquema <strong>de</strong> la arquitectura Fermi <strong>de</strong> NVIDIA.El lenguaje <strong>de</strong> programación utilizado para lasGPUs <strong>de</strong> Nvidia se <strong>de</strong>nomina CUDA (Compute UnifiedDevice Architecture) [11]. El lenguaje CUDA esmuy similar al lenguaje estándar C con la inclusión<strong>de</strong> algunas extensiones. En un programa escrito enCUDA po<strong>de</strong>mos diferenciar dos partes principales.<strong>La</strong> parte host que se ejecuta secuencialmente en laCPU, y la parte <strong>de</strong>vice que es ejecutada en la GPU enforma <strong>de</strong> funciones <strong>de</strong>nominadas Kernels. Un kernelsigue el mo<strong>de</strong>lo <strong>de</strong> ejecución SPMD (Single-ProgramMultiple-Data), don<strong>de</strong> un gran número <strong>de</strong> hilos seejecutan en paralelo. El programador organiza estoshilos en bloques <strong>de</strong> hilos (ver figura 1). Estos hilospue<strong>de</strong>n compartir datos y sincronizarse entre sí, sinembargo, no existen primitivas <strong>de</strong> sincronización entrehilos <strong>de</strong> distintos bloques, y la única manera <strong>de</strong>compartir datos es a través <strong>de</strong> la memoria principal<strong>de</strong> la GPU. A<strong>de</strong>más los bloques <strong>de</strong> hilos se agrupanen Grids. Todos los hilos que forman un Grid ejecutanel mismo kernel.III. Descripción <strong>de</strong> la aplicación BedpostEn esta sección <strong>de</strong>scribimos la aplicación secuencialBedpost perteneciente al software FSL [12],<strong>de</strong>sarrollada en el Centro <strong>de</strong> Investigación FMRIB<strong>de</strong> la <strong>Universidad</strong> <strong>de</strong> Oxford. El algoritmo 1 muestrael pseudocódigo <strong>de</strong> la aplicación Bedpost. Todoslos slices asociados con la imagen <strong>de</strong> un sujeto sonrecorridos secuencialmente procesando cada uno <strong>de</strong>sus voxels (véase figura 2). Este procesado consisteen dos partes bien diferenciadas:1. Aproximación inicial <strong>de</strong>l valor <strong>de</strong> los parámetrosmediante el algoritmo LevenbergMarquardt.2. El algoritmo <strong>de</strong> Monte Carlo con ca<strong>de</strong>nas <strong>de</strong>Markov (MCMC) para estimar el valor <strong>de</strong> losparámetros (también <strong>de</strong>scrito en el pseudocódigo<strong>de</strong>l algoritmo 1).En la primera etapa se aproximan los parámetrosa un valor inicial para facilitar que algoritmo MCMCpueda hacer una buena estimación. El mecanismo sebasa en un procedimiento iterativo <strong>de</strong> optimización.<strong>La</strong> segunda etapa toma como entrada los valorescalculados en la etapa anterior, aproximando conmás certeza la orientación final <strong>de</strong> la fibra en cadavoxel. Para ello, se utiliza el algoritmo MCMCdon<strong>de</strong> se proponen muestras para cada uno <strong>de</strong> losparámetros, generando para ello números aleatorios(los cuales son ajustados a una distribución normalestándar), aceptando o rechazando la muestra segúnun criterio que viene dado por el valor que toma laecuación 1, la cual se recalcula cada vez que se proponeun nuevo parámetro.El número <strong>de</strong> parámetros a estimar <strong>de</strong>pen<strong>de</strong> <strong>de</strong> lacantidad <strong>de</strong> fibras (f) que <strong>de</strong>seamos mo<strong>de</strong>lar en cadavoxel. Este número viene dado por la ecuación 2+3f.Por <strong>de</strong>fecto f = 2, y f no suele ser mayor <strong>de</strong> 4, es<strong>de</strong>cir, tenemos entre 8 y 14 parámetros.Los datos <strong>de</strong> entrada <strong>de</strong>l algoritmo Bedpost , es<strong>de</strong>cir, el número <strong>de</strong> slices, voxels, y gradientes <strong>de</strong>difusión viene dado en el tiempo <strong>de</strong> adquisición <strong>de</strong>las imágenes <strong>de</strong> resonancia, según el factor calidad/tiempoque se <strong>de</strong>see en los datos obtenidos.IV. Diseño <strong>de</strong> la aplicación Bedpost enCUDAUna primera alternativa <strong>de</strong> diseño paralelo <strong>de</strong>Bedpost viene motivada por la naturaleza paralela<strong>de</strong> todos los slices. Esta es la filosofía que siguen los<strong>de</strong>sarrollares <strong>de</strong> FSL [13], pudiendo hacer uso <strong>de</strong> variosprocesadores diferentes mediante el uso <strong>de</strong> Sun-GridEngine (SGE) [14], procesando cada uno <strong>de</strong> ellosun slice <strong>de</strong> manera in<strong>de</strong>pendiente. Este diseño, sinembargo, implica una gran carga <strong>de</strong> trabajo a cadaprocesador o hilo <strong>de</strong> ejecución, y por tanto no seadapta bien al mo<strong>de</strong>lo <strong>de</strong> ejecución CUDA, ya que requiere<strong>de</strong> una paralelización <strong>de</strong> la aplicación con unagranularidad mucho más fina, para así po<strong>de</strong>r sacarpartido <strong>de</strong> los miles <strong>de</strong> hilos que es capaz <strong>de</strong> ejecutaren paralelo.Un enfoque alternativo <strong>de</strong> diseño es <strong>de</strong>scen<strong>de</strong>r alnivel <strong>de</strong> voxels. Un slice pue<strong>de</strong> contener miles <strong>de</strong>voxels, y a<strong>de</strong>más se pue<strong>de</strong>n computar <strong>de</strong> forma in<strong>de</strong>pendiente,por lo que podríamos tener un hilo<strong>JP2011</strong>-161


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Algoritmo 1 Pseudocódigo <strong>de</strong> la aplicación BedpostBedpost1: para todo slice hacer2: para todo voxel hacer3: LevenbergMarquardt()4: MCMC()5: fin para6: fin paraMCMC1: para i = 0 hasta numIteraciones hacer2: para todo parametro hacer3: sample p = generar random()4: sample p n = normalizar(sample p)5: recalcular senal(direcciones)6: aceptarRechazar(sample p n)7: fin para8: fin paracomputando cada uno <strong>de</strong> los voxels <strong>de</strong> un slice <strong>de</strong>forma paralela tal y como muestra la figura 3. Fig. 3. voxels <strong>de</strong> un slice, agrupados en x bloques <strong>de</strong> tamañoy.El diseño <strong>de</strong>l algoritmo <strong>de</strong> Levenberg-Marquar<strong>de</strong>stá implementado en un único kernels basado enesta i<strong>de</strong>a. Cada hilo <strong>de</strong> CUDA sea mapeado con unvoxel, encargándose este <strong>de</strong> a<strong>de</strong>cuar sus valores iniciales.Por lo que tendremos tantos hilos como voxelstenga un slice concreto.Algoritmo 2 Pseudocódigo <strong>de</strong> la aplicaciónBedpost paralelizada en CUDA.1: para todo slice hacer2: bloqs := voxels/tamBloque13: levenbergKernel(bloqs, tamBloque1)4: genNumsKernel(bloqs, tamBloque1)5: ajuteNumsKernel(bloqs, tamBloque1)6: bloqs := (voxels ∗ direcs)/tamBloque27: mcmcKernel(bloqs, tamBloque2)8: fin paraEl caso <strong>de</strong>l algoritmo MCMC es un poco mas complejo.En este caso, el computo se ha divido en treskernels (véase el algoritmo 2).El primer kernel es encargado <strong>de</strong> la generación eficiente<strong>de</strong> números aleatorios. En cada iteración <strong>de</strong>lalgoritmo se <strong>de</strong>ben generar varios números aleatorios(dos por cada parámetro) lo que provoca que en slicescon varios miles <strong>de</strong> voxels se generen cientos <strong>de</strong>millones <strong>de</strong> números aleatorios. Estos números songenerados mediante el uso <strong>de</strong> la librería CURAND [15]<strong>de</strong> CUDA.Posteriormente, la mitad <strong>de</strong> los números pseudoaleatoriosque han sido generados antes <strong>de</strong>ben serajustados a una distribución normal estándar. Estose realiza mediante otro kernel para así po<strong>de</strong>r ejecutarun hilo por cada voxel.Finalmente se ejecuta el kernel MCMC. En este caso,el diseño difiere con los planteados anteriormente.Ahora tenemos tantos hilos como direcciones se quierananalizar para cada voxel, repartimos los voxelesentre los bloques (véase la figura 4). De este modoampliamos el número <strong>de</strong> hilos por bloque hasta alcanzarvalores entre 128 − 256 hilos. <strong>La</strong> existencia <strong>de</strong>slices con un número pequeño <strong>de</strong> voxels hacen queen ciertos casos no se pueda explotar el paralelismo<strong>de</strong> la GPU. A<strong>de</strong>más, este diseño nos beneficia a lahora <strong>de</strong> recalcular el valor <strong>de</strong> la ecuación 1, ya quese podrá realizar en paralelo para cada una <strong>de</strong> lasdirecciones. Fig. 4. m∗n∗direc hilos ejecutados en paralelo para el cálculo<strong>de</strong> m∗n voxels <strong>de</strong> un slice en direc direcciones, agrupadosen x bloques <strong>de</strong> tamaño y, don<strong>de</strong> y es múltiplo <strong>de</strong> direc.V. Evaluación <strong>de</strong> los ResultadosEn esta sección se muestran los resultados obtenidosen la ejecución <strong>de</strong> la aplicación Bedpost <strong>de</strong>lsoftware FSL comparando el tiempo <strong>de</strong> ejecución entreCPU y GPU.En nuestras pruebas se ha utilizado la versión 4.0<strong>de</strong> CUDA sobre una GPU Tesla C2050. Esta GPUse encuentra incorporada en un or<strong>de</strong>nador con dosprocesadores Intel Xeon E5620 a 2.40GHz y con 4GB<strong>de</strong> memoria principal. <strong>La</strong>s pruebas en CPU se hanrealizado utilizando un único hilo mapeado a uno <strong>de</strong>los cores <strong>de</strong>l sistema.Hemos dividido las pruebas en 4 partes, mostrandouna gráfica en escala logarítmica y un análisis <strong>de</strong>los resultados para cada una <strong>de</strong> ellas. Estas partes<strong>JP2011</strong>-162


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011se correspon<strong>de</strong>n con los distintos kernels que se han<strong>de</strong>sarrollado en CUDA:1. Ajuste <strong>de</strong> los parámetros iniciales conLevenberg-Marquardt.2. Generación <strong>de</strong> números pseudo-aleatorios.3. Ajuste <strong>de</strong> los números pseudo-aleatorios obtenidosa una distribución normal estándar.4. Algoritmo MCMC.En la figura 5 se observa el rendimiento <strong>de</strong> la ejecución<strong>de</strong>l algoritmo Levenberg-Marquardt en CPUy GPU, cuya función es ajustar los parámetros inicialesantes <strong>de</strong> llamar al procedimiento MCMC. Se hanrealizado pruebas para ajustar 8 y 14 parámetros (2y 4 fibras respectivamente) en slices con tamañosdiferentes en cuanto al número <strong>de</strong> voxels que contienen.Se observa que a mayor número <strong>de</strong> voxels enun slice (lo que conlleva un mayor número <strong>de</strong> hilosejecutándose en paralelo en GPU) obtenemos unamejora mayor en la GPU respecto a la CPU, llegandoa ser esta <strong>de</strong> 20X en el caso <strong>de</strong> 8 parámetros, y<strong>de</strong> 56X en el caso <strong>de</strong> 14 parámetros. Fig. 5. Relación <strong>de</strong> tiempos en CPU y GPU, en escala logarítmica,al ejecutar Levenberg-Marquardt con 8 y 14parámetros.<strong>La</strong> comparativa entre el tiempo empleado por laversión paralela y secuencial en cuanto a la generación<strong>de</strong> números pseudo-aleatorios es mostrada en lafigura 6. Como se ha comentado anteriormente, enCPU se ha utilizado la función rand() pertenecientea la librería CSTDLIB <strong>de</strong> C++, mientras que en GPUse ha utilizado la librería CURAND <strong>de</strong> CUDA. Como seaprecia en dicha figura, a partir <strong>de</strong> la generación <strong>de</strong>más <strong>de</strong> 5 millones <strong>de</strong> números aleatorios, resulta máseficiente su generación en GPU, llegando a obteneruna ganancia <strong>de</strong> 140X con 380 millones <strong>de</strong> númerosaleatorios.<strong>La</strong> figura 7 muestra la comparativa <strong>de</strong> rendimientoCPU y GPU <strong>de</strong>l kernel encargado <strong>de</strong> realizar el ajustea una distribución normal <strong>de</strong> los números pseudoaleatoriosobtenidos anteriormente. En este caso, apartir <strong>de</strong> la generación <strong>de</strong> 500.000 números empezamosa obtener mejoras en el tiempo <strong>de</strong> procesamientoen GPU con respecto al código secuencial, llegandoa conseguir una mejora <strong>de</strong> 14X con 350 millones <strong>de</strong>números.Por último, en la figura 8 se muestra la comparativa,entre ambas versiones para el tiempo que setarda en ejecutar el algoritmo MCMC y el tiempo total Fig. 6. Comparativa entre el uso <strong>de</strong> rand() en CPU y la libreríaCURAND en GPU, en escala logarítmica, para generar unconjunto <strong>de</strong> números aleatorios. Fig. 7. Relación <strong>de</strong> tiempos en CPU y GPU, en escala logarítmica,al ajustar un conjunto <strong>de</strong> números a una distribuciónnormal estándar.que requiere la aplicación Bedpost para su ejecucióncompleta (es <strong>de</strong>cir, teniendo en cuenta las 4 fases).En dicha figura se refleja el tiempo en segundos respectoal número <strong>de</strong> iteraciones que se realizan en elalgoritmo MCMC. A<strong>de</strong>más, se han realizado pruebaspara mo<strong>de</strong>lar 2 y 4 fibras (figuras 8a y 8b respectivamente).<strong>La</strong>s dimensiones <strong>de</strong> las imágenes que toma elalgoritmo como entrada son <strong>de</strong> 128∗128∗47∗35, don<strong>de</strong>las dimensiones hacen referencia a ancho ∗ alto ∗número <strong>de</strong> slices ∗ número <strong>de</strong> direcciones. Se pue<strong>de</strong>observar que la mejora <strong>de</strong>l tiempo <strong>de</strong>l algoritmo MCMCy <strong>de</strong>l tiempo total que se obtienen son proporcionales,en este caso, con los datos <strong>de</strong> entrada antes mencionados.<strong>La</strong> máxima mejora que se ha conseguidoes <strong>de</strong> 127X en GPU respecto a CPU al ejecutar elalgoritmo MCMC, mientras que la máxima mejora enel tiempo total <strong>de</strong> la aplicación Bedpost es <strong>de</strong> 85X.A<strong>de</strong>más, se han realizado pruebas con otras imágenes<strong>de</strong> entrada <strong>de</strong> diferentes tamaños. En la tabla Ise pue<strong>de</strong> observar un resumen <strong>de</strong> la mejora obtenidapor el algoritmo paralelizado en CUDA frente asu versión secuencial para cada una <strong>de</strong> las imágenesusadas en nuestras pruebas.VI. Conclusiones y Trabajo FuturoEn este artículo hemos discutido la paralelización<strong>de</strong>l análisis <strong>de</strong> imágenes con tensor <strong>de</strong> difusión en resonanciasmagnéticas en la GPU. Para ello, hemosutilizado la aplicación Bedpost incluida en el softwareFSL, <strong>de</strong>sarrollado en el centro <strong>de</strong> investigaciónFMRIB <strong>de</strong> la <strong>Universidad</strong> <strong>de</strong> Oxford.<strong>JP2011</strong>-163


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011 (a) 2 Fibras (b) 4 FibrasFig. 8. Comparativa <strong>de</strong> tiempo total <strong>de</strong> ejecución <strong>de</strong> Bedpost y MCMC entre CPU y GPU, en escala logarítmica, con unaimagen <strong>de</strong> dimensiones 128x128x47 y 35 direcciones diferentes en los gradientes, mo<strong>de</strong>lando 2 y 4 fibras, y alternando elnúmero <strong>de</strong> iteraciones para el algortimo MCMC.TABLA IMáxima mejora obtenida al ejecutar Bedpost en GPUpara diferentes tamaños <strong>de</strong> imagen respecto a suversión secuencial.DIM. IMAGEN NFIBRAS NITERS MEJORA128x128x47x352 9000 69X4 1125 85X256x256x47x352 4500 60X4 2250 65X128x104x60x622 9000 84X4 2250 83XNuestro análisis experimental en la GPU muestraunos resultados prometedores, llegando a obtenerunas aceleraciones en torno a 85x en comparacióncon el código secuencial.Tras comprobar que la GPU es una arquitecturaa<strong>de</strong>cuada para la paralelización <strong>de</strong>l aplicaciónBedpost, las futuras líneas <strong>de</strong> investigación irán dirigidasa la paralelización <strong>de</strong> otros aplicaciones incluidasen el software FSL.Agra<strong>de</strong>cimientosEl presente trabajo ha sido financiado mediantela Fundación Séneca (Agencia Regional <strong>de</strong> Cienciay Tecnología, Región <strong>de</strong> Murcia) con la ayuda00001/CS/2007, y también al MEC y la ComisiónEuropea FEDER con las ayudas CSD2006-00046 yTIN2009-14475-C04.Referencias[1] Denis Le Bihan, “Looking into the functional architectureof the brain with diffusion mri,” Nature ReviewsNeuroscience, vol. 4, pp. 469–480, 2003.[2] T.E.J. Behrens, H.Johansen Berg, S.Jbabdi, M.F.S.Rushworth, and M.W. Woolrich, “Probabilistic diffusiontractography with multiple fibre orientations: What canwe gain?,” NeuroImage, vol. 34, no. 1, pp. 144–155, 2007.[3] David Solomon Tuch, Diffusion MRI of complex tissuestructure, Ph.D. thesis, Massachusetts Institute of Technology,2002.[4] MSc. Diwei Zhou, Statistical analysis of diffusion tensorimaging, Ph.D. thesis, University of Nottingham, 2010.[5] J. E. Castro and J. T. Hernán<strong>de</strong>z, “Algoritmos aplicadosen el cálculo, análisis y aplicación <strong>de</strong>l tensor <strong>de</strong> difusión enimágenes médicas <strong>de</strong> da materia blanca cerebral,” RevistaColombiana <strong>de</strong> Física, vol. 42, no. 3, 2010.[6] T.E.J. Behrens, H.Johansen-Berg, M.W. Woolrich, S.M.Smith, C.A.M. Wheeler-Kingshott, P.A. Boulby, G.J.Barker, E.L. Sillery, K.Sheehan, O.Ciccarelli, A.J. Thompson,J.M. Brady, and P.M. Matthews, “Non-invasivemapping of connections between human thalamus andcortex using diffusion imaging,” Nature Neuroscience,vol. 6, no. 7, pp. 750–757, 2003.[7] Stamatios N. Sotiropoulos, Processing of Diffusion MRImages of the Brain: From Crossing Fibres to DistributedTractography,Ph.D. thesis, University of Nottingham,2010.[8] Behrens TE, Woolrich MW, Jenkinson M, Johansen-BergH, Nunes RG, Clare S, Matthews PM, Brady JM, andSmith SM., “Characterization and propagation of uncertaintyin diffusion-weighted mr imaging,” MagneticResonance in Medicine, vol. 50, no. 5, pp. 1077–1088,2003.[9] Jesper L.R. An<strong>de</strong>rsson, Mark Jenkinson, and StephenSmith, “Non-linear optimisation,” Tech. Rep. TR07JA1,FMRIB Centre, Oxford, United Kingdom, June 2007.[10] Jesper L.R. An<strong>de</strong>rsson, Mark Jenkinson, and StephenSmith, “Non-linear registration aka spatial normalisation,”Tech. Rep. TR07JA2, FMRIB Centre, Oxford,United Kingdom, June 2007.[11] NVIDIA, NVIDIA CUDA C Programming Gui<strong>de</strong> 4.0,2011.[12] Stephen M. Smith, Mark Jenkinson, Mark W. Woolrich,Christian F. Beckmann, Timothy E.J. Behrens, HeidiJohansen-Berg, Peter R. Bannister, Marilena De Luca,Ivana Drobnjak, David E. Flitney, Rami K. Niazy, JamesSaun<strong>de</strong>rs, John Vickers, Yongyue Zhang, Nicola DeStefano, J. Michael Brady, and Paul M. Matthews, “Advancesin functional and structural mr image analysis andimplementation as fsl,” Tech. Rep. TR04SS2, FMRIBCentre, Oxford, United Kingdom, September 2004.[13] Analysis Group FMRIB Oxford UK, “Fmrib softwarelibrary,” http://www.fmrib.ox.ac.uk/fsl/.[14] Inc. Sun Microsystems, “Sun n1 grid engine 6.1 user’sgui<strong>de</strong>,” 2007.[15] NVIDIA Corporation, “Cudacurand library,” 2010.[16] Jorge Ahualli, “Aspectos generales <strong>de</strong> las secuencias <strong>de</strong>difusión <strong>de</strong> imagen en resonancia magnética,” Revistaargentina <strong>de</strong> radiología, vol. 74, no. 3, pp. 227–237, 2010.[17] Denis Le Bihan, Jean-François Mangin, Cyril Poupon,Chris A. Clark, Sabina Pappata, Nicolas Molko, and HughesChabriat, “Diffusion tensor imaging: Concepts andapplications,” Journal of Magnetic Resonance Imaging,vol. 13, no. 4, pp. 534–546, 2001.<strong>JP2011</strong>-164


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Agent-Based Simulation to OptimizeHealthcare Emergency DepartmentsEduardo Cabrera 1 , Manel Taboada 2 y Emilio Luque 3Abstract— Mo<strong>de</strong>ling and simulation have beenshown to be useful tools in many areas of the Healthcareoperational management, field in which there isprobably no area more dynamic and complex thanhospital emergency <strong>de</strong>partments (ED). This paperpresents an ongoing research, an Agent-Based mo<strong>de</strong>lingand simulation to <strong>de</strong>sign a <strong>de</strong>cision support system(DSS) for the operation of Healthcare EmergencyDepartments (ED). This DSS aims to aid EDs managersin setting up strategies and management gui<strong>de</strong>linesto optimize the operation of EDs. This ongoingresearch is being performed by the Research Groupon Individual Oriented Mo<strong>de</strong>ling (IoM) of CAOS inthe University Autonoma of Barcelona (UAB) in closecollaboration with Hospital ED Staff. The simulationmain objective is to optimize the performance of suchcomplex and dynamic Healthcare ED. Optimization isperformed to find the optimal ED staff configuration,which consists of doctors, triage nurses, and admissionpersonnel, i.e. a multidimensional problem. Twodifferent in<strong>de</strong>xes, to minimize patient waiting time,and to maximize patient throughput, were proposedand tested and their results obtained appying an exhaustivesearch technique, yield promising results andbetter un<strong>de</strong>rstanding of the problem.Keywords— Optimization, healthcare operationalmanagement, emergency <strong>de</strong>partment, agent-basedsimulation, <strong>de</strong>cision support systems.I. IntroductionNO wadays, healthcare systems have becomelarge, complex, and quite dynamic environments,particularly Emergency Department (ED).ED is a sui generis unit of hospitals. It is open andfunctioning 24 hours a day, 365 days per year. Typically,ED patients could arrive by walking, or by ambulance,and they un<strong>de</strong>rgo a triage, which <strong>de</strong>terminethe acuity of their condition assigning them a prioritylevel. Patients with threatening disease, i.e. highpriority level, are treated almost immediatly by aphysician compared to those patients with less severeinjuries. Then, an initial diagnosis and treatment isproposed, and patients could be admitted into theservice or discharged. EDs have high <strong>de</strong>mand of service,which increases their cost, and they generallyoperate with limited healthcare resources and budget.In the <strong>de</strong>ca<strong>de</strong> leading up to 2006 in the USA,ED visits (patients) have increased by 32%, whereasthe number of EDs have <strong>de</strong>creased by 4.6%, and thenumber of visits per person increased by 18% [1].Also, in Spain between 2001 and 2007, the visits to1 Dpto. <strong>de</strong> Arquitectura <strong>de</strong> Computadores y SistemasOpe-rativos, Universitat Autònoma <strong>de</strong> Barcelona, e-mail:ecabrera@caos.uab.es2 Tomàs Cerdà Escuela <strong>de</strong> Ciencia Computacional, UniversitatAutònoma <strong>de</strong> Barcelona, e-mail: manel.taboada@eug.es3 Dpto. <strong>de</strong> Arquitectura <strong>de</strong> Computadores y SistemasOpe-rativos, Universitat Autònoma <strong>de</strong> Barcelona, e-mail:Emilio.luque@uab.esEDs have increased by 23.2% [2]. Over half of thosevisits to EDs are nonurgent and could be treatedin alternative healthcare settings. Overcrowding ofEDs is a worldwi<strong>de</strong> problem, and as a consequenceof such situation, waiting time increases, affectingquality and speed of care [3]. Despite EDs are un<strong>de</strong>rthose huge, and growing <strong>de</strong>mands they suffer severalbudget cuts. Nevertheless, such critical ED servicemust be satisfied with the best quality as quickly aspossible. An obvious solution to this problem is to increasethe capacity of EDs. Such capacity is limitedby the size of the healthcare facility and the availablestaff, which inclu<strong>de</strong>s physicians, nurses, admissions,and services personnel. However, such straightforwardsolution is not the best approach, and could beunrealizable. Healthcare system heads must maximize,for example, the use of healthcare resources, inor<strong>de</strong>r to minimize patient waiting time and increasepatient satisfaction, whereas being constrained bylimited budget.This paper presents the results of an ongoing researchproject that is being carried out by the ResearchGroup in Individual Oriented Mo<strong>de</strong>ling (IoM)in the University Autonoma of Barcelona (UAB),with the participation of the ED head team of theHospital of Saba<strong>de</strong>ll in Cataluña, Spain. The generalobjective of the project is to <strong>de</strong>velop a simulatorof ED’s operation that, used as a <strong>de</strong>cisionsupport system (DSS), could help the heads of EDsto set up strategies, and management gui<strong>de</strong>lines toenhance the performance of such EDs. As a firststep to towards this goal, the main objective of thiswork is to propose a simple but realistic simulationmo<strong>de</strong>l to represent the operation of EDs, in or<strong>de</strong>rto study their optimum performance un<strong>de</strong>r certainoperational and economical conditions. The mathematicalformalism of the latter is a multidimensionaloptimization problem which can be stated by equation(1):max / min f(X )subject tox ∈ C(1)where f : C → R, and f(X ) at any X ∈ C cannot beevaluated exactly, and must be estimated via a simulationprocedure by assuming that X is discrete,global sampling from X is possible. The goal is toi<strong>de</strong>ntify the staff members of EDs that optimize itsperformance, taking into account the complexity ofEDs and their optimum expected performance needsto be estimated via simulations. However, optimizationvia simulation is a difficult problem [4], as simulationsare usually computationally expensive, i.e.<strong>JP2011</strong>-165


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011even estimating f(X ) at a single point X ∈ C inequation (1) may require substantial effort. Consequently,only few alternatives can be explored.Herewith, the ED is mo<strong>de</strong>led by an Agent-BasedMo<strong>de</strong>l (ABM), in which all rules within the mo<strong>de</strong>lconcern the involved agents (in our case the doctors,triage nurses and admission personnel, and the patients),no higher level behavior is mo<strong>de</strong>led. Thesystem behavior emerges as a result of local level actionsand interactions [5]. This mo<strong>de</strong>l <strong>de</strong>scribes thecomplex dynamics found in an ED, representing eachindividual and system as an individual agent. Twodistinct kinds of agents have been i<strong>de</strong>ntified, activeand passive. Active agents represent the individualsinvolved in the ED, in this case all human actors,such as patients and ED staff (admission staff,nurses, doctors, etc). Passive agents represent servicesand other reactive systems, such as the informationtechnology (IT) infrastructure or services usedfor performing tests. State machines are used to representthe actions of each agent. This takes into consi<strong>de</strong>rationall the variables that are required to representthe many different states that such individual(a patient, a member of hospital staff, or any otherrole in the EDs) may be in throughout the course oftheir time in a hospital emergency <strong>de</strong>partment. Thechange in time of these variables, invoked by an inputfrom an external source, is mo<strong>de</strong>led as a transitionbetween states. The communication between individualsis mo<strong>de</strong>led as the inputs that agents receiveand the outputs they produce, both implicitly an<strong>de</strong>xplicitly. In or<strong>de</strong>r to control the agent interaction,the physical environment in which these agents interactalso has to be mo<strong>de</strong>led, being sufficient to doit as a series of interconnected areas, such as admissions,triage box, the waiting room, and consultationsuits.The remain<strong>de</strong>r of this article is organized as follows;section II <strong>de</strong>scribes the related works. The propose<strong>de</strong>mergency <strong>de</strong>partment mo<strong>de</strong>l is <strong>de</strong>tailed in sectionIII, while the results of initial simulation optimizationsare given in section IV. Finally, in section Vthe conclusions and future work are presented.II. Related worksThe interest on simulating healthcare systems isnot new, in 1979 computer simulations were appliedto hospital systems to improve the scheduling ofstaff members [6], and in another simulation [7] theaim was to quantify the impact that the number ofstaff members, and beds had on patient throughputtime. Moreover, a survey of discrete-event simulation(DES) in healthcare clinics was presented in [8].Although discrete-event simulation is wi<strong>de</strong>ly usedin simulating healthcare systems, agent technology isa good option in healthcare applications, since it isbetter to characterize the operation of complex systemsas the EDs are. ABM can explicitly mo<strong>de</strong>l thecomplexity arising from individual interactions thatarise in the real world. Agent-based simulation allowspeople to mo<strong>de</strong>l their real-world systems in waysthat either not possible or not readily accomodatedusing taditional mo<strong>de</strong>ling techniques, such as DESor system dynamics [9]. Previous works mo<strong>de</strong>linghealthcare systems have focused on patient schedulingun<strong>de</strong>r variable pathways and stochastic processdurations, the selection of an optimal mix of patientadmission to optimize the use of resources and patientthroughput [10]. Work has been performed toevaluate patient waiting times un<strong>de</strong>r different EDphysician schedules, but only one utilized real data[11] and another one patient diversion strategies [12],both using different <strong>de</strong>grees of agent-based mo<strong>de</strong>ling.There is a relevant article which uses ABM to simulatethe workflow in ED [13]. It focus on triage andradiology process, but not real data was used, theacuity of patients are not consi<strong>de</strong>r, and healthcareprovi<strong>de</strong>rs do not always serve patients in a first-comefirst-servebasis.Simulation optimization is used to improve the operationof ED in [14], using a commercial simulationpackage, and in [15] the authors combine simulationwith optimization, which involves a complexstochastic objective function un<strong>de</strong>r a <strong>de</strong>terministicand stochastic set of restrictions.Finally, an evolutionary multiobjective optimizationapproach is used for dynamic allocation of resourcesin hospital practice [16], while in [17] the authorsfound that agent-based approaches and classicaloptimization techniques complement each other.As stated above, this proposal addresses manyof the issues surrounding the mo<strong>de</strong>ling and simulationof a healthcare emergency <strong>de</strong>partment using theagent-based paradigm, where the efficiency of agentsin this area has not been totally explored yet. Basicrules governing the actions of the individual agentsare <strong>de</strong>fined, in an attempt to un<strong>de</strong>rstand micro levelbehavior. The macro level behavior, that of the systemas a whole, emerges as a result of the actionsof these basic building blocks, from which an un<strong>de</strong>rstandingof the reasons for system level behavior canbe <strong>de</strong>rived [18].III. Emergency <strong>de</strong>partment mo<strong>de</strong>lAs mentioned above, the Emergency Departmentmo<strong>de</strong>l <strong>de</strong>fined in this work is a pure Agent-BasedMo<strong>de</strong>l, formed entirely of the rules governing the behaviorof the individual agents which populate thesystem. Through the information obtained duringinterviews carried out with ED staff at the Hospitalof Saba<strong>de</strong>ll, two kinds of agents have been i<strong>de</strong>ntified;these are active and passive agents. The activeagents represent people and other entities that actupon their own initiative: patients, admission staff,sanitarian technicians, triage and emergency nurses,and doctors. The passive agents represent systemsthat are solely reactive, such as the loudspeaker system,patient information system, pneumatic pipes,and central diagnostic services (radiology service andlaboratories). All the <strong>de</strong>tails of both, active and passiveagents, as well as the communication mo<strong>de</strong>l, andthe environment where the agents interact are <strong>de</strong>-<strong>JP2011</strong>-166


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011tailed in [19].A. Problem <strong>de</strong>scriptionIV. OptimizationThe simulator for this work is used as a black boxas <strong>de</strong>scribed below, inclu<strong>de</strong>s simple realistic <strong>de</strong>scriptorsof the ED’s: agents, basic physical infrastructure,and operating practices. Nevertheless the morerealistic the simulator is, the better results and optimizationsare. It is implemented by the agentbasedsimulation environment NetLogo [20], whichis well suited for mo<strong>de</strong>ling complex systems such asthe EDs. For simplicity, only four different typesof active agents are consi<strong>de</strong>red: admission staff (A),nurses (N), doctors (D), and patients. The ED staffhave two kinds of expertise: low and high, labeledas junior, and senior, respectively. Junior staff willrequire more time to accomplish their tasks than seniors,which cost-wise are more expensive (see TableI).The initial scenario adopted for the experiments isto simulate patients moving through a simplified EDphysical infrastructure that inclu<strong>de</strong>s four primary areas:admissions, triage (up to three boxes), two waitingrooms (one for patients before triage, and theother for patients who have passed the triage process,and are waiting for treatment), and the diagnosisand treatment area (four boxes). The followingbasic patient attributes were assumed. Patientsarrive to the ED by their own, and wait to be atten<strong>de</strong>din the admission area. Then, patients stay inthe first Waiting Room (WR1), until a triage nursecall them. After the triage process patients pass toa second waiting room (WR2), and stay there untilan available doctor calls them to start the diagnosis,and to prescribe a treatment (which might inclu<strong>de</strong>laboratory tests) <strong>de</strong>pending on the patient’s symptoms,and physical condition. Finally, patients aredischarged from the ED. Such simplified ED layoutis shown in Figure 1. Although realistic treatmentis based on the acuity of patients, in this initial simulationpatients we assumed that patients have thesame path throughout the ED. In this experiment aconstant pattern of patients arrival pattern has beenassumed, since we would like first to work with asimpler mo<strong>de</strong>l. Also it will be assumed that patientsarrive to the ED after a certain time step, and withfour different patients arrival probabilities (P) 20, 40,60, and 80%. Those probability values are used toemulate the randomness of the incoming patients tothe ED.The multidimensional optimization problem consi<strong>de</strong>redin this paper aims to find the optimal EDstaff configuration un<strong>de</strong>r certain operational constrains(the optimal solution will correspond to theminimum value of an in<strong>de</strong>x which is <strong>de</strong>fined furtherdownin the application experiments). The dimensionof the problem corresponds to: the typesand number of ED staff consi<strong>de</strong>red, i.e. doctors(D), triage nurses (N), and admissions personnel (A),which could be, as stated above, junior or senior; theFig. 1: Agent Based Simulator of the simplifiedEmergency Department layout implemented withNetLogo.working time units consi<strong>de</strong>red for each of them, theirassociated cost units. The assumed values of each ofthose are shown in the Table I. This represents acombinatorial or multidimensional problem (whereeach variable or in this case ED staff member representsone dimension plus the patients arrival, i.e.the input to the ED). Such combinatorial problemis shown in Table II for doctors -14 cases- (nursesand admission personnel have similar combinations-9 cases for each of them). Taking this into accountspecific scenarios or configurations have to be simulatedseveral times, changing parameters to showthe effect of consi<strong>de</strong>ring different probabilities of thepatients arrival time, this strategy will allow us togenerate set of results from which particular effectscan be analyzed.TABLE I: Staff members with their associated costs,and working time according to their kind.Agent Cost (e) Time (ticks) # of AgentsSenior (S) Junior (J) Senior (S) Junior (J)Doctor (D) 1,000 500 260 350 1 – 4Nurse (N) 500 350 90 130 1 – 3Admin (A) 200 150 20 35 1 – 3TABLE II: 14 Doctors (D) combination. Two kindsof doctor, Junior (J), and Senior (S). DRi representsDiagnosis Roomi.DR1 DR2 DR3 DR4DJ - - -DS - - -DJ DJ - -DS DS - -DJ DJ DJ -DS DS DS -DJ DJ DJ DJDS DS DS DSDJ DS - -DJ DJ DS -DJ DJ DS DSDJ DJ DJ DSDJ DS DS DSDJ DS DS -Even with this simple setting of an ED the searchspace is large, i.e. the search space has 4,536 (which<strong>JP2011</strong>-167


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011results of assuming a combination of two types -junior or senior- of up to 4 doctors, 3 nurses, 3 admissions,and 4 different probabilities of patients arrival,i.e. 14 × 9 × 9 × 4) combinations from whichthe optimal combination that minimizes the <strong>de</strong>sirein<strong>de</strong>x, un<strong>de</strong>r some restrictions, will be obtained. Inthe experiments shown in sections IV-B and IV-C theperiod simulated of the ED operation was of 24 hrs.(which represent 25,000 ticks -NetLogo’s time stepforall the experiments, and an average input of 400patients, which is the average incoming patients thatthe heads of ED of the Hospital of Saba<strong>de</strong>ll have reported).Two different in<strong>de</strong>xes were set in or<strong>de</strong>r to evaluatethe utility of the Agent-Based ED simulator for optimizingthe resources. Exhaustive search techniquewas used to obtain the optimum in the experimentsreported in sections IV-B and IV-C. All simulationswere done using the simulator <strong>de</strong>scribed previously,using the NetLogo’s BehaviorSpace tool, serially andusing an IBM cluster, which has 32 compute no<strong>de</strong>swith 2 x Dual-Core Intel(R) Xeon(R) CPU 5160 runningat 3.00GHz, with 12 GB of RAM, and 4MB ofL2 share cache (2x2).B. First experimentThe first in<strong>de</strong>x aimed to minimize patient waitingtime in the ED, with cost configuration less orequal to 3,500 e. Thus, the first in<strong>de</strong>x is expressedmathematically in equation (2).(a) Average patient waiting time for a P = 20%.Min e Time (ticks) # staff D N A1 3,200 428 5 2 S 2 S 1 S2 2,900 428 5 2 S 1 S 2 S3 2,850 428 5 2 S 1 S 1 S, 1 J(b) Staff configurations that have the minimum wt for a P =20%. They are shown as triangles in Figure 2a.Fig. 2: Average patient waiting times graph and theircorresponding table with the optimal staff configurationsfor a P = 20% of patients arrival. Trianglepoints are the minimum.Minimize patient waiting time f(D, N, A)subject to D cost + N cost + A cost = Cost ≤ 3, 500 e(2)The results are shown in Figures 2, 3, 4, and 5;where the circle points are the staff configurationsthat satisfy the restriction, while the triangle pointsare the minimum for each different case of probability,20%, 40%, 60%, and 80%, respectively. Theminimal configurations are presented in Figures 2b,3b, 4b, and 5b, as well as their costs.In Figures 2a and 2b, there are three different staffconfigurations that have the average minimum waitingtime, but with different costs. Also, in the sameFigure 2a, it can be appreciated that there are manyother staff configurations that are quite close to theminimum time, but less expensive.In the other cases, where the probability P of patientsarrival increases, i.e. has higher probability ofpatients arrival, there are only few staff configurationsaround the minimum, or clearly only one. Notonly does the patient arrival increase, but also theminimum average patient waiting time, as expected,as well as the cost of the staff configuration, and alsothe standard <strong>de</strong>viation of the average patient waitingtime (wt) are shown in Table III. The number ofpatients increases at waiting rooms, both WR1 andWR2 ( shown in Figure 1) at times t1, t2, t3, andt4 (each time represents every 6,250 ticks of simulation),and finally the number of unatten<strong>de</strong>d patientsincreases as well. In Table III all these results are(a) Average patient waiting time for a P = 40%.Min e Time (ticks) # staff D N A1 3,150 514 5 2 S, 1 J 1 S 1 J2 3,200 514 7 4 J 2 S 1 S(b) Staff configurations that have the minimum wt for a P =40%. They are shown as triangles in Figure 3a.Fig. 3: Average patient waiting times graph and theircorresponding table with the optimal staff configurationsfor a P = 40% of patients arrival. Trianglepoints are the minimum.shown. It is noticed when the number of patient arrivalprobability is higher, i.e. 80%, patients in thewaiting rooms increases (shown in Table III).C. Second experimentThe second in<strong>de</strong>x aims to minimize a compoundin<strong>de</strong>x: cost × time, CT, subject to a time restrictionthat should be less or equal to 428, that is the average<strong>JP2011</strong>-168


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Minimize cost × time(CT) f(D, N, A)subject to T ime P =80% ≤ T ime P =20% 428(3)(a) Average patient waiting time for a P = 60%.Min e Time (ticks) # staff D N A1 3,400 790 7 1 S, 3 J 2 J 1 S(b) Staff configurations that have the minimum wt for a P =60%. They are shown as triangles in Figure 4a.Fig. 4: Average patient waiting times graph and theircorresponding table with the optimal staff configurationsfor a P = 60% of patients arrival. Trianglepoints are the minimum.Fig. 6: Results y = cost × time. Triangle points areminimum, and a worthy staff configuration, respectively.This in<strong>de</strong>x was set to test the simulator with a nonsimpleobjective function, as well as to find whichED staff configuration yields the best quality of service,i.e. to maximize patient throughput. The Figure6 shows all the search space, 16,632 staff scenarios(which results of assuming a combination of twotypes -junior or senior- of up to 8 doctors, 6 nurses,and 4 admissions, i.e. 44 × 27 × 14). There are manyscenarios that give a good in<strong>de</strong>x value, but there aretwo of them that are the most important, as shownin Table IV.TABLE IV: Two worthy staff configurations thatgive almost the same quality of service.(a) Average patient waiting time for a P = 80%.Min e Time (ticks) # staff D N A1 3,350 3,266 7 1 S, 3 J 2 J 1 J(b) Staff configurations that have the minimum wt for a P =80%. They are shown as triangles in Figure 5a.Fig. 5: Average patient waiting times graph and theircorresponding table with the optimal staff configurationsfor a P = 80% of patients arrival. Trianglepoints are the minimum.TABLE III: Results for the best average minimumfor each of the four presented scenarios.P Time σ wt e # atten<strong>de</strong>d # unatten<strong>de</strong>d # patients at WR1 # patients at WR2(ticks) patients patients t1, t2, t3, t4 t1, t2, t3, t420 428 48 (11%) 2850 83 1 0,0,0,0 0,0,0,040 514 81.5 (15.9%) 3150 182 4 0,0,0,1 0,0,0,060 790 174.5 (22.1%) 3400 290 8 1,1,0,1 3,2,4,180 3266 1670.4 (51.2%) 3350 294 100 8,19,32,43 12,25,37,51waiting time when the patients arrival probabilityis 20%. This in<strong>de</strong>x is expressed mathematically inequation (3).Best e Time (ticks) Cost × T ime # atten<strong>de</strong>d patients σ wt # staff D N A1 4,000 585.7 2,342,800 378 58.6 (10%) 9 6 J 2 J 1 J2 3,600 1,725.7 6,212,520 340 602.4 (34.9%) 9 5 J 2 J 1 S, 1 JAlthough both staff configurations are almost thesame, they have different minimum average waitingtime, this is why the first staff configuration label asBest 2, <strong>de</strong>spite its lower cost has a worst minimumaverage waiting time. Not only the in<strong>de</strong>x is differentand higher, but its standard <strong>de</strong>viation of patientwaiting time is higher. It is important to notice thata staff configuration a bit more expensive has almost10% lower variation coefficient of the patient waitingtime, as well as almost a third lower in<strong>de</strong>x value andminimum average waiting time.V. Conclusions and future workA simple but realistic Agent-Based Mo<strong>de</strong>l to simulateHealthcare Emergency Departments (ED) hasbeen proposed an applied. The main objective ofthe mo<strong>de</strong>l is to be used as a tool to help EDs managersin setting up strategies and management gui<strong>de</strong>linesto optimize the operation of EDs. The mo<strong>de</strong>l<strong>JP2011</strong>-169


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011takes into account the complexity and dynamic natureof the EDs which are difficult to characterize.The mo<strong>de</strong>l uses Moore state machines based agentswhich act and communicate within a <strong>de</strong>fined layout.The simulations presented here serve to testthe mo<strong>de</strong>l. Two simulation experiments were carriedout using real data about the staff configurationand the (minimum) physical infrastructure of aHospital ED. Two different in<strong>de</strong>xes were set to evaluatethe operation of the Agent-Based EmergencyDepartment simulator. Even though the search ofthe optimum staff configurations analyzed, 4,536 and16,632 for the first and second experiments, respectively,were performed through an exhaustive searchtechnique (which implies a lot of search time) theresults are encouraging, since not only they are asexpected (larger and more experienced staff lead toshorter average patient waiting time), but also showinteresting results when the waiting time standard<strong>de</strong>viation is analyzed. In<strong>de</strong>ed the simulation experimentsallowed to un<strong>de</strong>rstand, and analyse better theproblem. However, even with the small problem sizeanalyzed the number of combination is large, as wellas the computing time. Moreover, the resources thatthis problem would <strong>de</strong>mand to perform statisticalanalysis for longer periods (first to reproduce andthen to foretell) are huge. Therefore, a better optimizationapproach rather than exhaustive search,must be used.As future work, an alternative methodologyscheme for optimization is being <strong>de</strong>vised. Thisapproach consists in finding a continuous functionthat <strong>de</strong>scribes the Emergency Department operation,which is a discrete and multidimensional problem,and through such function will allow us to obtain theoptimum, or at least reduce the search space. Thus,getting as a result of doing such an intelligent searchwill very likely reduce time and computing resourcesutilized. This scheme would be an intermediate approachbetween an exhaustive search technique anda heuristic one. Moreover, due to the multidimensionalnature of the problem, i.e. large number of individuals,the number of states in the state machineof each individual, and the different time periods, alarge number of values should be computed. Therefore,High Performance Computing will have to beused.AcknowledgmentsThis research has been supported by the MICINNSpain, un<strong>de</strong>r contract TIN2007-64974.References[1] Stephen R. Pitts, W. Niska Richard, Xu Jianmin, andW. Burt Catherine, “National Hospital AmbulatoryMedical Care Survey: 2006 emergency <strong>de</strong>partment summary,”National health statistics reports, vol. 2008, no.7, August 2008.[2] “Unidad <strong>de</strong> urgencias hospitalaria. Estándares y recomendaciones,”2010.[3] Andrew P. Wilper, Steffie Woolhandler, Karen E. <strong>La</strong>sser,Danny McCormick, Sarah L. Cutrona, David H. Bor, andDavid U. Himmelstein, “Waits To See An Emergency DepartmentPhysician: U.S. Trends And Predictors, 1997–2004,” Health Affairs, vol. 27, no. 2, pp. w84–w95, 2008.[4] Michael C. Fu, “Feature article: Optimization for simulation:Theory vs. practice,” INFORMS Journal onComputing, vol. 14, no. 3, pp. 192–215, 2002.[5] Eric Bonabeau, “Agent-based mo<strong>de</strong>ling: Methods andtechniques for simulating human systems,” Proceedingsof the National Aca<strong>de</strong>my of Sciences, vol. 99, pp. 7280–7287, May 2002.[6] Walton M. Hancock and Paul F. Walter, “The useof computer simulation to <strong>de</strong>velop hospital systems,”SIGSIM Simul. Dig., vol. 10, no. 4, pp. 28–32, 1979.[7] Charles E. Saun<strong>de</strong>rs, Paul K. Makens, and <strong>La</strong>rry J.Leblanc, “Mo<strong>de</strong>ling emergency <strong>de</strong>partment operationsusing advanced computer simulation systems,” Annals ofEmergency Medicine, vol. 18, no. 2, pp. 134–140, 1989.[8] J. B. Jun, S. H. Jacobson, and J. R. Swisher, “Applicationof discrete-event simulation in health care clinics:A survey,” Journal of the Operational Research Society,pp. 109–123, February 1999.[9] Peer Olaf Siebers, Charles M. Macal, Jeremy Garnett,D. Buxton, and Michael Pidd, “Discrete-event simulationis <strong>de</strong>ad, long live agent-based simulation!,” Journal ofSimulation, vol. 4, no. 3, pp. 204–210, Sep 2010.[10] Anke K. Hutzschenreuter, Peter A. N. Bosman, IlonaBlonk-Altena, Jan van Aarle, and Han <strong>La</strong> Poutré,“Agent-based patient admission scheduling in hospitals,”in AAMAS ’08: Proceedings of the 7th internationaljoint conference on Autonomous agents and multiagentsystems, Richland, SC, 2008, pp. 45–52, InternationalFoundation for Autonomous Agents and Multiagent Systems.[11] Spencer S. Jones and R. Scott Evans, “An agent basedsimulation tool for scheduling emergency <strong>de</strong>partmentphysicians,” in AMIA Annual Symposium proceedings,AMIA Symposium, 2008, pp. 338–342.[12] Marek <strong>La</strong>skowski and Shamir Mukhi, “Agent-based simulationof emergency <strong>de</strong>partments with patient diversion,”in eHealth, 2008, pp. 25–37.[13] Lu Wang, “An agent-based simulation for workflow inemergency <strong>de</strong>partment,” in Systems and InformationEngineering Design Symposium, 2009. SIEDS ’09., 24-24 2009, pp. 19 –23.[14] T. Ruohonen, P. Neittaanmaki, and J. Teittinen, “SimulationMo<strong>de</strong>l for Improving the Operation of the EmergencyDepartment of Special Health Care,” in SimulationConference, 2006. WSC 06. Proceedings of the Winter,3–6 2006, pp. 453–458.[15] Mohamed A. Ahmed and Talal M. Alkhamis, “Simulationoptimization for an emergency <strong>de</strong>partment healthcareunit in Kuwait,” European Journal of OperationalResearch, vol. 198, no. 3, pp. 936 – 942, 2009.[16] Anke K. Hutzschenreuter, Peter A. Bosman, and HanPoutré, “Evolutionary multiobjective optimization fordynamic hospital resource management,” in EMO ’09:Proceedings of the 5th International Conference on EvolutionaryMulti-Criterion Optimization, Berlin, Hei<strong>de</strong>lberg,2009, pp. 320–334, Springer-Verlag.[17] Jan A. Persson, Paul Davidsson, Stefan J. Johansson,and Fredrik Wernstedt, “Combining agent-based approachesand classical optimization techniques,” in EU-MAS, 2005, pp. 260–269.[18] Hay<strong>de</strong>n Stainsby, Manel Taboada, and Emilio Luque,“Towards an agent-based simulation of hospital emergency<strong>de</strong>partments,” in SCC ’09: Proceedings of the2009 IEEE International Conference on Services Computing,Washington, DC, USA, 2009, pp. 536–539, IEEEComputer Society.[19] Manel Taboada, Eduardo Cabrera, Ma Luisa Iglesias,Francisco Epel<strong>de</strong>, and Emilio Luque, “An agent-based<strong>de</strong>cision support system for hospitals emergency <strong>de</strong>partments,”Procedia Computer Science, vol. 4, pp. 1870 –1879, 2011, Proceedings of the International Conferenceon Computational Science, ICCS 2011.[20] U. Wilensky, “Netlogo,” 1999, Northwestern University,Center for Connected Learning and Computer-BasedMo<strong>de</strong>ling.<strong>JP2011</strong>-170


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Reducción <strong>de</strong> ruido impulsivo Fijo y Uniformeen imágenes digitales usando las GPUs.M. Guadalupe Sánchez 1 Vicente Vidal 2 Jordi Bataller 3 Alejandro Rivera 4Resumen— <strong>La</strong> gran <strong>de</strong>manda <strong>de</strong> aplicaciones entiempo real y gráficos en 3D <strong>de</strong> alta <strong>de</strong>finición, han hechoque evolucionen no sólo en las implementaciones<strong>de</strong> gráficos, sino también las aplicaciones <strong>de</strong> propósitogeneral basada en la GPU. El problema <strong>de</strong> la reducción<strong>de</strong> ruido impulsivo en imágenes a color es unproceso ampliamente estudiado en el campo <strong>de</strong> procesamiento<strong>de</strong> imágenes. Con este fin, muchos métodosse han propuesto, sin embargo, el coste computacionalen la mayoría <strong>de</strong> ellos es muy alto si el tamaño <strong>de</strong>la imagen es gran<strong>de</strong> y se requiere procesamiento entiempo real. En este artículo presentamos un métodopara reducir el ruido impulsivo (mo<strong>de</strong>lo <strong>de</strong> valor fijo yaleatorio), basado en el concepto <strong>de</strong> peer group. Utilizamosla Unidad <strong>de</strong> Procesamiento Gráfico (GPU)para obtener una aplicación paralela mejorando la eficienciacomputacional. Los resultados muestran queel problema <strong>de</strong> la reducción <strong>de</strong> ruido impulsivo con elmétodo propuesto pue<strong>de</strong> ser paralelizado y es eficienteen calidad, coste computacional y robustez.Palabras clave— Eliminación <strong>de</strong> ruido, algoritmo paralelo,peer group, GPU, CUDA.I. IntroducciónMUCHOS <strong>de</strong>sarrolladores e investigadores estánencontrando aplicaciones prácticas basadas enlas GPUs (Graphics Processor Units) para acelerarel procesamiento <strong>de</strong> datos o en cálculos complejos.<strong>La</strong>s GPUs están especializadas en computación <strong>de</strong>cálculo intensivo y altamente paralelo. En la actualidadmuchas aplicaciones en el procesamiento <strong>de</strong>imágenes y ví<strong>de</strong>o requieren un rendimiento en tiemporeal, por ejemplo, en vi<strong>de</strong>o-vigilancia o en medicina.<strong>La</strong>s imágenes tien<strong>de</strong>n a ser dañadas <strong>de</strong>bido a sumala adquisición o transmisión a través <strong>de</strong> un canalcontaminado [1], [2], [3], lo que afecta su procesamiento.Esto hace necesario un proceso previo conla finalidad <strong>de</strong> eliminar el ruido en la imagen utilizandotécnicas <strong>de</strong> filtrado.Dos tipos comunes <strong>de</strong> ruido son, el ruido gaussianoy ruido impulsivo. El más usual es el ruidoimpulsivo, que se presenta durante la transmisión <strong>de</strong>datos por un canal contaminado, sensores ruidososo en errores en la captura <strong>de</strong> los datos. Estos erroressólo afectan a ciertos píxeles <strong>de</strong> la imagen [3].El mo<strong>de</strong>lo más común <strong>de</strong> ruido impulsivo (Salt yPepper o valor fijo)consi<strong>de</strong>ra que el impulso es, unvalor extremo en el rango <strong>de</strong> la señal reemplazandosu valor original. Un segundo tipo es cuando un pixeles reemplazado por un valor aleatorio uniformemente1 Dpto. <strong>de</strong> Sistemas y Computación, Instituto Tecnológico<strong>de</strong> Cd. Guzmán, e-mail: msanchez@dsic.upv.es2 Dpto. Sistemas Informáticos y Computación, Univ.Politécnica <strong>de</strong> Valencia, e-mail: vvidal@dsic.upv.es3 Dpto. Sistemas Informáticos y Computación, Univ.Politécnica <strong>de</strong> Valencia, e-mail: bataller@dsic.upv.es4 Dpto. Sistemas y Computación, Instituto Tecnológico <strong>de</strong>Cd. Guzmán, e-mail: arivera@itcg.edu.mxdistribuido <strong>de</strong>ntro <strong>de</strong>l rango <strong>de</strong> la señal [1]. En estetrabajo se aborda el ruido impulsivo <strong>de</strong> ambos tipos.Por lo general, las técnicas <strong>de</strong> eliminación <strong>de</strong> ruido<strong>de</strong> una imagen tienen dos pasos: la <strong>de</strong>tección y el filtrado<strong>de</strong> los pixeles ruidosos. Algunas técnicas parala <strong>de</strong>tección <strong>de</strong> píxeles corruptos utilizan el concepto<strong>de</strong> peer group. El peer group es el conjunto <strong>de</strong> pixelessimilares a uno dado, <strong>de</strong> acuerdo a una medida<strong>de</strong> distancia [4], [5].En este artículo presentamos un algoritmo paralelobasado en el peer group y la norma eucli<strong>de</strong>acomo la métrica <strong>de</strong> distancia. Nuestro método es unaadaptación <strong>de</strong> los algoritmos secuenciales presentadosen los paper [3], [6] y [9] para reducir el ruidoimpulsivo, para operar eficientemente en una GPU.Para <strong>de</strong>mostrar que el algoritmo es altamente paralelizabley eficiente en calidad y robustez, se comparanlos costes <strong>de</strong> cómputo paralelo con los <strong>de</strong> su versiónsecuencial.El trabajo se organiza <strong>de</strong> la siguiente manera. <strong>La</strong>sección 2 presenta la propuesta <strong>de</strong>l algoritmo paralelopara la GPU. El estudio experimental se muestraen la sección 3. <strong>La</strong> sección 4 analiza la complejidadcomputacional <strong>de</strong>l algoritmo con el enfoque en la utilización<strong>de</strong> la memoria <strong>de</strong> texturas. Por último en lasección 5 se concluye el trabajo.II. Algoritmo paralelo para <strong>de</strong>tectar yeliminar ruido (GPU-PGE)En este estudio, hemos implementado un algoritmoparalelo llamado GPU-PGE (Unidad <strong>de</strong> ProcesamientoGráfico - Peer Grup con métrica Eucli<strong>de</strong>a),que utiliza la arquitectura GPU para eliminar elruido impulsivo en imágenes digitales. El procesopara eliminar el ruido en las imágenes se ha divididoen dos etapas. En el primer paso (p 1 ) los píxeleserróneos se <strong>de</strong>tectan y en el segundo paso (p 2 ) lospíxeles erróneos son filtrados. En el p 1 los píxelesson etiquetados como corruptos o no corruptos, <strong>de</strong>acuerdo con el número <strong>de</strong> píxeles que pertenecen alpeer group P (x i , d). Para <strong>de</strong>terminar el conjunto<strong>de</strong> elementos que pertenecen al peer group, se utilizala norma euclí<strong>de</strong>a entre los píxeles (vectores) <strong>de</strong> laimagen a color <strong>de</strong>notada como ||x i − x j || 2 , don<strong>de</strong> x ies el píxel central <strong>de</strong> una ventana W tamaño n x n(n = 3, 5 ...) y el x j es un pixel vecino <strong>de</strong> x i en W .Por lo tanto, el P (x i , d) representa el conjunto:{x j ∈ W : ||x i − x j || 2 ≤ d} (1)El peer group asociado con el píxel x i en W <strong>de</strong>nota elconjunto <strong>de</strong> píxeles x j <strong>de</strong> W , <strong>de</strong> modo que la normaeuclidiana no exceda a d, don<strong>de</strong> d > 0. En [4] di-<strong>JP2011</strong>-171


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011vi<strong>de</strong>n la <strong>de</strong>tección <strong>de</strong> pixeles ruidosos en dos fases,en la primera fase, la imagen la divi<strong>de</strong>n en ventanasdisjuntas y los píxeles son etiquetados como corruptos,no corruptos y no diagnosticados, consi<strong>de</strong>randolos no diagnosticados en la segunda fase. En nuestraimplementación paralela no hemos dividido la imagenen las ventanas disjuntas ya que un solo threadprocesa completamente un pixel. Esto es, hay unthread por cada píxel en la imagen. Así, cada subprocesorealiza la clasificación (corrupto o no corrupto),y por lo tanto, tenemos un solo paso para la fase <strong>de</strong><strong>de</strong>tección.Utilizamos un kernel para ejecutar el paso 1 yotro para el paso 2. El primer kernel ejecuta elalgoritmo 1 GPU-PGE. Cada thread lee los valoresRGB <strong>de</strong> los píxeles y crea una ventana <strong>de</strong> tamañon x n para analizarla. Se calcula el peer group, sila cardinalidad es mayor o igual a m, entonces elpixel x i es etiquetado como no corrupto (p n c), <strong>de</strong>lo contrario el píxel es etiquetado como corrupto(p c ). Hemos añadido un byte padding (bp) a cadaconjunto RGB (3 bytes) <strong>de</strong> la imagen, que se utilizapara almacenar el estado <strong>de</strong>l píxel como corrupto ono corrupto.Algoritmo 1. GPU-PGE p 11. Cada thread analiza un pixel <strong>de</strong> la imagen2. Cada Thread do3. construye su ventana W <strong>de</strong> tamaño n × n, centrado enx i ;4. Lee los valores RGB <strong>de</strong> cada pixel <strong>de</strong>ntro <strong>de</strong> W ;5. Calcula el peer group P(x i , d), Ecuación (1);6. if ♯P(x i , d)≥ (m + 1) then7. x i es <strong>de</strong>clarado como pixel non-corrupted (p nc);8. escribir p nc en el byte padding bp;9. else10. x i es <strong>de</strong>clarado como pixelcorrupted (p c);11. escribir p c en el byte padding bp;12. end13. endDespués <strong>de</strong> aplicar el algoritmo 1, obtenemos lospíxeles etiquetados como p c y p nc . Para filtrar lospíxeles etiquetados como p c , el kernel 2 ejecuta elalgoritmo 2 GPU-PGE. Cada thread lee el byte bp,si se trata <strong>de</strong> un pixel corrupto, entonces aplicamosel método AMF (Filtro <strong>de</strong> Media Aritmética) <strong>de</strong> lospíxeles vecinos que no sean corruptos.Algoritmo 2. GPUPGE p 21. Cada thread lee el byte bp2. if pb==p c then3. Accesar al byte bp <strong>de</strong> los pixeles <strong>de</strong> W ;4. ∀p nc d W leer los valores RGB;5. Calcular el AMF <strong>de</strong> los pixeles no corruptos p c;6. Reemplazar el valor RGB con la salida <strong>de</strong> AMF;7. endIII. Estudio ExperimentalEn esta sección se presentan los resultados experimentalesrealizados en un Mac OS X (Intel Quad-Core Xeon <strong>de</strong> 2 x 2,26 GHz, 8 GB <strong>de</strong> RAM) conuna GPU <strong>de</strong> NVIDIA (GeForce GT 120, 512 MB <strong>de</strong>memoria).Para evaluar la eficacia <strong>de</strong>l filtro propuesto, hemosutilizado algunas imágenes <strong>de</strong> la Base <strong>de</strong> Datos <strong>de</strong>(KODAK), éstas se muestran en la figura 1. <strong>La</strong>simágenes están en formato RGB con 3 canales y 8bits por canal, don<strong>de</strong> cada píxel es un vector <strong>de</strong> componentescon tres valores enteros entre 0 y 255. Estasimágenes fueron contaminados con los dos tipos <strong>de</strong>ruido impulsivo.a b cFig. 1. Imágenes utilizadas. a) Caps 768x512 b) World2400x1200 c) Statua 512x768.El ruido uniforme lo <strong>de</strong>notaremos como NMγ. Elruido introducido en alguno <strong>de</strong> sus canales o en todoscon valores uniformemente distribuidos en el intervalo[0,255].El segundo tipo <strong>de</strong> ruido llamadoSalt and Pepper o valor fijo lo <strong>de</strong>notaremos comoNMα. En este tipo, el ruido introducido se presentaen algún canal o en todos, cambiando su valor poralguno <strong>de</strong> los extremos <strong>de</strong>ntro <strong>de</strong>l rango <strong>de</strong> la señal0 ó 255.El valor m y d <strong>de</strong>pen<strong>de</strong>rán <strong>de</strong> la intensidad y tipo<strong>de</strong> ruido que se maneje. <strong>La</strong> Tabla 1 muestra los resultadosóptimos <strong>de</strong> d. Como po<strong>de</strong>mos ver, el valor <strong>de</strong>d es menor en imágenes con variedad <strong>de</strong> colores y esmayor con poca variación <strong>de</strong>l color o colores oscuros.Para las imágenes Caps y Statua con ruido uniformeruido impulsivo, los mejores resultados se obtienencon m = 2. Por el contrario, el ruido fijo tienedos variantes: m = 2 cuando las imágenes tienen unporcentaje una menor o igual al 10% <strong>de</strong> intensidad<strong>de</strong> ruido y m = 3 cuando es superior al 10%.Para evaluar el <strong>de</strong>sempeño <strong>de</strong>l filtro paralelo propuesto,usamos las medidas objetivas PSNR (PeakSignal-to-Noise Ratio) y para medir la supresión <strong>de</strong>lruido, MAE (Mean Absolute Error) para medir laconservación <strong>de</strong> la señal.TABLA IValores Óptimos <strong>de</strong> d con diferentes <strong>de</strong>nsida<strong>de</strong>s <strong>de</strong>ruido impulsivo.Image NM NM NM NM NM NM NM NMα γ α γ α γ α γ5% 5% 10% 10% 20% 20% 30% 30%Caps 45 63 45 51 57 53 51 52Statue 70 70 70 70 70 70 70 65Los resultados experimentales <strong>de</strong> las tablas 2 y 3han sido comparados con otros filtros, cuyos resultadosestán publicados en el trabajo [4]. Los filtroscon los que han sido comparados son: VMF, FIVF,<strong>JP2011</strong>-172


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011NAVMF, PGF, FPGF, IPGF y IFPGF y sus resultadosse refieren a la ejecución <strong>de</strong> forma secuencial.<strong>La</strong> tabla 2 muestra los resultados obtenidos en calidadcon la imagen Caps y NMγ. <strong>La</strong> columna GPU-PGE* es una versión <strong>de</strong> la GPU-PGE si se conoce <strong>de</strong>antemano que el ruido <strong>de</strong> la imagen es <strong>de</strong> tipo valorfijo, trabajando sólo con píxeles que tienen un valorextremo en uno <strong>de</strong> sus canales.<strong>La</strong> tabla 3 presenta los resultados <strong>de</strong> calidad <strong>de</strong>la imagen Caps con ruido impulsivo valor uniforme.Como po<strong>de</strong>mos ver, en la mayoría <strong>de</strong> los casos el algoritmoparalelo se elimina mayor cantidad <strong>de</strong> ruidocomparándolo con los otros filtros.<strong>La</strong> figura 2 muestra la imagen Caps con 20% <strong>de</strong>ruido impulsivo valor fijo y uniforme, el mapa conlos píxeles corruptos encontrados, y las imágenes resultantes<strong>de</strong>spués <strong>de</strong>l paso <strong>de</strong> filtrado.TABLA IIIResultados <strong>de</strong>l filtro en comparación con otros parala imagen Caps corrupta con diferentes <strong>de</strong>nsida<strong>de</strong>s <strong>de</strong>ruido impulsivo valor uniforme5% 10% 20%Filter MAE PSNR MAE PSNR MAE PSNRNoisy 4.29 20.75 8.31 17.86 16.77 14.79VMF 2.74 31.68 2.96 31.07 3.54 29.12FIVF 0.32 38.32 0.66 35.11 1.34 31.71NAVMF 0.30 38.98 0.55 36.45 1.28 32.16PGF 0.44 37.59 0.63 36.25 1.20 33.42FPGF 0.41 38.05 0.63 36.35 1.35 32.62IPGF 0.27 39.23 0.52 36.66 1.15 32.62IFPGF 0.38 38.50 0.59 36.78 1.16 33.44GPUPGE 0.33 39.25 0.57 37.04 1.19 33.51TABLA IVTiempo en milisegundos <strong>de</strong> la ejecuación <strong>de</strong>lalgoritmo con la imagen World, usando acceso a lamemoria globalGPU GPU GPU TotalGPU y%Noise t 1 t 2 Total t 1 y t 2 CPU5% 53.09 36.27 89.36 111.2110% 64.81 57.26 122.08 143.9320% 64.79 75.65 140.45 162.2930% 64.80 82.25 147.06 168.91a b cd e fFig. 2. a) Imagen con un 20% <strong>de</strong> ruido impulsivo valor fijob) Detección <strong>de</strong> los pixeles ruidosos c) Imagen Filtradad) Imagen con 20% <strong>de</strong> ruido impulsivo valor uniforme e)Detección <strong>de</strong> los pixeles ruidosos f) Imagen Filtrada.TABLA IIResultados <strong>de</strong>l filtro en comparación con otros parala imagen Caps corrupta con diferentes <strong>de</strong>nsida<strong>de</strong>s <strong>de</strong>ruido impulsivo valor fijo5% 10% 20%Filter MAE PSNR MAE PSNR MAE PSNRNoisy 2.54 21.76 4.84 18.97 9.97 15.81VMF 2.65 32.11 2.80 31.66 3.05 30.94FIVF 0.31 37.95 0.63 35.22 1.21 32.41NAVMF 0.25 39.87 0.51 36.33 1.16 32.57PGF 0.41 37.43 0.66 34.63 1.28 31.24FPGF 0.39 37.26 0.66 34.16 1.54 29.59IPGF 0.23 39.32 0.41 37.79 0.86 34.91IFPGF 0.35 37.88 0.64 34.18 1.34 31.72GPUPGE 0.30 38.43 0.58 35.16 1.22 32.60GPUPGE* 0.27 39.27 0.51 35.84 1.46 33.67Hemos hecho la <strong>de</strong>tección y filtrado a la imagenWorld, con un 20% <strong>de</strong> ruido impulsivo valor uniforme.Los valores utilizados para m y d son m = 2y d = 49.Para esta imagen, hemos realizado una comparativa<strong>de</strong> tiempo entre las versión paralela y secuencial.<strong>La</strong> GPU tiene una memoria física que pue<strong>de</strong> ser utilizada<strong>de</strong> diferentes maneras, la más común es comouna memoria global compartida. Sin embargo, sepue<strong>de</strong> utilizar en los modos: memoria local, texturay constante [9]. El acceso a los datos almacenadosen la memoria global tiene mayor latencia que otrosmodos <strong>de</strong> acceso a los datos. En nuestra aplicación seutiliza el acceso a los datos en la memoria <strong>de</strong> texturapara mejorar la eficiencia computacional.<strong>La</strong> tabla 5 muestra el tiempo que tarda en ejecutarel algoritmo GPU-PGE para acce<strong>de</strong>r a los datos<strong>de</strong> la memoria global sin textura (sT) y la tabla 6, eltiempo que tarda en acce<strong>de</strong>r a la memoria global contexturas (T), para la NMγ con diferentes <strong>de</strong>nsida<strong>de</strong>s<strong>de</strong> ruido. Se muestra el tiempo que tarda en ejecutarcada paso (cada kernel) en la GPU y el tiempo total<strong>de</strong> procesamiento <strong>de</strong> la GPU y CPU. Como se pue<strong>de</strong>ver, cuando usamos la memoria global a través <strong>de</strong>texturas, el tiempo <strong>de</strong> procesamiento es, en el peor<strong>de</strong> los casos 31% menos que el acceso a la memoriaglobal sin texturas. A<strong>de</strong>más, el tiempo que toma lapreparación <strong>de</strong> la imagen en la CPU y la transferencia<strong>de</strong> los píxeles <strong>de</strong> CPU a GPU y viseversa, es enla mayoría <strong>de</strong> los casos <strong>de</strong>l 28,5% <strong>de</strong>l tiempo total.En la tabla 7 se muestra una comparativa <strong>de</strong> losresultados obtenidos por el algoritmo en la versiónsecuencial con la versión paralela utilizando la memoriacon o sin texturas. El speedup alcanzado es <strong>de</strong>12x-13x. <strong>La</strong> figura 3 muestra que el problema <strong>de</strong> lareducción <strong>de</strong> ruido impulsivo es completamente paralelizable.IV. Análisis ComputacionalEn esta sección se presenta el análisis computacional<strong>de</strong>l algoritmo GPU-PGE, <strong>de</strong>s<strong>de</strong> el punto <strong>de</strong>vista <strong>de</strong> los accesos <strong>de</strong> memoria y la <strong>de</strong>manda <strong>de</strong>operaciones.Como se mencionó en el anterior capitulo, el procesose ha dividido en dos etapas. Uno para <strong>de</strong>tectar<strong>JP2011</strong>-173


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA VTiempo en milisegundos en la ejecución <strong>de</strong>l algoritmocon la imagen World con acceso a la memoria globala través <strong>de</strong> texturasGPU GPU GPU GPU yCPU%Noise t 1 t 2 Total t 1 y t 2 Total5% 23.15 31.64 54.80 76.6310% 23.15 38.40 61.55 83.4820% 23.13 46.65 69.79 91.6230% 23.13 51.58 74.72 96.57TABLA VISpeedup <strong>de</strong> la versión paralela con respecto a laversión secuencial <strong>de</strong> la imagen World.GPU y GPU y TotalCPU CPU Sequential Speedup SpeedupsT T sT T%Noise Total Total Total5% 111.21 76.63 939.21 8.44 12.2510% 143.93 83.48 1035.61 7.19 12.4020% 162.29 91.62 1182.71 7.28 12.9030% 168.91 96.57 1284.46 7.60 13.30los pixeles erróneos p 1 y p 2 para el filtrado. Los datosse estructuran en la memoria global, <strong>de</strong> manera quecada píxel <strong>de</strong> la imagen se almacena en 4 bytes, tresbytes para almacenar los canales RGB y otro para elpadding. En nuestra aplicación, se consi<strong>de</strong>raron dosenfoques para el acceso a los datos en dos pasos: accesoa la memoria global sin texturas y el acceso a lamemoria global con texturas. El análisis se presentaa continuación:a) Acceso a la memoria global sin texturas (sT ):• p 1 : 3 x n 2 acceso <strong>de</strong> sólo lectura (sT r) paraobtener los valores RGB <strong>de</strong> los píxeles en W yun acceso a escritura (sT w) para el cuarto byte<strong>de</strong> RGB para indicar si el pixel es o no corrupto.Así, la expresión está dada porsT p 1 = (3 × n 2 )sT r + sT w (2)En este paso se realiza el cálculo <strong>de</strong> la distanciaeuclí<strong>de</strong>a (dE) para <strong>de</strong>terminar los píxeles queforman parte <strong>de</strong>l peer group, y su coste, dE=η×(tres sustracciones, dos adiciones, tres productosy una raíz cuadrada), don<strong>de</strong> η = n 2 − 1correspon<strong>de</strong>n a los píxeles vecinos <strong>de</strong> x i .• p 2 : n 2 accesos <strong>de</strong> lectura para obtener el valor(corrupto o no) que tiene el cuarto byte , 3 x(ηp n c) accesos <strong>de</strong> lectura para obtener los valoresRGB <strong>de</strong> todos sus vecinos que no son corruptospara el cálculo <strong>de</strong> la AMF, y tres accesos <strong>de</strong>escritura para el nuevo valor RGB y el númerototal <strong>de</strong> accesos sería,sT p 2 = (n 2 )sT r + (3 × ηp n c)sT R + 3sT w (3)En este paso se calcula la media aritmética <strong>de</strong>ηp n c, el costo es <strong>de</strong>: AM c = (tres adiciones ytres divisiones) ×p n cEl costo total <strong>de</strong>l uso <strong>de</strong> la memoria global es:sT = sT p 1 + dE + sT p 2 + AM c (4)b) Acceso a la memoria global con texturas (T):• p 1 : 3 x n 2 accesos <strong>de</strong> sólo lectura a la memoria<strong>de</strong> textura (T r) para obtener los valores RGB<strong>de</strong> los píxeles W , un acceso <strong>de</strong> escritura a lamemoria global (sT w) para el cuarto byte <strong>de</strong>lconjunto RGB para indicar si el píxel es o nocorrupto. Por lo tanto,T p 1 = (3 × n 2 )T r + 1sT w (5)El coste computacional <strong>de</strong> la distancia euclí<strong>de</strong>aes la misma que se presentó en el paso 1 <strong>de</strong> lamemoria global sin textura.• p 2 : n 2 accesos <strong>de</strong> lectura a la memoria <strong>de</strong> texturapara obtener el valor (corrupto o no corrupto),que contiene el cuarto byte <strong>de</strong>l conjunto RGB<strong>de</strong> W , 3 × (p n c) accesos a la memoria <strong>de</strong> texturapara obtener los valores RGB <strong>de</strong> todos susvecinos que no son corruptos para el cálculo <strong>de</strong>AMF, y tres accesos <strong>de</strong> escritura para el nuevovalor RGB en la memoria global, es <strong>de</strong>cir,T p 2 = (n 2 )T mr + (3 × p n c)T mr + 3sT w (6)El coste computacional <strong>de</strong> la media aritméticaes la misma que se presenta en el paso 1 <strong>de</strong> lamemoria global.El costo total <strong>de</strong>l uso <strong>de</strong> memoria <strong>de</strong> acceso globalcon textura,3000CPUGPUT = T s1 + dE + T s2 + AM c (7)msec25002000150010005000 5 10 20 30%noiseFig. 3. Comparación <strong>de</strong> la ejecución en GPU y CPULos costes presentados en las figuras 5 y 7 sonválidos cuando el número <strong>de</strong> píxeles que contiene laimagen N pic es menor o igual al número <strong>de</strong> threads(τ) que se liberan. De lo contrario, algunos threadque se lanzan tienen que trabajar más <strong>de</strong> una vez, yel coste computacional está dada por,(sT |T ) × β (8)don<strong>de</strong> β es la parte entera por encima <strong>de</strong>l cociente(N pic ÷ τ) + 1.Los costes totales presentados se correspon<strong>de</strong>n conlos pasos que se realizan cuando los datos están en lamemoria <strong>de</strong> la GPU. Otro coste computacional es la<strong>JP2011</strong>-174


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011preparación y transferencia <strong>de</strong> los datos <strong>de</strong> la CPUa la GPU, pero <strong>de</strong>pen<strong>de</strong>rá <strong>de</strong> la arquitectura <strong>de</strong> laGPU / CPU en uso. Los costes presentados en lastablas 5 y 6 correspon<strong>de</strong>n al total <strong>de</strong> las operacionesen la GPU, y el total <strong>de</strong> la CPU y la GPU.V. ConclusionesEn este trabajo presentamos un algoritmo paraleloimplementado para la GPU, que es muy eficiente enlo que respecta a la calidad <strong>de</strong> la imagen filtrada, asícomo en el coste computacional.El algoritmo utiliza el concepto <strong>de</strong> peer grouppara eliminar el ruido impulsivo <strong>de</strong> valor fijo y elvalor uniforme. Tiene dos pasos: en el primero se<strong>de</strong>tectan los pixeles erróneos. Los píxeles ruidososse corrigen en el segundo paso. El método tieneun comportamiento muy uniforme con respecto a laintensidad <strong>de</strong>l ruido impulsivo <strong>de</strong>l mismo tipo enlos resultados <strong>de</strong> reducción (PSNR). <strong>La</strong> eficiencia<strong>de</strong>l proceso se mantiene para los diferentes tipos <strong>de</strong>imágenes que se utilizan. Los beneficios computacionalesobtenidos en nuestro estudio con la GPUpara hacer frente a este problema, representan unareducción en el tiempo <strong>de</strong> cálculo <strong>de</strong> 12x-13x con respectoa la versión secuencial. Por esta razón, hacemosincapié en que la tecnología GPU ofrece mejorassignificativas en velocidad <strong>de</strong> cálculo y procesamiento<strong>de</strong> alto nivel a un coste cada vez más accesible, porlo que muchas aplicaciones lo están utilizando.Agra<strong>de</strong>cimientosEste estudio ha sido financiado por el MinisterioEspañol <strong>de</strong> Ciencia e Innovación bajo elproyecto con referencia TIN2008-06570-C04-04, y M.Guadalupe Sánchez agra<strong>de</strong>ce a la DGEST- ITCG porla beca concedida a través <strong>de</strong>l programa PROMEP(México).Referencias[1] J. G. Camarena, V. Gregori, S. Morillas, A.Sapena,Fast <strong>de</strong>tection and removal of impulsive noise using peergroup and fuzzy metrics, Journal of Visual Communicationand Image Representation, 19 (2008) 20-29.[2] J.G. Camarena, V. Gregori, S. Morillas and A.Sapena, Some improvements for image filtering usingpeer group techniques, Image Vis. Comput., vol. 28, no.1, pp. 188-201, 2010.[3] J. G. Camarena, V. Gregori, S. Morillas , A. Sapena,Two-step fuzzy logic-based method for impulse noise <strong>de</strong>tectionin colour images, Pattern Recognition Letters 31(2010) 1842-1849.[4] R. Lukac, B. Smolka, K. Martin, K. N. Plataniotis,and A. N. Venetsanopoulos, Vector filtering for colorimaging, IEEE Signal Process. Mag.,vol. 22, no. 1, pp.74-86, Jan. 2005.[5] S. Morillas, V. Gregori, and A. Hervás, Fuzzy PeerGroups for Reducing Mixed Gaussian-Impulse Noise FromColor Images, IEEE Transaction on Image Processing, Vol18 No 7, November 2009.[6] S. Morillas, V. Gregori and G. Peris-Fajarns, Isolatingimpulsive noise pixels in color images by peer grouptechniques, Comput. Vis. Image Un<strong>de</strong>rst., vol. 110, no. 1,pp. 102-116, 2008.[7] NVIDIA Corporation, NVIDIA Programming Gui<strong>de</strong>Version 2.3.1, http://www.nvidia.com/page/home.html,2009.[8] B. Smolka, Peer group switching filter for impulse noisereduction in color images, Pattern Recognition Letters 31(2010) 484-495<strong>JP2011</strong>-175


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-176


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Estrategias <strong>de</strong> Paralelización <strong>de</strong> Algoritmos <strong>de</strong>Razonamiento para Ontologías BiomédicasEduardo J. Cepas 1 , Ginés D. Guerrero 1 , José M. Cecilia 1 , José M. García 1 y Jesualdo T.Fernán<strong>de</strong>z 2Resumen— Actualmente las ontologías son un método<strong>de</strong> representación <strong>de</strong> conocimiento ampliamenteusado, especialmente las relacionadas con conceptosbiomédicos. Sin embargo su <strong>de</strong>sarrollo y uso están limitadospor la gran carga <strong>de</strong> procesamiento que requieretrabajar con ellas. Gracias al uso <strong>de</strong> sistemas<strong>de</strong> computación <strong>de</strong> altas prestaciones se pue<strong>de</strong>n intentarpaliar estas limitaciones. En este artículo analizamosel proceso <strong>de</strong> razonamiento con ontologías, yproponemos algunas posibles alternativas para intentaradaptar este razonamiento a un enfoque paralelo.Tras esto evaluamos alguna <strong>de</strong> las alternativas propuestascon el fin <strong>de</strong> ver hasta que punto es posibley/o viable su implementación, <strong>de</strong>bido a los problemasinherentes que surgen durante el proceso <strong>de</strong> paralelización.Palabras clave— Razonadores, Ontologías, FaCT++,Snomed-CT, Tableaux, Paralelismo.I. IntroducciónEL éxito <strong>de</strong> la Gene Ontology [1] a principios <strong>de</strong>este siglo generó un gran interés en el diseño,<strong>de</strong>sarrollo y uso <strong>de</strong> ontologías biomédicas. Debido aeste interés, se han organizado no solo grupos <strong>de</strong> interésen <strong>de</strong>sarrollo <strong>de</strong> ontologías biomédicas sino queorganizaciones como el OBO Foundry [2] han coordinadoel <strong>de</strong>sarrollo <strong>de</strong> más <strong>de</strong> 200 ontologías y vocabularioscontrolados biomédicos en los últimos años.Una ontología es una representación formal <strong>de</strong>l conocimientomediante un conjunto <strong>de</strong> conceptos pertenecientesa un dominio, y las relaciones existentesentre ellos. Para la representación <strong>de</strong> ontología seusa el Web Ontology <strong>La</strong>nguage (OWL) [3], que esel estándar <strong>de</strong>l W3C para el intercambio <strong>de</strong> contenidossemánticos en la web. Se pue<strong>de</strong> <strong>de</strong>cir que OWL<strong>de</strong>fine una familia <strong>de</strong> lenguajes <strong>de</strong> representación <strong>de</strong>conocimiento en función <strong>de</strong> la expresividad <strong>de</strong> losoperadores lógicos empleados. Dentro <strong>de</strong> los sublenguajes<strong>de</strong> OWL, OWL-DL es el más representativopor estar basado en lógica <strong>de</strong> <strong>de</strong>scripciones, lo cualpermite aplicar razonadores <strong>de</strong>sarrollados para estetipo <strong>de</strong> lógica a las ontologías, siendo OWL-DL ellenguaje empleado en la mayor parte <strong>de</strong> ontologíasbiomédicas disponibles en la actualidad.<strong>La</strong> importancia <strong>de</strong> las ontologías biomédicas se <strong>de</strong>bea varias razones. Como se ha mencionado antes,existen más <strong>de</strong> 200 ontologías biomédicas, siendo sinduda la disciplina científica que está más implicaday convencida <strong>de</strong> los beneficios <strong>de</strong> disponer <strong>de</strong> repre-1 Grupo <strong>de</strong> Arquitectura y Computación Paralela,Dpto. <strong>de</strong> Ingeniería y Tecnología <strong>de</strong> Computadores,Univ. <strong>de</strong> Murcia, e-mail: {ecepasqui, gines.guerrero,jmgarcia}@ditec.um.es.2 Grupo <strong>de</strong> Tecnologías <strong>de</strong> Mo<strong>de</strong>lado, Procesamiento y Gestión<strong>de</strong>l Conocimiento, Dpto. <strong>de</strong> Informática y Sistemas, Univ.Murcia, e-mail: jfernand@um.es.sentaciones formales y procesables por las máquinas<strong>de</strong>l conocimiento biomédicos. Por otro lado, las ontologíasbiomédicas tienen por lo general un gran tamañoy el volumen <strong>de</strong> información gestionado poraplicaciones biomédicas es elevado, por lo que se requiere<strong>de</strong> métodos avanzados <strong>de</strong> gestión <strong>de</strong> la informacióny el conocimiento. Finalmente, el trabajo <strong>de</strong>investigación biomédico se basa fundamentalmenteen la inferencia a partir <strong>de</strong> datos y conocimientosprevios, por lo que el soporte <strong>de</strong> métodos <strong>de</strong> razonamientoautomático es <strong>de</strong> vital importancia. Sin embargo,para el uso óptimo <strong>de</strong> las ontologías biomédicasexisten problemas actualmente no resueltos. Porun lado, las ontologías biomédicas han sido construidascon fin <strong>de</strong> anotación <strong>de</strong> resultados experimentalesen vez <strong>de</strong> para ser empleadas como soporte <strong>de</strong>inferencias automáticas. Sin embargo, existen métodosen <strong>de</strong>sarrollo para el enriquecimiento semántico<strong>de</strong> dichas ontologías [4]. Por otro lado, los razonadoresexistentes no respon<strong>de</strong>n en un tiempo razonablea las tareas <strong>de</strong> clasificación <strong>de</strong>mandadas porontologías semánticamente ricas durante el proceso<strong>de</strong> construcción, lo cual limita la implicación <strong>de</strong> losinvestigadores biomédicos en estos procesos.Es por ello que surge esta investigación, como unestudio sobre el uso <strong>de</strong> arquitecturas <strong>de</strong> alto rendimientopara dar soporte a los procesos <strong>de</strong> construccióny uso <strong>de</strong> ontologías biomédicas. El presente trabajose centrará en estudiar las posibles estrategiasque se pue<strong>de</strong>n seguir para paralizar estos razonadores,analizando <strong>de</strong> su viabilidad. El documento seorganiza como sigue: en la sección II introducimoslos conceptos necesarios para enten<strong>de</strong>r mejor el resto<strong>de</strong>l documento; posteriormente en la sección IIIse hace un estudio <strong>de</strong> los razonadores semánticos yse realiza una propuesta para su paralización, cuyaevaluación será llevada a cabo en la sección IV. En lasección V se presenta el estado <strong>de</strong>l arte y finalmentela sección VI muestra las conclusiones y el trabajofuturo.II. Preliminares<strong>La</strong>s dos principales funciones <strong>de</strong> un razonador sonla creación <strong>de</strong> un mo<strong>de</strong>lo a partir <strong>de</strong> una ontologíay la inferencia <strong>de</strong> nuevas propieda<strong>de</strong>s no <strong>de</strong>scritas.Para nuestra investigación usamos un razonadorsemántico llamado FaCT++ [6]. Está implementadoen C++ y basa su proceso <strong>de</strong> razonamiento enun algoritmo <strong>de</strong> razonamiento altamente optimizado,llamado Tableaux. FaCT++ preprocesa la ontología<strong>de</strong> entrada OWL-DL y la transforma en una base <strong>de</strong>conocimiento (KB), dividida en dos conjuntos: TBox<strong>JP2011</strong>-177


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011y ABox. <strong>La</strong>s TBoxs contienen conceptos que formanparte <strong>de</strong> la ontología, y se usa para crear un mo<strong>de</strong>lo<strong>de</strong> representación <strong>de</strong>l conocimiento a partir <strong>de</strong> ellos.<strong>La</strong> ABox contiene los individuos y las relaciones entreellos, haciendo uso <strong>de</strong> estas para inferir propieda<strong>de</strong>sy comprobar su consistencia con la ontología.FaCT++ tiene como objetivo principal clasificaruna ontología a partir <strong>de</strong> su TBox usando un algoritmoTableaux. Para ello se evalúa su organizaciónjerárquica (taxonomía), que es un grafo jerárquico<strong>de</strong> inclusión en don<strong>de</strong> cada nodo representa un concepto,y un nodo C es hijo <strong>de</strong> otro nodo D si existeentre ellos una relación <strong>de</strong> inclusión C ⊆ D, es <strong>de</strong>cir,C está incluido en D (D es más genérico que C,o C es una especialización <strong>de</strong> D). Como se verá acontinuación, para construir esta clasificación, se vacalculando el or<strong>de</strong>n parcial <strong>de</strong> inclusión entre conceptosmediante pruebas <strong>de</strong> inclusión entre pares <strong>de</strong>estos.El algoritmo Tableaux trabaja a varios niveles <strong>de</strong>abstracción y complejidad. En el nivel <strong>de</strong> abstracciónmás alto FaCT++ trabaja con conceptos. Divi<strong>de</strong> lacolección <strong>de</strong> conceptos en tres grupos según una serie<strong>de</strong> propieda<strong>de</strong>s: completamente <strong>de</strong>finidos (CD),no completamente <strong>de</strong>finidos (noCD) y no-primitivos(non-p). Los conceptos CD y noCD no requieren serprocesados mediante el algoritmo Tableaux completopara ser clasificados, mientras los conceptos non-phan <strong>de</strong> ser procesados por el algoritmo completo, portanto son computacionalmente más costosos <strong>de</strong> clasificar.Los conceptos no se clasifican en el mismoor<strong>de</strong>n en que aparecen, sino siguiendo un or<strong>de</strong>n quebusca minimizar el número <strong>de</strong> pruebas que va a necesitarcada concepto para clasificarse.<strong>La</strong> fase SUB (subsumption) comienza cada vez queun concepto es seleccionado y propuesto para ser clasificado.Consiste en <strong>de</strong>terminar la posición correcta<strong>de</strong>l nuevo concepto <strong>de</strong>ntro <strong>de</strong>l grafo parcial <strong>de</strong> inclusiónque hay construido hasta ese momento. Paraello se van haciendo pruebas <strong>de</strong> inclusión entre pares<strong>de</strong> conceptos, formados por el concepto actual ycada uno <strong>de</strong> los nodos que forman parte <strong>de</strong>l grafo <strong>de</strong>inclusión parcial. Estas pruebas siguen un proceso <strong>de</strong>clasificación en dos partes: TopDown que trata <strong>de</strong> <strong>de</strong>terminarlos padres, y BottomUp que <strong>de</strong>termina loshijos <strong>de</strong>l concepto actual. Sin embargo, el algoritmomás importante a este nivel es la Búsqueda Baa<strong>de</strong>r,que va recorriendo el grafo <strong>de</strong> inclusión actual enun or<strong>de</strong>n concreto, y <strong>de</strong>terminando que pruebas <strong>de</strong>inclusión hay que llevar a cabo. De esta forma <strong>de</strong>terminacuales son realmente necesarias y lo que es másimportante, el or<strong>de</strong>n en que han <strong>de</strong> hacerse.Durante la fase <strong>de</strong> más bajo nivel, fase SAT (satisfiability),cada prueba <strong>de</strong> inclusión C ⊆ D se lleva acabo instanciando a un razonador, y equivale a comprobarsi la supuesta inclusión se satisface <strong>de</strong> acuerdoa la KB, es <strong>de</strong>cir, si la contradice o no. <strong>La</strong> supuestainclusión se satisface si es posible construir un mo<strong>de</strong>lo<strong>de</strong> acuerdo a la KB que cumpla la relación C ⊆ D,o por el contrario es inconsistente si durante la construcción<strong>de</strong> este mo<strong>de</strong>lo se contradicen entre sí variosaxiomas, ya sean los generados o los ya existentes enla KB. <strong>La</strong> construcción <strong>de</strong> este mo<strong>de</strong>lo implica conocery tener en cuenta la lógica <strong>de</strong> <strong>de</strong>scripción enque está basada la ontología, ya que este mo<strong>de</strong>lo seirá construyendo incrementalmente, aplicando reglas<strong>de</strong> expansión basadas en los operadores matemáticosque están incluidos en dicha lógica.Inicialmente se parte <strong>de</strong> la suposición C ⊆ D,a esta premisa se le aplicará la regla <strong>de</strong> expansión<strong>de</strong>l operador ⊆ <strong>de</strong> la lógica subyacente (SHOIN (D)en el caso <strong>de</strong> OWL-DL y FaCT++), quedando queC ⊆ KB D ≡ (C ⊓ ¬D) no es posible en KB. Actoseguido se aplicaría la regla <strong>de</strong> expansión correspondienteal operador ⊓, y así sucesivamente. Si seconsigue expandir todas las reglas y terminar el mo<strong>de</strong>losin producir ninguna incoherencia el test SUB escierto, si por el contrario hay alguna contradicción,la suposición inicial C ⊆ D es falsa.Este proceso <strong>de</strong> creación <strong>de</strong> un mo<strong>de</strong>lo expandiendoreglas es el kernel <strong>de</strong>l razonador FaCT++, y es elproceso más costoso en el que emplea la mayor parte<strong>de</strong> su tiempo <strong>de</strong> procesamiento. El or<strong>de</strong>n en queestas nuevas reglas se comprueban influye <strong>de</strong>cisivamenteen el tiempo <strong>de</strong> procesamiento resultante, yaque el coste <strong>de</strong> aplicar los distintos operadores difiereenormemente entre unos y otros. FaCT++ trata estoestableciendo un or<strong>de</strong>n <strong>de</strong> aplicación <strong>de</strong> la nuevas reglasproducidas, las reglas no se expan<strong>de</strong>n en el or<strong>de</strong>nen que se producen. Para ello se usa una estructurabastante compleja llamada TODO list formada porvarias listas y colas <strong>de</strong> espera, en don<strong>de</strong> las reglas seclasifican según el operador lógico que contienen, yse aplican en un or<strong>de</strong>n modificable pre<strong>de</strong>finido mediantepriorida<strong>de</strong>s. El or<strong>de</strong>n usado por <strong>de</strong>fecto enFaCT++ es <strong>de</strong> menor a mayor coste computacional,priorizando siempre los operadores lógicos queimplican menor coste aunque hayan sido añadidosmás tar<strong>de</strong> que otros <strong>de</strong> mayor coste. Los operadoresque implican diversificar el mo<strong>de</strong>lo, lógicamente, seevalúan los últimos.III. PlanteamientoComo se verá más a<strong>de</strong>lante en el trabajo relacionado,los estudios llevados a cabo sobre opciones <strong>de</strong>paralelización <strong>de</strong> algoritmos Tableaux se encuentranen fases poco avanzadas, y no han mostrado gran<strong>de</strong>sprogresos en los últimos años. A continuación, mostraremosun estudio <strong>de</strong> la posible paralelización <strong>de</strong>algoritmo Tableaux según los dos niveles <strong>de</strong> abstracciónanteriormente comentados.A. Nivel SUB: paralelismo entre pruebas <strong>de</strong> inclusiónDurante el proceso <strong>de</strong> clasificación, cuando se vaa añadir un concepto nuevo al grafo parcial <strong>de</strong> inclusión,se conoce dicho concepto, y todos los nodosque forman dicho grafo. Con lo cual, cuando empiezala clasificación <strong>de</strong> un concepto se sabe a prioriel máximo número <strong>de</strong> pruebas que hay que realizarpara clasificarlo, y estas pruebas son perfectamenteparalelizables, ya que su resultado sólo <strong>de</strong>pen<strong>de</strong> <strong>de</strong><strong>JP2011</strong>-178


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011la base <strong>de</strong> conocimiento KB y no <strong>de</strong>l resultado <strong>de</strong>otras pruebas, ni <strong>de</strong>l estado <strong>de</strong>l grafo <strong>de</strong> clasificaciónen cada momento. Este estado <strong>de</strong>l grafo <strong>de</strong>terminaqué tests hay que hacer para clasificar un concepto,cuántos y cuáles son necesarios. Ante esto, algunasposibilida<strong>de</strong>s en paralelo que surgen son:Previamente a la clasificación, calcular en paralelotodas las posibles pruebas <strong>de</strong> inclusión entrecada par <strong>de</strong> conceptos <strong>de</strong> la ontología. Esto implicaque n conceptos necesitarían n ∗ (n − 1)test SUB. Esto supondría realizar muchas operacionesinnecesarias, lo que redundaría en unamejora, si la hubiera, poco significativa.Durante el proceso <strong>de</strong> clasificación, calcular enparalelo todas las posibles pruebas que comomucho habría que hacer para añadir un concepto.Esto supondría una sobrecarga mucho menorque la posibilidad anterior, ya que como muchohabría que hacer tantas pruebas para cada conceptocomo nodos <strong>de</strong>l grafo hubiera clasificadosen cada momento. Aun así, habría que evaluar sieste enfoque podría llegar a mejorar en algún casoa la versión secuencial FaCT++, que está basadaen heurísticas.B. Nivel SAT: paralelismo <strong>de</strong>ntro <strong>de</strong> la creación <strong>de</strong>un mo<strong>de</strong>loUn test SAT se correspon<strong>de</strong> con la aplicación <strong>de</strong>una regla <strong>de</strong> expansión durante el cálculo <strong>de</strong> un mo<strong>de</strong>lonecesario para realizar una prueba <strong>de</strong> inclusión.Por norma general estas reglas son <strong>de</strong>pendientes entresí, excepto las no <strong>de</strong>terministas que producen divergenciasen el mo<strong>de</strong>lo. Por lo tanto cambiar el or<strong>de</strong>nen que se evalúan, o evaluarlas en paralelo suponeun gran riesgo <strong>de</strong> que el resultado <strong>de</strong>l algoritmo nosea correcto o incluso <strong>de</strong> que su tiempo <strong>de</strong> ejecuciónse dispare. Los propios autores <strong>de</strong> FaCT++, advierten<strong>de</strong> que no se <strong>de</strong>be modificar el or<strong>de</strong>n en que sehacen las comprobaciones [6]. Estas limitaciones enel or<strong>de</strong>n se <strong>de</strong>ben, en parte, a intentar minimizar laexpansión <strong>de</strong>l mo<strong>de</strong>lo para garantizar la terminaciónsecuencial <strong>de</strong>l algoritmo. Habría que evaluar si enuna arquitectura paralela con mucha mayor potencia<strong>de</strong> cálculo se podrían relajar estas restricciones,garantizando igualmente la corrección y terminación<strong>de</strong>l algoritmo. Por otro lado, surge otro gran problemacuando se empieza la construcción <strong>de</strong> un mo<strong>de</strong>lo,ya que no se dispone <strong>de</strong> las reglas que hay que aplicar,es <strong>de</strong>cir, qué expansiones hay que hacer, ya quelo único que se tiene al comienzo es una restriccióninicial C ⊆ D y sólo en el momento en que se compruebey se expanda esta restricción se obtendrán lasnuevas restricciones a ser comprobar. Debido a estemotivo, en cada momento tendríamos muy pocas reglasque evaluar en paralelo, ya que se van obteniendoal ir expandiendo el mo<strong>de</strong>lo. Para obtener unaposible mejora, al igual que en el caso <strong>de</strong>l paralelismoa nivel SUB, es necesario disponer <strong>de</strong>l or<strong>de</strong>n <strong>de</strong>varios cientos o miles <strong>de</strong> reglas, lo cual es bastanteimprobable que suceda. A<strong>de</strong>más, las posibles reglasdisponibles en cada momento, difícilmente serían in<strong>de</strong>pendientesy habría que tener consi<strong>de</strong>raciones adicionalesque perjudicarían aún más el rendimiento.Una posible opción sería expandir todas las reglasdisponibles a la vez, o expandirlas según el tipo <strong>de</strong>operador en que se basen.IV. Evaluación <strong>de</strong> FaCT++<strong>La</strong>s ontologías usadas en las pruebas con FaCT++son cuatro: Snomed-CT, Thesaurus, Pombe y Nsennetsu.Snomed-CT [5] es la terminología médica másimportante en la actualidad, ya que constituye la base<strong>de</strong> conocimiento clínico <strong>de</strong> mayor uso en el ámbitosanitario. Muestra <strong>de</strong> su interés es su consi<strong>de</strong>ración<strong>de</strong> terminología oficial en varios países, entre ellosEspaña. Aunque su forma <strong>de</strong> representación nativano es OWL, en este trabajo usamos una conversiónautomática disponible en el Bioportal [7].Thesaurus es la ontología <strong>de</strong>sarrollada por el NCIpara el dominio <strong>de</strong>l cáncer, que también está disponibleen OWL en el Bioportal. Estas dos ontologíasson consi<strong>de</strong>radas referencia en el ámbito biomédicoy no se pue<strong>de</strong>n consi<strong>de</strong>rar semánticamente ricas <strong>de</strong>s<strong>de</strong>la perspectiva <strong>de</strong> los axiomas y operadores lógicosque incluyen. Se basan fundamentalmente en una taxonomía.Por su parte, Pombe y Nsennetsu son dosontologías generadas automáticamente a partir <strong>de</strong> losficheros <strong>de</strong> anotaciones <strong>de</strong> los genomas <strong>de</strong> SchizosaccharomycesPombe y Neorickettsia sennetsu Miyayamarespecto <strong>de</strong> Gene Ontology, usando la versiónenriquecida <strong>de</strong> Gene Ontology <strong>de</strong>scrita en [4]. Estasdos ontologías se pue<strong>de</strong>n consi<strong>de</strong>rar semánticamentericas <strong>de</strong>s<strong>de</strong> la perspectiva <strong>de</strong> los axiomas y operadoreslógicos que incluyen, pues contienen bastantepropieda<strong>de</strong>s semántica que relacionan las clases <strong>de</strong> laontología.A. Descripción <strong>de</strong> entorno <strong>de</strong> simulaciónSe han realizado pruebas con la versión FaCT++secuencial, y con una implementación paralela a nivelSUB en OpenMP. Para las pruebas secuenciales se hausado una máquina con dos procesadores Intel XeonCPU E5620 Quad-Core a 2.40GHz. Por otro lado,para las pruebas <strong>de</strong> la implementación en OpenMPse ha usado un superor<strong>de</strong>nador <strong>de</strong> memoria compartida<strong>de</strong>l Centro <strong>de</strong> Supercomputación <strong>de</strong> la FundaciónParque Científico <strong>de</strong> Murcia, cuyas principalescaracterísticas son las siguientes: HP Integrity SuperdomeSX2000 con 64 procesadores Intel Itanium2Dual-Core Montvale a 1.60Ghz y 1.5 TB <strong>de</strong> memoriacompartida.B. Perfiles <strong>de</strong> ejecuciónComo se ha dicho, FaCT++ divi<strong>de</strong> los conceptosque forman parte <strong>de</strong> cada ontología en tres tipos:CD, noCD y non-primitive. El comportamiento <strong>de</strong>lalgoritmo y el perfil <strong>de</strong> ejecución que se obtiene esdiferente según la composición <strong>de</strong> la ontología. Segúnel porcentaje <strong>de</strong> conceptos que hay <strong>de</strong> cada tipo seobtienen tres perfiles <strong>de</strong> ejecución:Conceptos CD: no requieren proceso <strong>de</strong> clasificación,la posición <strong>de</strong> cada concepto en el grafo<strong>JP2011</strong>-179


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA IResultados <strong>de</strong> la ejecución <strong>de</strong>l código secuencial <strong>de</strong> FaCT++Ontología T o ejec. (seg.) n o SUBs n o SATs SUBs/Concepto SATs/SUBSnomed-CT 446,61 15.028.965 1.608.815.309 51,62 107,048Thesaurus 31 410.923 50.590.753 5,13 123,115Pombe 951,19 42.196 10.268.799 1,12 243,36Nsennetsu 1.665,7 2.773 100.612.773 1,15 32,283<strong>de</strong> clasificación está Completamente Definida enla propia <strong>de</strong>finición <strong>de</strong> la ontología. Su coste <strong>de</strong>clasificación es muy bajo.Conceptos noCD: no necesitan realizar la faseSUB completa <strong>de</strong>l algoritmo Tableaux, yaque construyendo una caché <strong>de</strong> conceptos pue<strong>de</strong>nprescindir <strong>de</strong> la ejecución <strong>de</strong> la parte Top-Down/BottomUp y <strong>de</strong> la búsqueda Baa<strong>de</strong>r. Aúnasí su coste <strong>de</strong> clasificación es bastante alto.Conceptos non-primitive: son los más costosos<strong>de</strong> clasificar ya que necesitan razonamiento Tableauxcompleto.C. Versión secuencial<strong>La</strong>s primeras pruebas realizadas consisten en ejecutarla versión secuencial <strong>de</strong> FaCT++ con distintasontologías, y así po<strong>de</strong>r analizar sus tiempos <strong>de</strong> ejecución.Esto nos servirá para tener un punto <strong>de</strong> partidacon el cual po<strong>de</strong>r comparar futuras versiones paralelas.En la tabla I se muestra un listado <strong>de</strong> la informaciónrecolectada <strong>de</strong> la ejecución <strong>de</strong>l código secuencial,teniendo en cuenta los siguientes apartados:Tamaño <strong>de</strong> la ontología (número <strong>de</strong> conceptos).Tiempo medio <strong>de</strong> clasificación.Número <strong>de</strong> tests SUB y SAT realizados.Número medio <strong>de</strong> tests SUB necesarios para clasificarun concepto.Número <strong>de</strong> medio <strong>de</strong> tests SAT en que se expan<strong>de</strong>una prueba SUB.D. Versión paralela en OpenMPEn este apartado se propone la implementación <strong>de</strong>la segunda opción consi<strong>de</strong>rada en el apartado III-A,correspondiente a la paralelización <strong>de</strong> todas las pruebas<strong>de</strong> inclusión que se realizan para cada conceptoen el proceso <strong>de</strong> razonamiento. Dicha implementaciónserá llevada a cabo mediante el lenguaje <strong>de</strong> programaciónOpenMP [8].Para realizar esta implementación se calculan enparalelo todas las pruebas <strong>de</strong> inclusión entre un conceptoy todos los nodos <strong>de</strong>l grafo, cambiando el or<strong>de</strong>nen el que se recorre el grafo parcial <strong>de</strong> inclusión. Estoconlleva modificar la búsqueda Baa<strong>de</strong>r para que simplementese limite a comparar los resultados <strong>de</strong> laspruebas, en vez <strong>de</strong> tener que calcularlos. El cálculoparalelo <strong>de</strong> las pruebas se realiza mediante un bucle,que será fácilmente paralelizado en OpenMP mediantela directiva #pragma omp parallel for.Tras ejecutar este código en el supercomputadorTABLA IITiempos obtenidos por la versión paralela <strong>de</strong> FaCT++implementada en OpenMP para la ontologíaSnomed-CTVersión Tiempo Pérdida <strong>de</strong>(minutos) RendimientoSecuencial 7,45 -16 cores 511,73 68,7x32 cores 289,20 38,82x64 cores 181,26 24,33x128 cores 120,84 16,22xcon 16, 32, 64 y 128 cores, po<strong>de</strong>mos comprobar queel mejor tiempo que se obtiene es <strong>de</strong> 120,84 minutospara la ontología Snomed-CT, frente a los 7,45minutos que emplea su versión secuencial (véase latabla II), es <strong>de</strong>cir, unas 16,22 veces más lento. Esteresultado nos hace plantearnos si realmente se podríallegar a mejorar la versión secuencial con este enfoque,por lo que se ha realizado un estudio teórico alrespecto en el siguiente apartado.E. Estudio teórico <strong>de</strong> la paralelizaciónVamos a analizar el planteamiento anterior, paraasí comprobar teóricamente si paralelizando laspruebas <strong>de</strong> inclusión a nivel SUB se podría llegar amejorar a la versión secuencial <strong>de</strong> FaCT++. Paraello, primero estudiaremos que casos serían el mejory el peor en el algoritmo secuencial.Suponiendo constante el tiempo t <strong>de</strong> una prueba,que la ontología tiene n conceptos a clasificar, y quese tienen que realizar p(n) pruebas, el tiempo totalen realizar la clasificación secuencial total sería:T secuencial = p(n) ∗ tEl caso pésimo sería cuando cada concepto tieneque compararse con todos los nodos <strong>de</strong>l grafo en esemomento, es <strong>de</strong>cir, el concepto n tiene que realizarn − 1 pruebas, y la suma total <strong>de</strong> pruebas para nconceptos sería:T peor (n) =n ∗ (n − 1)2∗ tPara el mejor caso, tendríamos que buscar la formadon<strong>de</strong> cada concepto necesite realizar el mínimonúmero <strong>de</strong> test posibles para clasificarse. Debido acómo recorre el grafo en el algoritmo Baa<strong>de</strong>r, hay<strong>JP2011</strong>-180


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011que buscar la forma <strong>de</strong> expandir el grafo, compensandoentre anchura y profundidad.Los resultados para la ontolgía Snomed-CT son lossiguientes:T peor (n) = 16.532.438.203 ∗ t.T F aCT (n) = 15.028.965 ∗ tT mejor (n) = 4.716.324 ∗ t.Como vemos, en el caso óptimo se harían 4,7 millones<strong>de</strong> pruebas SUB, en el pésimo 16.532,4 millones,mientras que la búsqueda Baa<strong>de</strong>r <strong>de</strong> FaCT++ realizapoco más <strong>de</strong> 15 millones <strong>de</strong> pruebas. Por esteestudio se pue<strong>de</strong> afirmar que la versión secuencial <strong>de</strong>FaCT++ está muy cercana al caso óptimo, y que vaa ser muy difícil <strong>de</strong> mejorar mediante su paralelizaciónsin el uso <strong>de</strong> las heurísticas que, forzosamente,han <strong>de</strong> aplicarse secuencialmente.Por último, evaluamos cual sería el número <strong>de</strong> hilosóptimo que <strong>de</strong>bería haber en una aplicación paralela.Para planificar estas pruebas en paralelo consi<strong>de</strong>ramosotro parámetro, h = número <strong>de</strong> hilos, con lo cualel tiempo <strong>de</strong> clasificación en paralelo será:T paralelo =(p(n) ∗ t)hSegún este planteamiento, para po<strong>de</strong>r igualar eltiempo obtenido en el código secuencial habría queejecutar aproximadamente 1100 hilos en paralelo(T paralelo = T peor (n)/h = T F aCT (n)), claro está, enuna situación i<strong>de</strong>al don<strong>de</strong> no haya una sobrecargaproducida por la ejecución paralela <strong>de</strong> los hilos.V. Estado <strong>de</strong>l arteActualmente y hasta don<strong>de</strong> nuestro conocimientoalcanza, los trabajos que evalúan posibles alternativassobre como paralelizar un razonador o su proceso<strong>de</strong> clasificación se pue<strong>de</strong>n clasificar en los siguientesenfoques:Ejecutar varias instancias <strong>de</strong> un razonador:• Procesamiento distribuido.• Particionar en trozos in<strong>de</strong>pendientes una ontologíay ejecutar un razonador en paralelo concada trozo.Ejecutar una sola instancia <strong>de</strong> razonador:• Particionar en trozos <strong>de</strong>pendientes una ontologíay ejecutar un sólo razonador, con su algoritmo<strong>de</strong> clasificación en paralelo.• Clasificación en paralelo <strong>de</strong> reglas in<strong>de</strong>pendientes.A. Procesamiento distribuidoEn este enfoque se propone ejecutar varias instancias<strong>de</strong> un razonador coordinadas mediante un procesamientodistribuido. Existen varios artículos endon<strong>de</strong> se consi<strong>de</strong>ra y evalúa esta opción [9, 10]. Enellos se consi<strong>de</strong>ran dos posibles opciones: particionamiento<strong>de</strong> datos y particionamiento <strong>de</strong> reglas. Seafirma que una sola máquina no es suficiente paraprocesar tal cantidad <strong>de</strong> datos, y que por el contrariouna solución basada en un sistema distribuido es potencialmentemás escalable. Por último se consi<strong>de</strong>rantres enfoques actuales <strong>de</strong> razonamiento paralelo paradatos a escala web, como son los sistemas <strong>La</strong>rKC,MaRVIN y Reasoning-Hadoop.B. División <strong>de</strong> la ontología en trozos in<strong>de</strong>pendientesEn [11] se proponen dos posibles soluciones: dividirontologías en módulos in<strong>de</strong>pendientes, y por otrolado, rediseñar el proceso <strong>de</strong> razonamiento a bajo nivel.Se afirma que las ontologías no tienen comportamientomodular y que a<strong>de</strong>más los algoritmos <strong>de</strong> razonamientoestán altamente optimizados, lo que implicamuchas <strong>de</strong>pen<strong>de</strong>ncias. Sin embargo consi<strong>de</strong>ra quelos sistemas mo<strong>de</strong>rnos, basados en multiprocesadores<strong>de</strong> memoria compartida podrían ser una solución, yaque podrían paliar estas <strong>de</strong>pen<strong>de</strong>ncias. Pero tambiénse afirma que para po<strong>de</strong>r conseguir una mejora significativasería necesario disponer <strong>de</strong> un alto número<strong>de</strong> operaciones que po<strong>de</strong>r ejecutar en hilos paralelos,lo que obligaría a consi<strong>de</strong>rar también operaciones <strong>de</strong>terministas,las cuales implican un gran número <strong>de</strong><strong>de</strong>pen<strong>de</strong>ncias.C. Reglas in<strong>de</strong>pendientesCiertos estudios se centran en analizar las reglas<strong>de</strong> una lógica <strong>de</strong> <strong>de</strong>scripción y su comportamiento,intentando buscar aquellas que son in<strong>de</strong>pendientesentre si.En [12] se indica que las tareas necesarias duranteel cálculo <strong>de</strong> una prueba <strong>de</strong> inclusión SUB no son in<strong>de</strong>pendientes,pero que existen algunas operacionesno <strong>de</strong>terministas, como son las reglas <strong>de</strong> disyunción(o-lógico), o las reglas <strong>de</strong> restricciones <strong>de</strong> números(“como mucho”) que generan alternativas totalmentein<strong>de</strong>pendientes. Presenta un enfoque para paralelizarel algoritmo <strong>de</strong> procesamiento <strong>de</strong> consistenciaABox <strong>de</strong>l sistema RACE, don<strong>de</strong> usa una cola conprioridad para planificar la ejecución <strong>de</strong> tareas no<strong>de</strong>terministas en distintos hilos (similar a TODO list<strong>de</strong> FaCT++). Este diseño está orientado a sistemasSMP, don<strong>de</strong> todos los hilos tienen acceso a una memoriaprincipal y el acceso a la cola <strong>de</strong> prioridad serealiza <strong>de</strong> forma sincronizada. Entre sus resultados,se acerca a una mejora 4x con 6-12 hilos en algunoscasos <strong>de</strong> prueba concretos. En un trabajo posterior[13], se aña<strong>de</strong> una tercera regla no <strong>de</strong>terminista:“qualified number restriction”.D. Particionamiento en trozos <strong>de</strong>pendientes y clasificaciónen paraleloEn [14] se propone un nuevo algoritmo a nivel SUBque sustituye a la búsqueda Baa<strong>de</strong>r. Este divi<strong>de</strong> laentrada en particiones <strong>de</strong>pendientes que se procesanen paralelo y une posteriormente los resultados. Serealiza un estudio sobre parámetros influyentes en elalgoritmo, como son el número <strong>de</strong> hilos a ejecutaren paralelo, el número <strong>de</strong> conceptos por hilo y lasestrategias para particionar TBox. Su algoritmo seapoya en un preprocesamiento <strong>de</strong>l TBox <strong>de</strong> entradacon el sistema RACER que prepara la entrada parasu algoritmo. <strong>La</strong>s pruebas realizadas en paralelo proponenun número muy bajo <strong>de</strong> hilos (la mayoría con<strong>JP2011</strong>-181


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20112 y 5).En [15] se continua el trabajo anterior y se especificanalgunos <strong>de</strong>talles, como es el uso <strong>de</strong> un únicoárbol global compartido para todos los hilos. Establecenúmero <strong>de</strong> hilos a 2 y número <strong>de</strong> conceptos porhilo a 5. Presenta una <strong>de</strong>scripción completa <strong>de</strong> sunuevo algoritmo <strong>de</strong> clasificación que se basa en sustituira la búsqueda Baa<strong>de</strong>r y preprocesar el TBox <strong>de</strong>entrada para adaptarlo a sus necesida<strong>de</strong>s. Este nuevoplanteamiento necesita métodos adicionales paragarantizar su completitud y consistencia. Al final seobtiene una mejora <strong>de</strong> casi 2x con poca sobrecarga.VI. Conclusiones y trabajo futuroEn este documento se ha implementado una versiónparalela <strong>de</strong>l razonador semántico FaCT++. Obteniendocomo resultado unos tiempos <strong>de</strong> ejecuciónsuperiores a los <strong>de</strong> la versión secuencial. Esto es <strong>de</strong>bidoa que naturaleza <strong>de</strong>l problema hace que existanuna gran cantidad <strong>de</strong> <strong>de</strong>pen<strong>de</strong>ncias <strong>de</strong> datos, lo quelo hace muy difícil que su paralelización sea eficiente.A<strong>de</strong>más, FaCT++ hace uso <strong>de</strong> ciertas heurísticasque consiguen una reducción notoria <strong>de</strong> su tiempo <strong>de</strong>ejecución, las cuales implican la ejecución secuencial<strong>de</strong>l código, y por tanto, no pue<strong>de</strong>n ser paralelizadas.El presente trabajo supone una primera aproximacióna un campo sobre el cual no existe aún mucha bibliografía.Ninguna <strong>de</strong> las alternativas presentadas enel trabajo relacionado está lo suficientemente avanzadacomo para mostrar resultados relevantes. A<strong>de</strong>más,tampoco están orientadas a paralelizar el proceso <strong>de</strong>clasificación en sí mismo. Hay alguna aproximación,pero se basa en particionar la ontología, no en la paralelización<strong>de</strong>l algoritmo.Tras realizar un estudio teórico, estamos en disposición<strong>de</strong> afirmar que para alcanzar una mejoraconsi<strong>de</strong>rable habría que lanzar una gran cantidad <strong>de</strong>hilos ejecutándose en paralelo. Esto nos lleva a pensaren la utilización <strong>de</strong> arquitecturas masivamenteparalelas, como es el caso <strong>de</strong> las GPUs, que están teniendogran acogida en la comunidad científica parala paralelización <strong>de</strong> diversas aplicaciones.Otra opción <strong>de</strong> paralelizar la aplicación FaCT++sería hacer un rediseño <strong>de</strong> la misma pensando ensu paralelización, volviéndola a implementar <strong>de</strong>s<strong>de</strong>el principio siguiendo esta filosofía.Harris, M., Hill, D., Issel-Tarver, L., Kasarskis,A., Lewis,S., Matese, J., Richardson, J., Ringwald, M., Rubin, G.,Sherlock, Gene ontology: tool for the unification of biology,Nature Genetics 25, 25–29, 2000.[2] Smith, B., Ashburner, M., Rosse, C.,Bard, J.,Bug, W.,Ceusters, W., Goldberg, L., Eilbeck, K., Ireland, A., Mungall,C., Leontis, N., Rocca-Serra, P., Ruttenberg, A., Theobo foundry: coordinated evolution of ontologies to supportbiomedical data integration, Nat Biotech 25 (1087–0156),1251–1255, 2007.[3] OWL Web Ontology <strong>La</strong>nguage, http://www.w3.org/TR/owl-ref (accessed, May, 31th, 2011).[4] J.T. Fernan<strong>de</strong>z-Breis, L. Iannone, I. Palmisano, A. Rector,R. Stevens. Enriching the Gene Ontology via the Dissectionof <strong>La</strong>bels using the Ontology, NPre-Processor <strong>La</strong>nguage.EKAW 2010, Lecture Notes in Computer Science6317, 59–73, 2010.[5] Systematized Nomenclature of Medicine-Clinical Terms,http://www.ihtsdo.org/snomed-ct (accessed, May, 31th,2011).[6] D. Tsarkov and I. Horrocks, FaCT++ <strong>de</strong>scription logicreasoner: System <strong>de</strong>scription, Proc. of the Int. Joint Conf.on Automated Reasoning (IJCAR 2006), Lecture Notes inArtificial Intelligence vol. 4130, Springer (2006), pp. 292–297.[7] NCBO BioPortal, http://bioportal.bioontology.org(accessed, May, 31th, 2011).[8] The OpenMP Specification, http://www.openmp.org (accessed,May, 31th, 2011).[9] Li P., Zeng Y., Kotoulas S., Urbani J., and Zhong N., TheQuest for Parallel Reasoning on the Semantic Web, Proceedingsof the 2009 International Conference on ActiveMedia Technology, LNCS, 2009.[10] J. Urbani, Scalable and parallel reasoning in the SemanticWeb, The Semantic Web: Research and Applications,2010.[11] Bock, J. Parallel Computation Techniques for OntologyReasoning, The Semantic Web - ISWC 2008. Volume5318/2008 of Lecture Notes in Computer Science., SpringerBerlin / Hei<strong>de</strong>lberg (2008) 901–906.[12] Liebig, T., Muller, F., Parallelizing Tableaux-Based DescriptionLogic Reasoning, On the Move to MeaningfulInternet Systems 2007: OTM 2007 Workshops.Volume4806/2007 of Lecture Notes in Computer Science., SpringerBerlin / Heielberg (2007) 1135–1114[13] T. Liebig, A. Steigmiller, O. Noppens, Scalability viaParallelization of OWL Reasoning, Proceedings of the 4thWorkshop on New Forms of Reasoning for the SemanticWeb: Scalable & Dynamic, Heraklion, Greece, May 2010.[14] M. Aslani and V. Haarslev, Towards parallel classifcationof TBoxes, Proceedings of the 2008 International Workshopon Description Logics (DL-2008), Dres<strong>de</strong>n, Germany,May 13–16, (2008).[15] M. Aslani and V. Haarslev, TBox Classification in Parallel:Design and First Evaluation, Proc. 23rd Int. Workshopon Description Logics (DL2010), CEUR-WS 573, Waterloo,Canada, 2010.[16] I. Horrocks and U. Sattler, A Tableaux Decision Procedurefor SHOIQ, Proc. of IJ-CAI 2005, 2005.Agra<strong>de</strong>cimientosEste trabajo ha sido financiado conjuntamente mediantela Fundación Séneca (Agencia Regional <strong>de</strong>Ciencia y Tecnología, Región <strong>de</strong> Murcia) con la ayuda00001/CS/2007, y también al MEC y la ComisiónEuropea FEDER con las ayudas CSD2006-00046,TIN2009-14475-C04 y TIN2010-21388-C02-02. Tambiénqueremos agra<strong>de</strong>cer la ayuda prestada por elCentro <strong>de</strong> Supercomputación <strong>de</strong> la Fundación ParqueCientífico <strong>de</strong> Murcia, don<strong>de</strong> hemos llevado a cabonuestras pruebas.Referencias[1] Ashburner, M., Ball, C., Blake, J., Botstein, D., Butler, H.,Cherry, J., Davis, A., Dolinski, K., Dwight, S., Eppig, J.,<strong>JP2011</strong>-182


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Arquitecturas <strong>de</strong>l procesador, multiprocesadores y chipsmultinúcleo<strong>JP2011</strong>-183


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-184


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Real-Time Task Migration with DynamicPartitioning to Reduce Power ConsumptionJosé Luis March, Julio Sahuquillo, Salvador Petit, Houcine Hassan, and José Duato 1Abstract— Nowadays, a key <strong>de</strong>sign issue in embed<strong>de</strong>d systemsis how to reduce the power consumption, since batteries have alimited energy budget. For this purpose, several techniques suchas Dynamic Voltage Scaling (DVS) or task migration can be used.DVS allows reducing power by selecting the optimal voltage supply,while task migration achieves this effect by balancing the workloadamong cores.This paper first analyzes the impact on energy due to task migrationin multicore embed<strong>de</strong>d systems with DVS capability andusing the well-known Worst Fit (WF) partitioning heuristic. To reduceoverhead, migrations are only performed at the time that atask arrives to and/or leaves the system and, in such a case, onlyone migration is allowed.The huge potential on energy saving due to task migration, leadsus to propose a new dynamic partitioner, namely DP, that migratestasks in a more efficient way than typical partitioners. Unlike WF,the proposed algorithm examines which is the optimal target corebefore allowing a migration. Experimental results show that DP canimprove energy consumption in a factor up to 2.74 over the typicalWF algorithm.Keywords— Dynamic Partitioning, Task Migration, Power-Aware, Multi-Core, Multi-Thread, Real-Time, Embed<strong>de</strong>d Systems.I. INTRODUCTIONEMBEDDED systems is an important segment ofthe microprocessor market since they are becomingubiquitous in our life. Systems like PDAs, smart phones,or automotive, provi<strong>de</strong> an increasing number of functionalitiessuch as voice communication, navigation, or gaming,so that computational power is becoming more importantevery day. However, increasing computationalpower impacts on battery lifetime, so how to improvepower management is a major <strong>de</strong>sign concern.To <strong>de</strong>al with both computational and power managementrequirements, many systems use multicore processors.These processors allow a better power managementthan complex monolithic processors for the same levelof performance. Moreover, many manufacturers (Intel,IBM, Sun, etc.) <strong>de</strong>liver processors providing multithreadingcapabilities, that is, they provi<strong>de</strong> support to run severalthreads simultaneously. Some examples of currentmultithrea<strong>de</strong>d processors are Intel’s Montecito [1] andIBM Power 5 [2]. Also, leading manufacturers of the embed<strong>de</strong>dsector, like ARM, plan to inclu<strong>de</strong> multithreadingtechnology in next-generation processors [3].A power management technique that is being implementedin most current microprocessors is Dynamic VoltageScaling (DVS) [4]. This technique allows the systemto improve its energy consumption by reducing thefrequency when the processor has a low level of activity(e.g., a mobile phone that is not actively used). In a multicoresystem, the DVS regulator can be shared amongseveral cores, also referred to as global, or private to each1 Department of Computer Engineering (DISCA), UniversitatPolitècnica <strong>de</strong> València, e-mails: jomarcab@gap.upv.es,{jsahuqui,spetit,husein,jduato}@disca.upv.es.core. In the former case, all cores are forced to workat the same speed but less regulators are required so itis a cheaper solution. The latter case enables more energysavings since each core frequency can be properlytuned to its applications requirements but it is more expensive[5].Energy consumption in systems with a global DVSregulator can be further improved by properly balancingthe workload [6], [7]. To this end, a partitioner module isin charge of distributing tasks according to a given algorithm(e.g., Worst Fit [8] or First Fit) that selects the targetcore to run the task. Unfortunately, the nature of someworkload mixes prevents the partitioner from achieving agood balancing. To <strong>de</strong>al with this drawback some systemsallow tasks to migrate (move their execution) fromone core to another, which results in energy saving improvements.This work presents a dynamic power-aware partitioner,namely DP, for a multicore multithrea<strong>de</strong>d system that dynamically(at run-time) assigns tasks to cores and allowstask migration to improve energy consumption. Our focusis on tasks presenting real-time constraints, that is,tasks must end their execution before a given <strong>de</strong>adlineor run during several periods before leaving the system.The proposed partitioner readjusts possible dynamic imbalances(due to new arrivals or exits of tasks) by reallocatingtasks among cores. In this way, the workload canbe more fairly balanced, so system frequency -in manycases- can be reduced, thus enabling further energy consumptionimprovements. In addition, the number of migrationshas been limited in or<strong>de</strong>r to reduce overhead.Finally, as the aim of migration is to reduce imbalance,it makes sense to analyze the benefits of applying migrationwhen the workload changes. Three cases havebeen analyzed: both when a task arrives to and leaves thesystem, only when a task arrives to the system, and onlywhen a task leaves the system. Experimental results showthat enabling migration only on arrival in the classicalWF algorithm allows achieving energy improvements ina factor up to 2.18 with respect to the case where no migrationis allowed, while in the proposed DP algorithmthese improvements can be up to 2.74.The remaining of this paper is structured as follows.Section II discusses the related research on energy managementand task migration. Section III <strong>de</strong>scribes themo<strong>de</strong>led system, including the partitioner and the powerawarescheduler. Section IV presents the proposed workloadpartitioning algorithms. Section V analyzes experimentalresults of energy. Finally, Section VI presentssome concluding remarks.<strong>JP2011</strong>-185


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 1. Mo<strong>de</strong>led system.II. RELATED WORKScheduling in multiprocessor systems can be performedin two main ways <strong>de</strong>pending on the task queuemanagement: global scheduling, where a single taskqueue is shared by all the processors, or partitionedscheduling, that uses a private task queue for each processor.The former allows task migrations since all the processorsshare the same task queue. In the latter case, thescheduling in each processor can be performed by applyingwell-established uniprocessor theory algorithms suchas EDF (Earliest Deadline First) or RMS (Rate MonotonicScheduling). An example of global scheduling forsporadic tasks can be found in [9].In the partitioned scheduling case, research can focuseither on the partitioner or the scheduler. Acting inthe partitioner, recent works have addressed the energyawaretask allocation problem [10], [11], [8]. For instance,Wei et al. [10] reduce energy consumption byexploiting parallelism of multimedia tasks on a multicoreplatform combining DVS with switching-off cores. Aydinet al. [11] present a new algorithm that reserves asubset of processors for the execution of tasks with utilizationnot exceeding a threshold. Unlike our work, noneof these techniques use task migration among cores.Some proposals have been <strong>de</strong>aling with task migration.Bran<strong>de</strong>nburg et al. [12] evaluate some schedulingalgorithms (both global and partitioned) in terms ofscalability, although no power consumption were investigated.In [13] Zheng divi<strong>de</strong>s tasks into fixed and migrationtasks, allocating each of the latter to two cores, sothey can migrate from one to another. Unlike our work, inthis paper there is no consi<strong>de</strong>ration about dynamic workloadchanges (tasks arriving to and leaving the system),instead, all tasks are assumed to arrive at the same instant,so migrations can be scheduled off-line. Seo etal. [5] present a dynamic repartitioning algorithm withmigrations to balance the workload and reduce consumption.In [14] Brião et al. analyze how soft tasks migrationaffects NoC-based MPSoCs in terms of <strong>de</strong>adline missesand energy consumption. These two latter works focuson non-threa<strong>de</strong>d architectures.Regarding the scheduler, in [15] El-Haj-Mahmoud etal. virtualize a simultaneous multithrea<strong>de</strong>d (SMT) processorinto multiple single-threa<strong>de</strong>d superscalar processorswith the aim of combining high performance withreal-time formalism. In or<strong>de</strong>r to improve real-time taskspredictability, Cazorla et al. [16] <strong>de</strong>vise an interactiontechnique between the Operating System (OP) and anSMT processor. Notice that these works do not tackleenergy consumption.III. SYSTEM MODELFigure 1 shows a block diagram of the mo<strong>de</strong>led system.When a task reaches the system, a partitioner moduleallocates it into a task queue associated to a core,which contains the tasks that are ready for executionin that core. These task queues are components of thepower-aware scheduler that communicates with a DVSregulator, in charge of adjusting the working frequencyof the cores in or<strong>de</strong>r to satisfy the workload requirements.To focus our research, experiments consi<strong>de</strong>red a two-coreprocessor implementing three hardware threads each.Processor cores implement the coarse-grain multithreadingparadigm that switches the running threadwhen a long latency event occurs (i.e., a main memoryaccess). Thus, the running thread issues instructions toexecute while the other threads access memory, so overlappingtheir execution. In the mo<strong>de</strong>led system, the issueslots are always assigned to the thread executing the taskwith the highest real-time priority. If this thread stalls dueto a long latency memory event, then the issue slots aretemporarily reassigned until the event is resolved.A. Real-Time Task BehaviorThe system workload executes periodic hard real-timetasks. There is no task <strong>de</strong>pen<strong>de</strong>ncy and each task has itsown period of computation. A task can be launched to executeat the beginning of each active period, and it mustend its execution before reaching its <strong>de</strong>adline (hard realtime).The end of the period and the <strong>de</strong>adline of a task areconsi<strong>de</strong>red to be the same for a more tractable schedulingprocess. There are also some periods where tasks do notexecute since they are not active (i.e., inactive periods).In short, a task arrives to the system, executes severaltimes repeatedly, leaves the system, remains out of thesystem for some periods, and then it enters the system<strong>JP2011</strong>-186


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011again. This sequence of consecutive active and inactiveperiods allows to mo<strong>de</strong>l real systems mo<strong>de</strong> changes.Besi<strong>de</strong>s its period and <strong>de</strong>adline, a task is also characterizedby its Worst Case Execution Time (WCET).This parameter is used to obtain the task utilization:U = W CET . Different partitioning algorithms mayP erioduse this value in the process of allocating incoming tasksto a core, guaranteeing schedulability.B. Power-Aware SchedulerOnce a task is allocated to a core, it is inserted intothe task queue of that core, where incoming tasks are or<strong>de</strong>redaccording to the EDF policy [17], which priorizesthe tasks with the closest <strong>de</strong>adlines. Thus, the three taskswith the closest <strong>de</strong>adlines will be always mapped into thethree hardware threads implemented in each core.The scheduler is also in charge of calculating the targetspeed of each core according to the tasks’s requirements.In this sense, in or<strong>de</strong>r to minimize power consumption,each core will choose the minimum frequency that fulfillsthe temporal contraints of its task set. This information issent to the DVS regulator that selects the maximum frequency/voltagelevel among the requested by the cores.The target frequency is recalculated to check if it hasto be updated, but only when the workload changes, thatis, when a task arrives to and/or leaves the system. In theformer case, a higher speed can be required because theworkload increases. In the latter case, it could happen thata lower frequency could satisfy the <strong>de</strong>adline requirementsof the remaining tasks.Different speed values are consi<strong>de</strong>red for the powerawarescheduler, based on the frequency levels of a PentiumM [18] that are shown in Table I. The 5L configurationallows the system to work at any of these five levels,whereas the 3L mo<strong>de</strong> permits running tasks at thehighest, the lowest and the intermediate (300 Mhz) frequency.Futhermore, the overhead of changing the frequency/voltagelevel has been mo<strong>de</strong>led according to thevoltage transition rate in the Pentium M processor, that isapproximately 1mv/1µs [19].IV. PARTITIONING HEURISTICS WITH TASKMIGRATIONThere are several partitioning heuristics that can beused to distribute tasks among cores as they arrive to thesystem. The Worst Fit (WF) partitioning heuristic is consi<strong>de</strong>redone of the best choices in or<strong>de</strong>r to balance theworkload, thus improving energy savings [8]. WF balancesworkload by assigning the incoming task to theleast loa<strong>de</strong>d core. If more than one task arrives to the systemat the same time, it arranges the incoming tasks by<strong>de</strong>creasing utilization or<strong>de</strong>r and assigns them to the coresbeginning with the task with highest utilization. This algorithmwas initially used in partitioned scheduling, thus,TABLE IENERGY (E) USED PER FREQUENCY (F).F[MHz] 500 400 300 200 100E[pJ/cycle] 450 349.2 261.5 186.3 123.8Fig. 2. Task periods and migrations.it does not support task migration among cores by <strong>de</strong>sign.Therefore, once WF has assigned an incoming task to agiven core, the task remains in that core until it leaves thesystem (i.e., it has executed all its active periods).A. Extending Worst Fit to Support Task MigrationFigure 2 shows an example of how task migrationcould improve workload balancing. At the beginning ofthe execution (time t0), task 0 and task 1 are the onlytasks assigned to core 0 and core 1, respectively. Task 0presents an utilization around 25% (i.e., its WCET occupiesa quarter of its period), while the utilization of task1 is around 33%. At point t2, task 2, whose utilizationis around 66%, arrives to the system, and the WF algorithmassign it to core 0 (since it is the least loa<strong>de</strong>d core).Consequently, the system would exhibit a high workloadimbalance since the global utilization of core 0 and core1 would be 91% and 33%, respectively. To solve this imbalance,task 0 can be migrated to core 1, providing abetter balance (66% in core 0 versus 58% in core 1).The system can become unbalanced when the workloadchanges, that is, when a task arrives to or leaves thesystem. Thus, migration policies should apply in thesepoints in or<strong>de</strong>r to be effective. This leads to three variantsof the WF policy: W F in−out , W F in , and W F out .W F in−out allows migration when a task arrives to orleaves the system, W F in only when a new task arrives,and W F out only when a task leaves the system. To avoidperforming too much migrations, which could lead to excessiveoverhead, we limit the number of migrations performedwhen a task arrives to or leaves the system to onlyone.Figure 3 shows the Migration Attempt (MA) algorithm.This routine calculates the imbalance by subtractingthe utilization of the least loa<strong>de</strong>d core from the utilizationof the most loa<strong>de</strong>d one. This result is divi<strong>de</strong>dby two (since there are two cores) to obtain a theoreticalutilization value that represents the amount of work thatshould migrate to achieve a perfect balancing. Then, itsearches the task in the most loa<strong>de</strong>d core whose utilizationis the closest to this one. Notice that it could happenthat by migrating that task the workload balancing wouldnot improve (e.g., consi<strong>de</strong>r a situation where only onetask is assigned to the most loa<strong>de</strong>d core). Therefore, thealgorithm performs the migration only if it improves theworkload balancing.<strong>JP2011</strong>-187


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20111: imbalance ← max core utilization − min core utilization2: target utilization ← imbalance/23: minimum difference ← MAX V ALUE4: for all task in most loa<strong>de</strong>d core do5: if |U task − target utilization| < minimum difference then6: minimum difference ← |U task − target utilization|7: candidate ← task8: end if9: end for10: new max core utilization ← max core utilization − U candidate11: new min core utilization ← min core utilization + U candidate12: new imbalance ← |new max core utilization − new min core utilization|13: if new imbalance < imbalance then14: migrate(candidate)15: end ifFig. 3. Migration Attempt algorithm.B. Dynamic PartitionerThis subsection presents the proposed Dynamic Partitioner(DP). As done by the WF algorithm, DP also arrangesthe tasks arriving to the system by <strong>de</strong>creasing utilizationor<strong>de</strong>r. However, before assigning any incomingtask to a given core, DP checks how the workload balancingwould become if the incoming task was assignedto the first core. Then, it also calculates the effect ofperforming a migration attempt (as shown in Figure 3).These testings are performed for each core in the system.Finally, the core assignment that provi<strong>de</strong>s the best overallbalance is applied. Two versions of DP are consi<strong>de</strong>red:DP in and DP in−out . DP in refers to the <strong>de</strong>scribed DP algorithm,where a migration can be performed only whena task arrives to the system, while DP in−out also performsa migration attempt when a task leaves the system.Figure 4 <strong>de</strong>picts an example where the DP in heuristicimproves the behavior of W F in . The latter allocates theincoming task to core 0, and then performs a migrationattempt, but in this case, there is not any possible migra-Fig. 4. W F in vs DP in .tion enabling a better workload balancing. Thus, the finalimbalance becomes 20% (i.e., 90% − 70%). In contrast,when DP in is applied, it also checks the result of allocatingthe new task to core 1 (DP in B arrow) and thenconsi<strong>de</strong>ring one migration. In this case, the migrationenables a better balance since both cores remain equallyloa<strong>de</strong>d with 80% of utilization, which will be the distributionselected by DP in .To sum up, the main difference between W F in andDP in is that the former selects only one core and performsa migration attempt, whereas the proposed heuristicchecks different cores, and choses the best option interms of workload balance.V. EXPERIMENTAL RESULTSExperimental evaluation has been conducted by extendingthe Multi2Sim simulation framework [20], tomo<strong>de</strong>l the system <strong>de</strong>scribed in Section III. As stated before,experiments consi<strong>de</strong>red a two-core processor implementingthree hardware threads each. Internal corefeatures have been mo<strong>de</strong>led like an ARM11 MPCorebased processor, but modified to work as a coarse-grainmultithrea<strong>de</strong>d processor with in-or<strong>de</strong>r execution, twoinstructionissue width, and a 100-cycle memory latency.Benchmarks from the WCET analysis project [21]were used to prepare real-time workload mixes. Thesemixes have been <strong>de</strong>signed taking into account aspectssuch as task utilization, number of repetitions (task periodicity),and the sequence of active and inactive periods.The global system utilization varies in a single executionfrom 35% to 95%, in or<strong>de</strong>r to test the algorithms behavioracross a wi<strong>de</strong> range of situations. In addition, all resultsare presented and analyzed for a system implementingthree and five voltage levels.A. Impact of Applying Migrations at Different Points ofTimeThis section analyzes the best points of time to carryout migrations focusing on the standard WF algorithm(no migration is supported) and its variants supportingmigration (W F in−out , W F in , W F out ). Figure 5 showsthe relative energy consumption compared to the energyconsumed by the system working always at the<strong>JP2011</strong>-188


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011(a) 5L(a) 5L(b) 3LFig. 5. Worst Fit variants comparison for different DVS levels.(b) 3LFig. 6. WF versus DP for different DVS levels.maximum speed for diverse benchmark mixes and DVSconfigurations.As observed, migration can provi<strong>de</strong> huge energy savingswith respect to no migration (WF) regardless whenmigration is applied. For instance, in the 5-level systemwith task migration mixes 2 and 3 improve their energyconsumption in a factor up to 1.33 and 2.18, respectively,when compared with their execution in the same systemwithout migrations. This trend is also followed, althoughto a lesser extent, in the 3-level system.Comparing the three WF versions with task migration,it can be observed that if migration can apply only eachtime a new task arrives instead of when a task terminates,then much higher energy savings can be achieved. Themain reason is that the inter-arrival time standard <strong>de</strong>viationis higher than that of the inter-leaving time, sinceseveral tasks reach the system at the same time. Interarrivalstandard <strong>de</strong>viation values of the mixes are 24.48,43.98, and 14.65 Mcycles for mix 1, mix 2, and mix 3,respectively. On the other hand, the inter-leaving timeis, on average, 22.50, 36.40, and 12.32 Mcycles. Finally,W F in−out offers scarce benefits over W F in since it onlyadds a low number of extra migrations.Notice that if the system implements more DVS frequencylevels (5 levels in the figure), then more energysavings can be obtained since the system can select a frequencycloser to the optimal estimated by the scheduler.However, <strong>de</strong>spite this fact, an interesting observation isthat energy benefits due to migration in the 3-level systemcan reach or even surpass the benefits of having the 5-level system without migrations. For example, the energyconsumption of W F out for mix 3 in the 3-level system isaround 11% of the consumption of the baseline, whereasthe same value of WF in the 5-level system is 17%.B. Comparing DP versus WF variantsThis section analyzes the energy improvements oftwo variants of the proposed DP algorithm (DP in andDP in−out ) over the WF algorithm. For comparison pur-poses the best variant of the WF (W F in−out ) with migrationhas been also inclu<strong>de</strong>d in the plots. Figure 6 showsthe results.Results show that, regardless the mix and systemlevel,both variants of DP always consume less powerthan W F in−out . DP in−out achieves, for mixes 2 and3, energy improvements over WF in a factor up to 2.74and 1.56, respectively. Moreover, for mix 1, whereW F in−out is only able to find scarce benefits over WF,the proposed DP improves the energy consumption ofWF around 1.51.For a better un<strong>de</strong>rstanding of the algorithms behavior,we <strong>de</strong>fine the migration rate metric as the number of migrationsperformed by the algorithm divi<strong>de</strong>d by the numberof times that the migration algorithm is executed. Forinstance, regarding the in variant of the WF and DP algorithms,the migration rates of W F in are 62%, 54%,and 45% for mix 1, mix 2, and mix 3, respectively; whilefor DP in the corresponding values are 76%, 68%, and73%. This means that the proposal performs migrationsin some cases where the WF is not able to find any candidateto migrate at all.VI. CONCLUSIONSWorkload balancing has been already proved to be anefficient power technique in multicore systems. Unfortunately,unexpected workload imbalances can rise at runtimeprovi<strong>de</strong>d that the workload is dynamically changingsince new tasks arrive to or leave the system. To palliatethis situation this paper has analyzed the impact on energyconsumption of task migration combined with workloadbalancing.To prevent excessive overhead, task migration has beenstrategically applied at three different execution timeswhere the workload changes (at task arrival, at task termination,and in both cases). Results with respect tothe WF algorithm showed that applying migration atarrival time can save results in a factor up to around2.18. This results can be slightly improved if migration<strong>JP2011</strong>-189


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011is also applied when tasks terminate.Due to the potential of migration, this paper has proposedthe DP algorithm, which achieves much better energyimprovements than classical partitioning algorithmslike WF. The proposal improves energy consumption ina factor of 1.51 in some workloads where WF with migrationsprovi<strong>de</strong>s scarce benefits, and energy can be improvedin a factor up to 2.74 in the analyzed workloads.Experimental results also showed that migration canprovi<strong>de</strong> energy consumption improvements with respectto a more complex system with a higher number of frequency/voltagelevels. A final remark is that achievinga better workload balancing by allowing task migrationsnot only results in energy savings, but also allows a wi<strong>de</strong>rset of tasks to be scheduled.ACKNOWLEDGMENTSThis work was supported by Spanish CICYT un<strong>de</strong>rGrant TIN2009-14475-C04-01, and by Consoli<strong>de</strong>r-Ingenio un<strong>de</strong>r Grant CSD2006-00046.REFERENCES[1] C. McNairy and R. Bhatia, “Montecito: A Dual-Core, Dual-Thread Itanium Processor,” IEEE Micro, vol. 25, no. 2, pp. 10–20,2005.[2] R. Kalla, B. Sinharoy, and J.M. Tendler, “IBM Power5 Chip: ADual-Core Multithrea<strong>de</strong>d Processor,” IEEE Micro, vol. 24, no. 2,pp. 40–47, 2004.[3] Agam Shah, Arm plans to add multithreading tochip <strong>de</strong>sign, ITworld, 2010, [Online]. Available:http://www.itworld.com/hardware/122383/arm-plans-addmultithreading-chip-<strong>de</strong>sign.[4] C. Hung, J. Chen, and T. Kuo, “Energy-Efficient Real-Time TaskScheduling for a DVS System with a Non-DVS Processing Element,”in Proceedings of the 27th Real-Time Systems Symposium,Rio <strong>de</strong> Janeiro, Brazil, 5-8 December 2006, pp. 303–312, IEEEComputer Society.[5] E. Seo, J. Jeong, S. Park, and J. Lee, “Energy Efficient Schedulingof Real-Time Tasks on Multicore Processors,” IEEE Transactionson Parallel and Distributed Systems, vol. 19, no. 11, pp. 1540–1552, 2008.[6] J. Donald and M. Martonosi, “Techniques for Multicore ThermalManagement: Classification and New Exploration,” in Proceedingsof the 33rd Annual International Symposium on ComputerArchitecture, Boston, MA, USA, 17-21 June 2006, pp. 78–88,IEEE Computer Society.[7] J.L. March, J. Sahuquillo, H. Hassan, S. Petit, and J. Duato, “ANew Energy-Aware Dynamic Task Set Partitioning Algorithm forSoft and Hard Embed<strong>de</strong>d Real-Time Systems,” To be publishedon The Computer Journal, 2011.[8] T. A. AlEnawy and H. Aydin, “Energy-Aware Task Allocationfor Rate Monotonic Scheduling,” in Proceedings of the 11th RealTime on Embed<strong>de</strong>d Technology and Applications Symposium, SanFrancisco, CA, USA, 7-10 March 2005, pp. 213–223, IEEE ComputerSociety.[9] S. Kato and N. Yamasaki, “Global EDF-based Scheduling withEfficient Priority Promotion,” in Proceedings of the 14th InternationalConference on Embed<strong>de</strong>d and Real-Time Computing Systemsand Applications, Kaohisung, Taiwan, 25-27 August 2008,pp. 197–206, IEEE Computer Society.[10] Y. Wei, C. Yang, T. Kuo, and S. Hung, “Energy-Efficient Real-Time Scheduling of Multimedia Tasks on Multi-Core Processors,”in Proceedings of the 25th Symposium on Applied Computing,Sierre, Switzerland, 22-26 March 2010, pp. 258–262, ACM.[11] H. Aydin and Q. Yang, “Energy-Aware Partitioning for MultiprocessorReal-Time Systems,” in Proceedings of the 17th InternationalParallel and Distributed Processing Symposium, Workshopon Parallel and Distributed Real-Time Systems, Nice, France, 22-26 April 2003, p. 113, IEEE Computer Society.[12] B. B. Bran<strong>de</strong>nburg, J. M. Calandrino, and J. H. An<strong>de</strong>rson, “Onthe Scalability of Real-Time Scheduling Algorithms on MulticorePlatforms: A Case Study,” in Proceedings of the 29th Real-TimeSystems Symposium, Barcelona, Spain, 30 November - 3 December2008, pp. 157–169, IEEE Computer Society.[13] Liu Zheng, “A Task Migration Constrained Energy-EfficientScheduling Algorithm for Multiprocessor Real-time Systems,” inProceedings of the International Conference on Wireless Communications,Networking and Mobile Computing, Shanghai, China,21-25 September 2007, pp. 3055–3058, IEEE Computer Society.[14] E. Brião, D. Barcelos, F. Wronski, and F. R. Wagner, “Impact ofTask Migration in NoC-based MPSoCs for Soft Real-time Applications,”in Proceedings of the International Conference on VLSI,Atlanta, GA, USA, 15-17 October 2007, pp. 296–299, IEEE ComputerSociety.[15] A. El-Haj-Mahmoud, A.AL-Zawawi, A. Anantaraman, andE. Rotenberg, “Virtual Multiprocessor: An Analyzable, High-Performance Architecture for Real-Time Computing,” in Proceedingsof the International Conference on Compilers, Architecturesand Synthesis for Embed<strong>de</strong>d Systems, San Francisco, CA,USA, 24-27 September 2005, pp. 213–224, ACM Press.[16] F. Cazorla, P. Knijnenburg, R. Sakellariou, E. Fernán<strong>de</strong>z,A. Ramirez, and M. Valero, “Predictable Performance in SMTProcessors: Synergy between the OS and SMTs,” IEEE Transactionson Computers, vol. 55, no. 7, pp. 785–799, 2006.[17] T.P. Baker, “An Analysis of EDF schedulability on a multiprocessor,”IEEE Transactions on Parallel and Distributed Systems, vol.16, no. 8, pp. 760–768, 2005.[18] R. Watanabe, M. Kondo, M. Imai, H. Nakamura, and T. Nanya,“Task Scheduling un<strong>de</strong>r Performance Constraints for Reducingthe Energy Consumption of the GALS Multi-Processor SoC,” inProceedings of the Design Automation and Test in Europe, Nice,France, 16-20 April 2007, pp. 797–802, ACM.[19] Q. Wu, M. Martonosi, D. W. Clark, V. J. Reddi, D. Connors,Y. Wu, J. Lee, and D. Brooks, “A Dynamic Compilation Frameworkfor Controlling Microprocessor Energy and Performance,”in Proceedings of the 38th Annual IEEE/ACM International Symposiumon Microarchitecture, Barcelona, Spain, 12-16 November2005, pp. 271–282, IEEE Computer Society.[20] R. Ubal, J. Sahuquillo, S. Petit, and P. López, “Multi2Sim: ASimulation Framework to Evaluate Multicore-Multithrea<strong>de</strong>d Processors,”in Proceedings of the 19th International Symposium onComputer Architecture and High Performance Computing, Gramado,RS, Brazil, 24-27 October 2007, pp. 62–68, IEEE ComputerSociety.[21] Malardalen Real-Time Research Center, Vasteras, Swe<strong>de</strong>n,WCET Analysis Project. WCET Benchmark Programs, 2006, [Online].Available: http://www.mrtc.mdh.se/projects/wcet/.<strong>JP2011</strong>-190


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Unified Locality-sensitive Signatures forTransactional MemoryR. Quislant, E. Gutierrez, O. Plata and E.L. Zapata 1Abstract— Transactional Memory (TM) systemsmust record the memory locations read and writtenby concurrent transactions in or<strong>de</strong>r to <strong>de</strong>tect conflicts.Some TM implementations use signatures forthis purpose, which summarize read and write sets inboun<strong>de</strong>d hardware at the cost of false positives due toaddress aliasing. Signatures are usually implementedas two separate (one for reads and another for writes)per-thread Bloom filters.It is known that the false positive rate increaseswith the size of the transactions, and this have astrong negative impact in the performance of theirconcurrent execution. In a previous work, authors<strong>de</strong>veloped a technique with the aim of reducing theprobability of false positives by exploiting spatial locality.In this paper we propose a new technique basedon joining the two Bloom filters into a single one andpartially sharing the hash function mappings for readsand writes. This unification technique is combinedwith the locality-sensitive one and it is proved thatthe false positive rate is further reduced.This paper proves that unified locality-sensitive signaturesimprove the execution performance of largeconcurrent transactions in most tested co<strong>de</strong>s comparedto separate signatures, without increasing significantlythe required hardware area and with a smallincrement of power consumption.Keywords— Hardware transactional memory, signatures,Bloom filters, memory localityI. IntroductionTRANSACTIONAL Memory (TM) [1], [2]emerges as an alternative to the conventionalmultithrea<strong>de</strong>d programming to ease the writing ofconcurrent programs. TM introduces the concept oftransaction that allows semantics to be separatedfrom implementation. A transaction is a block ofcomputations that appears to be executed withatomicity and isolation. Thus, transactions replacea pessimistic lock-based mo<strong>de</strong>l by an optimistic oneand solve the abstraction and composition problems.TM systems execute transactions in parallel, committingnon-conflicting ones. A conflict occurs whena memory location is accessed by several concurrenttransactions and at least one access is a write. Therefore,TM systems must record the memory locationsread and written by concurrent transactions in or<strong>de</strong>rto <strong>de</strong>tect conflicts. Some TM implementations usesignatures for this purpose, which summarize readand write sets in boun<strong>de</strong>d hardware at the cost offalse positives due to address aliasing (different memorylocations have the same representation in thesignatures). Signatures are usually implemented astwo separate (one for reads and another for writes)per-thread Bloom filters [3]. Examples of systemsthat use signatures are BulkSC [4], LogTM-SE [5],1 Dept. of Computer Architecture, University of Málaga, e-mail: {quislant, eladio, oplata, zapata}@uma.esSigTM [6], FlexTM [7], and STMlite [8].It is known that the false positive rate increaseswith the size of the transactions, and this have astrong negative impact in the performance of theirconcurrent execution. In a previous work [9], authors<strong>de</strong>veloped a technique with the aim of reducing theprobability of false positives. This technique <strong>de</strong>finesnew hash function mappings so that nearby locatedaddresses share some bits in the Bloom filters, that is,it exploits spatial locality. In this paper we propose anew technique based on joining the two Bloom filtersinto a single one and partially sharing the hash functionmappings for reads and writes without addingsignificant hardware complexity. The rationale behindthis technique is the uneven cardinality thattransactional read/write sets exhibit, where read setsare usually larger than write sets. As a result, thesignature for reads populates much more than theone for writes and, consequently, the false positiverate for the read signature may be high while, at thesame time, the write filter has still a low occupation,with negligible false positive rate. When sharing thefilter, both the read and the write false positive ratescan be equalized. This unification technique is combinedwith the locality-sensitive one and it is provedthat the false positive rate is further reduced.The proposed unified locality-sensitive signatureshave been implemented in the Wisconsin GEMSLogTM-SE simulator [10], in or<strong>de</strong>r to evaluate theirperformance, and in CACTI [11] in or<strong>de</strong>r to evaluatethe hardware area and energy requirements. Experimentalresults show that the proposed approach isable to reduce the false positive rate and improve theexecution performance in most of the tested co<strong>de</strong>s,without increasing the required hardware area in anoticeable amount and slightly increasing the powerconsumption.The rest of the paper is organized as follows. Innext section we present a background on signatures,<strong>de</strong>scribing how they are usually <strong>de</strong>signed and implemented.A brief review of the related work is discussed.In Section III we introduce our proposedunified signature <strong>de</strong>sign, discussing its basics, howthey are implemented, and a comparison with theseparate signature <strong>de</strong>sign. Section IV presents areaand energy requirements. Section V shows an analysisof our proposed signatures and <strong>de</strong>termines falsepositive rates in different contexts. Next, Section VIpresents the implementation of unified signatures onthe GEMS simulator, and discusses how our novelsignature <strong>de</strong>sign may improve the execution performancein several cases.clu<strong>de</strong>s the paper.Finally, Section VII con-<strong>JP2011</strong>-191


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Read SetSignatureAddress...h0 h1 hk-1Address...h0 h1 hk-1Unified SignatureRS Address... h0 hs-1WS Address... hs h's hk-1 h'k-10 1 1 0 0 1 1 0 ... 0 1 0 10 2 m /k...k single-ported SRAMs of 2 m /k bits0 1 0 1 ... 0 1 0 1 0 1 1 0 ... 0 1 0 10 2 m+1 /kWrite SetSignatureAddress...h'0 h'1 h'k-1Address...h'0 h'1 h'k-1RS Addressh0...hs-1hsWS Addressh's...hk-1h'k-10 1 1 0 0 1 1 0 ... 0 1 0 10 2 m /k...k single-ported SRAMs of 2 m /k bits...s single-portedSRAMs of 2 m+1 /k bits...k-s double-portedSRAMs of 2 m+1 /k bitsFig. 1. Parallel Separate Signatures. Design (left) and implementation(right)Fig. 2. Parallel Unified Signatures. Design (up) and implementation(down).II. Background and Related WorkIn the context of TM, each concurrent thread usesits signatures to record all the memory locations issuedwhen executing insi<strong>de</strong> a transaction. These locationsare sorted out into a read set (RS) and awrite set (WS). Thus, each thread needs a pair ofprivate signatures. As they are used for conflict <strong>de</strong>tectionamongst concurrent transactions, signaturesdo not tolerate false negatives (un<strong>de</strong>tected true conflicts)but may assume a limited amount of false positives(false conflicts). On the other hand, the RS andWS sizes are unknown in advance, therefore, signaturesshould not limit the number of addresses to betracked. In addition, test and insertion of an addressshould be fast operations.Fulfilling the requirements above, Ceze et al. [12]proposed a signature implementation with perthreadBloom filters. These filters were <strong>de</strong>vised totest whether an element is a member of a set in atime and space-efficient way. The Bloom filter comprisesa bit array and k different hash functions thatmap elements into k randomly distributed bits of thearray. At first, all the array bits are set to 0. Insertingan element into the Bloom filter consists insetting to 1 the k bits given by the hash functions.Test for membership consists in checking that thosek bits are asserted.Bloom filters are also known as true or regularBloom filters. Sanchez et al. [13] proposed theparallel Bloom filter as an alternative hardwareefficientimplementation of regular Bloom filters.Whereas the regular filter is implemented as a k-ported SRAM, the parallel one consists of k 1-portedSRAMs, yielding the same or better false positivesrate. The same work conclu<strong>de</strong>s that Bloom filtersshould inclu<strong>de</strong> H3 class hash functions [14], insteadof bit-selection hash functions [15], since they arecloser to random distribution. However, H3 hashingsare hardware expensive and need an XOR treeper hash bit.An alternative hardware-efficient implementationof hash functions, Page-Block-XOR hashing (PBX),has been proposed in [16]. They use the concept ofentropy to find input bits to the hash functions withhigh randomness, allowing to reduce the hardwarecomplexity of those functions. Notary also proposesa technique to reduce the number of asserted bitsin the signature, based on segregating addresses intoprivate and shared sets. Then, only the shared addressesare recor<strong>de</strong>d in the signature. This solutionrequires support at the compiler, runtime/libraryand operating system levels. In addition, the programmermust <strong>de</strong>fine which objects are private orshared.Recently, Choi et al. [17] proposed adaptive grainsignatures, that keep the history of transactionaborts and dynamically changes the input bit rangeto the hash functions based on the abort history. Theaim of this <strong>de</strong>sign is to reduce the number of falsepositives that harm the execution performance.III. Unified Signature DesignParallel Bloom filters have been proved to yieldsimilar or better performance than regular ones andthey require less hardware [13] [9]. Consequently,regular implementation will not be taken into accountin this paper.Parallel Bloom filters comprise k arrays of 2 m /kbits, each of which is only in<strong>de</strong>xed by its own hashfunction. Figure 1 shows the <strong>de</strong>sign and implementationof parallel Bloom signatures. They consist oftwo separate parallel filters to record the read setand write set addresses. Parallel filters can be implementedas single-ported SRAMs, thus saving inhardware area with respect to regular filters whichare implemented as multi-ported SRAMs.The unified counterpart for the parallel separatesignature is <strong>de</strong>picted in Figure 2. In this case, thebit array is also partitioned into k smaller arrays but(2 m+1 /k)-bit length. Each array is in<strong>de</strong>xed by twohash functions, one for the read set, h [0,k−1] , and theother one for the write set, h ′ [0,k−1] . Consequently,parallel unified filters need 2-ported SRAMs insteadof single-ported ones taking about twice the area ofparallel separate filters. To alleviate this problem,s SRAMs can be ma<strong>de</strong> single-ported. This way, anaddress inserted as a read address is also inserted asa write and vice-versa.The motivation behind unified signatures comefrom Table I which shows the percentage of addressesthat have been both read and written insi<strong>de</strong> transactionsfor each benchmark (a <strong>de</strong>scription of the simulationenvironment can be found in Section VI-A)with respect to the total number of addresses (with-<strong>JP2011</strong>-192


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLE IPercentage of addresses that have been both readand written insi<strong>de</strong> transactions.Bench % Bench %Bayes 51.0 <strong>La</strong>byrinth 15.3Genome 16.0 SSCA2 25.0Intru<strong>de</strong>r 7.1 Vacation 8.4Kmeans 48.6 Yada 45.0TABLE IIArea (mm 2 ) and dynamic energy per access (nJ)requirements of parallel separate and parallelunified signatures. 32nm technology. k = 4.AreaEnergyFilter size (2 m ) 4Kbit 16Kbit 4Kbit 16KbitSeparate 0.0084 0.0292 0.0020 0.0047Unified s = 0 0.0191 0.0640 0.0030 0.0081Unified s = 3 0.0098 0.0331 0.0026 0.0068out repetition). About 50% of locations are bothread and written for Bayes, Kmeans and Yada. Overall,about 30% of total locations addressed by eachbenchmark has been both read and written.In or<strong>de</strong>r to work out the value of s a tra<strong>de</strong> off betweenhardware requirements and signature performancehas to be carried out. On the one hand, if sis set to k, the unified signature implements k singleportedSRAMs. Thus, such a signature requires thesame hardware than the parallel separate signaturebut it is unable to discriminate between read andwritten addresses and it could <strong>de</strong>gra<strong>de</strong> the performance.On the other hand, if s is set to 0, the unifiedsignature implements k double-ported SRAMsincreasing the hardware requirements but maximizingthe probabilities of discrimination between readand written addresses. Section VI-B explores everypossible scenario.Finally, hash functions are implemented as H3XOR functions [14] that only comprise a set of XORgate trees per function. XOR gate trees do not requiresignificant area and, moreover, they can be replacedby a single line of XOR gates by using PBXhashing [16].IV. Hardware RequirementsTable II compares the area required by unified andseparate signatures for several filter sizes. “Filtersize” row is the size of one set filter, i.e. 4Kbit meanstwo filters of 4Kbit (for RS and WS) for separate signaturesand one filter of 8Kbit for unified ones. Weused CACTI 6.5 [18] to mo<strong>de</strong>l the SRAMs using the32nm technology no<strong>de</strong>. Parallel separate signaturescomprise eight single-ported SRAMs (4 for the RSand 4 for the WS) as k = 4, while parallel unifieds = 0 signatures have four double-ported SRAMs.Separate read/write ports are used. Parallel unifieds = 3 signatures have three single-ported SRAMsand only one double-ported SRAM. Ports are dualen<strong>de</strong>dwhich means that two lines are required perbitline.Table II shows that parallel separate signaturesyield the best area and energy numbers. Regardingthe parallel unified s = 0 signature, it is about twicelarger than the parallel separate signature due to itsdouble-ported SRAMs. The parallel unified s = 3configuration, is the closest to the parallel separateone in terms of area. It is only a 13% larger becauseof the double-ported SRAM. However, parallelunified s = 3 signatures outperforms parallel separateones as seen in Section VI-C. Regarding energy,Table II shows a 30% increment in dynamic energyconsumption for parallel unified s = 3 signatures.Concerning the hashing logic area, Sanchez etal. [13] worked out one-fifth of the SRAM area for 4XOR hash functions. This can be halved using PBXhashing [16] without impact in the performance.V. False Positive AnalysisLet A be a sequence of addresses, to be inserted ina single Bloom filter of 2 m bits with k hash functions,whose cardinality is n = Card(A). The false positiveprobability is commonly calculated [13] [9] as:(p FP (m, k, n) = 1 − ( ) )1 − 1 nk k2 . (1)mEq. (1) can be adapted to the locality-sensitivesignature scheme of [9] by consi<strong>de</strong>ring two supplementaryparameters: f which is the probability of anaddress to be local, that is, near to another one in thesequence, and b which measures the average numberof bits asserted by a local reference with respect to itsclosest neighbor in the sequence. The value of f will<strong>de</strong>pend on the spatial locality of the program. Thevalue of b can be estimated as b = 1 2 +2· 14 +3· 18 +4· 18for the locality-sensitive signatures <strong>de</strong>fined in [9] withk = 4 hash functions. For such signatures the falsepositive probability is given now by:(p FP LOC(m, k, n, f) = 1 − ( ) )1 − 1 n(1−f)k+nfb k2 .m(2)First, consi<strong>de</strong>r separate filters, where the read andwrite sets are stored separately, in or<strong>de</strong>r to comparetheir false positive rates to those of the unifiedfilter. Let us <strong>de</strong>fine p R = Card(R−R∩W ) andCard(W −R∩W )Card(R∪W )Card(R∪W )p W = as the probability of an addressof the sequence being only read or written, respectively,as a function of the cardinality of the read (R)and write (W) sets. Consequently, n = Card(R∪W ).Also an address in the sequence can be both readand written with probability p RW = Card(R∩W )Card(R∪W ) .Therefore, the false positive probability in each filter,assuming locality-sensitive signatures, can be expressedas:p readFP LOC=p writeFP LOC=(1 − ( ) )1 − 1 n(pR+p RW )¯kk2 ,m(1 − ( ) ) (3)1 − 1 n(pW +p RW )¯kk2 , mwhere ¯k = (1 − f)k + fb ≤ k is the average numberof hash insertions in the locality-sensitive scheme.The effective false positive rate will finally <strong>de</strong>pendon how many checks take place on each separate filter.This way, a mathematical expectation of the<strong>JP2011</strong>-193


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLE IIISignature scheme, separate (sep) or unified (uni), with the lowest false positive rates according to Eqs. (4)and (5) for several values of the given parameters (Bloom filters with m = 10 and k = 4).❍ f ❍n ❍0.20.8p R = 0.15 p R = 0.25 p R = 0.5p RW = 0.2 p RW = 0.5 p RW = 0.2 p RW = 0.5 p RW = 0.2 p RW = 0.5c R0.2 0.5 0.8 0.2 0.5 0.8 0.2 0.5 0.8 0.2 0.5 0.8 0.2 0.5 0.8 0.2 0.5 0.8128 uni uni sep uni uni sep uni uni sep uni uni uni sep uni uni sep uni uni256 uni uni sep uni uni sep uni uni sep uni uni uni sep uni uni sep uni uni512 uni uni sep uni uni sep uni uni sep uni uni uni sep uni uni sep uni uni768 uni sep sep uni sep sep uni sep sep uni uni uni sep sep uni sep sep uni1024 uni sep sep uni sep sep uni sep sep uni uni uni sep sep uni sep sep uni128 uni uni sep uni uni sep uni uni sep uni uni uni sep uni uni sep uni uni256 uni uni sep uni uni sep uni uni sep uni uni uni sep uni uni sep uni uni512 uni uni sep uni uni sep uni uni sep uni uni uni sep uni uni sep uni uni768 uni uni sep uni uni sep uni uni sep uni uni uni sep uni uni sep uni uni1024 uni uni sep uni sep sep uni uni sep uni uni uni sep uni uni sep sep unifalse positive rate for the separated locality-sensitivesignatures can be expressed as:E[p SEPARATEFP LOC(m, k, n, f)] = c R p readFP LOC+ c W p writeFP LOC.(4)Here c R and c W <strong>de</strong>note the probability of each filterbeing checked during the sequence of references.This checking pattern is directly linked to the way inwhich the threads inspect the potential data <strong>de</strong>pen<strong>de</strong>ncies.It remains unknown until run-time, beingvery <strong>de</strong>pen<strong>de</strong>nt on the parallelization strategy andthe input data. Other important issues having influenceon the checking pattern are the coherence protocoland the abort/resume policy of transactions.Regarding unified filters, Eq. (2) is still valid aslong as the k hashing functions used by reads andwrites are disjoint. To make a fair comparison, thesize of the unified locality-sensitive filter must be thesum of the sizes of the separate filters. Thus, the falsepositive probability for this unified locality-sensitivefilter is given byp UNIFIEDFP LOC(m, k, n, f) = p FP LOC (m+1, k, n(1+p RW ), f).(5)In Table III several scenarios are shown for differentvalues of the parameters <strong>de</strong>fined above. Eqs. (4)and (5) have been evaluated with high and low valuesfor the given parameters: locality (f), only readaddresses (p R ), read and written addresses (p RW ),and number of checks in the read filter (c R ). Notethat p R + p RW + p W = 1 and c R +c W = 1. <strong>La</strong>bels inthe table point out the scheme (separate or unified)with the lowest false positive rate according to equations.In the 66% of the explored scenarios the unifiedscheme beats the separate one. Nevertheless, thescenario which is closer to real workloads is c R = 0.5,i.e. read and write filters are evenly checked, becausethe TM system assures strong atomicity [1] and datarequested to main memory (out of the bounds of TM)must be checked in both filters. Notice that, in thiscase, the unified scheme yields better false positiverates until the filter gets filled in about 2 3of its totalcapacity. With high locality such a limit shifts to 3 4or even disappears.A. MethodologyVI. EvaluationTo evaluate the performance of our unifiedlocality-sensitive signatures we used Simics [19] fullsystem execution-driven simulator along with theTM module GEMS [10] from the Wisconsin MultifacetProject. Simics simulates the SPARC architectureand it is able to run an unmodified copy of aSolaris operating system. Solaris 10 was installed onthe simulated machine and all workloads run on topof it. GEMS’s Ruby module implements the LogTM-SE TM [5] and also inclu<strong>de</strong>s a <strong>de</strong>tailed timing mo<strong>de</strong>lfor the memory system. Ruby was modified to inclu<strong>de</strong>the proposed unified signature <strong>de</strong>sign <strong>de</strong>scribedin Section III.The base CMP system consists of 16 in-or<strong>de</strong>r,single-issue cores with a 32KB split, 4-way associative,64B block private L1 cache each. L2 cache isunified, 8MB, 16-bank, 8-way associative, and 64Bblock size. A packet-switched interconnect with 64Blinks connects the cores and cache banks. Cache coherenceimplements the MESI protocol and maintainsan on-chip directory which holds a bit vectorof sharers. Main memory is 4GB.Simulation experiments use perfect signatures (nofalse positives, hardware unimplementable) as thereference. Filter size ranges from 64 bits, whichmatches the word length in SPARC architecture, to8K bits length, which matches the performance ofperfect signatures for the simulated benchmarks. Allfilters use 4 hash functions of the H3 family [14].Same H3 matrices of Ruby were used.The benchmarks belong to the Stanford’s STAMPsuite [20] which is <strong>de</strong>signed for TM research and inclu<strong>de</strong>sa wi<strong>de</strong> range of applications with emphasison large read and write sets. STAMP workloadshave been adapted to GEMS by applying Luke Yen’spatches from the University of Wisconsin, Madison.Table IV summarizes the input parameters and maintransactional characteristics of the benchmarks.B. Unified Signature ResultsUnified signature motivation and <strong>de</strong>sign are <strong>de</strong>scribedin Section III. Table III shows that the percentageof addresses both read and written insi<strong>de</strong><strong>JP2011</strong>-194


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLE IVWorkloads: Input parameters and TM characteristicsBench Input #xactTime avg avg max maxin xact |RS| |W S| |RS| |W S|Bayes -v32 -r1024 -n2 -p20 -s0 -i2 -e2 523 94% 76.9 40.9 2067 1613Genome -g512 -s64 -n8192 30304 86% 12.1 4.2 400 156Intru<strong>de</strong>r -a10 -l128 -n128 -s1 12123 96% 19.1 2.5 267 20Kmeans -m40 -n40 -t0.05 -i rand-n1024-d1024-c16 1380 6% 99.7 48.5 134 65<strong>La</strong>byrinth -i rand-x32-y32-z3-n64 158 100% 76.5 62.9 278 257SSCA2 -s13 -i1.0 -u1.0 -l3 -p3 47295 19% 2.9 1.9 3 2Vacation -n4 -q60 -u90 -r16384 -t4096 24722 97% 19.7 3.6 90 30Yada -a20 -i 633.2 5384 100% 62.7 38.4 776 510Execution time (normalized to Perfect)706050403020100Execution time (normalized to Perfect)6543210Bayes64 128 256 512 1K 2K 4K 8KSignature size (bits)<strong>La</strong>byrinth256 512 1K 2K 4K 8KSignature size (bits)Execution time (normalized to Perfect)1.31.251.21.151.11.0510.950.9Execution time (normalized to Perfect)43.532.521.510.50Genome64 128 256 512 1K 2K 4K 8KSignature size (bits)SSCA264 128 256 512 1K 2K 4K 8KSignature size (bits)Execution time (normalized to Perfect)20151050Execution time (normalized to Perfect)543210Intru<strong>de</strong>r64 128 256 512 1K 2K 4K 8KSignature size (bits)Vacation64 128 256 512 1K 2K 4K 8KSignature size (bits)Execution time (normalized to Perfect)8642Execution time (normalized to Perfect)1.31.251.21.151.11.0510.950.9Kmeans64 128 256 512 1K 2K 4K 8KSignature size (bits)Yada064 128256512 1K 2K 4K 8KSignature size (bits)SeparateUnified s=0Unified s=1Unified s=2Unified s=3Unified s=4Fig. 3. Execution time normalized to perfect signature comparing separate to unified signatures. Parameter s varies from 0(2-ported SRAMS) to 4 (1-ported).transactions is substantial, so we conducted the experimentsto find out the number of hash functionsthat can be shared by read and write filters withoutlosing performance. For that purpose, sharedfunctions range from s = 0, all SRAMs are doubleported,to s = 4, all SRAMs are single-ported whichmeans that every insertion into the read set is alsoan insertion into the write set and vice-versa.Figure 3 shows the execution time of unified signatures.The more read set and write set hash functionsare shared (s > 0) the better results are obtained forall the benchmarks. In fact, the best results are obtainedfor s = 4 in every benchmark except Bayesand Genome, which execution is slowed down about1.25× with respect to separate filters for 8Kbit signatures.Therefore, unified s = 3 signatures should beused instead of s = 4 ones, as these benchmarks arenot pretty sensitive to read and write discriminationbut other might be.C. Unified Locality-Sensitive Signature ResultsLocality-sensitive hashing [9] takes advantage oflocality of reference to store an address stream moreconcisely in a Bloom filter. Locality-sensitive hashfunctions store nearby locations sharing some bits ofthe bit array, thus lowering the occupancy of the filter.For contiguous addresses, the number of hashingoutputs with different values is 1. Addresses withdistance 2 are different in no more than 2 hashingoutputs and, addresses with distance greater than2 k−1 − 1 may have no hashing outputs in common.Figure 4 shows the results of unified s = 3 localitysensitivesignatures. Two possibilities are shown:• L1: This scheme makes that the hash functionsh 3 and h ′ 3 assert less bits in their filter. Thisreduces the false positive rate because of lowoccupancy, but the filter may fail to discriminatereads/writes from nearby located reads/writes.• L2: This scheme is the opposite to L1. In thiscase, h 3 and h ′ 3 behaves as normal but the othersassert less bits. The filter not sharing thehash functions stay the same as in s = 3 configuration,discriminating between locations readand written, and the other filters get the localityimprovement.As Figure 4 shows, results for L1 scheme arepractically the same than those for L2 for everybenchmark except <strong>La</strong>byrinth, Genome and Yada.<strong>La</strong>byrinth behaves better with L2 for small signaturesand, Genome and Yada get slightly worse resultsfor small signatures and L2. Unified localitysensitivesignatures outperform separate and separatelocality-sensitive ones in most of the cases.VII. ConclusionsWe propose a unified signature <strong>de</strong>sign in the contextof transactional memory which keep track ofboth the read and write sets in the same filter withoutadding significant hardware complexity. Several<strong>JP2011</strong>-195


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Execution time (normalized to Perfect)6543210Bayes64 128 256 512 1K 2K 4K 8KSignature size (bits)Execution time (normalized to Perfect)43.532.521.510.50Genome64 128 256 512 1K 2K 4K 8KSignature size (bits)Execution time (normalized to Perfect)543210Intru<strong>de</strong>r64 128 256 512 1K 2K 4K 8KSignature size (bits)Execution time (normalized to Perfect)1.31.251.21.151.11.0510.950.9Kmeans64 128 256 512 1K 2K 4K 8KSignature size (bits)Execution time (normalized to Perfect)302520151050<strong>La</strong>byrinth256 512 1K 2K 4K 8KSignature size (bits)Execution time (normalized to Perfect)1.31.251.21.151.11.0510.950.9SSCA264 128 256 512 1K 2K 4K 8KSignature size (bits)Execution time (normalized to Perfect)20151050Vacation64 128 256 512 1K 2K 4K 8KSignature size (bits)Execution time (normalized to Perfect)1086420Yada64 1282565121K 2K 4K 8KSignature size (bits)SeparateLocalityUnified s=3Unified s=3 L1Unified s=3 L2Fig. 4. Execution time normalized to perfect signatures comparing separate, separate locality and unified s = 3 signaturesenhanced with locality hashing (L1 and L2)configurations of unified signatures are analyzed an<strong>de</strong>valuated. Additionally, unified signatures are enhancedusing locality-sensitive hashing, proposed bythe authors in a previous work.The proposed unified locality-sensitive signatureswere implemented in the Wisconsin GEMS simulator,in or<strong>de</strong>r to evaluate their performance, and inCACTI to evaluate the hardware area and energyrequirements. Experimental results show that theunified approach improve the execution performancein most of the tested co<strong>de</strong>s, without increasing therequired hardware area in a noticeable amount, makingof it a good alternative to separate signatures.AcknowledgmentThis work has been supported by the Ministry ofEducation of Spain with project CICYT TIN2006-01078 and by the Junta <strong>de</strong> Andalucia with projectP08-TIC-04341.References[1] J.R. <strong>La</strong>rus and R. Rajwar, Transactional Memory, Morgan& Claypool Pub., 2007.[2] M. Herlihy and J.E.B. Moss, “Transactional memory:Architectural support for lock-free data structures,”in 20th Ann. Int’l. Symp. on Computer Architecture(ISCA’93), 1993, pp. 289–300.[3] B.H. Bloom, “Space/time tra<strong>de</strong>-offs in hash coding withallowable errors,” Communications of the ACM, vol. 13,no. 7, pp. 422–426, 1970.[4] L. Ceze, J. Tuck, P. Montesinos, and J. Torrellas,“BulkSC: Bulk enforcement of sequential consistency,”in 34th Ann. Int’l. Symp. on Computer Architecture(ISCA’07), 2007, pp. 278–289.[5] L. Yen, J. Bobba, M.R. Marty, K.E. Moore, H. Volos,M.D. Hill, M.M. Swift, and D.A. Wood, “LogTM-SE: Decouplinghardware transactional memory from caches,”in 13th Int’l. Symp. on High-Performance Computer Architecture(HPCA’07), 2007, pp. 261–272.[6] C.C. Minh, M. Trautmann, J. Chung, A. McDonald,N. Bronson, J. Casper, C. Kozyrakis, and K. Olukotun,“An effective hybrid transactional memory system withstrong isolation guarantees,” in 34th Ann. Int’l. Symp.on Computer Architecture (ISCA’07), 2007, pp. 69–80.[7] A. Shriraman, S. Dwarkadas, and M.L. Scott, “Flexible<strong>de</strong>coupled transactional memory support,” in 35th Ann.Int’l. Symp. on Computer Architecture (ISCA’08), 2008,pp. 139–150.[8] M. Mehrara, J. Hao, P.-C. Hsu, and S. Mahlke, “Parallelizingsequential applications on commodity hardwareusing a low-cost software transactional memory,” in ACMSIGPLAN Conf. on Programming <strong>La</strong>nguage Design andImplementation (PLDI’09), 2009, pp. 166–176.[9] R. Quislant, E. Gutierrez, O. Plata, and E.L. Zapata,“Improving signatures by locality exploitation for transactionalmemory,” in Int’l Conf. on Parallel Architecturesand Compilation Techniques (PACT’09), 2009, pp.303–312.[10] M.M.K. Martin, D.J. Sorin, B.M. Beckmann, M.R.Marty, M. Xu, A.R. Alamel<strong>de</strong>en, K.E. Moore, M.D.Hill, and D.A. Wood, “Multifacet’s general executiondrivenmultiprocessor simulator GEMS toolset,” ACMSIGARCH Comput. Archit. News, vol. 33, no. 4, pp. 92–99, 2005.[11] S.J.E. Wilton and N.P. Jouppi, “CACTI: an enhancedcache access and cycle time mo<strong>de</strong>l,” IEEE Journal ofSolid-State Circuits, vol. 31, no. 5, pp. 677 –688, 1996.[12] L. Ceze, J. Tuck, J. Torrellas, and C. Cascaval, “Bulk disambiguationof speculative threads in multiprocessors,”in 33th Ann. Int’l. Symp. on Computer Architecture(ISCA’06), 2006, pp. 227–238.[13] D. Sanchez, L. Yen, M.D. Hill, and K. Sankaralingam,“Implementing signatures for transactional memory,” in40th Ann. IEEE/ACM Int’l Symp. on Microarchitecture(MICRO’07), 2007, pp. 123–133.[14] L. Carter and M. Wegman, “Universal classes of hashfunctions,” J. Computer and System Sciences, vol. 18,no. 2, pp. 143–154, 1979.[15] M. V. Ramakrishna, E. Fu, and E. Bahcekapili, “Efficienthardware hashing functions for high performancecomputers,” IEEE Trans. on Computers, vol. 46, no. 12,pp. 1378–1381, 1997.[16] L. Yen, S.C. Draper, and M.D. Hill, “Notary: Hardwaretechniques to enhance signatures,” in 41stAnn. IEEE/ACM Int’l Symp. on Microarchitecture (MI-CRO’08), 2008, pp. 234–245.[17] W. Choi and J. Draper, “Locality-aware adaptivegrain signatures for transactional memories,” in IEEEInt’l. Symp. on Parallel and Distributed Processing(IPDPS’10), 2010, pp. 1–10.[18] N. Muralimanohar, R. Balasubramonian, and N. Jouppi,“CACTI 6.0: A tool to mo<strong>de</strong>l large caches,” Tech. Rep.HPL-2009-85, HP <strong>La</strong>boratories, 2009.[19] P.S. Magnusson, M. Christensson, J. Eskilson, D. Forsgren,G. Hallberg, J. Hogberg, F. <strong>La</strong>rsson, A. Moestedt,B. Werner, and B. Werner, “Simics: A full system simulationplatform,” IEEE Computer, vol. 35, no. 2, pp.50–58, 2002.[20] C. Cao Minh, J. Chung, C. Kozyrakis, and K. Olukotun,“STAMP: Stanford Transactional Applications forMulti-Processing,” in IEEE Int’l Symp. on WorkloadCharacterization (IISWC’08), 2008, pp. 35–46.<strong>JP2011</strong>-196


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Overriding the Coherence Protocolto Improve Directory CachesBlas Cuesta, Alberto Ros, María E. Gómez, Antonio Robles, and José Duato 1Abstract— Performance of shared-memory multiprocessors<strong>de</strong>pends to a large extent on the cachecoherence protocol. Protocols based on directorycaches give excellent performance, but their performanceand scalability is jeopardized by the limitedsize of directory caches along with the increasing sizeof systems. Most memory blocks referred by parallel/sequentialapplications are private and, therefore,do not require coherence maintenance. We proposean approach so that directory caches can take advantageof this fact avoiding the tracking of such privateblocks. Thus, the amount of information that theymust store is consi<strong>de</strong>rably reduced, which in turn lowersthe number of directory entries evicted. Since theoperating system helps processors to implement thisapproach, it only requires minor modifications. Simulationresults show that our proposal allows directorycaches to avoid the tracking of about 57% of theaccessed blocks. This contributes to shorten applicationruntime by 15% (when directory cache size ispreserved) or to maintain system performance (whenusing up to eight times smaller directory caches).Keywords— Multiprocessor, cache coherence, directorycache, operating system, coherence <strong>de</strong>activation,private blockI. IntroductionTASKS carried out by high-performance sharedmemorymultiprocessors [1] are increasinglycomplex, which generates a <strong>de</strong>mand for larger andmore powerful systems. The performance of thesesystems <strong>de</strong>pends to a large extent on the cache coherenceprotocol. One scalable approach to provi<strong>de</strong>coherence is the use of directory caches [2], [3].Directory caches keep track of all memory blocksstored in processor caches and that information isused to maintain coherence upon processor accessesto shared blocks. To be able to ensure coherent accessesto all memory blocks, when a directory cacheentry is evicted, all the cached blocks associated tosuch an entry are invalidated. Since systems inclu<strong>de</strong>more and more processors and cores and the size ofdirectory caches is quite limited, directory caches suffera lot of evictions. As a result, a large amount ofblocks are invalidated from processor caches, which<strong>de</strong>gra<strong>de</strong>s system performance.Since enlarging the size of directory caches is not areasonable solution (due to access latency and arearequirements), it is necessary to make the most ofthe available space. To this end, we take advantageof the fact that a significant fraction of the referredmemory blocks are privately used (i.e., accessed byonly one processor [4]). This is illustrated in Figure1, which shows that about 75% (on average) ofthe accessed blocks are private. Since they are notshared, they cannot suffer inconsistencies and, consequently,they do not require coherence maintenance.1 Department of Computer Engineering, UniversitatPolitècnica <strong>de</strong> València, e-mail: {blacuesa, aros, megomez,arobles, jduato}@gap.upv.esPrivate vs. shared blocks1.00.90.80.70.60.50.40.30.20.10.0PrivateSharedBarnesCholeskyFig. 1.FFTOceanRadiosityRaytrace-optVolrendWater-NsqTomcatvUnstructuredFaceRecMPG<strong>de</strong>cMPGencSpeechRecBlackscholesCannealSwaptionsFluidanimatex264ApacheSPEC-JBBAverageFraction of private versus shared blocks.Therefore, directory caches do not need to keep informationabout private blocks. By doing this, directorycaches will be less <strong>de</strong>man<strong>de</strong>d and the numberof directory entries evicted (and, in turn, the numberof invalidated cached blocks) can be drasticallyreduced.To i<strong>de</strong>ntify private blocks without using <strong>de</strong>dicatedhardware resources, we <strong>de</strong>vise a mechanism ai<strong>de</strong>dby the operating system (OS). The i<strong>de</strong>a is that, by<strong>de</strong>fault, every new page loa<strong>de</strong>d into main memoryis consi<strong>de</strong>red as private (which makes all its blocksbe consi<strong>de</strong>red as private as well). While only oneprocessor accesses the blocks within a private page,the page is kept as private and the accesses to themoverri<strong>de</strong> the coherence protocol, which prevents directorycaches from tracking them. However, whenthe OS <strong>de</strong>tects that a processor wishes to access ablock within a private page previously accessed by adifferent processor, the OS triggers a coherence recoverymechanism for the page. This mechanism restoresthe coherence for all the blocks within such apage and, from that moment on, the page is consi<strong>de</strong>redas shared. The accesses to blocks within sharedpages are handled by the coherence protocol, whichenforces their tracking.Simulation results show that, thanks to our proposal,directory caches omit the tracking of about57% (on average) of the accessed memory blocks.This reduces the number of evictions of directorycache entries and, as a result, the number of invalidationsof cached blocks, which leads to cachemiss reductions of about 35%. Doing so, system performanceimproves by about 15% (on average) an<strong>de</strong>nergy consumption is reduced by about 40% (onaverage). Alternatively, simulations also show thata system implementing our proposal performs similarlyto a system that uses directory caches eighttimes larger.The rest of the paper is organized as follows. SectionII discusses the related work. Our proposal is<strong>de</strong>scribed in Section III. We characterize the simulationenvironment in Section IV and present theevaluation results in Section V. Finally, Section VIdraws some conclusions.<strong>JP2011</strong>-197


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011P0 P1 MCmemory reference to block AA is in private pagecache miss on private block Anon−coherent request issuecache miss resolvedmemory reference to block AA is in private page, but it should be sharedtrigger the coherence recovery mechanismA is now in shared pagecache miss on shared block Acoherent request issuecache miss resolvedresolve non−coherent missoverri<strong>de</strong> coherence protocol(do not keep trackin directory cache)OSresolve coherent missuse coherence protocol(keep track indirectory cache)Fig. 2. Overview of the proposal. P0 and P1 are processorsand MC is the memory controller. The sha<strong>de</strong>d backgroundindicates that the OS is in charge at that moment.II. Related WorkLike our approach, some proposals use the OSto <strong>de</strong>tect private and shared pages. Hardavellas etal. [4] uses this <strong>de</strong>tection to propose an efficientdata placement policy for distributed shared caches(NUCA). While the mechanism for <strong>de</strong>tecting privatepages is similar to ours, its application is completelydifferent (data placement) and it does not consi<strong>de</strong>rcoherence aspects. On the other hand, Kim et al. [5]employ OS <strong>de</strong>tection to reduce the fraction of snoopsin token-based protocols. That work is based onthe fact that, although most referred blocks are private,the small fraction of shared blocks accounts formost cache misses. By <strong>de</strong>tecting the shared blocksand their sharing <strong>de</strong>gree, they can replace broadcastmessages by multicast. Unfortunately, this proposalrequires consi<strong>de</strong>rable extra hardware, increases thecomplexity, and adds OS overhead.Some proposals [6], [7], [8] use coarse-grain trackingof blocks to filter unnecessary traffic. However,those proposals have high storage requirements, areextremely complex, and entail consi<strong>de</strong>rable modificationsof the cache <strong>de</strong>sign. Besi<strong>de</strong>s, they just aimtraffic reduction.Similarly to our proposal, other works [9], [8] takeadvantage of OS structures. Contrariwise, they keepthe block sharers with the goal of reducing trafficor energy consumption. Unfortunately, those techniquesincrease storage requirements and entail importanthardware modifications, which make themdifficult to implemented in real systems.Zeffer et al. [10], [11] propose a combination ofsoftware and hardware to provi<strong>de</strong> coherence. In particular,a trap-based architecture <strong>de</strong>tects fine-grainedcoherence violations in hardware, triggers a coherencetrap when one occurs, and maintains coherenceby software in coherence trap handlers. In this case,the software overhead is quite high, which consi<strong>de</strong>rablyincreases the latency, and extra hardware isrequired to speed up the coherence trap handling.Fensch et al. [12] propose a coherence protocolthat does not require hardware support. It avoids thepossibility of incoherence by not allowing multiplewritable shared copies of pages. However, that proposalrequires release consistency, introduces extraoverhead regarding hardwired systems, and is onlysuitable for CMPs.virtual addressvirtual addresstagtagVVTLB entrypage table entryphysical addressphysical addressdatadataPCPLkeeperFig. 3. TLB and page table entry format. Sha<strong>de</strong>d fields areextra fields. V is the valid bit, P is the private bit, L isthe locked bit, and C is the cached-in-TLB bit.III. Coherence DeactivationIn or<strong>de</strong>r to avoid inconsistencies, directory cachestrack all cached memory blocks. However, a significantfraction of them are private and cannot suffer inconsistencies.To avoid this unnecessary informationwhich <strong>de</strong>creases the effectiveness of directory caches,we propose a technique that dynamically <strong>de</strong>tects privateblocks and avoid their tracking.The general i<strong>de</strong>a is that, by <strong>de</strong>fault, every newpage loa<strong>de</strong>d into main memory is consi<strong>de</strong>red as private.Cache misses for blocks belonging to privatepages overri<strong>de</strong> the coherence protocol. As a result,directory caches do not keep track of them. Whenthe OS <strong>de</strong>tects that two different processors try toaccess blocks within the same private page, it triggersa coherence recovery mechanism that restoresthe coherence status of every block within the privatepage and converts it into shared. From thatmoment on, the page is consi<strong>de</strong>red as shared and thememory accesses to its blocks are resolved accordingto the coherence protocol, which ensures their tracking.Figure 2 outlines this. First, P0 references thememory block A, which causes a cache miss. Since Abelongs to a private page, P0 issues a non-coherentrequest, which is served without tracking it. <strong>La</strong>ter,P1 references the same memory block A and a TLBmiss happens. While the OS is handling the miss, itrealizes that the page should become shared. Consequently,it triggers the coherence recovery mechanism.When it finishes, the page becomes shared andthe access to the cache proceeds, resulting in a cachemiss. Since the referred block belongs to a sharedpage, a coherent request is issued, which is trackedby the directory cache.Next sections walk through different key aspectsof our proposal such as the generation and service ofnon-coherent requests (Section III-A), the <strong>de</strong>tectionof shared pages (Section III-B), and the coherencerecovery mechanism (Section III-C).A. Non-Coherent RequestsOn memory references, processors first access theirTLB to translate the virtual addresses of blocks intophysical addresses. As shown in Figure 3, each TLBentry is mainly ma<strong>de</strong> up of the virtual address of thepage, the corresponding physical address, and otherproperties associated to the translation. Since someof the bits associated to the translation are not used,we take advantage of two of them to inclu<strong>de</strong> twonew fields: the private bit (P), which differentiatesbetween private and shared pages, and the locked bit(L), which is used to avoid un<strong>de</strong>sirable race conditions(as explained later in Section III-C).<strong>JP2011</strong>-198


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011MemoryoperationP0 keeperP1 initiatorhome MCHitOperationsuccessfulMiss resolvedFig. 4.HitAccessto cacheYesNon−coherentrequestAccessto TLBMissPrivatepage in TLBMark pageas sharedMissNoMiss resolvedCoherentrequestCoherencerecoveryFaultAdd pagetable entry(private)NoAccess topage tableYesIs this thepage keeper?HitStore page tableentry in TLBPrivate pageBlock diagram of the general working scheme.YesNotrigger coherence recoveryrecovery requestpage P keeper P0lock page P in TLBevict cache<strong>de</strong>victionsblocks of Pwait for pendingoperationsset TLB entry to sharedunlock page P in TLBrecovery donepage Pend coherence recoveryset page table entry to sharedOSwrite datato memoryTIMEP is used when a memory reference causes a cachemiss. Hence, if the cache miss is for a block belongingto a private page, a non-coherent requestis issued. Otherwise, a coherent request is issued.Non-coherent requests overri<strong>de</strong> the coherence protocoland they are always served by main memory. Inaddition, directory caches do not track them. Thisbehaviour has two primary advantages. First, neithera lookup nor an insertion in the directory cacheis required, which helps to reduce the latency of cachemisses, the contention at memory controllers, andthe energy consumption. Second, directory cachesare not so conten<strong>de</strong>d and, therefore, their capacitycan be better exploited to track blocks that reallyneed coherence.B. Detection of Shared PagesAs shown in Figure 3, page tables require threeadditional fields. Private (P) indicates whether thepage is private or shared. If P is set, keeper indicatesthe i<strong>de</strong>ntity of the only processor that hasaccessed the page blocks. The cached-in-TLB bit(C) indicates whether the keeper field is valid ornot. These extra fields only require extra OS storagespace, which is very small. Particularly, their size is2 + log 2 (N) bits, where N is the number of processorsin the system. Thus, assuming an 8-processorsystem, only 5 extra bits per entry are required.On a page table fault, the OS allocates a new pagetable entry with the virtual to physical address translation.In addition, since every newly loa<strong>de</strong>d page isconsi<strong>de</strong>red as private, P is set and C is cleared indicatingthat the entry is not cached in any TLByet. When a TLB miss takes place in a processor,it retrieves the information from the page table andstores it in its TLB. The extra fields in the page tableare updated insi<strong>de</strong> a critical section during the resolutionof TLB misses according to the following fourpremises: (1) if C is clear (i.e., the page blocks havenot been cached yet), C is set and the i<strong>de</strong>ntity of theprocessor requesting the page table entry is kept inkeeper; (2) if both C and P are set and keeper matchesthe requester (the keeper processor suffered a TLBeviction and it requires such information again), nochanges are necessary; (3) if both C and P are setand keeper does not match the requester (two differentprocessors are trying to access blocks within thesame private page), the coherence recovery mechanismis triggered and, when it finishes, P is cleared;and (4) if C is set and P is clear (the page is shared),no changes are necessary.Fig. 5. Flushing-based recovery mechanism. P0 and P1 areprocessors and MC is the home no<strong>de</strong>. Solid arrows aremessages due to the recovery mechanism, whereas dashedarrows are messages due to the coherence protocol.Figure 4 <strong>de</strong>picts all the actions that take place onmemory operations.C. Coherence Recovery MechanismBefore turning a private page into shared, the recoverymechanism has to ensure that the directorycache keeps proper track of every block within thepage. This can be done by two different strategies:(1) not modifying the directory cache and evictingall the page blocks from the keeper’s cache (flushingbasedrecovery) or (2) updating the directory cachewith proper track of every cached block within thepage (updating-based recovery). Next two sectionsexplain these mechanisms in <strong>de</strong>tail.C.1 Flushing-based Recovery MechanismThe simplest way to restore the coherence statusof the blocks belonging to a page that has to becomeshared is by evicting all the page blocks so that thenext time any of them is accessed, the directory cachecan begin to keep proper track of them. This mechanismworks as follows.First, the initiator (no<strong>de</strong> that triggers the coherencerecovery) issues a recovery request for the involvedpage to its keeper, which is obtained from thepage table during the page table fault resolution.Second, on the recovery request arrival, the keeperperforms four operations: (1) it locks the correspondingTLB entry by setting the L bit, which preventsthe keeper from issuing new requests for any of thepage blocks; (2) the keeper performs a cache lookup,flushing (and, if required, writing-back) every cachedblock within the involved page; (3) the keeper checksits MSHR (Miss Status Holding Registers) structureto wait for the completion of the pending misses orevictions for any of the page blocks; and (4) thekeeper marks the TLB entry corresponding to theinvolved page as shared, unlocks it, and sends to theinitiator a recovery done message.Third, when the initiator receives the recoverydone message, the recovery mechanism finalizes andthe page is set as shared in both the page table andthe local TLB. Notice that, during this process, theOS has exclusive access to the involved page table entryand no other processor can access it so that raceconditions cannot take place. Figure 5 illustrates anexample of how this mechanism works.<strong>JP2011</strong>-199


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011P0 keeperP1 initiatorhome MClock page P in TLBset TLB entry to sharedunlock page P in TLBpage Plook for cachedblocks of Pwait for pendingoperationskeeper P0 page Pcached blocks 1010..0recovery requestrecovery responserecovery donetrigger coherence recoverypage Pkeeper P0end coherence recoveryset page table entry to sharedrecovery target doneOSdirectory cache updatingtagACpage Psharing co<strong>de</strong>P0P0keeper P0Fig. 6. Updating-based recovery mechanism. P0 and P1 areprocessors and MC is the home no<strong>de</strong>.After completing this process, we know for surethat the blocks belonging to the recovered page arenot cached. Thus, from that moment on, directorycaches can keep proper track of them.C.2 Updating-based Recovery MechanismThe main advantage of the flushing-based recoveryis that its implementation in real systems is feasibleand straightforward. However, the flushing ofall cached blocks may increase the miss rate of processorcaches (this is analyzed in Section V). To addressthis potential drawback, we propose an alternativeimplementation based on updating the directorycache information that works as follows.First, the initiator issues a recovery request to thecorresponding page keeper.Second, the page keeper locks the correspondingTLB entry on the arrival of the recovery request andlooks for the blocks within the page that are presentin its cache. The addresses of those blocks are co<strong>de</strong>din a bit vector, which is inclu<strong>de</strong>d in a recovery response.After composing the bit vector, the keeperchecks its MSHR structure and waits for the outstandingoperations on any of the page blocks (ifany). Once the pending operations complete, therecovery response is sent to the home memory controller.Third, upon the receipt of a recovery response,the home memory controller proceeds to update itsdirectory cache according to the received bit vector.In particular, it creates a new directory cache entryfor every block cached by the keeper. The sharingco<strong>de</strong> of every new entry can be easily set becauseit knows that, at that moment, the keeper is theonly one with a valid copy of the block. When thedirectory cache updating finalizes, the home no<strong>de</strong>sends a recovery target done message back to the pagekeeper.Forth, when the keeper receives the recovery targetdone message, it marks the TLB entry correspondingto the page as shared, unlocks the correspondingTLB entry, and sends a recovery done message tothe initiator, finalizing the recovery process. Figure6 shows an example of how the updating-basedrecovery mechanism works.TIMETABLA ISystem parameters.Memory ParametersProcessor frequency3.2 GHzCache block size64 bytesProcessor cache2MB, 4-wayProcessor cache access latency 2nsDirectory cache256KB, 4-wayDirectory cache access latency 2nsDirectory cache coverage ratio 2×, worst-case 0.25×Memory access latency (local bank) 60nsPage size4KB (64 blocks)Network ParametersNetwork topologyHypercubeData message size68 and 72 bytesControl message size4 and 8 bytesNetwork bandwidth12.8GB/sInter-die link latency2nsInter-processor link latency20nsFlit size4 bytesLink bandwidth1 flit/cycleAfter completing the updating-based recoverymechanism for a page, we know for sure that the directorycache holds proper track of the page blocks.IV. Evaluation MethodologyWe evaluate our proposals with full-system simulationusing Virtutech Simics [13] running Solaris 10and exten<strong>de</strong>d with the Wisconsin GEMS toolset [14],which enables <strong>de</strong>tailed simulation of multiprocessorsystems. The interconnection network is mo<strong>de</strong>ledwith GARNET [15]. Finally, we also use the Mc-PAT tool [16], assuming a 45nm process technology,to measure energy consumption.For the evaluation of our proposals, we first mo<strong>de</strong>la cache coherent HyperTransport system optimizedwith directory caches similar to those of the AMDMagny-Cours. The simulated system has 8 processors(16 cores) and its parameters are shown in TableI. We refer to this system as the base architectureand our proposals are implemented upon it.We simulate a wi<strong>de</strong> variety of parallel workloadsfrom 3 suites (SPLASH-2 [17], ALPBenchs [18], andPARSEC [19]), two scientific benchmarks, and twocommercial workloads [20]. Due to time requirements,we are not able to simulate these benchmarkswith large working sets. Consequently, as done inmost works [7], [21], [12], we simulate the applicationsassuming smaller data-sets. To avoid alteringthe results, we reduce four times the size of both processorcaches and directory caches. Notice that, sincethe size of all the simulated caches are proportionallyreduced, the coverage ratio of directory caches is thesame as in Magny-Cours (2×).All the reported experimental results correspondto the parallel phase of benchmarks. We account forthe variability in multi-threa<strong>de</strong>d workloads by doingmultiple simulation runs for each benchmark and injectingsmall random perturbations in the timing ofthe memory system.V. Performance EvaluationOur proposal is based on the fact that mostreferred blocks are privately used by processors.Crosses in Figure 7 show the fraction of actual privateblocks. As observed, about 75% (on average)of the referred blocks are private. Since our proposalworks at a page granularity, it cannot i<strong>de</strong>ntifyall the private blocks because, when a page contains<strong>JP2011</strong>-200


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Private blocks rateNormalized cache miss rate1.00.90.80.70.60.50.40.30.20.10.0FlushingI<strong>de</strong>alBarnesCholeskyFig. 7.BarnesCholeskyFFTOceanRadiosityRaytrace-optVolrendWater-NsqTomcatvUnstructuredFaceRecMPG<strong>de</strong>cMPGencSpeechRecBlackscholesCannealSwaptionsFluidanimatex264ApacheSPEC-JBBAverageFraction of actual versus <strong>de</strong>tected private blocks.1. Base 2. Flushing 3. Updating1.11.00.90.80.70.60.50.40.30.20.10.0Fig. 8.FFTOceanRadiosity3C Coherence Coverage FlushingRaytrace-optVolrendWater-NsqTomcatvUnstructuredFaceRecMPG<strong>de</strong>cMPGencSpeechRecBlackscholesCannealSwaptionsFluidanimatex264ApacheNormalized cache miss rate classification.SPEC-JBBAverageboth private and shared blocks or just private blocksaccessed by different processors, the page is consi<strong>de</strong>redas shared. Bars in Figure 7 show the fraction ofblocks that our mechanism <strong>de</strong>tects as private. Thus,our proposal <strong>de</strong>tects that 57% on average are privateblocks and the other 18% of the blocks are misclassified.Since directory caches do not track blocks <strong>de</strong>tectedas private, less blocks contend for their entries.Consequently, they suffer fewer evictions and,therefore, less blocks are invalidated from processorcaches. As a result, the processor cache miss rateis reduced by 35% (on average), as Figure 8 shows.This figure illustrates the fraction of cache misses(normalized to the base system) when <strong>de</strong>activatingthe coherence and assuming the two proposed recoverymechanisms. Cache misses are classified in fourdifferent groups: 3C misses comprise Cold, Capacity,and Conflict misses; coherence misses refer tothose caused by invalidations due to write requestsissued by other processors; coverage misses are thosecaused by the invalidations issued by the directorycaches due to replacements; and flushing misses aredue to evictions performed by the recovery mechanism.Since our proposal aims at improving theeffectiveness of directory caches, it acts on coveragemisses, which are reduced by about 75% on average.Furthermore, as shown in the figure, contraryto what might be thought, the use of the flushingbasedrecovery mechanism does not entail an increaseof the total number of cache misses with respect tothe updating-based implementation.The reduction of both directory cache evictionsand processor cache misses drastically reduces the coherencetraffic by about 40% on average, as <strong>de</strong>pictedin Figure 9. This figure shows the network trafficgenerated by the assumed cache coherence protocolusing our proposal normalized to the base system.Each bar plots the number of flits transmitted acrossthe interconnection network.The latency of the recovery mechanisms is consi<strong>de</strong>rablebecause it inclu<strong>de</strong>s a search in the cache ofthe page keeper and, in case of the updating-basedmechanism, it also inclu<strong>de</strong>s several accesses to the directorycache to add the required entries. However,the recovery mechanism is not often used and, there-Normalized network trafficRecovery actions per 1000 misses1.11.00.90.80.70.60.50.40.30.20.10.022.020.018.016.014.012.010.08.06.04.02.00.0BarnesCholeskyBarnesCholeskyFig. 10.FlushingUpdatingFFTOceanRadiosityFig. 9.FlushingRaytrace-optUpdatingFFTOceanRadiosityRaytrace-optVolrendWater-NsqTomcatvUnstructuredFaceRecMPG<strong>de</strong>cMPGencSpeechRecBlackscholesCannealSwaptionsFluidanimatex264ApacheSPEC-JBBAverageNormalized network traffic (in flits).23.2VolrendWater-NsqTomcatvUnstructuredFaceRecMPG<strong>de</strong>cMPGencSpeechRecBlackscholesCannealSwaptionsFluidanimatex264ApacheSPEC-JBBAverageCoherence recovery triggers per 1000 cache misses.fore, its impact on the overall performance is almostunnoticeable. To illustrate this, Figure 10 shows thenumber of times that the coherence recovery mechanismis triggered per 1000 cache misses. On average,this mechanism is only triggered about 3 times per1000 cache misses (up to 23 for the SPEC-JBB application).As a result, cache misses have much moreimpact on the whole runtime of applications than thecoherence recovery mechanism.Mainly due to the reduction in the number of cachemisses, the runtime of applications can be significantlyreduced, as <strong>de</strong>picted by the bar labeled asflushing in Figure 11. Since the results are quite similarfor both recovery mechanisms, we only show theresults for the mechanism based on flushing. Thus,according to these results, the proposed techniquecan lead to improvements in application runtime ofabout 15% on average. The systems where the storagerequirements are critical can also take advantageof our proposal because, by means of it, the size ofdirectory caches can be drastically reduced while obtaininggood performance. This is illustrated by thebars labeled as DC:2, DC:4, and DC:8, which representthree configurations with a half, a fourth, andan eighth of the base cache size, respectively. We cansee that our proposal allows us to reduce the size ofdirectory caches up to eight times while still maintainingthe execution time of applications similar (onaverage) to that of the base system.Figure 12 shows the dynamic energy consumption.First, the energy consumption of directory cachesis reduced because non-coherent requests do not accessthem. This reduction becomes more significantas the directory cache size <strong>de</strong>creases. Second, theenergy consumption of memory controllers is alsoreduced. In this case, as directory caches becomesmaller, the number of cache misses increases and,consequently, more accesses to memory controllerswill be required, which increases its consumption.Third, the energy consumption of the interconnectionnetwork lowers because of the reduction in networktraffic. Thus, the overall consumption of thesethree components is reduced by about 40% on average.Although, the overall energy consumption increasesas directory caches become smaller, it is stilllower than that of the base system using directorycaches 8 times larger.<strong>JP2011</strong>-201


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Normalized execution time1.31.21.11.00.90.80.70.60.50.40.30.20.10.0BarnesFlushingFlushing DC:2CholeskyFlushing DC:4Flushing DC:81.60 2.42FFTOceanRadiosityRaytrace-optVolrendWater-NsqTomcatvUnstructuredFaceRecMPG<strong>de</strong>cMPGencSpeechRecBlackscholesCannealSwaptionsFluidanimatex264ApacheSPEC-JBBAverageFig. 11. Execution time normalized to the base system. DC:2, DC:4, and DC:8 stand for directory caches with their sizedivi<strong>de</strong>d by 2, 4, and 8, respectively.Dynamic energy2.01.81.61.41.21.00.80.60.40.20.01. Base 2. Updating 3. Flushing 4. Flushing DC:2 5. Flushing DC:4 6. Flushing DC:8BarnesCholeskyDirectoryCache MemoryController NetworkFFTOceanRadiosityRaytrace-optVolrendWater-NsqTomcatvUnstructuredFaceRecMPG<strong>de</strong>cMPGencSpeechRecBlackscholesCannealSwaptionsFluidanimatex264ApacheSPEC-JBBAverageFig. 12. Dynamic energy consumption normalized to the base system. DC:2, DC:4, and DC:8 stand for directory caches withtheir size divi<strong>de</strong>d by 2, 4, and 8, respectively.3.02The static energy consumption is not shown in Figure12 because it is really tight to application runtime.Besi<strong>de</strong>s, in directory caches, it also <strong>de</strong>pendson the directory size. Thus, when using directorycaches 2, 4, and 8 times smaller than that in the basesystem, the static power consumption is reduced by48%, 74%, and 86%, respectively.VI. ConclusionsThe proposal ma<strong>de</strong> in this paper aims to improvethe effectiveness of directory caches. It takes advantageof the fact that most referred memory blocksare private and, therefore, they do not require coherencemaintenance. Thus, directory caches do notkeep track of them. Since the amount of informationstored by directory caches is drastically reduced, thenumber of blocks invalidated from processor cachesdue to replacements in directory caches also lowers(by about 57% on average). This contributes to increasesystem performance (15%) or to reduce thestorage requirements of directory caches (8 times).Due to the simplicity of the proposed technique,it can be implemented without modifying the coherenceprotocol or the processor hardware, being itsimplementation feasible in actual systems.AcknowledgmentsThis work has been supported by Generalitat Valencianaun<strong>de</strong>r Grant PROMETEO/2008/060.Referencias[1] P. Conway et al., “Cache hierarchy and memory subsystemof the AMD opteron processor,” IEEE Micro, vol.30, no. 2, pp. 16–29, Apr. 2010.[2] B. W. O’Krafka et al., “An empirical evaluation of twomemory-efficient directory methods,” in 17th Int’l Symp.on Computer Architecture (ISCA), June 1990, pp. 138–147.[3] A. Gupta et al., “Reducing memory traffic requirementsfor scalable directory-based cache coherence schemes,”in Int’l Conference on Parallel Processing (ICPP), Aug.1990, pp. 312–321.[4] N. Hardavellas et al., “Reactive NUCA: Near-optimalblock placement and replication in distributed caches,”in 36th Int’l Symp. on Computer Architecture (ISCA),June 2009, pp. 184–195.[5] D. Kim et al., “Subspace snooping: Filtering snoopswith operating system suport,” in 19th Int’l Conferenceon Parallel Architectures and Compilation Techniques(PACT), Sept. 2010, pp. 111–122.[6] A. Moshovos, “RegionScout: Exploiting coarse grainsharing in snoop-based coherence,” in 32nd Int’l Symp.on Computer Architecture (ISCA), June 2005, pp. 234–245.[7] J. F. Cantin et al., “Improving multiprocessor performancewith coarse-grain coherence tracking,” in 32thInt’l Symp. on Computer Architecture (ISCA), June2005, pp. 246–257.[8] J. Zebchuk et al., “A framework for coarse-grain optimizationsin the on-chip memory hierarchy,” in 40thIEEE/ACM Int’l Symp. on Microarchitecture (MICRO),Dec. 2007, pp. 314–327.[9] N. D. Enright-Jerger et al., “Virtual circuit tree multicasting:A case for on-chip hardware multicast support,”in 35th Int’l Symp. on Computer Architecture (ISCA),June 2008, pp. 229–240.[10] H. Zeffer et al., “TMA: A trap-based memory architecture,”in 20th Int’l Conference on Supercomputing (ICS),June 2006, pp. 259–268.[11] H. Zeffer et al., “A case for low-complexity MP architectures,”in ACM/IEEE Conference on Supercomputing(SC), Nov. 2007, pp. 10–16.[12] C. Fensch et al., “An OS-based alternative to full hardwarecoherence on tiled CMPs,” in 14th Int’l Symp. onHigh-Performance Computer Architecture (HPCA), Feb.2008, pp. 355–366.[13] P. S. Magnusson et al., “Simics: A full system simulationplatform,” IEEE Computer, vol. 35, no. 2, pp. 50–58,Feb. 2002.[14] M. M. K. Martin et al., “Multifacet’s general executiondrivenmultiprocessor simulator (GEMS) toolset,” ComputerArchitecture News, vol. 33, no. 4, pp. 92–99, Sept.2005.[15] N. Agarwal et al., “GARNET: A <strong>de</strong>tailed on-chip networkmo<strong>de</strong>l insi<strong>de</strong> a full-system simulator,” in IEEE Int’lSymp. on Performance Analysis of Systems and Software(ISPASS), Apr. 2009, pp. 33–42.[16] S. Li et al., “McPAT: An Integrated Power, Area, andTiming Mo<strong>de</strong>ling Framework for Multicore and ManycoreArchitectures,” in 42nd IEEE/ACM Int’l Symp. onMicroarchitecture (MICRO), Dec. 2009, pp. 469–480.[17] S. C. Woo et al., “The SPLASH-2 programs: Characterizationand methodological consi<strong>de</strong>rations,” in 22nd Int’lSymp. on Computer Architecture (ISCA), June 1995, pp.24–36.[18] M. Li et al., “The ALPBench benchmark suite for complexmultimedia applications,” in Int’l Symp. on WorkloadCharacterization, Oct. 2005, pp. 34–45.[19] C. Bienia et al., “The PARSEC benchmark suite: Characterizationand architectural implications,” in 17th Int’lConference on Parallel Architectures and CompilationTechniques (PACT), Oct. 2008, pp. 72–81.[20] A. R. Alamel<strong>de</strong>en et al., “Evaluating non-<strong>de</strong>terministicmulti-threa<strong>de</strong>d commercial workloads,” in 5th WorkshopOn Computer Architecture Evaluation using CommercialWorkloads (CAECW), Feb. 2002, pp. 30–38.[21] N. D. Enright-Jerger et al., “Virtual tree coherence:Leveraging regions and in-network multicast tree for scalablecache coherence,” in 41th IEEE/ACM Int’l Symp.on Microarchitecture (MICRO), Nov. 2008, pp. 35–46.<strong>JP2011</strong>-202


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Overcoming the Scalability Constraints ofCoherence Protocols of Commodity SystemsAlberto Ros 1 Blas Cuesta 1 Ricardo Fernán<strong>de</strong>z-Pascual 2 María E. Gómez 1Manuel E. Acacio 2 Antonio Robles 1 José M. García 2 y José Duato 1Abstract— AMD has recently launched the twelvecoreMagny-Cours processors. They inclu<strong>de</strong> a directorycache that increases the scalability of the coherenceprotocol applied by Opterons. This directorycache uses a 3-bit pointer for i<strong>de</strong>ntifying the ownerno<strong>de</strong> of a memory block, which prevents Magny-Cours-based servers from being built beyond 8 no<strong>de</strong>s.In this paper, we propose and <strong>de</strong>velop an externallogic to extend the coherence domain of Magny-Coursprocessors beyond the 8-no<strong>de</strong> limit while maintainingthe advantages provi<strong>de</strong>d by the directory cache. Evaluationresults for up to a 32-no<strong>de</strong> system show howthe performance offered by our solution scales withthe increment in the number of no<strong>de</strong>s. Particularly,we reduce runtime by 47% in a 32-die system respectto the 8-die Magny-Cours system.Keywords— High-performance computing, sharedmemory, cache coherence, directory protocol, coherenceextension, scalability, traffic filtering.I. IntroductionAMD has recently launched the six- and twelvecoreversions of its Opteron processors, co<strong>de</strong>namedIstanbul and Magny-Cours [1], respectively.These commodity systems increase the number ofcores per processor package with respect to the previousgeneration of Opteron processors. However,the novelty of these systems is the inclusion of a directorycache, called HT Assist Probe Filter (HTA)[2], whose main aim is to reduce the number ofmessages generated by the cache coherence protocol.The Magny-Cours protocol, which is an adaptationof the protocol <strong>de</strong>fined by the coherent HyperTransport(cHT) specification, allows to build asmall cache-coherent shared memory multiprocessor(up to eight dies) in a single board.The addition of the HTA reduces cache miss latencyand coherence traffic, thereby increasing thescalability of the protocol. However, the HTA suffersthe addressing limitations imposed by the cHTspecification, which limits the coherence domain forIstanbul and Magny-Cours processors up to 8 dies(or no<strong>de</strong>s) [1]. This goes against the current commercialinterest in <strong>de</strong>veloping cluster-based HPC systemsable to offer large cache-coherent shared memory addressspaces, such as the SGI Ultraviolet (Altix UV)[3] machines.The addressing limitation of the cHT specificationis solved in the new High No<strong>de</strong> Count (HNC)HyperTransport specification [4], which extends the1 Dpto. <strong>de</strong> Informática <strong>de</strong> Sistemas y Computadores, Univ.Politécnica <strong>de</strong> Valencia, e-mail: {aros,blacuesa,megomez,arobles,jduato}@gap.upv.es2 Departamento <strong>de</strong> Ingeniería y Tecnología <strong>de</strong> Computadores,Univ. Murcia, e-mail: {rfernan<strong>de</strong>z,meacacio,jmgarcia}@ditec.um.escHT specification by encapsulating standard cHTmessages into HNC packets. However, as currentOpteron processors do not implement this extension,the coherence domain remains limited to 8 dies beingrequired an external logic to overcome this limitation.In this work, we present a <strong>de</strong>vice, called bridgechip or EMC 2 (Exten<strong>de</strong>d Magny-Cours Coherence)chip, that (1) provi<strong>de</strong>s a way to efficiently extend thecoherence domain provi<strong>de</strong>d by the new generation ofAMD Opteron processors beyond the 8-die limit, (2)maintains the advantages provi<strong>de</strong>d by the HTA, and(3) filters additional coherence traffic to enhance theHTA effectiveness. The EMC 2 chip is ad<strong>de</strong>d to eachboard in the system, replacing one of the existingdies. It manages the communication between dies indifferent boards by performing conversions betweencHT and HNC packets.We have proposed three different implementationsfor the EMC 2 chip that cover a wi<strong>de</strong> set of tra<strong>de</strong>offsbetween their area requirements and the amountof traffic filtered by them. Additionally, to improvethe scalability of our <strong>de</strong>sign, we have proposed anapproach that reduces the number of replacementsin the HTA.Simulation results show that our proposal allowsto build large-scale shared-memory servers based onthe new-generation Opteron processors, able to exploitthe advantages of the HTA at the overall systemlevel. Particularly, the bridge chip named asEMC 2 -OXSX reduces the average execution time ofthe evaluated applications by 47% for a 32-die systemrespect to the 8-die system allowed by Magny-Cours, while obtaining an excellent compromise betweenarea and traffic requirements.The remain<strong>de</strong>r of this paper is organized as follows.Section II outlines the Magny-Cours cachecoherence protocol. We present our proposals forextending AMD Magny-Cours cache coherence capabilitiesin Section III. We <strong>de</strong>scribe our simulationenvironment in Section IV and present the evaluationresults in Section V. Finally, we draw conclusions inSection VI.II. AMD Magny-Cours Cache CoherenceAMD Opteron processors use the cache coherenceprotocol <strong>de</strong>fined by the cHT specification [5]. Thisprotocol was <strong>de</strong>signed to perform efficiently in a systemwith a small number of processors connectedwith tightly-coupled point-to-point HyperTransportlinks. It can be characterized as a directory-based<strong>JP2011</strong>-203


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Core 0512kBL2Core 1 Core 2 Core 3 Core 4512kBL2512kBL2512kBL2System Request Interface (SRI)512kBL2Core 5512kBL2Nest 0 Nest 1 Nest NNo<strong>de</strong> 0 No<strong>de</strong> 1 No<strong>de</strong> 0 No<strong>de</strong> 1 No<strong>de</strong> 0 No<strong>de</strong> 1No<strong>de</strong> 2 No<strong>de</strong> 3 No<strong>de</strong> 2 No<strong>de</strong> 3. .No<strong>de</strong> 2 No<strong>de</strong> 3L3 tagXBARL3 data array(6MB)EMC 2 chip EMC 2 chipEMC 2 chipMemoryControllerMCT/DCTDRAMFig. 1.DRAMHTAProbeFilter4 HyperTransportTM3 PortsBlock diagram of Magny-Cours dies.protocol without directory information, also knownas Dir 0 B [6]. This lack of directory information reducesthe memory overhead and avoids the latencyof accessing it.Accesses to memory blocks are serialized by theirhome no<strong>de</strong> (memory controller), which will broadcastmessages known as Broadcast Probe (BP). No<strong>de</strong>sreply to BPs with Probe Response (PR) messages,which are collected by the requester. Once the requestis satisfied, the requester sends a Source Done(SD) to the home no<strong>de</strong>, which is allowed to proceedwith the next request for the block. The requiredBPs do not excessively increase bandwidth consumptionin small systems. However, as the number ofno<strong>de</strong>s grows, both the bandwidth consumed and thetime required to receive and process all the PRsincrease dramatically. Finally, writebacks of dirtyblocks are sent to their home no<strong>de</strong> which will replyto the requester with a Target Done (TD) message.Like in the previous case, the transaction ends witha SD.Recent Istanbul and Magny-Cours processors inclu<strong>de</strong>a small on-chip directory cache [2] called HTAssist Probe Filter (HTA), as shown in Figure 1.The HTA holds an entry for every block from thehome no<strong>de</strong> cached in the system. Each entry has 4bytes which are used to store a tag, a state (EM, O,S1 or S) 1 , and a pointer to the current owner of theblock (3 bits). This information is used to (1) filterunnecessary BPs when no copy of the data is cachedand (2) to replace some BPs with unicast DirectedProbe (DP) messages. In case of a DP, only one response,called Directed Response (DR), is generated.Upon a miss on the HTA, a new entry must be allocated,which may require to replace an existing one.Before performing the replacement, all the cachedcopies of the block i<strong>de</strong>ntified by the replaced entrymust be invalidated either by a DP (if the replace<strong>de</strong>ntry is in EM or S1 state) or by a BP (if it is in Oor S state).As Figure 1 <strong>de</strong>picts, a portion (1MB of 6MB available)of the L3 cache is <strong>de</strong>dicated to HTA entries toavoid adding a large overhead in uniprocessor systems.This provi<strong>de</strong>s enough space for 256K entriesorganized in 64K 4-way sets, which are enough fortracking 16MB (256K entries × 64 bytes/block) ofdata cached in the system.1 Blocks are stored in caches according to the MOESI states.Switch FabricFig. 2. Overview of the proposed system. Thick arrows insi<strong>de</strong>the boards represent x16 cHT links while the narrow onesare x8 cHT links.Since the cHT packet format assumes 3-bit fieldsto i<strong>de</strong>ntify coherent no<strong>de</strong>s, Magny-Cours systems arestill limited to 8 dies. The HNC HyperTransportspecification addresses this last problem by extendingthe cHT specification. To this end, it <strong>de</strong>fines theconcept of nest as any addressable entity (which canbe anything from a single processor up to a motherboardcontaining several processors) and an exten<strong>de</strong>dpacket format that can encapsulate standard cHTmessages and uses a nest-based addressing scheme.However, it does not establish how packets shouldbe handled when they move between local and remotedomains. Besi<strong>de</strong>s, the HTA imposes an additionallimitation because the pointer used to enco<strong>de</strong>the current owner of a cached block has only 3 bits,bounding the Magny-Cours systems to a maximumof 8 dies. To overcome these two problems we proposethe EMC 2 chip <strong>de</strong>scribed in the next section.III. Extending Magny-Cours CoherenceWe assume the system illustrated in Figure 2. Asshown, it comprises several processor boards (referredto as nests). Each nest contains 4 processordies (referred to as no<strong>de</strong>s) and the EMC 2 bridge chipwhich acts as (1) a network interface controller forthe entire nest, (2) a translator between cHT andHNC packets, and (3) an extension of the HTAs ofthe no<strong>de</strong>s. Each board inclu<strong>de</strong>s a consecutive fractionof the physical memory addresses.A. Extending the Coherence DomainTo maintain coherence between no<strong>de</strong>s in differentnests, we propose the use of the EMC 2 chip, whoseblock diagram is shown in Figure 3. From the pointof view of no<strong>de</strong>s, the EMC 2 chip is seen as anotherno<strong>de</strong> insi<strong>de</strong> the nest. The EMC 2 chip and all theno<strong>de</strong>s in a nest are fully connected through a cHTinterconnect. The different nests are connected by anInfiniBand switch fabric and they communicate usingHNC packets encapsulated into InfiniBand packets.Every cHT packet conveys the information of thetransaction it belongs to: the no<strong>de</strong> that initiated thetransaction (SrcNo<strong>de</strong>), its unit (SrcUnit), and a tag(SrcTag). When the EMC 2 chip has to translate acHT packet into a HNC packet it must inclu<strong>de</strong> the informationabout the associated transaction. To thisend, it adds to the previous information the nest (SrcNest)where the SrcNo<strong>de</strong> is located. In this way,transactions can also be unequivocally i<strong>de</strong>ntified outsi<strong>de</strong>a nest.<strong>JP2011</strong>-204


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Internal PortsExternal PortsFig. 3.IBA/HNC AdaptersPendingCommandQueueMSTETTMSHRControlUnitEHTAcHT Packet AdapterHNC/IBA AdaptersExternal Ports Internal PortsBlock diagram of the EMC 2 chip.On a HNC packet arrival belonging to an externaltransaction (i.e., that initiated outsi<strong>de</strong> the nest),the EMC 2 chip has to forward it insi<strong>de</strong> the nest asa cHT packet. To avoid conflicts with the existingcHT packets belonging to internal transactions (initiatedinsi<strong>de</strong> the nest), the EMC 2 chip associates thegenerated cHT packet with a new internal transactionthat will have a new SrcTag local to its nestand a new SrcNo<strong>de</strong> (the EMC 2 chip i<strong>de</strong>ntifier itself).On the other hand, when a cHT packet for thatnew transaction arrives to the EMC 2 chip, the HNCpacket to which it is translated restores the originali<strong>de</strong>ntifiers of the external transaction. To supportthese operations, the Matching Store Table (MST)inclu<strong>de</strong>d in the EMC 2 chip (see Figure 3) keeps thematching between the i<strong>de</strong>ntifiers of external transactionsand those of the internal ones. The numberof MST entries, and consequently, the number of externaltransactions simultaneously in progress in thenest, is boun<strong>de</strong>d by the maximum number of tagsthat can be generated by the cHT specification (i.e.,32 tags). When the MST is full and a new entrycannot be allocated, the incoming packets will haveto be temporally stored in the Pending CommandQueue.The MST entries created by Broadcast/DirectedProbes are valid until the associated response goesback to the EMC 2 chip. However, the entries allocatedby requests remain until the arrival of thecorresponding Source Done. Due to the limited numberof MST entries, if every MST in the system wasfull of the entries allocated by requests, a <strong>de</strong>adlockscenario could occur. This is because probes wouldbe unable to allocate new entries, and therefore, thepending requests would never complete. To avoid it,the MST must reserve at least one entry for Broadcast/DirectedProbes.Another function of the EMC 2 chip is to collect allthe responses received as a consequence of a probeand transforming them into just one response packet(if nee<strong>de</strong>d). To accomplish this task, the EMC 2 chipuses the MST. However, given that MST entries areonly allocated on the arrival of messages belongingto external transactions, we need another table thathelps the EMC 2 chip to collect the responses associatedto internal transactions. This additional table iscalled Exten<strong>de</strong>d Tag Table (ETT) and it has 512 entries(32 tags/no<strong>de</strong> × 4 units/no<strong>de</strong> × 4 no<strong>de</strong>s/nest).Unlike the MST, it is able to store all the transactionsrequesting an entry in it.B. Extending the HTA FunctionalityTo maintain and extend the functionality of theHTAs as well as to reduce the generated coherencetraffic, every EMC 2 chip inclu<strong>de</strong>s a directory cachecalled Exten<strong>de</strong>d HTA (EHTA), as shown in Figure 3.An EHTA tracks the memory blocks whose home islocated in its nest and that may also be cached in aremote no<strong>de</strong> (outsi<strong>de</strong> its nest). However, the EHTAis not aware of the blocks only cached insi<strong>de</strong> its nest.Since a HTA only knows the existence of the no<strong>de</strong>sinsi<strong>de</strong> its nest, when the owner is in a remote no<strong>de</strong>,the HTA will think that it is cached by the EMC 2chip. Therefore, the EHTA inclu<strong>de</strong>d in the EMC 2chip will be in charge of tracking the actual locationof the owner, that is, its nest (ownerNest field) andno<strong>de</strong> (ownerNo<strong>de</strong> field) i<strong>de</strong>ntifiers. Given that thereare four HTAs per nest and each one holds 256K entries,we will assume 1M entries for each EHTA (64K16-way sets). Doing so will prevent EHTA from limitingthe number of blocks that can be simultaneouslycached outsi<strong>de</strong> the home nest below the limitimposed by the local HTAs themselves.In addition to the information of the owner, theEHTA also inclu<strong>de</strong>s some information that helps it inthe traffic filtering task. In or<strong>de</strong>r to cover a wi<strong>de</strong> setof tra<strong>de</strong>-offs between area requirements and amountof filtered traffic, we propose three different EHTAconfigurations.• The EMC 2 chip with the first configuration,called EMC 2 -Base, inclu<strong>de</strong>s an EHTA that implementsthe same states as the HTA: EM, O,S1, S. These states, that require just two bitsper entry, are the only information used to filtercoherence traffic.• The second configuration, assumed by theEMC 2 -OXSX chip, adds two additional states,OX and SX, which will require three bits forcodifying all the states. These new states areparticularly inten<strong>de</strong>d to turn Broadcast Probesinto Directed Probes when all the remote copiesof a certain block are located in the same nest.Notice that on the arrival to the remote nest,the Directed Probe will be turned again into aBroadcast Probe in case of having to invalidatemore than one copy.• The EMC 2 -BitVector chip, which inclu<strong>de</strong>s thethird EHTA configuration, adds a bit-vector foreach EHTA entry to the first configuration. Thebit-vector inclu<strong>de</strong>s a bit for every remote nestin the system, indicating if associated block iscached or not in the corresponding nest. Thisallows replace Broadcast Probes with multicastprobes. Although it is the configuration thatfilters more traffic, it needs one extra bit perremote nest for each EHTA entry what makes itthe most area-<strong>de</strong>manding approach.Since the three EHTA configurations are quite similarwe only show the protocol transitions <strong>de</strong>pendingon the EHTA states for the EMC 2 -OXSX chip becauseit is the one that achieves a better traffic-area<strong>JP2011</strong>-205


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLE IIScenarios <strong>de</strong>pending on the HTA state (rows) and the EHTA state (columns).X EM OX O S1 SX S Iowner out owner inEM no copy in/out- - - - -no copy outld / st:DP→DP ld / st: -owner out owner out owner out owner in owner in owner in owner inOno copy outcopies incopies in owner nest copies outcopies in copies in1 copy outcopies incopies out (1 nest)copies incopies outcopies inno copy outcopies inld:DP→DP ld:DP→DP ld:DP→DP ld: - ld: - ld: - ld: -st:BP→DP st:BP→DP* st:BP→BP st:BP→DP st:BP→DP* st:BP→BP st:BP→Filteredowner in memoryowner in memoryS1 - - -1 copy outno copies in- -no copy out1 copy inld: - / st:DP→DP ld / st: -owner in memory owner in memory owner in memory owner in memoryS - - - 1 copy outcopies incopies out (1 nest)copies incopies outcopies inno copy outcopies inld:- / st:BP→DP ld:- / st:BP→DP* ld:- / st:BP→BP ld:- / st:BP→Filteredowner in memoryI - - - - - - no copy in/outld / st: -StateEMOXOS1SXSITABLE IEHTA States of the EMC 2 -OXSX chip.DescriptionOnly the owner’s copy is cached outsi<strong>de</strong> the homenest. Other copies may be cached insi<strong>de</strong>.The owner’s copy is cached outsi<strong>de</strong> the home nest.Other copies may be cached either in the home nestor in the owner nest.The owner’s copy is cached outsi<strong>de</strong> the home nest.Other copies may be cached in any nest.At most one shared copy is cached outsi<strong>de</strong> the homenest.Only shared copies cached outsi<strong>de</strong> the home nest, allof them located in the same nest.Only shared copies cached outsi<strong>de</strong> the home nest.They can be located in any nest.No valid copy of the block cached outsi<strong>de</strong> the homenest.tra<strong>de</strong>-off, as we will discuss in Section V. First, TableI <strong>de</strong>scribes the possible EHTA states.Table II <strong>de</strong>picts the different scenarios that canappear <strong>de</strong>pending on the block state in both theEHTA and the HTA. For each combination, it showsa short <strong>de</strong>scription of how the block is cached andthe actions performed (if any) un<strong>de</strong>r load and storetransactions. The three possible actions are: (1) noaction, (2) turning a Broadcast Probe into a DirectedProbe, and (3) filtering a Broadcast Probe. Noticethat the bold actions entail a reduction in coherencetraffic. In this table, in/out refers to insi<strong>de</strong>/outsi<strong>de</strong>the home nest, and ld/st to load/store. DP* meansthat the BP turns into a DP, but only while the DPis transmitted between nests. However, when theDP reaches a nest, the DP is turned into a BP (onlyinsi<strong>de</strong> that nest).IV. Simulation EnvironmentWe evaluate our proposals with full-system simulationusing Virtutech Simics [7] exten<strong>de</strong>d with theWisconsin GEMS toolset [8], which enables <strong>de</strong>tailedsimulation of multiprocessor systems. For mo<strong>de</strong>lingthe interconnection network, we have used GARNET[9], a <strong>de</strong>tailed network simulator inclu<strong>de</strong>d in GEMS.Finally, we have also used the CACTI 5.3 tool [10],assuming a 45nm process technology, to measure thearea required by our proposals.For the evaluation of our proposals, we have firstimplemented the Magny-Cours cache coherence protocol.Then we have <strong>de</strong>signed and implementedTABLE IIISystem parameters.Memory ParametersProcessor frequencyCache block sizeAggregate L1+L2 cachesL3 cacheAverage cache access latency (L1+L2+L3)HT assist (probe filter)HT assist access latencyEMC 2 chip processing latencyMemory access latency (local bank)3.2 GHz64 bytes3MB, 4-way5MB, 16-way2ns1MB, 4-way4ns16ns100nsNetwork ParametersIntra-nest topologyFully-connectedInter-nest topologyHypercubeData message size68 or 72 bytesControl message size4 or 8 bytesHyperTransport bandwidth (16 bits, 6.4GT/s) 12.8GB/sInter-die link latency2nsInter-socket link latency20nsInfiniBand bandwidth (12x, 10Gb/s)12GB/sInter-nest communication (one way)150nsFlit size4 bytesLink bandwidth1 flit/cyclethe behavior and the architecture of three differentEMC 2 chips explained in Section III. We have runsimulations from 8 to 32 dies and with 1 and 2 coresper die. For the Magny-Cours (MC ) system we onlysimulate one nest with 8 dies. For the EMC 2 systemwe simulate 4 dies per nest (plus the EMC 2 chip).The parameters assumed for the systems evaluatedin this work are shown in Table III.We have evaluated our proposal with a severalscientific workloads from the SPLASH-2 benchmarksuite [11]: Barnes (16K particles), Cholesky (tk16),FMM (16K particles), Ocean (514×514 ocean) Raytrace(teapot) and Water-Sp (512 molecules). Allthe experimental results reported in this work correspondto the parallel phase of these benchmarks.V. Evaluation ResultsIn this section, we show how our proposals supportmore than 8 dies while scaling in terms of executiontime. Additionally, we compare the threebridge chips proposed in this paper in terms of networktraffic, cache miss latency, execution time, andarea requirements. Since the number of no<strong>de</strong>s ofthe evaluated configurations is not enough to fill theMST, we do not perform an evaluation of a systemthat employs the unused die i<strong>de</strong>ntifiers in the nest toincrease the number of available tags since it is notnecessary.<strong>JP2011</strong>-206


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Local: 28.6%Remote: 71.4%EM 5.9%OS1SIEM OX O S1 SX S I0.3% 0.2% 2.0%1.4% 0.9%EM 11.2% 5.6% 3.5% 0.8%0.0%0.5%0.3%7.9%0.0%0.0% 0.0% 1.9% 0.0%5.9%0.0%0.2%2.6% 0.0% 0.2% 1.9% 0.2% 0.5% 1.2%0.0% 0.0%0.0%0.0%0.0% 0.0% 0.0% 0.0%2.3%O 0.8% 1.2% 14.7% 0.7% 0.5% 2.3% 0.2% 2.4% 2.7% 7.2% 2.4% 0.3% 0.1% 0.0%S1SIRead: 63.7% Write: 36.3%EM OX O S1 SX S I0.0%0.0% 0.0% 0.0% 0.0%6.7%Fig. 4. Characterization of cache misses according to theHTA (vertical) and EHTA (horizontal) states, read/writemisses, and local/remote misses. Results show the averageof all the evaluated benchmarks. Crossed cells representimpossible combinations of states. The darker the colorof a cell is, the higher the miss percentage is. <strong>La</strong>rger cellsindicate that the EHTA is not reached, and therefore, thestate can be any one of those covered by the cell.A. Cache Miss CharacterizationFirst of all, it is important to characterize the applicationsin or<strong>de</strong>r to get an i<strong>de</strong>a of the percentage ofcache misses that can take advantage of the EHTAfiltering capabilities. Figure 4 shows this characterizationfor a 32-die system with the EMC 2 -OXSXchip, as a representative example (see Table II).Our EMC 2 chips can reduce network traffic onlywhen a write miss happens for a block in O or Sstates in the HTA (i.e., when a Broadcast Probe isreceived). On average for the consi<strong>de</strong>red applications,this happens for 21.7% of cache misses in a32-die configuration. Depending on the state in theEHTA, the EMC 2 chip can either filter the BroadcastProbe or convert it into a Directed Probe. Note thatfor the remaining misses, the HTA already filters theprobes.B. Network TrafficFor each Broadcast Probe issued by the homeno<strong>de</strong>, we show in Figure 5 the average number ofBroadcast/Directed Probes that arrive to the dies.This number is plotted for systems from 8 to 32 dies,with one core per die, and for the three EMC 2 chipsproposed and the base Magny-Cours system with 8dies. Without any filtering this number should be8, 16, and 32 for 8-, 16-, and 32-die systems, respectively.Since Magny-Cours does not filter BroadcastProbes (due to write misses), the average numberof probes arriving to a die is always 8. However,for the same system size our protocols reduce thisnumber by filtering some probes. Obviously, whenwe consi<strong>de</strong>r 8 dies (i.e., 2 nests), there is only oneremote nest, so all EMC 2 chips behave in the sameway. For larger systems, we can see that the more coherenceinformation the HTA stores, the more trafficit filters. Particularly, for a 32-die system we cansee that the average number of received probes isreduced by 23.6% (24.4/32), 49.7% (16.1/32), andAvg. probes received per BP2520151050MC_8EMC2-Base_8EMC2-OXSX_8EMC2-BitVector_8EMC2-Base_16EMC2-OXSX_16EMC2-BitVector_16EMC2-Base_32EMC2-OXSX_32EMC2-BitVector_32Barnes Cholesky FMM Ocean Radiosity Water-Sp AverageFig. 5. Number of probes received for each broadcast probesent by the home die.Normalized miss latency5.04.54.03.53.02.52.01.51.00.50.0MC_8EMC2-Base_8EMC2-OXSX_8EMC2-BitVector_8EMC2-Base_16EMC2-OXSX_16EMC2-BitVector_16EMC2-Base_32EMC2-OXSX_32EMC2-BitVector_32Barnes Cholesky FMM Ocean Radiosity Water-Sp AverageFig. 6.Normalized miss latency.61.6% (12.3/32) for EMC 2 -Base, EMC 2 -OXSX, andEMC 2 -BitVector, respectively.This reduction in the number of probes receivedby the dies has two consequences: (1) the number ofgenerated probe responses is also reduced, and (2)the network congestion and the coherence controllercongestion <strong>de</strong>creases. They lead to less time waitingfor Probe Responses, and therefore, shorter cachemiss latency, which will results in improvements inexecution time.C. Execution TimeAs we can see in Figure 6, cache miss latencyincreases when we move from MC 8 to EMC 2 8.This is because the latency for transmitting messagesamong nests is higher than among dies. While inMC 8 there are 8 dies in the same nest, in EMC 2 8the 8 dies are distributed in two nests.On the other hand, when we consi<strong>de</strong>r a largersystem, the cache miss latency increases. Nevertheless,we reduce the final execution time becausethe applications can be distributed among more dieswhich consi<strong>de</strong>rably reduces the workload of each die.Finally, we can observe the reduction in averagecache miss latency achieved for some EMC 2 chipsfor the 32die configuration. Compared to EMC 2 -Base, EMC 2 -OXSX reduces the average miss latencyby 3.7%, and EMC 2 -BitVector by 5.0%. As we canobserve, this percentage is expected to increase forlarger scale configurations. These reductions in cachemiss latency finally translate into improvements inexecution time.Figure 7 shows the normalized execution timewhen we increase the number of dies. We can seethat, although for the 8-die configuration our proposalsbehave worse than MC 8 (due to the internestlatency), when we extend the coherence domainthrough the bridge chip and allow a higher numberof no<strong>de</strong>s, the execution time of the applications issignificantly reduced. Particularly, EMC 2 -OXSX 32and EMC 2 -BitVector 32 improve MC by 47% on average.Comparing the three proposals in a 32-diesystem, EMC 2 -OXSX and EMC 2 -BitVector obtainsimilar execution time and slightly improve EMC 2 -Base (≈4%).<strong>JP2011</strong>-207


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Normalized execution time1.41.21.00.80.60.40.20.0MC_8EMC2-Base_8EMC2-OXSX_8EMC2-BitVector_8EMC2-Base_16EMC2-OXSX_16EMC2-BitVector_16EMC2-Base_32EMC2-OXSX_32EMC2-BitVector_32Barnes Cholesky FMM Ocean Radiosity Water-Sp AverageFig. 7.Normalized execution time.TABLE IVSize of the different bridge chips for 32-die systems.Struct Entries Assoc Entry size AreaETT 128 1 540 bits 0.64mm 2MST 32 1 607 bits 0.23mm 2EMC 2 -Base EHTA 1M 16 tag + 8 bits 25.72mm 2EMC 2 -OXSX EHTA 1M 16 tag + 9 bits 25.97mm 2EMC 2 -BitVec EHTA 1M 16 tag + 15 bits 33.38mm 2D. Area RequirementsThe different EMC 2 chips cover a wi<strong>de</strong> tra<strong>de</strong>-offbetween memory requirements and filtered traffic.This section studies the area of these chips and theirtra<strong>de</strong>-offs for a 32-die configuration.The three chips differ in the size of the EHTA.Its sizes and those of the ETT and MST are <strong>de</strong>scribedin Table IV. The EHTA of the EMC 2 -Baseis the one that less bits needs per entry (the tag plus8 bits including state, owner die, and owner nest).The EHTA of the EMC 2 -OXSX needs an extra bitfor codifying the two additional states. Finally, theEHTA of the EMC 2 -BitVector needs seven extra bitsfor storing the vector of remote nests.Figure 8 plots the tra<strong>de</strong>-off of these three chips interms of network traffic and area requirements. Thetotal area of each chip has been calculated by addingthe areas (in mm 2 ) of the three data structurespresented in the chip (without consi<strong>de</strong>ring controllogic). The normalized network traffic correspondsto the average number of flits transmitted by eachswitch in the whole system for the six benchmarksevaluated in this work, and normalized to EMC 2 -Base. We can observe that, EMC 2 -OXSX reducesthe traffic by 10.6% compared to EMC 2 -Base, whileEMC 2 -BitVector reduces the traffic by 15%. Moreover,the area of EMC 2 -OXSX is very close to thearea of EMC 2 -Base. Therefore, we can conclu<strong>de</strong> thatEMC 2 -OXSX achieves a good compromise betweennetwork traffic and area requirements.VI. ConclusionsIn this paper, we have exten<strong>de</strong>d by an externallogic (EMC 2 chip) the coherence domain of the AMDMagny-Cours processors beyond the 8-die limit imposedby both the cHT specification and the ownerfield of the HTA. The proposed chip not only maintainsthe HTA capability to filter the coherence trafficover the entire system, but also filters additionaltraffic, which provi<strong>de</strong>s the scalability required tobuild large-scale servers. Evaluation results for up toa 32-no<strong>de</strong> system show how the runtime of the applicationsscales with the number of no<strong>de</strong>s, reducing theapplication runtime by 47% on average (compared tothe 8-die Magny-Cours system).Normalized network trafficFig. 8.1.00.95EMC0.9EMC-OXSX0.85EMC-BitVector0.825 26 27 28 29 30 31 32 33 34 35Area required (mm2)Traffic-area tra<strong>de</strong>-off for a 32-die system.We have proposed and analyzed three EMC 2 chipconfigurations able to provi<strong>de</strong> different tra<strong>de</strong>offs betweenfiltered network traffic and required siliconarea. Particularly in a 32-die system, EMC 2 -OXSXachieves a good compromise between network traffic(10.6% of traffic reduction compared to EMC 2 -Base)and reducing area requirements (22.2% of area reductioncompared to EMC 2 -BitVector).AcknowledgementsThis work has been supported by Generalitat Valencianaun<strong>de</strong>r Grant PROMETEO/2008/060, bySpanish Ministry of Ciencia e Innovación un<strong>de</strong>r grant“TIN2009-14475-C04-02”, and by European ComissionFEDER funds un<strong>de</strong>r grant “Consoli<strong>de</strong>r Ingenio-2010 CSD2006-00046”.References[1] Pat Conway, Nathan Kalyanasundharam, Gregg Donley,Kevin Lepak, and Bill Hughes, “Cache hierarchyand memory subsystem of the AMD opteron processor,”IEEE Micro, vol. 30, no. 2, pp. 16–29, Apr. 2010.[2] Patrick Conway, “Computer system with integrated directoryand processor cache,” U.S. Patent 6868485, Mar.2005.[3] SGI, “Technical advances in the SGI Altix UV architecture,”whitepaper, 2009.[4] Jose Duato, Fe<strong>de</strong>rico Silla, Sudhakar Yalamanchili, BrianHol<strong>de</strong>n, Paul Miranda, Jeff Un<strong>de</strong>rhill, Mario Cavalli, andUlrich Brüning, “Extending HyperTransport protocol forimproved scalability,” in 1st Int’l Workshop on Hyper-Transport Research and Applications (WHTRA), Feb.2009, pp. 46–53.[5] Jonathan M. Owen, Mark D. Hummel, Derrick R. Meyer,and James B. Keller, “System and method of maintainingcoherency in a distributed communication system,” U.S.Patent 7069361, June 2006.[6] Anant Agarwal, Richard Simoni, John L. Hennessy, andMark A. Horowitz, “An evaluation of directory schemesfor cache coherence,” in 15th Int’l Symp. on ComputerArchitecture (ISCA), May 1988, pp. 280–289.[7] Peter S. Magnusson, Magnus Christensson, and JesperEskilson, et al, “Simics: A full system simulation platform,”IEEE Computer, vol. 35, no. 2, pp. 50–58, Feb.2002.[8] Milo M.K. Martin, Daniel J. Sorin, and Bradford M.Beckmann, et al, “Multifacet’s general execution-drivenmultiprocessor simulator (GEMS) toolset,” ComputerArchitecture News, vol. 33, no. 4, pp. 92–99, Sept. 2005.[9] Niket Agarwal, Tushar Krishna, Li-Shiuan Peh, and NirajK. Jha, “GARNET: A <strong>de</strong>tailed on-chip networkmo<strong>de</strong>l insi<strong>de</strong> a full-system simulator,” in IEEE Int’lSymp. on Performance Analysis of Systems and Software(ISPASS), Apr. 2009, pp. 33–42.[10] Shyamkumar Thoziyoor, Naveen Muralimanohar,Jung Ho Ahn, and Norman P. Jouppi, “Cacti 5.1,”Tech. Rep. HPL-2008-20, HP <strong>La</strong>bs, Apr. 2008.[11] Steven Cameron Woo, Moriyoshi Ohara, Evan Torrie,Jaswin<strong>de</strong>r Pal Singh, and Anoop Gupta, “The SPLASH-2 programs: Characterization and methodological consi<strong>de</strong>rations,”in 22nd Int’l Symp. on Computer Architecture(ISCA), June 1995, pp. 24–36.<strong>JP2011</strong>-208


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Efficient hardware support for locksynchronization in Many-core CMPsJosé L. Abellán, Juan Fernán<strong>de</strong>z y Manuel E. Acacio 1Abstract—Synchronization is of paramount importance to exploitthread-level parallelism on many-core CMPs.In these architectures, synchronization mechanismsusually rely on shared variables to coordinate multithrea<strong>de</strong>daccess to shared data structures thus avoidingdata <strong>de</strong>pen<strong>de</strong>ncy conflicts. Lock synchronizationis known to be a key limitation to performance andscalability. On the one hand, lock acquisition throughbusy waiting on shared variables generates additionalcoherence activity which interferes with applications.On the other hand, lock contention causes serializationwhich results in performance <strong>de</strong>gradation. Thispaper proposes and evaluates GLocks, a hardwaresupportedimplementation for highly-conten<strong>de</strong>d locksin the context of many-core CMPs. GLocks use atoken-based message-passing protocol over a <strong>de</strong>dicatednetwork built on state-of-the-art technology.This approach skips the memory hierarchy to provi<strong>de</strong>a non-intrusive, extremely efficient and fair lockimplementation with negligible impact on energy consumptionor die area. A comprehensive comparisonagainst the most efficient shared-memory-based lockimplementation for a set of microbenchmarks and realapplications quantifies the goodness of GLocks. Performanceresults show an average reduction of 42%and 14% in execution time, an average reduction of76% and 23% in network traffic, and also an averagereduction of 78% and 28% in energy-<strong>de</strong>lay 2 product(ED 2 P) metric for the full CMP for the microbenchmarksand the real applications, respectively. In lightof our performance results, we can conclu<strong>de</strong> thatGLocks satisfy our initial working hypothesis. GLocksminimize cache-coherence network traffic due to locksynchronization which translates into reduced powerconsumption and execution time.Keywords— Many-core CMP, lock synchronization,global line.I. Introduction and MotivationWHILE the number of cores currently offeredin general-purpose CMPs has already goneabove ten (e.g., the 12-core 2-die AMD’s Magny-Cours <strong>de</strong>sign [1]), the well-known Moore’s <strong>La</strong>w statesthat soon there will be available on-chip the resourcesrequired to integrate dozens of cores or even hundredsof them. CMPs of this kind are commonlyreferred to as many-core CMPs. For instance, the experimentalresearch microprocessor: 48-core SinglechipCloud Computer [2].If current trends continue, future many-coreCMP architectures will implement the hardwaremanaged,implicitly-addressed, coherent cachesmemory mo<strong>de</strong>l [3]. With this memory mo<strong>de</strong>l, allon-chip storage is used for private and shared cachesthat are kept coherent by hardware. Communicationbetween threads is performed by writing to andreading from shared memory. In or<strong>de</strong>r to guarantee1 Departamento <strong>de</strong> Ingeniería y Tecnología <strong>de</strong>Computadores, <strong>Universidad</strong> <strong>de</strong> Murcia, e-mail:{jl.abellan,juanf,meacacio}@ditec.um.esFig. 1. Potential benefits for Raytrace when using i<strong>de</strong>al locks.the integrity of shared data structures, most currentsystems support synchronization through a combinationof hardware (such as atomic read-modify-writeinstructions like test&set) and software (higher-levelmechanisms such as locks or barriers implementedatop the un<strong>de</strong>rlying hardware primitives) [4]. In thisway, implementations of locks usually rely on sharedvariables which are atomically updated.The use of shared variables for lock synchronizationhas two important implications for performanceand scalability in many-core CMPs. First, the cachecoherence protocol must come into play in or<strong>de</strong>r tomaintain the consistency of shared variables acrossall levels of the memory hierarchy. Coherence activitytranslates into traffic injection in the interconnectionnetwork. As a result, an ever-growingamount of resources may need to be <strong>de</strong>voted to supportlock synchronization as the number of coresin many-core CMPs increases. Moreover, lock acquisitionand release operations timing is <strong>de</strong>eply affectedby the performance and scalability of the cachecoherence protocol especially un<strong>de</strong>r the presence ofhighly-conten<strong>de</strong>d locks. Second, lock contention haslong been recognized as a key impediment to performanceand scalability since it causes serialization [5].Consequently, the longer the idle time spent on lockacquisition and release operations, the larger the parallelefficiency reduction.As an evi<strong>de</strong>nce, we show in Figure 1 the potentialbenefits to performance when lock synchronizationsdo not involve the cache coherence protocol andhave zero latency. To do that, the Raytrace applicationfrom the SPLASH-2 benchmark suite [6] isrun by using distinct lock implementations (for <strong>de</strong>tailsabout the evaluation see Section III). In eachcase, we highlight in gray the fraction of the executiontime due to the locks. Shared-memory-basedlocks use test-and-test&set (see TATAS bar inFigure 1). In turn, i<strong>de</strong>al locks (see IDEAL bar in Figure1) do not <strong>de</strong>al with the cache coherence protocolto eliminate any inherited performance or scalabilitysi<strong>de</strong> effect. Besi<strong>de</strong>s, lock acquisition and release<strong>JP2011</strong>-209


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011operations take a single clock cycle each to minimizeserialization due to contention. As expected, i<strong>de</strong>allocks clearly outperform shared-memory-based lockssince the lock acquisition and release operations accountfor a significant fraction of the execution timein Raytrace. However, a post-mortem analysis ofRaytrace lock usage reveals that only 2 out of its 34locks are highly-conten<strong>de</strong>d. In this sense, if all thelocks other than the highly-conten<strong>de</strong>d ones are implementedusing regular shared-memory-based locks,a reduction in the execution time similar to that ofi<strong>de</strong>al locks is obtained (see TATAS-1 and TATAS-2bars 1 in Figure 1). The latter result suggests thatonly highly-conten<strong>de</strong>d locks can truly benefit from amore efficient lock implementation.In this paper, we present and evaluate a newlock synchronization mechanism aimed at acceleratinghighly-conten<strong>de</strong>d locks. Our proposal, namelyGLocks, leverages existing global lines technology [7]to <strong>de</strong>ploy a <strong>de</strong>dicated on-chip global-line-based network.To show the benefits <strong>de</strong>rived from GLocks,we evaluate the performance of several microbenchmarksand real applications from the SPLASH-2benchmark suite [6] on a 32-core CMP simulator [8].Performance results show an average reduction of42% and 14% in execution time for the microbenchmarksand the real applications, respectively. Inaddition, they exhibit an average reduction of 76%and 23% in network traffic, for the microbenchmarksand the real applications respectively, given the factthat GLocks do not <strong>de</strong>al with the main data network.This traffic reduction also leads to an averagereduction of 78% and 28% in energy-<strong>de</strong>lay 2 product(ED 2 P) metric for the full CMP, for the microbenchmarksand the real applications, respectively.The rest of the paper is organized as follows. Wepresent GLocks in Section II. Section III <strong>de</strong>scribesour simulation environment and analyzes the performancebenefits <strong>de</strong>rived from GLocks. Finally, SectionIV presents the main conclusions of our work.II. The GLocks MechanismIn this section, we present our proposal to buildan efficient synchronization mechanism for highlyconten<strong>de</strong>dlocks in many-core CMPs.A. G-line-based NetworkThe GLocks mechanism proposed in this work relieson a G-line-based network as can be observedin the example in Figure 2. For simplicity, we concentrateon a version of the proposed network providingsupport for one lock. As can be observed, theG-line-based network is ma<strong>de</strong> up of two kind of components.G-lines (horizontal and vertical finer blacklines), that are used to transmit the signals requiredby the synchronization protocol; and controllers (R,Sx and Cx), that actually implement the synchronizationprotocol.1 TATAS-X means that one (X=1) or two (X=2) of thehighly-conten<strong>de</strong>d locks have been implemented as i<strong>de</strong>al locks.Fig. 2. GLocks architecture for a 9-core CMP with a 2D-meshnetwork.On the one hand, every G-line is a wire that enablesthe transmission of 1 bit of information acrossone dimension of the chip in a single cycle. In thisway, the G-line-based network employs one G-lineper transmitter and lock. Every G-line will be usedto request the associated lock and grant lock acquisitions.In this way, for any 2D-mesh layout the totalnumber of G-lines per lock that would be nee<strong>de</strong>d isequal to C − 1, where C is the number of cores ofthe CMP (e.g. 8 G-lines for the 9-core CMP shownin Figure 2).On the other hand, we distinguish two types ofcontrollers: the local controllers (Cx in Figure 2)and the lock managers (R and Sx in Figure 2).The local controllers send and receive signals toand from their corresponding lock managers throughtheir <strong>de</strong>dicated G-lines (e.g. C1 sends and receivessignals to/from S1). The exception is when the localcontroller is located in the same core as its associatedlock manager. In this case, the functionality of thelocal controller is encapsulated in the lock manager,and communication is performed locally by meansof a flag. For example, S1 monitors not only signalsfrom local controllers 1 and 2 (C1, C2) through theircorresponding G-lines, but also from the local corethrough an internal flag (for clarity, this flag is notshown in Figure 2).Finally, to have a clear un<strong>de</strong>rstanding of our proposal,we represent the architecture <strong>de</strong>scribed aboveas the hierarchy shown in Figure 3. In particular, theG-line-based network that our proposal is based oncan be represented as a three-level hierarchy. Theroot of the hierarchy is the primary lock manager.The secondary lock managers would be located atthe intermediate no<strong>de</strong>s. Finally, the leaves of thehierarchy would be the processor cores (with the localcontrollers). All elements are connected usingG-lines (continuous lines) or locally by means of aninternal flag (dashed lines). The flags (fx and fSx)store the signals sent by the controllers to the correspondinglock manager (primary and secondary). Inthis way, we need flags not only to store the signalssent between Sx and the local controllers (one flagper Cx controller: f1 for C1, f2 for C2, etc.), butalso to store the signals transmitted between R andSx (one flag per Sx controller: fS1 for S1, fS2 forS2, etc.).<strong>JP2011</strong>-210


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 3. Logical view of the G-line-based network for a 9-coreCMP with a 2D-mesh network.(a) All cores request the lock at the same time (cycle 1).B. Synchronization ProtocolThe synchronization protocol implemented on topof the G-line-based network previously <strong>de</strong>scribed isbased on the exchange of 1-bit messages (signals)between the local controllers and the lock managers.More specifically, the protocol uses three types ofsignals to perform a lock synchronization. The REQand REL signals, which are sent from the local controllersto their corresponding lock manager to askfor the lock and to release the lock, respectively; andthe TOKEN signal which is sent from a lock managerto a particular local controller to grant access to alock. In addition, these signals are also transmittedbetween primary and secondary lock managers in alock synchronization. In particular, the secondarylock managers ask for the lock by sending the REQsignal to the primary lock manager and receive authorizationfrom the latter through the TOKEN signal.Similarly, after the lock is released, a secondarylock manager notifies the primary one by means ofthe REL signal.Lock managers (both the primary and secondaryones) use a round-robin strategy to grant the lockamong those processor cores which are competingfor becoming the next owner. Let’s assume that allof the cores in Figure 3 send the REQ signal to theircorresponding secondary lock manager at the sametime. In this case, the TOKEN signal granting thelock would be received by Core0 first; then, onceCore0 has released the lock, Core1 would becomethe next hol<strong>de</strong>r; and so on, until Core8 is reached.Next, the process would start again from Core0 ifthere are additional pending lock requests. Since theGLocks mechanism is aimed at accelerating highlyconten<strong>de</strong>dlocks we do not expect that the election ofthe strategy to grant the lock in these situations willhave an impact on performance. However, this is akey <strong>de</strong>sign point to ensure the fairness expected froma lock implementation [4]. The latter is the reasonwhy we use the round-robin strategy.As an example of how the synchronization protocolworks, Figure 4 presents the case where the 9 coresof the CMP <strong>de</strong>picted in Figure 2 try to get access tothe lock at the same time. To clarify the explanation,the arrows in the figure mark the sense of thetransmissions. Moreover, each arrow is labeled withthe cycle in which communication occurs, startingwith cycle 1. Finally, we highlight with dark grey(b) Lock is granted to Core0 (cycle 4).(c) Core0 releases the lock (cycle m) and S1 <strong>de</strong>signates Core1to be the next lock hol<strong>de</strong>r (cycle m+1 ).(d) Core2 releases the lock (cycle p) and S2 <strong>de</strong>signates Core3to be the next lock hol<strong>de</strong>r (cycle p+3 ).Fig. 4. Example of lock synchronization un<strong>de</strong>r the GLocksmechanism.the flags that are written and the core that acquiresthe lock in each case.At cycle 0, all cores try to get the lock (see Figure4(a)). To do this, every local controller (Cx inthe figure) sends the REQ signal at cycle 1 to thecorresponding secondary lock manager (Sx in thefigure). As a result, all fx flags would be written,and each Cx would be busy-waiting until the TO-KEN signal is received. At cycle 2, once each Sx<strong>de</strong>tects that at least one of its fi flags has been written,REQ signals towards the primary lock manager(R in the figure) are sent in or<strong>de</strong>r to write the correspondingfSx flags. At this moment, R must makea <strong>de</strong>cision about the secondary lock manager thatwill be granted the lock ownership. This process is<strong>JP2011</strong>-211


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLE ICMP baseline configuration.Number of cores 32CoreCache line sizeL1 I/D-CacheL2 Cache (per core)Memory access timeNetwork configurationNetwork bandwidthLink widthTechnology3GHz, in-or<strong>de</strong>r 2-way64 Bytes32KB, 4-way, 2 cycles256KB, 4-way, 12+4 cycles400 cycles2D-mesh75 GB/s75 bytes45 nmshown in Figure 4(b). In this case, R would chooseS1 by following the round-robin scheduling policy alreadydiscussed and would send the TOKEN signalat cycle 3. At cycle 4 and based on the round-robinpolicy, S1 chooses Core0 and sends the TOKEN signalgranting access to the lock. Figure 4(c) showsthe scenario in which an Sx can grant the lock ownershipwithout involving any additional notificationsto R. More specifically, once Core0 releases the lockat cycle m, its controller sends the REL signal (bywriting to the local f0 flag, as we mentioned) to S1.Next, at cycle m + 1, S1 grants the lock ownership(by means of the TOKEN signal) to the next coreby following the round-robin policy from the activefx flags. In this case, Core1 becomes the new lockhol<strong>de</strong>r. In the same way, Core2 would be grantedthe lock in cycle n + 1 (m < n). Finally, in Figure4(d) we illustrate the scenario when an S finishesits scheduling because either it has reached the lastactive f or there are no more pending local requestsfor the lock. In this case, S must send the REL signaltowards R, which will choose another availableSj lock manager from those that activated the fSxflags. In the figure, S1 sends the REL signal to R atcycle p + 1 (n < p), which following the round-robinpolicy grants the lock to S2. Finally, S2 sends theTOKEN signal giving access to the lock to Core3 atcycle p + 3.III. EvaluationIn this section we give <strong>de</strong>tails of our experimentalmethodology and performance results.A. TestbedIn or<strong>de</strong>r to support GLocks, the Sim-PowerCMP [8] performance simulator has beenexten<strong>de</strong>d. Sim-PowerCMP is a <strong>de</strong>tailed architecturelevelpower-performance simulation tool that simulatestiled-CMP architectures with a shared L2cache on-chip and a MESI directory-based cachecoherence protocol. Table I summarizes the valuesof the main configurable parameters assumed in thiswork.B. BenchmarksTo evaluate the performance benefits <strong>de</strong>rived fromGLocks, five microbenchmarks and three scientificapplications are used. On the one hand, the microbenchmarks(SCTR, MCTR, DBLL, PRCO andACTR) exhibit different highly-conten<strong>de</strong>d accesspatterns to shared data that can be commonly foundin parallel applications. To implement the microbenchmarkswe follow a methodology similar tothe one used in [9]. On the other hand, regardingreal applications, we have consi<strong>de</strong>red two programsbelonging to the SPLASH-2 benchmark suite [6](Ocean and Raytrace), and a well-known sorting algorithm(QSORT). These applications were chosensince they present a significant lock synchronizationoverhead due to the existence of highly-conten<strong>de</strong>dlocks 2 . In fact, these locks are accessed followingsimilar patterns to those of the microbenchmarks.We summarize the characteristics of the microbenchmarksand applications used in this work in Table II.For each of them we account for the input size, thetotal number of different locks, the number of theselocks that are highly-conten<strong>de</strong>d (H-C Locks), andpoint out the highly-conten<strong>de</strong>d lock access patternsin terms of the microbenchmarks they are similar to.C. Lock ImplementationsTo fairly quantify the benefits of our GLocks mechanism,we consi<strong>de</strong>r the case that highly-conten<strong>de</strong>dlocks found in the benchmarks previously <strong>de</strong>scribedare implemented by using MCS Locks. We use MCSLocks because they are consi<strong>de</strong>red one of the mostefficient software algorithms for lock synchronizationun<strong>de</strong>r high contention. In particular, MCSLocks gracefully manage high-contention situationsby having a distributed queue of waiting lock requesters.On the other hand, for the rest of locks(non-conten<strong>de</strong>d ones), we employ the Simple Lock algorithmenhanced with the test-and-test&set optimizationdue to it has been shown to lead to lowerlatencies when threads try to acquire a lock withoutcompetition. Finally, since the number of highlyconten<strong>de</strong>dlocks is commonly very small in real applications(up to 2 in the applications evaluated inthis work), we assume that two GLocks are provi<strong>de</strong>dat hardware level. We would like to point out thatto <strong>de</strong>termine the contention of locks, we performed apost-mortem analysis of the benchmarks un<strong>de</strong>r studywhere locks use the Simple Lock algorithm enhancedwith the test-and-test&set optimization. For further<strong>de</strong>tails of this analysis we refer to [10].D. Performance ResultsIn this section, we evaluate the performance benefits<strong>de</strong>rived from our GLocks mechanism.D.1 Execution TimeFigure 5 shows the execution times that are obtainedfor the set of benchmarks un<strong>de</strong>r study wheneither GLocks or MCS Locks are employed for thehighly-conten<strong>de</strong>d locks (GL bars and MCS bars respectively).In particular, execution times have been2 In this work, highly-conten<strong>de</strong>d locks are those locks accessedby all threads simultaneously or very close in time.<strong>JP2011</strong>-212


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLE IIConfiguration of the benchmarks and lock-related characteristics.Benchmark Input Size Locks H-C Locks Access PatternSCTR 1,000 iterations 1 1 -MCTR 1,000 iterations 1 1 -DBLL 1,000 iterations 1 1 -PRCO 1,000 iterations 1 1 -ACTR 1,000 iterations 2 2 -RAYTR teapot 34 2 SCTROCEAN 258x258 ocean 3 1 SCTRQSORT 16384 elements 1 1 PRCOFig. 5.Normalized Execution Time.normalized with respect to those obtained whenMCS Locks are used. Additionally, each bar showsthe fraction of the execution time due to lock andbarrier synchronizations (Lock and Barrier categoriesrespectively), memory accesses (Memory category)and computation (Busy category). Finally,average execution times are shown in separate barsfor the microbenchmarks (AvgM ) and applications(AvgA).Regarding the microbenchmarks, we can observethat our proposal presents an average reduction of42% in execution time (see AvgM ). On other hand,the fraction of the execution time that lock synchronizationconsumes is lower when real applications areconsi<strong>de</strong>red (14% on average). In these cases, mostof the time is spent on computations and memoryaccesses (Busy and Memory categories). The exactextent of the reduction in each case <strong>de</strong>pends onboth: the number of highly-conten<strong>de</strong>d locks thateach microbenchmark has (see Table II), and alsothe contention rates exhibited by each lock. In more<strong>de</strong>pth, the time taken to acquire and release the lockis drastically reduced as <strong>de</strong>rived from the improvementsshown in the Lock category. And second, thefact that our proposal removes from the main datanetwork all extra coherence traffic that a sharedmemory-basedlock implementation would introduce,also has effect on the Barrier category for the ACTRmicrobenchmark.D.2 Network TrafficOur proposal does not generate any coherencemessages on the main data network when perform-Fig. 6.Normalized Network Traffic.ing lock synchronizations. At the end, this translatesinto significant reductions in terms of network traffic.Figure 6 shows the total network traffic acrossthe main data network. In particular, each bar plotsthe number of bytes transmitted through the interconnectionnetwork (the total number of bytes transmittedby all the switches of the interconnect) normalizedwith respect to the MCS case. Each bar isbroken down into three categories: Coherence correspondsto the messages generated by the cache coherenceprotocol (e.g. invalidations and Cache-to-Cachetransfers); Request comprehends messages generatedwhen load and store instructions miss in cache andmust access a remote directory; and finally, Replyinvolves the messages with data.For the microbenchmarks, important reductions innetwork traffic are achieved (76% on average). Onthe other hand, the scientific applications exhibitlower reductions in network traffic (23% on average).These network traffic reductions stem from the fractionof the execution time <strong>de</strong>voted to lock synchronizationand the amount of network traffic that issaved. For instance, Ocean presents the lowest reductionin network traffic since less than 5% of itsexecution time (see Figure 5) is spent on locks.D.3 Energy EfficiencyFinally, we also consi<strong>de</strong>r the benefits in energy efficiencythat our proposal entails. More specifically,we present in Figure 7 the normalized energy-<strong>de</strong>lay 2product (ED 2 P) metric for the full CMP. To accountfor the energy consumed by the GLocks architecture(the G-lines-based network <strong>de</strong>scribed in Section II-<strong>JP2011</strong>-213


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 7. Normalized energy-<strong>de</strong>lay 2 product (ED 2 P) metric forthe full CMP.A), we extend the Sim-PowerCMP with the consumptionmo<strong>de</strong>l of G-lines and controllers employedin [11].As in the previous two sections, all results in Figure7 have been normalized with respect to the MCScase. As it can be observed, important improvementsin the ED 2 P metric of the whole CMP areachieved when applying our proposal. In particular,the GLocks mechanism brings average improvementsin ED 2 P of 78% and 28% for the microbenchmarksand real applications, respectively. In general, themagnitu<strong>de</strong> of these savings is directly related to theextents of the improvements in execution time andnetwork traffic previously reported. In more <strong>de</strong>pth,GLocks employ less number of instructions executedper lock acquisition and release operation than MCSLocks, since the latter must <strong>de</strong>al with a distributedqueue of waiting threads requesting the lock, Obviously,less instructions executed means less energyconsumed in the processor cores. Moreover, since wereduce the latency of lock acquisitions, the busy-waitprocess is also shortened with GLocks. Finally, giventhe fact that our proposal skips the memory hierarchy,we save all the energy <strong>de</strong>rived from coherenceactivity when locks are executed. In particular, weremove all of the L1 cache misses related to lock operationsand the corresponding messages transferredacross the interconnect. This brings reductions inthe energy consumed at the L2 cache banks and theinterconnection network.IV. ConclusionsLock contention is recognized as a key constraintto performance and scalability on many-coreCMPs when trying to exploit thread-level parallelism.In this paper we have proposed GLocks, anew hardware-supported implementation for highlyconten<strong>de</strong>dlocks. GLocks <strong>de</strong>ploys a <strong>de</strong>dicated on-chipnetwork built with existing technology with minimalimpact on energy consumption or die area. The useof a token-based messaging-protocol atop this networkprovi<strong>de</strong>s an extremely efficient and completelyfair behavior. Performance results obtained on a simulated32-core CMP with a 2D-mesh data networkfor a set of microbenchmarks and real applicationscorroborate our statements. An average reduction of42% and 14% in execution time, an average reductionof 76% and 23% in network traffic, and an averagereduction of 78% and 28% in the energy-<strong>de</strong>lay 2 product(ED 2 P) metric for the full CMP are achieved, forthe microbenchmarks and the real applications, respectively.As future work, we plan to complete this studyby extending the applicability of GLocks. First,since the current G-line-based network <strong>de</strong>sign limitsthe maximum size of the CMP, it becomes necessaryto somehow extend the mechanism to supportlarger CMPs. To do this, there are two possiblepaths to explore: a hierarchical G-line-basednetwork and longer G-line latencies. Finally, thecurrent GLocks mechanism does not consi<strong>de</strong>r multiprogrammedworkloads. To <strong>de</strong>al with them, a fewGLocks could be statically or dynamically sharedamong all of the workloads.AcknowledgmentsThis work was supported by the Spanish MEC andMICINN, as well as European Comission FEDER funds, un<strong>de</strong>rGrants “CSD2006-00046” and “TIN2009-14475-C04”. José L.Abellán is supported by fellowship 12461/FPI/09 from FundaciónSéneca - Agencia <strong>de</strong> Ciencia y Tecnología <strong>de</strong> la Región<strong>de</strong> Murcia (II PCTRM 2007-2010). Finally, we would like tothank Fabrizio Petrini for his invaluable contribution at theearly stage of this work.References[1] P. Conway, “Bla<strong>de</strong> Computing with the AMD Magny-Cours Processor,” in Proceedings of the 21 st Symposiumon High Performance Chips, 2009.[2] Single-chip Cloud Computer. [Online]. Available:http://techresearch.intel.com/articles/Tera-Scale/1826.htm[3] J. L. et al., “Comparing Memory Systems for Chip Multiprocessors,”ACM SIGARCH Computer ArchitectureNews, vol. 35(2), pp. 358–368, 2007.[4] D. E. C. et al., Parallel Computer Architecture: A Hardware/SoftwareApproach. Morgan Kaufmann, 1998.[5] N. R. T. et al., “Analyzing Lock Contention in Multithrea<strong>de</strong>dApplications,” in Proceedings of 15 th ACMSIGPLAN Symposium on Principles and Practice ofParallel Programming, 2010.[6] S. C. W. et al., “The SPLASH-2 Programs: Characterizationand Methodological Consi<strong>de</strong>rations,” in Proceedingsof 22 nd International Symposium on Computer Architecture,1995.[7] R. C. et al., “Near Speed-of-Light Signaling over On-ChipElectrical Interconnects,” IEEE Journal of Solid StateCircuits, vol. 38(5), pp. 834–838, 2003.[8] A. F. et al., “Sim-PowerCMP: A Detailed Simulator forEnergy Consumption Analysis in Future Embed<strong>de</strong>d CMPArchitectures,” in Proceedings of 21 st International Conferenceon Advanced Information Networking and ApplicationsWorkshops, 2007.[9] R. R. et al., “Transactional Lock-free Execution of LockbasedPrograms,” in Proceedings of 10 th Annual Conferenceon Architectural Support for Programming <strong>La</strong>nguagesand Operating Systems, 2002.[10] J. L. A. et al., “GLocks: Efficient Support for Highly-Conten<strong>de</strong>d Locks in Many-Core CMPs,” in Proceedingsof the 25 th IEEE International Parallel & DistributedProcessing Symposium, 2011.[11] T. K. et al., “NoC with Near-I<strong>de</strong>al Express Virtual Channelsusing Global-Line Communication,” in Proceedingsof 16 th IEEE Symposium on High Performance Interconnects,2008.<strong>JP2011</strong>-214


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011A Cooperative and Scalable Built-In Self-TestArchitecture for NoCsC. Gómez, M.E. Gómez, P. López, J. Duato 1 , A. Strano, D. Ludovici, M. Favalli, D. Bertozzi 2Abstract— This paper proposes a built-in self-test/self-diagnosisprocedure at start-up of an on-chip network (NoC). ConcurrentBIST operations are carried out after reset at each switch, thus resultingin scalable test application time with network size. The keyprinciple consists of exploiting the inherent structural redundancyof the NoC architecture in a cooperative way, thus <strong>de</strong>tecting faultsin test pattern generators too. At-speed testing of stuck-at faultscan be performed in less than 1200 cycles regardless of their size,with an hardware overhead of less than 11%.Keywords—Network-on-Chip, Test Pattern Generation.I. INTRODUCTIONNoCs are rapidly becoming the reference communicationfabric for multi-core computing platforms both inhigh-performance processors and in many embed<strong>de</strong>d systems[7], [3]. As the integration <strong>de</strong>nsities and the uncertaintiesin the manufacturing process keep increasing,complementing NoCs with efficient test mechanisms becomesa key requirement to cope with high <strong>de</strong>fect rates[6], [11]. Above all, the NoC testing infrastructure shouldnot be conceived in isolation, but should be coherently integratedinto a reliability framework taking care of fault<strong>de</strong>tection, diagnosis and network reconfiguration and recoveryto preserve yield [9].Moreover, wear-out mechanisms such as oxi<strong>de</strong> breakdown,electro-migration and mechanical/thermal stressbecome more prominent in aggressively scaled technologyno<strong>de</strong>s. These breakdown mechanisms occur overtime, therefore the methodology and the infrastructureused for production testing should be <strong>de</strong>signed for re-useduring the system lifetime as well, thus enabling graceful<strong>de</strong>gradation of the NoC over time.The <strong>de</strong>tection and i<strong>de</strong>ntification of failures is the foundationof any reliability framework. Unfortunately, <strong>de</strong>velopingsuch a testing infrastructure for a NoC is a seriouschallenge. The controllability/observability of NoClinks and sub-blocks is relatively reduced, due to the factthat they are <strong>de</strong>eply embed<strong>de</strong>d and spread across the chip.Also, pin-count limitations restrict the use of I/O pins<strong>de</strong>dicated for the test of the different NoC components.A number of other concerns were raised in [10] on theuse of external testers for nanoscale chip testing: lack ofscalability of test data volumes, high cost for full clockspeed testing, poor suitability for the extension of productiontesting to lifetime testing. As an effect, a migrationfrom external testers to built-in self-test (BIST)infrastructures was envisioned in [10], and was later confirmedby the large amount of works in the open literaturetargeting scalable BIST architectures for NoC testing [2],[22], [17]. At the same time, the limited fault coveragethat functional and pseudo-random testing can achieve onthe control path of NoC switches when test generatorsare outsi<strong>de</strong> the switch has further pushed the adoption ofBIST units at least for such control blocks [8].In this direction, this paper relies on a full BIST strategyfor NoC testing. A key principle of our approachconsists of exploiting the inherent structural redundancyprovi<strong>de</strong>d by NoCs. Each switch is comprised of inputports, output ports, arbiters and FIFOs that are duplicatedfor each channel. This feature is used to <strong>de</strong>velop a veryeffective test strategy which consists of testing multiple1 Dept. of Computer Engineering, <strong>Universidad</strong> Politecnica <strong>de</strong> Valencia,Spain.2 ENDIF, University of Ferrara, 44100 Ferrara, Italy.i<strong>de</strong>ntical blocks in parallel and of cutting down on thenumber of test pattern generators. This is done both at theabstraction level of the switch micro-architecture (e.g.,testing of the output port arbiters in parallel) and of theNoC architecture (i.e., testing of all NoC switches in parallel).The inherent parallelism of our BIST proceduremakes our testing infrastructure highly scalable and bestsuited for large network sizes.Four main features differentiate our testing frameworkfrom most previous work. First, we take on the challengeof generating <strong>de</strong>terministic test vectors on-chip ata limited area overhead. At the same time, this enablesus to report much shorter test application times than typicalpseudo-random testing frameworks and larger faultcoverage in the control path than most functional testingframeworks for NoCs. Second, we account for thetedious problem of faults affecting test pattern generators(TPGs) and provi<strong>de</strong> large coverage for them. This isdone without implementing more hardware redundancybut fully exploiting the existing one by means of a cooperativetesting framework among switches. Third, ourtesting framework targets double and triple stuck-at faultsfrom the ground up, and not as an afterthought, in additionto an almost 100% coverage of single stuck-atfaults. Fourth, our framework is not limited to regular2D meshes, but can be applied to a much wi<strong>de</strong>r range ofnetwork topologies.Our BIST procedure is suitable both for productionand for lifetime testing, and is complemented by a builtinself-diagnosis logic distributed throughout the networkarchitecture able to pinpoint the location of <strong>de</strong>tectedfaults in each switch. This diagnosis outcome matchesthe reconfigurability requirements of logic-based distributedrouting and is therefore the stepping stone intoa novel network reconfiguration strategy that will be <strong>de</strong>velopedin future work.II. PREVIOUS WORKConsi<strong>de</strong>ring the regular and modular structure of onchipnetworks, test strategies previously proposed for systemswith i<strong>de</strong>ntical cores [14], [23] can be applied tothe NoC. However, both approaches incur a significantoverhead for DfT structures (full-scan and IEEE 1500wrapped cores with registered I/O pins).It is showed in [13] that traditional full-scan andboundary scan strategies like [18], [21], [15], [17] incuran hardly affordable area overhead. [13] also proposes apartial scan technique in combination with an IEEE 1500-compliant test wrapper. Area overhead is greatly reduced,but test application times amount to tens of thousandsof clock cycles and test pattern generation time does notscale.As opposed to using scan paths and wrappers for testaccess, [4] consi<strong>de</strong>rs the case where test patterns are appliedat the bor<strong>de</strong>r I/Os of the network. The method wasthen exten<strong>de</strong>d in [5] to support fault diagnosis, while theDfT infrastructure was <strong>de</strong>veloped in [8]. While very highfault coverage was achieved, the time complexity of thetest configurations is square with respect to the rank ofthe NoC matrix. Moreover, in or<strong>de</strong>r to apply test patternsfrom network boundaries at-speed, a large number of testpins are necessary.In [19], it is proposed to add <strong>de</strong>dicated logic to enable<strong>JP2011</strong>-215


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011INPUT WESTINPUT EAST...LBDR WESTLBDR EASTARBITER NORTHARBITER SOUTH...OUTPUT NORTHOUTPUT SOUTHFig. 1. Modular structure of the baseline switch architecture. Not allconnections are showed.analysis of response from each FIFO in the switch, howeverno test data is presented. In [16] the possibility torepair the NoC during testing is envisioned, however errorinformation is computed once for all and thus cannothandle situations where the chip slowly <strong>de</strong>gra<strong>de</strong>s.[20] proposes a built-in self-test and self-diagnosis architectureto <strong>de</strong>tect and locate faults in the FIFOs and inthe MUXes of the switches. Unfortunately, the controlpath is left out of the framework.In [2] an automatic go/no-go BIST operation is proposedat start up of a 2D mesh NoC. Low fault coverage isachieved for the switch controller, moreover the methodologyapplies only to a 2D mesh. That i<strong>de</strong>a is evolved in[12], where a fault coverage close to 100% is documentedwith a few thousand clock cycles. However, the area costof the BIST architecture is the main concern of this work.The pattern based testing section from the more generalreliability framework presented in [9] reports a testingmethodology relying on random test pattern generationand signature analysis. Unfortunately, testing takesas large as 200000 cycles with 10000 patterns per test.With respect to previous work, we claim a more efficientuse of NoC structural redundancy for testing anddiagnosis purposes through the use of a cooperative testingframework. With respect to scan-based approaches,we reduce area overhead while at the same time <strong>de</strong>tectingTPG faults. With respect to functional testing solutions,we provi<strong>de</strong> efficient testing of the control path as welland provi<strong>de</strong> better test time scalability. With respect topseudo-random testing, we cut down on the test applicationtime. We also take on the challenge pointed by [2] ofexploiting architecture behavior knowledge to come upwith a set of customized test patterns for NoC components.III. TARGET ARCHITECTUREWithout lack of generality, we use the xpipesLiteswitch architecture [1] to prove viability of our testingmethodology in a realistic NoC setting. The baselineswitch architecture is illustrated in Fig.1. It implementsboth input and output buffering and relies on wormholeswitching. The crossing latency is 1 cycle in the link and1 cycle in the switch itself. Flit width assumed in this paperis 32 bits, but can be easily varied. Without lack ofgenerality, in this paper the size of the output buffers is 6flits, while it is 2 flits for the input buffers.This switch relies on a stall/go flow control protocol. Itrequires two control wires: one going forward and flaggingdata availability (”valid”) and one going backwardand signaling either a condition of buffer filled (”stall”)or of buffer free (”go”).The switch architecture is extremely modular and exposesa large structural redundancy, i.e., a port-arbiter,a crossbar multiplexer and an output buffer are instantiatedfor each output port, while a routing module is casca<strong>de</strong>dto the buffer stage of each input port. This commonfeature to all switch architectures will be intensively exploitedin this work.We implement distributed routing by means of a routeselection logic located at each input port. Forwardingtables are usually adopted for this purpose, although...they feature poor area and <strong>de</strong>lay scalability with networksize [24]. The possibility to implement logic-based distributedrouting (LBDR) while retaining the flexibility offorwarding tables has been recently <strong>de</strong>monstrated in [26].In practice, LBDR consists of a selection logic of the targetswitch output port relying on a few switch-specificconfiguration bits (namely routing R xy , connectivity C zand <strong>de</strong>route bits dr t ). The number of these bits (14 inthis case) is or<strong>de</strong>rs of magnitu<strong>de</strong> less than the size of aforwarding table, yet makes the routing mechanism reconfigurable.Our testing and diagnosis framework has been conceivedto enable a network reconfiguration strategy leveragingthe cost-effective flexibility offered by the LBDRrouting mechanism. An algorithm is reported in [26] forcomputation of the switch configuration bits given thetopology connectivity pattern. This algorithm might beexecuted by a centralized NoC manager and in practiceneeds the list of failed links to recompute the configurationbits for correct routing with the available communicationresources. Failure of a switch input or output portcan be viewed as the failure of the connected link. Ourdiagnosis strategy will therefore target this requirementand will provi<strong>de</strong> an indication of whether input and outputports of a switch are operational.IV. BUILT-IN SELF-TEST/DIAGNOSIS FRAMEWORKThe key i<strong>de</strong>a of our BIST/BISD framework consistsof exploiting the inherent structural redundancy of anon-chip network. We opt for testing the NoC switchesin parallel, thus making test application time in<strong>de</strong>pen<strong>de</strong>ntof network size. Communication channels betweenswitches are tested as a part of the switch testing framework.Each switch can in turn test its manyfold internal instancesof the same sub-blocks (crossbar muxes, communicationchannels, port arbiters, routing modules) concurrently.In fact, all the instances are assumed to be i<strong>de</strong>ntical,therefore they should output the same results if thereis no fault. As a consequence, the test responses fromthese instances are fed to a comparator tree. This makesthe successive diagnosis much easier. There is a uniquetest pattern generator (TPG) for all the instances of thesame block, thus cutting down on the number of TPGs.Although the principle is similar to what has been proposedin [14], [22], [13], there is a fundamental difference.If the TPG of a set of block instances is affectedby a fault, then the comparison logic will not be able tocapture this since all instances provi<strong>de</strong> the same wrongresponse. To avoid this, a cooperative framework is <strong>de</strong>vised,such that each switch tests the block instances ofits neighboring switches.As an example, a switch tests the incoming communicationchannels from its north/south/west/east neighbors(i.e., it feeds their test responses to its local comparatortree), thus checking the responses to distinct instances ofthe same TPG. This way, a non-null coverage of TPGfaults becomes feasible. Fig.2(a) clearly illustrates thecooperative testing framework for communication channelsand the need for a single TPG instance per switchto feed test patterns to all of its output ports. Faultsin the TPG, in the output buffer, in the link and in theinput buffer will be revealed in the downstream switch.Each switch ends up testing its input links, while its outputlinks will be tested by their respective downstreamswitches.The same principle can be applied for the testingof switch internal block instances associated with eachoutput port: crossbar muxes and output port arbiters.Fig.2(b) shows the case of port arbiters. The main requirementfor testing these instances is that the communicationchannels bringing test responses to the compara-<strong>JP2011</strong>-216


OUTLBLB<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TPGTPGTPGSOUTHARBITERDRTPGBUFLINKINBUFCHANNELCOMPARATORTPGTPGEASTARBITERARBITERCOMPARATORWESTARBITERTPGTPGLBDRLBDRCOMPARATORLBDRTPGDRNORTHARBITERTPGTPGTPG(a) Testing communication channels.(b) Testing output port arbiters.(c) Testing LBDR routing logic.Fig. 2. The cooperative and concurrent testing framework saving TPG instances and covering their faults.UPSTREAM SWITCHDOWNSTREAM SWITCHtors in the downstream switches are working correctly.TO LOCALCOMPARATORSTO COMPARATORSClearly, testing these modules can only occur after communicationchannels have been tested. Therefore, thevalidOutput BufferInput Bufferprocedures in Fig.2(a) and Fig.2(b) occur sequentially inTPGDatastall_channel(normal)stall_outstall_in stall_in (normal) stall_channeltime. Should one communication channel result <strong>de</strong>fective,this would not be a problem, since it would not make stall_channelsFrom localTPGof local input portsstall_in (testing)any sense to test and use a port arbiter when the correspondingport is not operational. Crossbar multiplexersstall_channel (testing)associated with each output port are tested in the sameFig. 3. Practical implementation of communication channel testing.way and are hereafter not illustrated in Fig.2 for lack ofspace.the fault may be located either in the input buffer or in theFinally, the methodology can be exten<strong>de</strong>d to test block LBDR module, in the connected communication link orinstances associated with each switch input port with even in the output buffer and associated port arbiter andsome modifications. This is the case of the LBDR routing crossbar multiplexer of the upstream switch. This furtherblock. The key i<strong>de</strong>a to preserve the benefits of cooperativeand concurrent testing is to carry test patterns rather ing is that the link is unusable, and this is enough forlevel of <strong>de</strong>tail is not nee<strong>de</strong>d, since in any case the mean-than test responses over the communication channels to a global controller to recompute the reconfiguration bitsneighboring switches, where the LBDR instances are for the LBDR mechanism.stimulated and their responses compared (see Fig.2(c)). In the final implementation, other 5 bits will be nee<strong>de</strong>dIf the channel is not working properly, then testing and to co<strong>de</strong> the diagnosis outcome because of practical implementationissues, as discussed in section IV-A.use of the downstream routing block is useless, since it isassociated with an input port which will not be used. Common to most current NoC testing frameworks,A BIST engine is embed<strong>de</strong>d into each switch and regulatesthe testing procedure. This latter is in fact splitthe un<strong>de</strong>rlying assumption for correct operation of ourBIST/BISD infrastructure is that the reset signal can beinto four phases in time: testing of communication channels,testing of the crossbar, testing of the arbiters, test-synchronously <strong>de</strong>asserted in all switches of the networkat the same time.ing of the LBDR routing blocks. The serial executionof test phases for the switch internal components is dictatedprimarily by the limited flit width, constraining the Communication channels inclu<strong>de</strong> input/output buffersA. Testing communication channelsamount of test patterns that can be transmitted at the same and their intermediate links, as illustrated in Fig.3: alltime over the communication channel, and also by the these elements are jointly tested by means of a singlelimited availability of comparators, although in our case TPG and the test patterns are handcrafted for them basedthe former effect comes into play first. As the flit width on knowledge of their behavior.increases, then we can perform more testing operations Our approach in this direction was to expand the finitestate machine (FSM) of the <strong>de</strong>vice un<strong>de</strong>r test (DUT)in parallel, starting from those components that have alimited amount of primary input/outputs (e.g., the arbiter into all its possible states. Therefore, we have <strong>de</strong>finedwith the LBDR).a sequential test pattern that drives the FSM to each ofA fundamental difference with respect to a lot of previouswork is that we do not rely on pseudo-random testing reaches the expected state for all the test patterns thereits states. In this way, we can ensure that if the FSM(like in [9]), which gives rise to large testing times. We are no faults insi<strong>de</strong> the DUT. As an example, the FSM ofuse <strong>de</strong>terministic test patterns instead, which are handcraftedfor the specific block un<strong>de</strong>r test by exploiting the buffer receives a set of valid flits, the buffer has tothe buffers <strong>de</strong>fines that if the Stall signal is asserted andknowledge of the architecture behavior. This way, the store the flits that it receives until it becomes full. Onereduced number of test patterns enables the serialization test pattern to check this behavior would fill up the bufferof test phases without making test application time skyrocket(see section V-A).whether the output buffer correctly asserts the Full signal.by asserting the Stall signal, and would in the end checkOn a cycle by cycle basis, comparator outputs are fed The datapath is obviously much easier to test by means ofto a diagnosis logic which i<strong>de</strong>ntifies where exactly the only few test patterns.fault occurred. In our diagnosis framework, each switch From an implementation viewpoint, there are severalchecks whether test responses from its input ports are corrector not. As a consequence, the outcome of the diagno-input of the output buffer directly controllable to the TPGpractical issues. On one hand, we had to make the stallsis is co<strong>de</strong>d in only 5 bits, one for each input port of the to raise its stuck-at fault coverage to almost 100% (seecurrent switch (they would be of course doubled if a tworailco<strong>de</strong> is implemented to protect them against stuck-at On the other hand, the stall channel signal of the in-Fig.3).faults). A ’1’ indicates that the port is faulty. In practice, put buffer, which lies in the downstream switch, should<strong>JP2011</strong>-217


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TEST PATTERNCOUNTERNEXT PATTERNCLOCK CYCLECOUNTER100101..100010..001100..111001..100011..000001..110101..000111..111110..OUTPUT BUFFER STALLINPUT BUFFER STALLOUTPUT BUFFER WRITEBUFFER INPUT DATADUT RESETFig. 4. TPG for communication channels.be driven by the TPG as well. This would require anadditional wire in the switch-to-switch link. A similarconcern is that the stall out signal from the output buffershould be brought to the comparators in the downstreamswitch, again requiring an additional wire in the link.To avoid the extra wires, we opted for the solution inFig.3: stall channel is driven by the TPG of the downstreamswitch, while stall out is brought to the comparatortree in the upstream switch. From the testing viewpointnothing changes, since all channel TPGs inject thesame patterns synchronously, and so do the comparators.The only difference lies in the fault coverage of TPGfaults, which is likely to be <strong>de</strong>creased a bit. In fact, those(upstream) TPG faults that can be <strong>de</strong>tected by only monitoringstall out will not be <strong>de</strong>tected, since all the stall outsignals brought to the local comparators will be driven bythe same TPG. Similarly, some faults in the (downstream)TPG will not be <strong>de</strong>tected, since the comparators compareresponses to stall channel signals generated by the samefaulty TPG: the responses will look like the same. Theseimplementation variants, nee<strong>de</strong>d to adapt the conceptualtesting scheme to the constraints of the real implementation,will be proven in section V-A to only marginally<strong>de</strong>crease fault coverage of the TPGs, while leaving faultcoverage for the communication channel obviously unaffected.The only major implication is that the fault <strong>de</strong>tectionframework becomes even more collaborative: some (veryfew) faults in the channel and/or TPGs are now <strong>de</strong>tectedin the upstream switch comparators instead of the downstreamones. Therefore, other 5 additional diagnosis bitsare nee<strong>de</strong>d, flagging a fault in the output port of a switch.The global controller will combine this (OR operation)with the faults <strong>de</strong>tected at the input port of the downstreamswitch to get the complete indication of a faultacross the entire channel.B. TPG for communication channelsA test pattern can be easily generated in hardware byusing a clock cycle counter and some logic to generatethe values of the input signals for the DUT. In or<strong>de</strong>r toextend this approach to a TPG able to generate all the testpatterns for a given DUT, we can inclu<strong>de</strong> an additionalcounter. This latter will indicate the current test patternwithin the test sequence. Figure 4 <strong>de</strong>picts the resultingconceptual scheme for the channel TPG. The actual gatelevelimplementation <strong>de</strong>pends on the logic synthesis tooland on the synthesis constraints. The two counters act asa FSM driving the control signals of two levels of multiplexing:the first one selects the current test pattern, whilethe second one selects the current clock cycle and associatedinput vector for the buffer.It is however possible to easily compact the combinationallogic, because there are a lot of test patterns thatinclu<strong>de</strong> other test patterns. For instance, by checking theresponse not only at the end of the test pattern, but alsosomewhere in the middle, it is often possible to <strong>de</strong>tectanother fault. This perfectly matches with the capabilityof our BIST framework, which even performs check responseat each clock cycle. Therefore, it is possible in ourimplementation to perform a compaction of test patternsby generating in hardware only those patterns including asubset of the other ones, thus largely saving test time andTPG area.C. Testing Other Internal Switch ModulesA similar process is followed to generate <strong>de</strong>terministictest patterns for the port arbiters, the LBDR modules andthe crossbar. Also the implementation of their TPGs isi<strong>de</strong>ntical, and so are the optimization techniques.Again, the most relevant practical implementation issueconcerns the communication of test patterns or responsesacross the switch-to-switch links for the crossbarand LBDR module. The crossbar outputs 34 bits in responseto a test vector: 32 data bits, 1 valid bit and 1stall bit. The communication channel can only carry 32bits (the valid bit of the channel needs to be permanentlyset to 1 during test vector transmission, while the stallsignal travels in the opposite direction). The two remainingcrossbar signals (valid and stall) which do not fit intothe link can be either transmitted by means of additionallines used only during testing, or alternatively checkedby local comparators, similarly to what has been done forthe communication channel. We took the latter approach,and the results in section V-A again confirm the marginalcoverage reduction on TPG faults. Fault coverage of thecrossbar is not affected at all by this choice.Unlike other modules, test vectors for the LBDR modulesshould be transmitted across the link, and they take31 lines (the primary inputs of the LBDR module). So,they perfectly match with the current flit width, provi<strong>de</strong>dthe number of network <strong>de</strong>stinations does not exceed 64.From there on, the test vector width starts growing logarithmicallywith the number of <strong>de</strong>stinations, and additionallines may be required on the link.In contrast, the use of a larger flit width in the network(e.g., 64 bits) would automatically solve the problem. Inthat case, the test patterns of the LBDR block and the testresponses of the arbiter could even be communicated atthe same time over the link. Also, since LBDR moduleand arbiters have only few outputs, their response checkingcould be performed at the same time on the availabletree of comparators, thus cutting down on the test applicationtime (see section V-A).D. Fault <strong>de</strong>tection and diagnosisThe core of the diagnosis unit is given by comparatorswhich can be implemented in two different ways, by usinga level of XORs and an OR gate to provi<strong>de</strong> a singleoutput encoding of the equality test, or by using a two-railchecker TRC (with the second word which is negated).We opted for the TRC approach, which achieves the selftestingand fault-secure properties [27] although leadingto a more complex circuit.In the diagnosis unit we use 10 different comparatorsto compare data from all the possible pairs of switch inputports. A smaller number of comparators could be used.Unless time multiplexing is exploited, this would tra<strong>de</strong>cost for diagnosis capability. The maximum number ofusable comparators also <strong>de</strong>pends on the number of switchI/O ports. In what follows, we will focus on the internalswitches of a 2D mesh for the sake of simplicity (featuring5 I/O ports, including the local connection to thenetwork interface), however all irregular topologies supportedby LBDR and making use of switches with at least3 I/O ports are suitable for our methodology. Obviously,the lower the number of ports, the lower the diagnosiscapability.If we <strong>de</strong>note two faults in different ports un<strong>de</strong>r comparisonas equivalent if they produce the same output sequencein response to the same input stimuli, then our<strong>JP2011</strong>-218


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20110FAULTY INPUT PORT N0FAULTY OUTPUT PORT N70000BISTINPUT BUFFERNORTHfromallinputportsTOCOMPARATORSCOMPARATORSfromallinputportsTOCOMPARATORSLBDR_NIN_NN_REQ_NARBITERTPG(in inputs_N)DIAGNOSISCROSSBARTPGinputs_Ninputs_SIN_NIN_S0000FAULTY INPUT PORT SFAULTY INPUT PORT WFAULTY INPUT PORT EFAULTY INPUT PORT FROM NI..N_stall_N.N_stall_SARB_NCROSSBARTPGCHANNELTPGFAULTY OUTPUT PORT TO NILBDRTPGN_stallCROSSBARTPGB I S T E N G I N E0000CROSSBAR MUXNORTHFAULTY OUTPUT PORT SFAULTY OUTPUT PORT WFAULTY OUTPUT PORT EFig. 5. BIST-enhanced switch architecture.OUTPUT BUFFERcomparator and diagnosis logic is able to: diagnose thecorrect position of 1 or 2 faulty channels affected byequivalent or non-equivalent faults; diagnose the correctposition of 3 faulty channels affected by non-equivalentfaults; <strong>de</strong>tect the presence of 4 and 5 faulty channels.Anyway, since a 5x5 switch affected by 4 or 5 faults hasto be discar<strong>de</strong>d, we don’t distinguish between these twoscenarios.One might argue that when a communication channelfails, then the following testing phases have less inputsavailable and diagnosis capability reduces. In practice,this effect plays only a minor role, since a fault on a communicationchannel means that also (say) the arbiter ofthat channel should be consi<strong>de</strong>red faulty (unusable). So,the diagnosis capability reduces, but also the number ofinput ports to be checked reduces as well.When a switch features only three I/O ports, then the<strong>de</strong>tection and diagnosis capabilities change as follows.Single stuck-at faults can be diagnosed while doublefaults can be <strong>de</strong>tected, provi<strong>de</strong>d they are not equivalent.If they are equivalent, then diagnosis fails. However,when two faults are <strong>de</strong>tected in two ports out of three,the switch should be discar<strong>de</strong>d anyway.As regards the possible presence of faulty comparators,let us first note that any input vector producing less thanfour ones corresponds to faults in less than four comparators(we are neglecting the case where all 5 channels arefaulty and 4 of them have equivalent faults, which is veryunlikely). In case the number of faulty comparators islarger than 3, some configuration exists which may producea wrong diagnosis. Let us note, however, that it issufficient to have a single test vector (not a test sequence)featuring less than four ones to immediately recognizethe presence of faulty comparators because no combinationof faulty channels may produce such response.E. BIST-enhanced switch architectureThe switch architecture enriched with the BIST infrastructureis illustrated in Fig.5. Only one section is reported.The figure is necessarily at a high abstractionlevel, and signal-level connection <strong>de</strong>tails previously illustratedin sections IV-A and IV-C are purposely omitted.A test wrapper consisting of multiplexers can beclearly seen, which enables test pattern injection of TPGsin the modules they test. At the output of the input buffer,test patterns are directly fed to the LBDR module, sincethey are carried by the communication channel as normalnetwork traffic. A multiplexer in front of each outputbuffer selects between the switch datapath, the test patternsfrom the LBDR TPG (feeding the LBDR module ofthe downstream switch), the channel TPG (directly feedingthe channel) and the arbiter test responses (checkedin the downstream switch). A BIST engine drives the 4NORTHSwitch Area(um2)6000050000400003000020000100000VANILLA500MHzBISTVANILLA700MHzFig. 6. Area overhead for BIST implementation as a function of targetspeed.100,0%90,0%80,0%70,0%60,0%50,0%40,0%30,0%20,0%10,0%0,0%<strong>JP2011</strong>-219CHANNEL TPG (i<strong>de</strong>al) CHANNEL TPG (real) ALLOCATOR TPG LBDR TPG CROSSBAR TPG (i<strong>de</strong>al) CROSSBAR TPG (real)Fig. 7. Coverage of TPG faults.phases of the testing procedure by acting upon the controlsignals of the test wrapper.During the first three phases (communication channel,crossbar, arbiter testing), outputs of the input buffers areselected to feed the comparator tree, while in the lastphase (LBDR testing), all LBDR outputs are selected.Test response check and diagnosis are performed at eachclock cycle, and result in the setting of 10 bits, indicatingwhether each input/output port is faulty or not.V. EXPERIMENTAL RESULTSWe performed placement-aware logic synthesis andplace&route of a 5x5 switch on an industrial 65nm technologylibrary. The baseline switch architecture of Fig.1is compared with its BIST-enhanced counterpart. Synthesizingfor maximum performance gives approximatelythe same maximum (post-layout) operating speed of 700MHz for both architectures, thus proving that our BISTenabledswitch is capable of at-speed testing.Fig.6 shows the area overhead for BIST implementationas a function of the target speed. Area overhead is11%, which peaks at 21% when maximum performanceis required. In this latter case, the multiplexers on thecritical path are primary targets for <strong>de</strong>lay optimization inexchange for more area.When consi<strong>de</strong>ring the BIST infrastructure in isolationmost of the overhead comes from the on-chip generationof test patterns (almost 31%) and from the multiplexers(44%) of the test wrapper. Interestingly, although arbitersand LBDR require less test vectors than the communicationchannel, their TPGs are far more complex due tohigher irregularity of their test patterns.Switch sub-block Test patterns Test vectors CoverageComm. channel 58 464 99.4%Arbiter 82 328 97.1%Crossbar 72 72 99.8%LBDR 240 240 98.7%TABLE ICOVERAGE FOR SINGLE STUCK-AT FAULTS.Test CycleCoverageOur 864 - 1104 99.3%[20] 3.88 x 10 2 - 2.89 x 10 3 97.79%[21] 4.05 x 10 5 95.20%[12] 2.74 x 10 3 99.89%[13] 9.45 x 10 3 - 3.33 x 10 4 98.93%[22] 5 x 10 4 - 1.24 x 10 8 N.A.[8] 320 99.33%[9] 200 x 10 3 full (no exact numbers)TABLE IITEST APPLICATION TIME AND COVERAGE OF DIFFERENT TESTINGMETHODS.


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Multiplicity of Fault Injection 2 3 4 5Coverage 99.2% 96.4% 96.6% 96.6%TABLE IIICOVERAGE FOR MULTIPLE RANDOM STUCK-AT FAULTS.A. Fault CoverageTab.1 reports the total number of <strong>de</strong>terministic test patterns(and test vectors) generated for each tested module,and the associated coverage. This latter was <strong>de</strong>rived bymeans of an in-house ma<strong>de</strong> gate-level fault simulationframework: (one or more) faults are applied to any or selectedgate inputs, then our testing procedure is run on theaffected netlist and the diagnosis outcome is comparedwith the expected one.It can be seen that in all cases the coverage for singlestuck-at faults closely tracks 100%. The number of testvectors provi<strong>de</strong>s the test application time (in clock cycles).A network with a flit width of 32 bits, as assumedso far, would therefore take 1104 clock cycles for testing,regardless of the network size. If we assume 64 bit flits,then LBDR testing occurs in parallel with arbiter testingand total test time reduces to 864 cycles.These numbers compare favorably with previous work,as Tab.2 shows. Only [20] and [8] in some cases do better.However, [20] does not test the control path while [8]reports 320 cycles for a 3x3 mesh (ma<strong>de</strong> of a simplifiedswitch architecture) which however grow linearly withnetwork size. Also, this latter approach makes additionaluse of BIST logic for the control path not accounted forin the statistics.We feel that area overhead is hardly comparable withprevious work since whenever numbers are available, featuresof the testing frameworks are very different (e.g.,control path not tested [20], test patterns generated externally[21], [13], diagnosis missing [21], [12], [13], [22],lack of similar test time scalability [4], [8], NoC architecturewith overly costly links [12]). Moreover, the impactof synthesis constraints is never discussed.Fig.7 reports the coverage of TPG faults. While singlestuck-at faults in the allocator and channel TPGs featurea coverage of roughly 95%, worse results are obtainedfor the LBDR and especially for the crossbar TPGs. Weverified that their lower coverage is a direct consequenceof the low number of test patterns they generate. The <strong>de</strong>signercan then choose whether increasing crossbar TPGarea and having it generate more patterns or <strong>de</strong>dicating aseparate test phase to TPGs. Also, when comparing realvs i<strong>de</strong>al coverage of channel and crossbar TPGs, it is possibleto assess the marginal reduction of TPG fault coverageas an effect of the local (instead of remote) check ofsome signals of these modules in the switch they belongto (see section IV-A and IV-C).Since our BIST infrastructure targets multiple stuck-atfaults from the ground up, we characterized fault coveragefor multiple faults as well. We have injected multiplefaults randomly in the gate-level netlist of the switch andchecked the diagnosis response. Fault multiplicity was2,3, 4 and 5 and fault injections for a given multiplicitywere repeated 1000 times, as in [9]. As Tab.3 shows, theproposed BIST framework provi<strong>de</strong>s a higher than 96%coverage in every scenario. Interestingly, the coveragesaturates with 4 and 5 faults since the probability to injecterrors in a module already affected by an error becomeshigh.VI. CONCLUSIONSThis work <strong>de</strong>velops a scalable built-in self-test andself-diagnosis infrastructure for NoCs taking full advantageof their structural redundancy through a cooperativetesting and diagnosis framework. Table-less logic baseddistributed routing is the foundation of our approach, an<strong>de</strong>nables network reconfiguration with only 10 diagnosisbits per switch. We prove the achievement of standardfault coverage targets at an affordable area overhead.However, we do more than that: we quantify coverage formultiple faults and aim at the coverage of faults affectingTPGs as well. This latter is a key step forward to makethe move from scan-based approaches to scalable BISTapproaches viable.ACKNOWLEDGEMENTSThis work has been partially supported by the NANOCEuropean Project (FP7-ICT-248972), and by the SpanishGovernment un<strong>de</strong>r the grant TIN2009-14475-C04-01.REFERENCES[1] S.Stergiou et al., ”Xpipes Lite: a Synthesis Oriented Design Libraryfor Networks on Chips”, DAC, pp.559-564, 2005.[2] K.Petersen, J.Oberg, ”Utilizing NoC Switches as BIST-Structuresin 2D Mesh Network-on-Chip”, Future Interconnects and Networkon Chip Workshop, 2006.[3] D.Wentzlaff et al., ”On-Chip Interconnection Architecture of theTile Processor”, IEEE Micro, vol.27, no.5, pp.15-31, 2007.[4] J.Raik, V.Govind, R.Ubar, ”An External Test Approach forNetwork-on-a-Chip Switches”, Proc. of the IEEE Asian Test Symposium2006, pp.437-442, Nov. 2006.[5] J.Raik, V.Govind, R.Ubar, ”Test Configurations for DiagnosingFaulty Links in NoC Switches”, Proc. ETS, 2007.[6] M. Mishra and S. Goldstein, ”Defect tolerance at the end of theroadmap”, in ITC, pages 1201-1211, 2003.[7] D. A. IIitzky, J. D. Hoffman, A. Chun and B. P. Esparza, ”Architectureof the Scalable Communications Core’s Network on Chip”,IEEE MICRO, 2007, pp. 62-74.[8] J.Raik, V.Govind, R.Ubar, ”DfT-based External Test and Diagnosisof Mesh-like NoCs”, IET Computers and Digital Techniques,October 2009.[9] V.Bertacco, D.Fick, A.DeOrio, J.Hu, D.Blaauw, D.Sylvester, ”VI-CIS: A Reliable Network for Unreliable Silicon”, DAC 2009,pp.812-817.[10] Y.Zorian, ”Testing the monster chip”, IEEE Spectrum, pp.54-60,1999.[11] Y.Zorian, ”Embed<strong>de</strong>d Memory Test and Repair: Infrastructure IPfor SoC Yield.”, International Test Conference, pp.340-349,2002.[12] K.Peterson, J.Oberg, ”Toward a Scalable Test Methodology for2D-mesh Network-on-Chip”, DATE 2007, pp.75-80, 2007.[13] A.M. Amory, E.Briao, E.Cota, M.Lubaszewski, F.G.Moraes, ”AScalable Test Strategy for Network-on-Chip Routers”, Proc. of ITC2005.[14] K.Arabi, ”Logic BIST and Scan Test Techniques for MultipleI<strong>de</strong>ntical Blocks”, IEEE VLSI Test Symnposium, pp.60-68, 2002.[15] C.Grecu, P.Pan<strong>de</strong>, B.Wang, A.Ivanov, R.Saleh, ”Methodologiesand Algorithms for Testing Switch-Based NoC Interconnects”,IEEE DFT 2005, pp.238-246, 2005.[16] B.Vermeulen, J.Delissen, K.Goossens, ”Bringing CommunicationNetworks on a Chip: Test and Verification Implications”, IEEECommunications Magazine, vol.41-9, pp.74-81, 2003.[17] R.Ubar, J.Raik, ”Testing Strategies for Network on Chip”, inBook: ”Network on Chip”, edited by A.Jantsch and H.Tenhunen,Kluwer Aca<strong>de</strong>mic Publisher, pp.131-152, 2003.[18] C.Aktouf, ”A Complete Strategy for Testing an on-Chip MultiprocessorArchitecture”, IEEE Design and Test of Computers,vol.19-1, pp.18-28, 2002.[19] Panda et al., ”Design, Synthesis and Test of Networks on Chips”,IEEE Design and Test of Computers, vol.22, issue 8, pp.404-413,2005.[20] S.Y.Lin, C.C.Hsu, A.Y.Wu, ”A Scalable Built-In Self-Test/Self-Diagnosis Architecture for 2D-mesh Based Chip MultiprocessorSystems”, IEEE Int. Symp. on Circuits and Systems, pp.2317 -2320, 2009[21] M.Hosseinabady, A.Banaiyan, M.N.Bojnordi, Z.Navabi, ”A ConcurrentTesting Method for NoC Switches”, DATE, pp.1171 - 1176,2006[22] C.Grecu, P.Pan<strong>de</strong>, A.Ivanov, R.Saleh, ”BIST for Network-on-Chip Interconnect Infrastructures”, VLSI Test Symposium, page 6,2006.[23] Wu, Y. and MacDonald, P., ”Testing ASICs with Multiple I<strong>de</strong>nticalCores”, IEEE Transactions on Computer-Ai<strong>de</strong>d Design ofIntegrated Circuits and Systems, vol. 22-3, 2003, pp. 327-336.[24] S.Rodrigo, S.Medardoni, J.Flich, D.Bertozzi, J.Duato, ”EfficientImplementation of Distributed Routing Algorithms for NoCs”,IET-CDT, pp.460-475, vol.3, issue 5, 2009.[25] Submitted paper un<strong>de</strong>r review[26] S.Rodrigo, J.Flich, A.Roca, S.Medardoni, D.Bertozzi,J.Camacho, F.Silla, J.Duato, ”Addressing Manufacturing Challengeswith Cost-Effective Fault Tolerant Routing”, NOCS 2010,pp.35-32, 2010.[27] P.K. <strong>La</strong>la, ”Self-checking and fault tolerant Digital Design”, MKPublishers 2001.<strong>JP2011</strong>-220


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20111Modular Distributed Switch: Spreading the Switchalong the LinkAntoni Roca, Carles Hernán<strong>de</strong>z, José Flich, Fe<strong>de</strong>rico Silla, José DuatoAbstract—It is well-known that current Chip Multiprocessor (CMP)and high-end MultiProcessor System-on-Chip (MPSoC) <strong>de</strong>signsare growing in their number of components. Networks-on-Chip(NoC) provi<strong>de</strong> the required connectivity for such CMP andMPSoC <strong>de</strong>signs at reasonable costs. However, as technologyadvances, links become the critical component in the NoC. First,because the power consumption of the link is extremely high withrespect the power consumption of the rest of components (mainlyswitches), becoming unacceptable for long global interconnects.Second, the <strong>de</strong>lay of a link does not scale with technology, thus,<strong>de</strong>grading the performance of the network.In this paper we present a new switch architecture thatreduces the negative impact of links on the NoC. We call ourproposal distributed switch. The distributed switch moves thecircuitry of a standard switch onto the links. Then, packetsare buffered, routed, and forwar<strong>de</strong>d at the same time they arecrossing the link. Distributing a standard switch onto the linkimproves the tra<strong>de</strong> off between the power consumption and theoperating frequency of the entire network. In contrast, arearequirements are increased. The distributed switch reduces upto 14.8% the peak power consumption while increases its areaup to 22%. Furthermore, the distributed switch is able to increasethe maximum achievable frequency with respect to the standardswitch up to 14.3%.I. INTRODUCTIONAs technology advances, current Chip MultiProcessor(CMP) and high-end MultiProcessor System-on-Chip (MP-SoC) <strong>de</strong>signs are growing in their number of components.This ever growing number of <strong>de</strong>vices <strong>de</strong>mands an efficient interconnectstructure insi<strong>de</strong> the chip. Networks-on-Chip (NoC)have been accepted as an efficient and scalable solution forCMPs and MPSoCs [1]. The i<strong>de</strong>a is quite simple, a pointto-pointnetwork insi<strong>de</strong> the chip is implemented connectingall the <strong>de</strong>vices. In this scenario, and with the expectationsto reach hundreds of cores in the near future, an efficientimplementation of the NoC becomes a challenge. The NoCis built from basic components, as switches and networkinterfaces which are connected by links, thus building thetopology and final network structure.The most basic link implementation is a driver connectedto a wire. The driver is a necessary element that feeds thewire with the required signal. Minimizing the <strong>de</strong>gradation thatthe signal suffers when crossing the wire is mandatory in the<strong>de</strong>sign phase. However, this basic <strong>de</strong>sign is unpractical dueto its huge power consumption. A commonly accepted wayto build a link is to insert several smaller drivers (repeaters)along the link [2]. By introducing the proper number and sizeof repeaters, it is possible to minimize the power consumptionGrupo <strong>de</strong> Arquitecturas Paralelas , Universitat Politècnica <strong>de</strong> València, e-mail: anrope2@gap.upv.es.of the link [3]. However, <strong>de</strong>spite the power optimization whenintroducing repeaters along the link, the link interconnectintroduces two major problems. First, its power consumptionis still the main contribution to the total power consumptionof the network. In fact, link power can become unacceptablyhigh, even when using repeaters, thus limiting data bandwidth[4]. Second, link <strong>de</strong>lay is a critical parameter that doesnot improve with process scaling [2], that is, as technologyscales down, the latency of the link becomes the bottleneck ofthe network, <strong>de</strong>grading the performance of current and futurenetworks.In this paper we present a new switch architecture thatreduces the negative impact of links on the NoC. The maincontribution of our new switch architecture is to move anentire pipelined switch onto the link, thus modifying the finalfloorplan of the network. We distribute along the link the tasksand logic of a switch, that is typically <strong>de</strong>signed by placingall its logic grouped in a single area. We call this proposaldistributed switch. In our distributed switch, the architecture ofthe switch and the link are glued. Packets are buffered, routed,and forwar<strong>de</strong>d at the same time they are crossing the link. Themain benefit of spreading the switch over the link is that thetra<strong>de</strong> off between the power consumption and the operatingfrequency of the entire network is improved. In particular, upto 14.8% in peak power reduction is achieved.The rest of the paper is organized as follows. Section IIpresents a simple and modular switch, used as the startingpoint for the <strong>de</strong>sign of the distributed switch, which is laterpresented in Section III. Then, the link that connects twomodular switches (modular link) and the link that connectstwo distributed switches (distributed link) are <strong>de</strong>signed inSection IV. In Section V an area comparison of the differentswitch architectures is carried out. Section VI analyses andcompares the power consumption of the different proposals.Finally, some conclusions and future work are presented inSection VIII.II. MODULAR SWITCHThe modular switch is a pipelined buffered wormhole switchwith two stages. A complete <strong>de</strong>scription and analysis of theswitch can be seen in [5]. The main characteristic of the switchis that each output port is managed in<strong>de</strong>pen<strong>de</strong>ntly. That is, eachoutput port has its own circuitry (output port controller) whichis not connected to the circuitry of the rest of output ports,as can be seen in Figure 1(a). This figure shows a modularswitch consisting of five input/output ports. Each input portcan reach any output port direction except the output portthat goes in the same direction of the input port (U turns are<strong>JP2011</strong>-221


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20112not allowed). Also, the local port connecting the core and theswitch can be reached from any input port. Thus, each outputport works as a 4-to-1 switch. That is, each output port is ableto buffer, route, and forward those packets that request thatoutput port. Figure 1(b) shows the block diagram of an outputport controller. As it can be seen, the output port controllercircuitry – and hence all the switch – is composed of twodifferent modules: the Routing Computation (RC) module, andthe Arbitration-Crossbar (AC) module.ARBITERDATA IN 1DATA IN 2FLOW CONTROLCLKBUFFERFLOW CONTROLDATA_OUTFig. 2. AC module schematic.Fig. 1.(a) Modular switch schematic.Modular switch schematic.(b) Output port controller schematic.The AC module, <strong>de</strong>picted in Figure 2, is the most importantcomponent in the switch. It performs the arbitration, switchtraversal (crossbar), and buffering stages present in a pipelinedswitch. The simplicity of this module allows the switch to befaster than a simple and canonical switch, as shown in [5].The AC module is a simple two-to-one multiplexer with itsoutput registered. An arbiter <strong>de</strong>ci<strong>de</strong>s which input is going to beconnected with the output of the module. The arbiter has beenimplemented using a simple round-robin arbiter. The buffer inthe AC module is able to store two flits. Then, each inputoutputpath of the switch is able to store four flits (two perstage). The buffer is implemented by using a mux-in-first-outbuffer [6]. By using this structure for the buffer, the zeroloadlatency of the modular switch is one cycle per stage,that is, when no contention exists, a flit needs two cycles tocross the modular switch. Finally, Stop&Go flow control hasbeen implemented between modules insi<strong>de</strong> the output portcontroller. This flow control is i<strong>de</strong>ntical to the flow controlimplemented between modules of different switches. Thestoring capability of the AC module can be set to any value at<strong>de</strong>sign time. However, if the buffer size of the AC module islower than two, the round-trip-time between modules cannotbe fulfilled and, hence, there is no possibility to transmitconsecutive flits without introducing bubbles. Therefore, theAC module fixes the operating frequency of the output portcontroller and hence, the operating frequency of the entireswitch.The RC module performs the routing computation. Ourswitch is <strong>de</strong>signed to perform a simple XY routing algorithm.Other routing algorithms can be leveraged. Nevertheless, asa <strong>de</strong>terministic routing is being used in our <strong>de</strong>sign, eachRC module is able to perform look-ahead routing [7], whichincreases the overall performance of the switch. Figure 1(b)also shows the pipeline of the switch, where each column ofAC modules represents a different stage. On the other hand,as the RC module is not in the critical path of the switch, theRC has no latency restrictions. In the modular switch, the RCtasks are performed in parallel with the second AC stage (seeFigure 1(b)).The modular switch <strong>de</strong>sign requires increasing the resourcesof the switch. In fact, the buffer requirements – and hence thearea – of this modular switch is higher than the area of acanonical switch [5]. In contrast, a higher operating frequencycan be obtained [5]. Another penalty that this switch presentsis the increment in metallizations at the input si<strong>de</strong> of theswitch. Note in Figure 1(a) that each input port is connectedto all output ports. That increment in metallizations increasesthe power consumption of the switch.The switch in Figure 1(a) is inten<strong>de</strong>d for 2D meshes.Thus, four ports are used to provi<strong>de</strong> connectivity with theneighbouring switches and the fifth port connects to the localcomputing core. Nevertheless, in or<strong>de</strong>r to complete the switch<strong>de</strong>sign, floorplan needs to be taken into account, in or<strong>de</strong>r toknow the link length. In this regard, link length <strong>de</strong>pends on theexact size of the tiles in the CMP chip, as the 2D mesh NoCwill cover all the die area. Thus, in or<strong>de</strong>r to avoid <strong>de</strong>signingthe whole tile, which is out of the scope of this paper, weused the MCPAT tool [8] to find out the area required by thetile when synthesized using a 45nm technology no<strong>de</strong>. MCPATtool results show that the tile requires 5.77mm 2 , links being2.4mm long if square tiles are assumed. On the other hand,total die size is slightly larger than 400mm 2 , assuring that itis manufacturable [9].Finally, links are divi<strong>de</strong>d into data and flow control sublinks.Data sublink width is set to 8 bytes. Flow control sublink widthis set to 2 bits. Then, the total link width is 66 bits. Flit sizeis set to data link width.A. Critical PathAs each output port controller is in<strong>de</strong>pen<strong>de</strong>nt and i<strong>de</strong>nticalto the other output port controllers, fixing the critical path of anoutput port controller is equivalent to fix the critical path of theentire switch. If we analyze the <strong>de</strong>lay of the paths of a switch,we observe that the paths that set the critical path (slowestpath) are those that interconnect two adjacent switches. Thatis, the slowest path in the switch is the data path between twoswitches and the flow control that connects the AC modules oftwo adjacent switches. In both cases, the <strong>de</strong>lay is contributedby a combinational logic that creates the signals and the link<strong>de</strong>lay to transmit those signals from one switch to another.<strong>JP2011</strong>-222


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20113In or<strong>de</strong>r to know such <strong>de</strong>lays, the switch has been implementedusing the 45nm technology open source Nangate[10] with Synopsys DC. We have used M1-M3 metallizationlayers to perform the Place&Route with Ca<strong>de</strong>nce Encounter.We observe, after synthesizing the modular switch that thecombinational <strong>de</strong>lay of the data path and the flow controlpath are almost i<strong>de</strong>ntical. The minimum combinational <strong>de</strong>layreachable by the synthesis tool for those paths is 0.53ns. Then,the critical path (T) of a switch is:T = 0.53ns + link <strong>de</strong>lay (1)where the link <strong>de</strong>lay will be set in or<strong>de</strong>r to fullfill the networkrequirements. It is noteworthy to mention, that the modularswitch presented in this paper has a critical path that is up to15% shorter than the critical path of a canonical switch [5].III. DISTRIBUTED SWITCHThe modular switch <strong>de</strong>sign presented in the previous sectionhas an interesting property. Each output port has its owncircuitry that is in<strong>de</strong>pen<strong>de</strong>nt from the circuitry of the restof output ports (see Figure 1(a)). This property allows themodular switch presented in Section II to be distributed overthe links while keeping the connectivity of the switch with itsneighbours. That is, it allows to spread the circuitry of eachoutput port controller of the switch along the link that connectsthat output port circuitry with the adjacent switch. Each of thestages of the output port controller is located at half the lengthof the link connecting to the adjacent switch.There are several benefits of distributing the switch over thelink. First, power consumption is reduced without increasingthe <strong>de</strong>lay of the communication between switches. That is,distributing the switch over the link forces the link to bepipelined (distributed link). However, the pipeline of thedistributed link is not only introduced to minimize powerconsumption but to perform the switching tasks. Pipelining thelink minimizes the <strong>de</strong>lay constraints of the link. Then, powerconsumption of the link is reduced. Thus, interconnects canbe <strong>de</strong>signed reducing the power consumption meanwhile thepipeline of a message is not increased.The second benefit of distributing the switch over the linkis that any stage of the pipelined switch is connected to afragment of the link (sublink). Thus, the effects of processvariation over the pipelined switch can be easily minimized, asshown in [11], where a simple technique to reduce the processvariation effects of the switch was presented. Basically, anyperformance variation in the switch is compensated by makingthe link faster, which is a simple and well-known technique.However, this technique could not be used insi<strong>de</strong> a pipelinedswitch [12]. In a distributed switch, any stage of the switch isconnected to a sublink and, therefore, any process variation ofany pipeline stage of the switch can be compensated by thesublink that is connected to. The impact of process variationon the distributed switch is left to future work.Distributing the switch over the link may have a negativeconsequence, as the length of the wires between AC modulesincreases. Remember that in the modular switch, any inputport is connected to all the output port controllers insi<strong>de</strong> theswitch. In the distributed switch, this interconnection becomeslonger because AC stages are separated from each other.This effect can be seen in Figure 3. The figure shows theconnectivity between two modular switches and its equivalentdistributed link. While a typical link has a length of L plus thelength of the wire insi<strong>de</strong> the switch (negligible), the distributedswitch presents six smaller links of length L/2, accountingfor a total of 3L routed wires per distributed link. Then, adistributed link, presents three times more routed wires thanthe equivalent centralized link. Despite the increment in routedwire, the length reduction of each sublink in a distributed linkwill reduce the <strong>de</strong>lay constraint of these sublinks and then,reducing the total power consumption of the distributed link.(a) Link between adjacent modularswitches.Fig. 3.Link scheme for both scenarios.L/2L/2INCREMENTED ROUTEDWIRES(b) Equivalent distributed link.The negative effect of these longer wires is minimizedby using higher metallization layers, achieving low powerconsumption (see Section IV). This is the case of the distributedswitch. In contrast, in the modular switch distancebetween AC modules are shorter as they are insi<strong>de</strong> the switcharea and, hence, they are routed by using lower metallizationlayers which have worse properties, and hence, higher powerconsumption.Figure 4(a) shows the floorplan of a 3x3 2D-mesh withstandard (modular) switches. Note that, each modular switchis suited in a single area, equidistant to other switches.Figure 4(b) shows the floorplan of a 3x3 2D-mesh whendistributed switches are implemented. Interconnection wireshave been omitted for clarity. Note that, the AC modulesof the different distributed switches are spread on the die.Each AC module is connected to AC modules at distance L/2as explained before. Sha<strong>de</strong>d AC modules represent a singledistributed link, as shown in Figure 3(b).The critical path of this switch can be computed in thesame way as the critical path of the modular switch. Thecombinational logic <strong>de</strong>lay of the distributed switch is i<strong>de</strong>nticalto the combinational logic of the modular switch and thereforethe <strong>de</strong>lay of the combinational part of the critical path remainsi<strong>de</strong>ntical. However, remember that for the distributed switchthe link length is half the length of the modular switch link.The length reduction of the distributed switch sublinks allowsthe <strong>de</strong>signer to reduce the link <strong>de</strong>lay of the distributed sublinkswith respect to the link <strong>de</strong>lay of the centralized links. Similarly,by fixing the same link <strong>de</strong>lay for both sublinks, the distributedsublink consumes less power than the centralized link.<strong>JP2011</strong>-223


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20114Wire Length 2.4 1.2 0.6Number of repeaters 7 6 3Size of the repeaters 15 6 6TABLE INUMBER AND SIZE OF THE REPEATERS OF A WIRE.(a) Floorplan with standard switches. (b) Floorplan with distributedswitches.Fig. 4.2D mesh floorplan with standard and distributed switches.IV. WIRE DESIGNIn this section we <strong>de</strong>scribe the <strong>de</strong>sign of the wire betweenswitches for both scenarios: when modular switches are used,and when distributed switches are implemented.Wire <strong>de</strong>lay has been set to 0.47ns to match the operatingfrequency of the switch to 1 GHz (see Section II-A) for boththe modular (or standard) switch and the distributed switch.In contrast, wire length differs from one switch <strong>de</strong>sign to theother. As mentioned in Section II, wire length for the modularswitch is set to 2.4mm. For the distributed switch, although thetile is i<strong>de</strong>ntical, wire configuration is different and, therefore,in practice wire length is divi<strong>de</strong>d by two, being 1.2mm (seeSection III). We do not take into account switch area in anyof both <strong>de</strong>signs.We use the higher metallization layers offered by thetechnology (M9-M10) to route the interconnection wires. Themain reason to use the highest metallization layers is that theselayers allow the <strong>de</strong>signer to use lower metallization layers forother purposes, as SRAM. Then, it is possible to route wiresbetween switches over functional modules as SRAM [13], thatis, route wires without using <strong>de</strong>dicated area for them. Notethat, the repeaters inserted along a wire use the same type ofresources as other functional blocks.Each segment of the wire is represented by a resistor anda capacitor that mo<strong>de</strong>l the resistance and the capacitanceof this segment of the wire, respectively. In our case, wehave mo<strong>de</strong>lled the wire by using the 5-pi wire mo<strong>de</strong>l [14].We insert repeaters along the wire when nee<strong>de</strong>d [2]. Thismethod reduces interconnect <strong>de</strong>lay and signal transition times.In or<strong>de</strong>r to minimize the power consumption of a wire, itis necessary to insert the proper number of minimum sizedrepeaters [3] that satisfies the <strong>de</strong>lay constraint imposed by theoperating frequency of the switch. This technique is calledpower-optimal repeater insertion [3]. Table I shows the numberand size (gain) of the repeaters of a wire for different wirelengths, when using the optimal repeater insertion techniquetogether with the wire parameters.V. AREA RESULTSIn this section we analyze the area of the modular anddistributed switch. Remember that both switches are i<strong>de</strong>nticalfrom a functional point of view, meaning that both switchesprovi<strong>de</strong> the same output response for an i<strong>de</strong>ntical input stimuli.Then, there is no difference in performance (at cycle level)when introducing both switches in a network.Table II shows the area occupied by the logic for bothswitches, the repeaters of a link, and the total area occupiedby the switch and the repeaters. As can be seen, the distributedswitch occupies a 13.82% less area than the modular switch.The main reason is that the distributed switch presents a simpler<strong>de</strong>sign that helps the synthesis tool to optimize the <strong>de</strong>sign.Furthermore, the modular switch presents some intermoduleconnectivity resources that the distributed switch does notpresent. Table II also shows the area occupied by the repeatersinserted along the link for a modular, and a distributedlink. As the number of sublinks increases in the distributedlink, the number of repeaters increases. As a consequence,area resources required by distributed switches increase withrespect to the modular switch. Finally, Table II shows wholeswitch area results for the different architectures presented.The area of the whole switch is calculated consi<strong>de</strong>ring thearea of switch modules and the area of the repeaters of fourlinks. As shown, the distributed switch architecture presents a22% more area than the modular switch.Area (um 2 ) Switch Repeaters TotalModular Switch 28356.72 2697.3 39145Distributed Switch 24437.28 5845.32 47817TABLE IIAREA COMPARISONVI. POWER CONSUMPTIONA. Switch Modules Power ConsumptionTable III shows the total power consumption of a modularswitch and its equivalent distributed switch. Table III showsalso the clock tree power consumption. The power consumptionhas been obtained using the Power Compiler tool bySynopsis. Results shows that the distributed switch has a lowerpower consumption, obtaining a reduction of 11.95%. Thissaving in power is due to the synthesis tool improvementdue to the simplicity of the distributed switch <strong>de</strong>sign andthe intermodule connectivity of the modular switch that isnot present in the distributed switch. In the same way, thedistributed switch also achieves a remarkable power reductionin the clock tree. Concretely, clock tree power consumptionof the modular switch is 14.78 mW, whereas the distributedswitch clock tree power is only 12.05 mW, representing a18.47% redutcion of power consumption.Power (mW) Clock tree TotalModular 14.78 71.21Distributed 12.05 62.7TABLE IIIPOWER CONSUMPTION OF A MODULAR AND A DISTRIBUTED SWITCH<strong>JP2011</strong>-224


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20115B. Wire Power ConsumptionIn this section we analyze the power consumption of a singlewire for different wire lengths, see Table IV. Power consumptionhas been obtained using Ca<strong>de</strong>nce Virtuoso. Powerconsumption of a wire <strong>de</strong>pends on the input signal. In theabsence of signal transition, the wire only consumes leakagepower which is negligible. Then, the dynamic power is themain power consumption source. Table IV also shows that asthe length of the wire <strong>de</strong>creases, the power consumption ofthe wire <strong>de</strong>creases. In average, this <strong>de</strong>crement is on average55%.Power Consumption (uW)Wire length (mm) Input transition No input transition2.4 358 0.8001.2 152 0.3500.6 69.3 0.162TABLE IVPOWER CONSUMPTION IN A CLOCK CYCLE FOR DIFFERENT LINK LENGTHSC. Link Power ConsumptionWire power consumption values in Table IV are used tocompute the power consumption of both the modular and thedistributed link (see Section IV). Define N as the total numberof wires in a link. N is set to 66 (see Section IV). Define P s (l)the total power consumption during a clock cycle of a singlewire of length l when there is no input transition (third columnin Table IV). Define P y (l) the total power consumption duringa clock cycle of a wire of length l when there is an inputtransition (second column in Table IV).As shown in the previous section, the power consumptionon a wire <strong>de</strong>pends on the input signal. Additionally, theprobability of having an input signal transition in a link wire<strong>de</strong>pends on both the link utilization (L u ) and the switchingactivity. Note that the switching activity (α) is <strong>de</strong>fined as theaverage probability of bit transition when flits traverse thelink. Typical values of switching activity are in the range of0.3 − 0.5 [15].In this paper, T is <strong>de</strong>fined as the probability that aninput signal modifies its value. This parameter takes intoconsi<strong>de</strong>ration both the probability of transmitting a flit andthe switching activity. Concretely, the value of T is given byT = L u ∗α. Finally, the power consumption of a modular link(P m ) as <strong>de</strong>fined in Section IV is:P m (T ) = N ∗T ∗P y (2.4mm)+N ∗(1−T )∗P s (2.4mm) (2)The power consumption of the modular link has two terms.The first term <strong>de</strong>fines the dynamic power consumption of thelink, whereas the second term <strong>de</strong>fines the link static powerconsumption of the link (when no information is crossing thelink).To measure the power consumption of a distributed link(P d ), it is necessary to remark that a distributed link is ma<strong>de</strong>of six sublinks of length 1.2mm. Thus, when no information iscrossing the link, the static power of the distributed link is thestatic power consumption of six sublinks of length 1.2mm. Incontrast, as mentioned before, the dynamic power consumptionFig. 5.power consumption (mW)252015105distributed linkmodular link00 0.2 0.4 0.6 0.8 1link utilization rate (T)Power consumption of a modular link and a distributed link.<strong>de</strong>pends on the number of flits that crosses the link (<strong>de</strong>fined bythe probability T ). As shown in Figure 3, the distributed linkis two stages long. Thus, any flit that crosses a distributed link,will traverse two small sublinks. Therefore, by assuming thesame traffic rate as in the modular link (<strong>de</strong>fined by probabilityT ), the distributed link is traversed by a number of flits <strong>de</strong>finedby the probability 2 ∗ T . Then, the power consumption of adistributed switch is:P d (T ) = 2 ∗ N ∗ T ∗ P y (1.2mm)+2 ∗ N ∗ (1 − T ) ∗ P s (1.2mm) + 4 ∗ N ∗ P s (1.2mm)Figure 5 shows the average power consumption per clockcycle of a modular and a distributed link for different valuesof T . For high traffic rates (high values of T), the distributedlink consumes less power than the modular link. Concretely,for T = 1, the distributed link is able to save 3.47mW perclock cycle (up to 14.68%). On the contrary, for low trafficrates (low values of T), the higher number of routed wiresin the distributed link causes the distributed link to consumemore power. However, when low traffic rate is present in thenetwork, the main contributor of the power consumption is theleakage power of the link, which is negligible in comparisonwith the dynamic power consumption of those links (seeSection VI-B). For T = 0 the distributed link only consumes138.6uW per clock cycle, while the modular link consumes52.8uW. The difference then is only 85uW per clock cycle.Anyway, for low link utilization rates, the different links overthe network are inactive. In these long inactivity periods, linkscan be turned off reducing power consumption to zero. Insuch network scenario, the link power consumption is mainly<strong>de</strong>fined by the dynamic power consumption of the link. Inthat case, the distributed link provi<strong>de</strong>s a power consumption<strong>de</strong>crement of 14.68%, which is the power consumption savingwhen only the dynamic power consumption is taken intoaccount (T = 1).As <strong>de</strong>scribed before, the distributed switch achieves betterpower results for low values of link utilization. Moreover,for real application scenarios, we have measured the linkutilization, obtaining that T is, in average, 6%. In that case, thedistributed link reaches a saving top in power consumption of(3)<strong>JP2011</strong>-225


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20116Fig. 6.operating frequency (GHz)1.61.41.210.8distributed switchmodular switch15 20 25 30 35 40 45 50 55 60peak power consumption (mW)Operating frequency of a modular and a distributed switch.8.7% with respect to the modular link. However, among otherreasons, the peak power of a CMP processor must be keptlower than a threshold, as the increasing heat dissipation inCMP architectures with multiple cores in a single die, maycause an increase of the thermal induced failures [16]. Peakpower saving of the distributed link is 14.68%.VII. OPERATING FREQUENCYIn previous sections we analysed how by reducing linklength, the power consumption of the distributed switch isreduced over the modular switch. The same is true for thepower consumption of the distributed link over the powerconsumption of the modular link. Those results have beenobtained when both scenarios work at the same operatingfrequency in or<strong>de</strong>r to allow a fair comparison. However,reducing link length has another important benefit. Whenshortening the link, the minimum link <strong>de</strong>lay – that sets thetotal latency of the switch – can be reduced. That is, givena power budget, the distributed link is able to work at higherfrequencies.Figure 6 shows the operating frequency of the distributedswitch and the modular switch with respect to the powerconsumption of their respective links. Note that, for the sameoperating frequency, the distributed link consumes less powerthan the modular one. Furthermore, the distributed switch isable to reach a maximum operating frequency higher than themodular switch. Concretely, the maximum operating frequencyof the distributed switch is 1.65GHz, whereas the maximumoperating frequency of the modular switch is 1.44GHz or, inother words, the maximum frequency of the distributed switchis 14.3% higher than that of the modular switch.VIII. CONCLUSIONSIn this paper a distributed switch architecture is presented.The distributed switch spreads the circuitry of a typical switcharchitecture along the link. Thus, each stage of a switch islocated at half the distance than in a conventional network.By reducing the distance between modules, the peak powerconsumption of NoC links can be reduced. As a drawback,the number of routed wires is increased.Results confirm that the distributed switch architecture isable to reduce peak power consumption by 14.8% in NoClinks at the expense of a 22% increase in the total area ofthe switch. Moreover, modules of the switch architecture alsosave power. Concretely, the distributed switch modules presenta power consumption reduction of 11.95%.On the other hand, results also show that given a powerbudget the frequency of the distributed switch is always higherthan the frequency of the modular switch. Moreover, themaximum achievable frequency of the distributed switch ishigher. In particular, the maximum operating frequency of thedistributed switch is a 14.3% higher.ACKNOWLEDGEMENTSThis work was supported by the Spanish MEC and MICINN,as well as European Commission FEDER funds, un<strong>de</strong>r GrantsCSD2006-00046 and TIN2009-14475-C04. It was also partly supportedby the project NaNoC (project label 248972) which is fun<strong>de</strong>dby the European Commission within the Research Programme FP7.REFERENCES[1] J. Flich et al., Designing Network On-Chip Architectures in theNanoscale Era, ser. Computational Science Series, D. Bertozzi et al.,Eds. Chapman and Hall, 2010.[2] R. Ho, et al., “The future of wires,” in Proceedings of the IEEE, 2001,pp. 490–504.[3] G. Chen et al., “Low-power repeaters driving RC and RLC interconnectswith <strong>de</strong>lay and bandwidth constraints,” IEEE Trans. VLSI Syst., vol. 14,no. 2, pp. 161–172, 2006.[4] D. Schinkel, et al., “Low-power, high-speed transceivers for networkon-chipcommunication,” IEEE Trans. VLSI Syst., vol. 17, no. 1, pp.12–21, 2009.[5] A. Roca, et al., “A low-latency modular switch for CMP systems,”University of Valencia, Tech. Rep., 2011. [Online]. Available:www.disca.upv.es/jflich/techreportmodularswitch.pdf[6] G. <strong>de</strong> Micheli et al., Networks on Chips: Technology And Tools, ser. InSystems on Silicon. Morgan Kaufmann Pub, July 2006.[7] J.-K. Peir et al., “Look-ahead routing switches for multistage interconnectionnetworks,” J. Parallel Distrib. Comput., vol. 19, no. 1, pp. 1–10,1993.[8] S. Li, et al., “McPAT: an integrated power, area, and timing mo<strong>de</strong>lingframework for multicore and manycore architectures,” in MICRO, 2009,pp. 469–480.[9] C. Liu, et al., “Organizing the last line of <strong>de</strong>fense before hitting thememory wall for cmp,” in HPCA, 2004, pp. 176–185.[10] 45nm FreePDK. The Nangate open cell library. [Online]. Available:https://www.si2.org/openeda.si2.org/projects/nangatelib/[11] S. Medardoni, et al., “Variation tolerant NoC <strong>de</strong>sign by means of selfcalibratinglinks,” in DATE, 2008, pp. 1402–1407.[12] C. Hernan<strong>de</strong>z, et al., “Improving the performance of GALS-based NoCsin the presence of process variation,” in NOCS, 2010, pp. 35–42.[13] G. Passas, et al., “A 128 x 128 x 24gb/s crossbar interconnecting 128tiles in a single hop and occupying 6% of their area,” in NOCS, 2010,pp. 87–95.[14] I. Benito, “Global interconnects in the presence of uncertainty,” Ph.D.dissertation, University of Massachusetts, 2008.[15] A. Kahng, et al., “Orion 2.0: A fast and accurate noc power and areamo<strong>de</strong>l for early-stage <strong>de</strong>sign space exploration,” in Design, AutomationTest in Europe Conference Exhibition, 2009. DATE ’09., 2009, pp. 423–428.[16] Y. Wang, et al., “Temperature-constrained power control for chip multiprocessorswith online mo<strong>de</strong>l estimation,” in Proceedings of the 36thannual international symposium on Computer architecture, 2009, pp.314–324.<strong>JP2011</strong>-226


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Reducing the Energy Consumption ofHardware Prefetching in Many-Core CMPsusing Reply PartitioningAntonio Flores, Manuel E. Acacio, and Juan L. Aragón 1Resumen— In this work, we show how to reduce theenergy impact of prefetching techniques in the contextof tiled CMPs. Our proposal is based on ReplyPartitioning, a technique that classifies all coherencemessages into critical and short, and non-critical andlong messages; and the use of a heterogeneous interconnectionnetwork comprised of low-latency wires forcritical messages and low-energy wires for non-criticalones and prefetched lines. Detailed simulations of a16-core CMP show that our proposal obtains improvementsof up to 75% in the energy consumed by theinterconnect (45-50% on average) with almost negligiblecost in terms of execution time (average <strong>de</strong>gradationof 3%).Palabras clave— Tiled Chip-Multiprocessor, Energy-Efficient Architectures, Hardware Prefetching, HeterogeneusOn-Chip Interconnection Network.I. IntroductionTODAY, multi-core architectures are envisionedas the only way to ensure performance improvements.In this way, <strong>de</strong>signs with tens of cores on thedie will be a reality within this <strong>de</strong>ca<strong>de</strong>. Additionally,future many-core CMPs with several tens (oreven hundreds) of processor cores probably will be<strong>de</strong>signed as arrays of replicated tiles connected overan on-chip switched direct network [1]. These tiledarchitectures have been claimed to provi<strong>de</strong> a scalablesolution for managing the <strong>de</strong>sign complexity, and effectivelyusing the resources available in advancedVLSI technologies. Maybe, one of the best knownexamples of a tiled CMP architecture today is the80-core Intel’s Polaris prototype [2].However, one of the greatest bottlenecks to provi<strong>de</strong>high performance and energy efficiency in suchtiled CMP architectures is the high cost of on-chipcommunication through global wires [3]. Wang et al.[4] reported that the on-chip network of the Raw processorconsumes 36% of the total chip power. Magenet al. [5] also attribute 50% of overall chip power tothe interconnect. Most of this power is consumed inthe point-to-point links of the interconnect [4]. Thus,wires pose major performance and power consumptionproblems as technology shrinks and total diearea increases.One way to tackle problems due to wire <strong>de</strong>lay is touse latency hiding techniques like hardware prefetching,which eliminates some cache misses and/or overlapsthe latencies of others. Unfortunately, hardwareprefetching significantly increases on-chip communicationsince coherence between the L1 caches of the1 Dpto. Ingeniería y Tec. <strong>de</strong> Computadores, Univ. Murcia,e-mail: {aflores,meacacio,jlaragon}@ditec.um.es.tiled CMP must be ensured, increasing the powerconsumption of the on-chip interconnect.Another approach to alleviate the negative effectof wire <strong>de</strong>lays and the increasing interconnect powerconsumption is the use of heterogeneous on-chip interconnectionnetworks [6], i.e., an interconnect withlinks comprised of wires with varying physical properties.By tuning wire width and spacing, it is possibleto <strong>de</strong>sign wires with varying latency and bandwidthproperties. Similarly, by tuning repeater sizeand spacing, it is possible to <strong>de</strong>sign wires with varyinglatency and energy properties. This paper exploressuch an approach by proposing the use of ReplyPartitioning[7], a technique that allows criticalmessages to be transmitted using low latency wiresmeanwhile the rest of messages, including prefetchedlines, are transmitted using low power wires, in thecontext of hardware prefetching. Detailed simulationsof a 16-core CMP show average improvementsof 10% in execution time and 38% in the ED 2 P metricof the interconnect (28% of the full CMP).The rest of this paper is organized as follows. SectionII reviews some related work. Our proposal forefficient message management in tiled CMPs is presentedin section III. Section IV <strong>de</strong>scribes the evaluationmethodology and presents the results of theproposed mechanism, and finally, section V summarizesthe main conclusions of the work.II. Related WorkThe on-chip interconnection network is a critical<strong>de</strong>sign element in a multi-core architecture and, consequently,it is the subject of several recent works.Among others, Kumar et al. [8] analyze several onchipinterconnection mechanisms and topologies, andquantify their area, power, and latency overheads.Their study conclu<strong>de</strong>s that the <strong>de</strong>sign choices for theinterconnect have a significant effect on the rest ofthe chip, potentially consuming a significant fractionof the real estate and power budget.Hardware prefetching has been proposed an<strong>de</strong>xplored by many researchers [9][10][11], and iscurrently implemented in many existing systems[12][13]. From mid-sixties, early studies [14] of cache<strong>de</strong>sign recognized the benefits of prefetching. Hardwareprefetching of separate cache blocks was laterimplemented in the IBM 370/168 and Amdahl 470V[15]. Smith summarizes several of these early approachesin his survey of cache memories [16]. Jouppi[17] introduced stream buffers that trigger succes-<strong>JP2011</strong>-227


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011sive cache line prefetches on a miss. Chen andBaer [9] proposed variations of stri<strong>de</strong>-based hardwareprefetching to reduce the cache-to-memory latency.Dahlgren et. al. [18] proposed an adaptive sequential(unit-stri<strong>de</strong>) prefetching scheme that adaptsto the effectiveness of prefetching. Ki and Knowles[19] used extra cache bits to increase the accuracyof prefetching. Srinivasan et. al. [20], classifiedprefetches according to whether they reduce or increasemisses or traffic.On the other hand, a reduced number of workshave attempted to exploit the properties of a heterogeneousinterconnection network at the microarchitecturelevel in or<strong>de</strong>r to reduce the interconnectenergy share. Beckmann and Wood [21] propose theuse of transmission lines to access large L2 on-chipcaches in or<strong>de</strong>r to reduce the required cache areaand the dynamic power consumption of the interconnectionnetwork. In [6], Balasubramonian et al.make the first proposal of wire management at themicroarchitecture level. They introduce the conceptof a heterogeneous interconnect that is comprisedof wires with varying area, latency, bandwidth,and energy characteristics, and they applyit to register communication within a clustered architecture.In particular, cache accesses are acceleratedby sending a subset of the address bits on lowlatencywires to prefetch data out of the L1 D-cache,while non-critical register values are transmitted onlow-power wires. They extend this proposal in [22]with techniques aimed at accelerating cache accessesin large L2/L3 split caches (L2/L3 NUCA architectures)by taking advantage of a lower-bandwidth,lower-latency network.Recently, Cheng et al. [23] applied the heterogeneousnetwork concept to the cache coherence trafficproblem in CMPs. In particular, they proposean interconnection network composed of three setsof wires with varying latency, bandwidth and energycharacteristics, and map coherence messages tothe appropriate set taking into account their latencyand bandwidth needs. They report significant performanceimprovement and interconnect energy reductionwhen a two-level tree interconnect is used toconnect the cores and the L2 cache. Unfortunately,insignificant performance improvements are reportedfor direct topologies (such as the 2D mesh typicallyemployed in tiled CMPs [2]).wires that are routed over memory arrays, as in [8].It can be seen that L-Wires yield a two-fold latencyimprovement at a four-fold area cost. On the otherhand, PW-Wires are <strong>de</strong>signed to reduce power consumptionwith twice the <strong>de</strong>lay of baseline wires (andthe same area cost).More recently, we have proposed in [7] Reply Partitioning,a technique that allows all coherence messagesto be classified into two groups: critical andshort, and non-critical and long. In particular, ReplyPartitioning focuses on replies that carry dataand split them into a critical and short Partial Replymessage that carries the word requested by the processor,in addition to a non-critical Ordinary Replywith the rest of the cache block. Reply Partitioningaims to use a heterogeneous interconnection networkcomprised of low-latency wires for critical messagesand low-energy wires for non-critical ones, which alsoallows for a more balanced workload. Note that inthe original proposal of Reply Partitioning, no hardwareprefetching technique was consi<strong>de</strong>red.Finally, in [24] we presented a proposal for carryingout energy-efficient hardware prefetching using lowpowerlinks to transmit most of the additional trafficthat prefetching generates, whereas the remainingtraffic employs baseline wires. Improvements of upto 30% in the power consumed by the interconnectwas obtained with almost negligible cost in terms ofexecution time.III. A Proposal for Efficient MessageManagement in Tiled CMPs withHardware PrefetchingIn this section we present our proposal for improvingthe performance and reducing the energy dissipatedby hardware prefetching in tiled CMPs. Thissection starts with a <strong>de</strong>scription of the tiled CMP architectureassumed in this paper, followed by a classificationof the messages in terms of both their criticalityand size when prefetching is employed an<strong>de</strong>nds with the <strong>de</strong>scription of the proposed mechanism.A. Tiled CMP ArchitecturesTABLA IArea, <strong>de</strong>lay and power characteristics of wireimplementations.Wire Type Relative <strong>La</strong>tency Relative Area Dynamic Power (W/m) Static Powerα=Switching Factor W/mB-Wire (8X plane) 1x 1x 2.65α 1.0246B-Wire (4X plane) 1.6x 0.5x 2.9α 1.1578L-Wire (8X plane) 0.5x 4x 1.46α 0.5670PW-Wire (4X plane) 3.2x 0.5x 0.87α 0.3074PW-Wire (8X plane) 2x x 0.80α 0.2720Fig. 1.Tiled CMP architecture overview.Table I shows the relative area, <strong>de</strong>lay and powercharacteristics of L- and PW-Wires compared tobaseline wires (B-Wires), as reported in [23]. A65 nm process technology is consi<strong>de</strong>red, where 4Xand 8X metal planes are used for global inter-coreA tiled CMP architecture consists of a number ofreplicated tiles connected over a switched direct network(Fig. 1). Each tile contains a processing corewith primary caches, a slice of the L2 cache, and aconnection to the on-chip network. The L2 cache is<strong>JP2011</strong>-228


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011shared among the different processing cores, but itis physically distributed between them. Therefore,some accesses to the L2 cache will be sent to thelocal slice while the rest will be serviced by remoteslices. In addition, the L2 cache stores (in the tags’part of the local L2 slice) the directory informationnee<strong>de</strong>d to ensure coherence between the L1 caches.On a L1 cache miss, a request is sent down to theappropriate tile where further protocol actions areinitiated based on that block’s directory state, suchas invalidation messages, intervention messages, datawriteback, data block transfers, etc. A stri<strong>de</strong>-basedtechnique is used as prefetcher [9][18][19], with a referenceprediction table (RPT) to keep the informationfor the most recently used memory instructions.The organization of the RPT is <strong>de</strong>picted in Fig. 2.Table entries contain the address of the memory instruction,the previous address accessed by this instruction,a stri<strong>de</strong> value for those entries which followa stri<strong>de</strong> pattern and a state field which records theentry’s current state. In this paper, we assume aprocess technology of 65 nm, a tile area of approximately25 mm 2 , and a die size in the or<strong>de</strong>r of 400mm 2 [1][25]. Further <strong>de</strong>tails about the evaluationmethodology and the simulated CMP configurationcan be found in section IV.Fig. 2.PCeffective addressinstruction tag previous address stri<strong>de</strong> stateprefetch addressThe organization of the reference prediction table.B. Classification of messages in Tiled CMP Architectureswith PrefetchingThere are a variety of message types traveling onthe interconnect of a CMP, each one with propertiesthat are clearly distinct. In general, we can classifymessages into the following groups (see Fig. 3):Request messages, that are generated by cache controllersin response to L1 cache misses, or a likelyfuture L1 cache miss when prefetching is consi<strong>de</strong>red,and sent to the corresponding home L2 cache to <strong>de</strong>mandprivileges over a memory line. Response messagesto these requests, generated by the home L2cache controller or, alternatively, by the remote L1cache that has the single valid copy of the data, andthey can carry the memory line or not. Coherencecommands, that are sent by the home L2 cache controllerto the corresponding L1 caches to ensure coherence.Coherence responses, sent by the L1 cachesback to the corresponding home L2 in response tocoherence commands. Replacement messages, thatthe L1 caches generate in case of exclusive or modifiedlines being replaced (replacement hints are notsent for lines in shared state).RequestResponseCohe commandCohe responseReplacementSrc Dest Type Control AddressSrc Dest Type MSHR Cache BlockSrcDestType MSHRSrc Dest Type Control AddressSrcSrcDestDestType MSHRType MSHRSrc Dest Type Control AddressCache BlockSrc Dest Type Control Address Cache BlockFig. 3. Classification of messages that travel on the interconnectionnetwork of a Tiled CMP Architecture.Messages involved in the L1 cache coherence protocolshown in Fig. 3 can be classified accordingto their criticality into critical and non-critical messages.We say that a message is critical when it is inthe critical path of the L1 cache miss. In other case,we call the message as non-critical. As expected, <strong>de</strong>layinga critical message will result in longer L1 cachemiss latencies. On the other hand, slight slowdownsin the <strong>de</strong>livery of non-critical messages will not causeany performance <strong>de</strong>gradation. Applying Reply Partitioningwe can split reply messages that carry datainto a short critical message containing the sub-blockof the cache requested by the core as well as a longnon-critical message with the whole cache line. Thispartitioning allows for a more energy-efficient use ofthe heterogeneous interconnect since now all shortmessages have been ma<strong>de</strong> critical whereas all longmessages have been ma<strong>de</strong> non-critical. The formercan be sent through L-Wires whereas the latter canbe sent through PW-Wires. Using this criterion, allmessages related with prefeching could be consi<strong>de</strong>redas non-critical because they <strong>de</strong>al with data blocksthat will be nee<strong>de</strong>d in the future. It is clear thatenergy is saved, theoretically without affecting performanceif the <strong>de</strong>lay imposed is not too high, whenthis kind of messages travel on slower, power-efficientPW-Wires. Critical messages will be sent through L-Wires.Fig. 4 (top) plots the fraction of each messagetype for a 16-core CMP configuration when stri<strong>de</strong>prefetching (K=1, 3) is consi<strong>de</strong>red and for the applicationsused in our evaluation (see section IV-A for evaluation <strong>de</strong>tails). Results have been normalizedwith respect to a base configuration withoutprefetching. As pointed out before, hardwareprefetching significantly increases on-chip communication.Average increases of about 20% in networktraffic are observed. And, on average, between 18%to 32% of the network traffic is due to prefetching(prefetch requests, their corresponding replies andall coherence traffic involved), whereas the rest hasto do with ordinary messages.Even more interesting is Fig. 4 (bottom) whichshows a breakdown of the network power consumptionfor each message type. Again, results are normalizedwith respect to the network power consump-<strong>JP2011</strong>-229


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA IIConfiguration of the evaluated baseline CMParchitecture and applications.CMP ConfigurationProcess technology65 nmTile area 25 mm 2Number of tiles 16Cache line size64 bytesCore4GHz, in-or<strong>de</strong>r 2-way mo<strong>de</strong>lL1 I/D-Cache32KB, 4-wayL2 Cache (per core) 256KB, 4-way, 6+2 cyclesMemory access time400 cyclesNetwork configuration2D meshNetwork bandwidth75 GB/sLink width75 bytes (8X-B-Wires)Link length5 mmApplicationProblem sizeBarnes-Hut16K bodies, 4 timestepsEM3D 9600 no<strong>de</strong>s, 5% remote links, 4 timestepsFFT256K complex doublesLU-cont 256 × 256, B=8Ocean-Nonc258 × 258 gridUnstructuredmesh.2K, 5 timestepsWater-spa512 molecules, 4 timestepsFig. 4. Breakdown of the messages that travel on the interconnectionnetwork for a 16-core CMP (top) and percentageof the power consummed in the interconnect by each typeof message (bottom).tion when no prefetching technique is used. Theamount of power consumed in the interconnect associatedwith prefetching traffic ranges from 21-35%<strong>de</strong>pending on K.As previously commented, most of this power isconsumed in the point-to-point links, and therefore,message size plays a major role. In particular,prefetch replies are 67-byte long since they carrycontrol information (3-bytes) and a cache line (64bytes). On the contrary, requests and coherencecommands are 11-byte long since besi<strong>de</strong> control information(3 bytes) they also carry address information(8 bytes). Finally, coherence replies are just3-byte long. The use of a heterogeneous interconnectcomprised of low-latency L-Wires and powerefficientPW-Wires allows for a more energy-efficientinterconnect utilization. However, as the number ofL-Wires is smaller because of their four-fold areacost (relative to baseline wires) only short messagescan take full advantage of them, this inclu<strong>de</strong>s partialreplies generated by Reply Partitioning mecanishmwith almost negligible cost in terms of execution time(average <strong>de</strong>gradation of 3%)in response to both ordinaryand prefetch requests. On the other hand,since message size has direct impact on the powerdissipated in the interconnect, significant energy savingscan be obtained when long messages, includingprefetched lines, are sent using PW-Wires. It is importantto note that we also split prefetched lines toavoid an increment of late prefetches.IV. Experimental ResultsThis section shows the results that are obtained forour proposal un<strong>de</strong>r different scenarios and comparethem against those achieved with the configurationthat employs just B-Wires, which is taken as baseline.A. Evaluation MethodologyThe results presented in this work have been obtainedthrough <strong>de</strong>tailed simulations of a full CMP.We have employed a cycle-accurate CMP powerperformancesimulation tool, Sim-PowerCMP [26],that estimates both dynamic and leakage power andis based on RSIM . In particular, Sim-PowerCMPemploys as performance simulator a modified versionof RSIM that mo<strong>de</strong>ls the architecture of the tiledCMP presented in section III. Sim-PowerCMP alsoimplements already proposed and validated powermo<strong>de</strong>ls for both dynamic power and leakage powerof each processing core, as well as the interconnectionnetwork.Table II (top) shows the architecture configurationused across this paper. It <strong>de</strong>scribes a 16-core CMPbuilt in 65 nm technology. The tile area has beenfixed to 25 mm 2 , including a portion of the secondlevelcache [1]. With this configuration, links that interconnectrouters configuring the 2D mesh topologymeasure around 5 mm. Table II (bottom) shows theapplications used in our experiments. Barnes-Hut,FFT, LU-cont, Ocean-Nonc and Water-nsq are fromthe SPLASH-2 benchmark suite; Berkeley EM3Dsimulates the propagation of electro-magnetic wavesthrough objects in three dimensions; and Unstructuredis a computational fluid dynamics applicationthat uses an unstructured mesh. Problem sizes havebeen chosen commensurate with the size of the L1caches and the number of cores used in our simulations.All experimental results reported in this work<strong>JP2011</strong>-230


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011are for the parallel phase of these applications.B. Simulation results and analysisIn this section we analyze the impact of our proposalon both the execution time and the power consumptionfor the inter-core links. All results havebeen normalized with respect to the baseline nonprefetchingconfiguration where only B-Wire, unidirectional75-byte wi<strong>de</strong> links are consi<strong>de</strong>red (with theexception of Fig. 7 where results are normalized withrespect to a 16-core CMP with stri<strong>de</strong> prefetching).Fig. 6. Classification of the different types of prefetches observedfor the B-Wire only L- + PW-Wire interconnect.Fig. 5. Normalized execution time for different prefetchingschemes (with and without heterogeneous links) for a 16-core CMP.Fig. 5 shows the normalized execution times withrespect to that obtained for the baseline configurationfor a 16-core CMP without prefetching. In particular,barlines show the normalized execution timesfor the stri<strong>de</strong>-based prefetch technique (K=1, 3) appliedto the L1D private caches. Each prefetcher containsthree separate filter tables: positive unit stri<strong>de</strong>,negative unit stri<strong>de</strong>, and non-unit stri<strong>de</strong>. Once a filtertable entry <strong>de</strong>tects a miss stream, the prefetcherallocates an entry in the stream table and initiatesthe prefetch of K consecutive cache blocks. Forcomparison purposes, the normalized execution timeobtained when only B-Wires are employed is alsoshown. On average, we obtain average improvementsin execution time that range from 5% (K=3)to 8% (K=1) when no heterogeneous network is consi<strong>de</strong>red,which <strong>de</strong>monstrates the convenience of usinghardware prefetching in future many-core CMPs.This improvement has high variability, ranging fromalmost negligible or even a slight <strong>de</strong>gradation forBarnes, Unstructured and Water-SPA to improvementsof 20-25% for em3d and Ocean-Nonc.This observed variability is due to the memory accesspatterns exhibited by the applications. Someapplications, as FFT or LU-Cont, present regularmemory access patterns that lead to high percentageof useful prefetches. as we can see in Fig. 6 (top)where we present a classification of the prefetches. Inthis figure, prefetches are classified into: useful if theprefetched line is accessed before being replaced, lateif other requests coalesce into the MSHR allocatedfor the prefetched line, useless if the prefetched linegets replaced before it is requested by the processor,unnecesary if the prefetch coalesces into a MSHRfor an already-on-the-fly cache miss, and invalidatedif the prefetched line gets invalidated before beingrequested by the processor.On the other hand, applicationssuch as Water shows a high percentage oflate or useless prefetches that lead to negligible improvementsin the execution time.Going back to Fig. 5 again, when heterogeneouslinks are consi<strong>de</strong>red, an average slowdown of about3% is observed with respect to the B-Wire-onlyconfiguration with prefetching. This <strong>de</strong>gradationis explained by the additional <strong>de</strong>lay of sending theprefetch replies through PW-Wires. Results showthat 2-5% of the previously useful prefetches are nowclassified as late prefetches, explaining the observedslowdown.Fig. 7. Normalized link enery consumption for stri<strong>de</strong> prefetching(K=1, 3) over L- + PW-Wires links (baseline configuration:16-core CMP with prefetching).However, the benefits of using a heterogeneous interconnectin the context of hardware prefetching, aswe propose, can be noticed when consi<strong>de</strong>ring the networkenergy dissipation. Fig. 7 plots the normalizedlink energy when Reply Partitioning is used over L-+ PW-Wires links. The baseline configuration is a16-core CMP with the same prefetching configurationbut using only B-Wire links. Reductions of upto 75% are obtained (55-60% on average) and in thiscase the variability among applications is reduced.Better results are obtained, as expected, for K=3 due<strong>JP2011</strong>-231


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011to the bigger emphasis on prefetching traffic (as seenin Fig. 4). This leads to more important reductionsin the link energy dissipation when prefetched linesare sent through PW-Wires. These improvementstranslate into average energy reductions of 7% whenthe full CMP is consi<strong>de</strong>red.V. ConclusionsIn this work we propose a energy-efficient messagemanagement mechanism for tiled CMPs that consistsof two approaches. The first one is Reply Partitioning,a technique that allows all coherence messagesto be classified into two groups: critical andshort, and non-critical and long. In particular, ReplyPartitioning concentrates on replies that carrydata, including prefethed lines, and splits them intoa critical and short Partial Reply message that carriesthe word requested by the processor and a noncriticalOrdinary Reply with the rest of the cacheblock. The second approach of our proposal is theuse of a heterogeneous interconnection network comprisedof low-latency wires for critical messages andlow-energy wires for non-critical ones which also allowsfor a more balanced workload.Results obtained through <strong>de</strong>tailed simulations of a16-core CMP show that the proposed on-chip messagemanagement mechanism can reduce the energydissipated by the links of the interconnection networkabout 60%, on average, with little impact in the executiontime (<strong>de</strong>gradation of 3%, on average). Finally,these reductions translate into overall CMP energysavings of 7%. These results reveal that correctlyorganizing the interconnection network and properlymanaging the different types of messages through ithave significant impact on the energy consumed byCMPs, especially for next-generation <strong>de</strong>nse CMP architectures.AcknowledgmentsThis work was supported by the Spanish MEC andMICINN, as well as European Comission FEDERfunds, un<strong>de</strong>r Grants CSD2006-00046 and TIN2009-14475-C04.References[1] Michael Zhang and Krste Asanovic, “Victim Replication:Maximizing Capacity while Hiding Wire Delay inTiled Chip Multiprocessors,” in Proc. of the 32nd Int’lSymp. on Computer Architecture (ISCA-32), June 2005,pp. 336–345.[2] S. Vangal, J. Howard, G. Ruhl, et al., “An 80-Tile1.28TFLOPS Network-on-Chip in 65nm CMOS,” inSolid-State Circuits Conference (ISSCC’07), 2007, pp.98–589.[3] R. Ho, KW. Mai, and MA. Horowitz, “The Future OfWires,” Proceedings of the IEEE, vol. 89, no. 4, pp. 490–504, April 2001.[4] Hang-Sheng Wang, Xinping Zhu, et al., “Orion: APower-Performance Simulator for Interconnection Networks,”in Proc. of the 35th Int’l Symp. on Microarchitecture(MICRO’02), November 2002, pp. 294–305.[5] Nir Magen, Avinoam Kolodny, Uri Weiser, and NachumShamir, “Interconnect-Power Dissipation in a Microprocessor,”in Proc. of the 6th Int’l Workshop on SystemLevel Interconnect Prediction (SLIP-6), February 2004,pp. 7–13.[6] Rajeev Balasubramonian, Naveen Muralimanohar, et al.,“Microarchitectural Wire Management for Performanceand Power in Partitioned Architectures,” in Proc. of the11th Int’l Symp. on High-Performance Computer Architecture(HPCA-11), February 2005, pp. 28–39.[7] Antonio Flores, Juan L. Aragón, and Manuel E. Acacio,“Heterogeneous Interconnects for Energy-Efficient MessageManagement in CMPs,” IEEE Trans. Comput., vol.59, no. 1, pp. 16–28, 2010.[8] Rakesh Kumar, Victor Zyuban, and Dean M. Tullsen,“Interconnections in Multi-Core Architectures: Un<strong>de</strong>rstandingMechanisms, Overheads and Scaling,” inProc. of the 32nd Int’l Symp. on Computer Architecture(ISCA-32), June 2005, pp. 408–419.[9] Tien-Fu Chen and Jean-Loup Baer, “Effective Hardware-Based Data Prefetching for High-Performance Processors,”IEEE Trans. Comput., vol. 44, no. 5, pp. 609–623,1995.[10] Doug Joseph and Dirk Grunwald, “Prefetching UsingMarkov Predictors,” in Proc. of the 24th Int’l Symp. onComputer Architecture (ISCA’97)), 1997, pp. 252–263.[11] Amir Roth, Andreas Moshovos, and Gurindar S. Sohi,“Depen<strong>de</strong>nce Based Prefetching for Linked Data Structures,”SIGPLAN Not., vol. 33, no. 11, pp. 115–126,1998.[12] Glenn Hinton, Dave Sager, et al., “The Microarchitectureof the Pentium 4 Processor,” Intel Technology Journal,vol. 1, 2001.[13] B. Sinharoy, R. N. Kalla, et al., “POWER5 System Microarchitecture,”IBM J. Res. Dev., vol. 49, no. 4/5, pp.505–521, 2005.[14] W. Anacker and C. P. Wang, “Performance Evaluationof Computing Systems with Memory Hierarchies,” IEEETrans. on Computers, vol. 16, no. 6, pp. 764–773, <strong>de</strong>cember1967.[15] A.J. Smith, “Sequential Program Prefetching in MemoryHierarchies,” Computer, vol. 11, no. 12, pp. 7–21, 1978.[16] Alan Jay Smith, “Cache Memories,” ACM Comput.Surv., vol. 14, no. 3, pp. 473–530, september 1982.[17] Norman P. Jouppi, “Improving Direct-Mapped CachePerformance by the Addition of a Small Fully-AssociativeCache and Prefetch Buffers,” SIGARCH Comput. Archit.News, vol. 18, no. 3a, pp. 364–373, 1990.[18] Fredrik Dahlgren, Michel Dubois, and Per Stenström,“Sequential Hardware Prefetching in Shared-MemoryMultiprocessors,” IEEE Trans. Parallel Distrib. Syst.,vol. 6, no. 7, pp. 733–746, 1995.[19] Ando Ki and Alan E. Knowles, “Adaptive Data PrefetchingUsing Cache Information,” in Proc. of the 11th Int’lConf. on Supercomputing (ICS’97), 1997, pp. 204–212.[20] Viji Srinivasan, Edward S Davidson, and Gary S Tyson,“A Prefetch Taxonomy,” IEEE Trans. on Computers,vol. 53, pp. 126–140, 2004.[21] Bradford M. Beckmann and David A. Wood, “TLC:Transmission Line Caches,” in Proc. of the 36th Int’lSymp. on Microarchitecture (MICRO-36), December2003, pp. 43–54.[22] Naveen Muralimanohar and Rajeev Balasubramonian,“The Effect of Interconnect Design on the Performanceof <strong>La</strong>rge L2 Caches,” in 3rd IBM Watson Conf. on Interactionbetween Architecture, Circuits, and Compilers(P=ac2), October 2006.[23] Liqun Cheng, Naveen Muralimanohar, et al.,“Interconnect-Aware Coherence Protocols for ChipMultiprocessors,” in Proc. of the 33rd Int’l Symp.on Computer Architecture (ISCA’06), June 2006, pp.339–351.[24] A. Flores, J.L. Aragón, and M.E. Acacio, “Energy-Efficient Hardware prefetching for CMPs Using HeterogeneousInterconnects,” in Proc. of the 18th EuromicroInt’l Conf. on Parallel, Distributed and Network-Based Computing (EUROMICRO-PDP’10), February2010, pp. 147–154.[25] Li Zhao, Ravi Iyer, et al., “Performance, Area and BandwidthImplications on <strong>La</strong>rge-Scale CMP Cache Design,”in Proc. of the 1st Workshop on Chip MultiprocessorMemory Systems and Interconnects (CMP-MSI’07). Inconjunction with HPCA-13), February 2007.[26] Antonio Flores, Juan L. Aragón, and Manuel E. Acacio,“An Energy Consumption Characterization of On-ChipInterconnection Networks for Tiled CMP Architectures,”J. Supercomput., vol. 45, no. 3, pp. 341–364, 2008.<strong>JP2011</strong>-232


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Mo<strong>de</strong>lling Permanent Fault Impact onCache PerformanceDaniel Sánchez 1 , Yiannakis Sazei<strong>de</strong>s 2 , Juan L. Aragón 1 and José M. García 1Abstract—The probability of parametric and wear-out failuresexacerbates due to the increase of static and dynamicvariations. Specifically, caches that dominate the areaof mo<strong>de</strong>rn processors and are built with minimumsizedSRAM cells are very susceptible to faults.In this paper, we present an analytical mo<strong>de</strong>l for<strong>de</strong>termining the implications on cache miss-rate dueto the use of block-disabling, a mechanism which disablesfaulty portions of the cache, to mitigate randomcell failure. Whereas previous proposals are basedon the simulation of different fault-maps, our mo<strong>de</strong>lavoids them and provi<strong>de</strong>s exact measures rather thanapproximations.Our evaluation reveals, for the assumptions, programsand cache configuration used in this study,that a relative small number of random fault maps,100-1000, is sufficient to obtain accurate mean andstandard-<strong>de</strong>viation values for the miss-rate.I. IntroductionOver the past 50 years, technological advanceshave enabled continuous miniaturization of circuitsand wires. Unfortunately, the scaling of <strong>de</strong>vice areahas been followed by at least two negative consequences:a slowdown of both voltage scaling andfrequency increase, due to slower scaling of leakagecurrent as compared to area scaling [1], [2] and ashift to probabilistic <strong>de</strong>sign and less reliable siliconprimitives as a result of static [3] and dynamic [4]variations.A recently published resilience roadmap un<strong>de</strong>rlinesthe magnitu<strong>de</strong> of the problem we are confrontedwith [5]. Table I shows the predicted p fail (probabilityof failure) for inverters, latches and SRAM cellsdue to random dopant fluctuations as a function oftechnology no<strong>de</strong>. This study clearly shows that, forall types of circuits, the p fail increases at a muchfaster rate than the area scaling. However, not all circuitsare equally vulnerable: SRAM cells, which areusually built with minimum-sized <strong>de</strong>vices, are highlymore likely to fail. These alarming trends are leadingto forecast that the performance and cost benefitsfrom area scaling will be hin<strong>de</strong>red unless scalabletechniques are <strong>de</strong>veloped to address the power andreliability challenges. Thus, the <strong>de</strong>velopment of reliabilitytechniques for future processors which areboth scalable and performance-effective is essential,especially for caches that take most of the real-estatein processors and contain numerous SRAM vulnerablecells.One option is to rely on the error-correction-co<strong>de</strong>s(ECC) already in place to <strong>de</strong>tect and correct soft-1 Dept. of Computer Engineering, Univ. of Murcia. e-mail:{dsanchez,jlaragon,jmgarcia}@ditec.um.es2 Department of Computer Science, Univ. of Cyprus. e-mail:yanos@cs.ucy.ac.cyTABLE IPredicted p fail for different types of circuits andtechnologies.Technology Inverter <strong>La</strong>tch SRAM45nm ≈ 0 ≈ 0 6.1e-1332nm ≈ 0 1.8e-44 7.3e-0922nm ≈ 0 5.5e-18 1.5e-0616nm 2.4e-58 5.4e-10 5.5e-0512nm 1.2e-39 3.6e-07 2.6e-04errors. However, ECC is not a performance-friendlymechanism for permanent errors because, potentially,every access to a faulty block will incur theECC repair overhead. Furthermore, ECC soft-errorcapabilities are reduced when some bits protected bythe ECC co<strong>de</strong> are already faulty. Thus, ECC maynot be the best option to repair a large number ofparametric or wear-out faults in a cache.Another approach is to disable cache portions suchas blocks or words [6], [7], [8] that contain faulty bitsupon permanent error <strong>de</strong>tection (at manufacturingor in the field). These disabled blocks are not replacedwith a spare 1 , which results in a reduction ofcache capacity. Block disabling is an attractive optionbecause of its low overhead, e.g., 1 bit per cacheblock 2 , but the reduced cache capacity can <strong>de</strong>gra<strong>de</strong>performance. Therefore, it is important to <strong>de</strong>terminethe performance implications of block disabling toassess its usefulness.Previous block disabling-based studies (such as [7],[9], [10], [11], [12], [13], [14], [15]) rely on the use ofan arbitrary number (small or large) of random faultmaps.Each random fault-map indicates faulty cachecell locations and <strong>de</strong>termines the disabled faultycache blocks. The fault-maps are used either toobtain the performance <strong>de</strong>gradation of a programthrough cycle accurate simulation, or to <strong>de</strong>terminethe impact on miss-rate of a program’s address trace.However, the number of fault maps used in thesestudies is very small as compared to the number ofall possible maps. Therefore, the accuracy of previouswork in predicting expected performance has notbeen established.Our proposition to address this shortcoming is ananalytical mo<strong>de</strong>l that calculates the Expected MissRatio (EMR) for a given address trace of an application,cache configuration and random probabilityof permanent cell failure. Furthermore, we show1 Disabling can be employed after spares have been exhausted.2 This logical bit needs to be resilient either through circuit<strong>de</strong>sign or extra protection, because if faulty it ren<strong>de</strong>rs wholecache faulty.<strong>JP2011</strong>-233


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011how to obtain the standard <strong>de</strong>viation for the EMR(SD MR) which provi<strong>de</strong>s an indication for the rangeof expected <strong>de</strong>gradation of the cache. Finally, we explainhow to produce a probability distribution forthe EMR for a given number of faulty blocks. Allthese are accomplished without producing or usingfault-maps. This analytical mo<strong>de</strong>l can be useful formanufacturers to analyze the impact of permanentfaults in caches and tune their <strong>de</strong>signs by using anappropriate number of spares or modifying the granularityof disabling techniques.The mo<strong>de</strong>l capabilities are <strong>de</strong>monstrated throughan analysis of the trends of the cache miss-rate meanand standard <strong>de</strong>viation with smaller feature size (andp fail ) for L1 data caches.The remain<strong>de</strong>r of the paper is organized as follows:Section II presents our mo<strong>de</strong>l to calculate the EMRand SD MR. In Section III we <strong>de</strong>scribe the methodologyand the evaluation results. Finally, Section IVresumes the main conclusions of this work.II. Exact Mo<strong>de</strong>l for Cache Miss RateBehavior with FaultsIn this section, we present an analytical mo<strong>de</strong>lthat can <strong>de</strong>termine the Expected Miss Ratio (EMR),standard <strong>de</strong>viation of the Miss Ratio (SD MR), and aprobability distribution of miss-ratios (PD MR) for agiven program address trace, cache configuration andrandom probability of permanent cell failure. TheEMR captures the average cache performance <strong>de</strong>gradationdue to random faulty cells. The SD MR provi<strong>de</strong>sindication about the range of this performance<strong>de</strong>gradation, whereas PD MR reveals its shape (distribution).These characteristics can be used to assessthe implications of faults in a cache and comparedifferent cache reliability schemes.A. Assumptions and DefinitionsThe mo<strong>de</strong>l assumes that permanent faulty cells occurrandomly (uncorrelated) with probability p fail .This random fault behavior is indicative of faults dueto random-dopant-fluctuations [16] and line-edgeroughness[17], two prevalent sources of static variations.The systematic component of process variationmanifests itself at a larger scale (e.g., at thegranularity of microarchitectural units or whole core)and can be addressed by coarse-grain techniques likebody biasing [3]. The random variation occurs at afiner grain and cannot be handled with manufacturingprocess tuning or coarse grain techniques [18].The mo<strong>de</strong>l presented in this work assumes that thesystematic failures have been addressed and examinesthe implications of random faults in memorycells.A cache configuration is <strong>de</strong>fined by the numberof sets (s), ways per set (n), and block size in bits(k). We consi<strong>de</strong>r a block containing one or more permanentlydamaged bits as faulty. In that case, thefaulty block is disabled, reducing the capacity of thecache. Faults are assumed to be <strong>de</strong>tected with postmanufacturingand/or boot time tests, ECC, andbuilt-in self tests. The mo<strong>de</strong>l is suited for policiesthat induce total priority or<strong>de</strong>r in the replacement.In our case, we have focused on a basic LRU policy.Each program address trace is simulated througha cache simulator to obtain, for a given cache configuration,the vector M. This vector contains n + 1elements, an element more than the number of cacheways. M i corresponds to the total misses when thereare only n − i valid ways in each set in the cache.More specifically, M i equals to sum of all the referenceswhich hit in the i least recently used blocksin each set, plus the misses of the fault free cache.For example, M 0 equals to the misses of a fault-freecache, M n represents the misses of a cache in whichevery way is entirely faulty, meaning all accesses aremisses, and M 1 equals to the misses of the fault-freeplus all the hits in the LRU position.B. EMR and SD MRThis section shows how the mo<strong>de</strong>l obtains theEMR and SD MR given a cell’s p fail , cache configurationand the miss vector of an address trace. Themo<strong>de</strong>l calculates the probability for a cache blockfailure using the following expression (based on wellknownbinomial probability):p bf = 1 − (1 − p fail ) k (1)Although p bf provi<strong>de</strong>s information about the fractionof blocks that are expected to fail in the cache,the impact on the miss ratio is unknown, as it <strong>de</strong>pendson the fault location and the amount of accesseswhich maps to faulty block locations. However,with the p bf we can obtain the probability distributionpe i for the number of faulty ways in a set: npe i = p i bfi (1 − p bf ) n−i (2)which provi<strong>de</strong>s, for every possible value of i [0...n],the probability of having n−i non-faulty ways. Thisdistribution is very useful because it provi<strong>de</strong>s insightabout how likely it is to lose a given numberof ways in a set and, what is more important,it can be used to obtain the expected numberof misses. The expectation of a random variableX = x 0 , x1..., x m in which each possible value hasprobability p = p 0 , p 1 , ..., p m is calculated as:E[X] =mx i · p i (3)i=0In our case, the random variable X corresponds tothe total number of misses for a cache with faults; x icorresponds to the total misses when there are onlyn − i valid ways in each set in the cache; and p i theprobability of having i faulty ways in a set. Therefore,we can express the expectation of the numberof cache misses with disabled blocks as:E misses =nM i · pe i (4)i=0<strong>JP2011</strong>-234


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011and obtain the expected miss ratio of the cacheusing:EMR = E misses(5)accessesThis simple formula can be used to obtain the exactEMR without using fault-maps. I.e. it <strong>de</strong>terminesthe EMR as if all possible fault-maps for agiven random p fail had been taken into account. Thekey insight behind this formula, expressed better inEq. 2, is that caches have a useful property: for thesame number of faulty blocks f in a set, the reducedassociativity will be the same n − f. I.e., for analyzingblock-disabling, what matters is the number offaulty-ways in a set, not which specific ways in theset are faulty. Thus, the complexity of the problemis reduced.The EMR provi<strong>de</strong>s a useful indication about theaverage case performance for a given p fail . However,we have no information about the variation in themiss ratio. Variation is useful for assessing whetherdisabled blocks lead to caches with wi<strong>de</strong> variation(less predictable) miss rate.One way to measure this variation is through thestandard <strong>de</strong>viation of the MR or SD MR. Unfortunately,the standard <strong>de</strong>viation cannot be directly obtainedfor the whole cache. However, given that wealready know the probability distribution of faultyblocks in a set, we can calculate variation as:∀j[0...s], V AR E missesj =npe i · (x ij − E missesj ) 2i=0(6)where x ij is the number of misses obtained whenhaving n − i non-faulty ways in the j th set.Although the total EMR is equal to the sum ofindividual sets EMR j :EMR =sEMR j (7)j=1we cannot combine the variation of each set in thesame way. Instead, we compute the <strong>de</strong>viation for themisses of the whole cache SD MR by using the rootmean square in the form: sV AR EMR jj=1SD MR =(8)accessesC. MR probability distributionThe SD MR only provi<strong>de</strong>s the range of <strong>de</strong>viationof the miss ratio. But, what may be more usefulto know is a probability distribution of cache misses(PD MR) within the <strong>de</strong>viation range.We propose to build a probability distribution ofmisses in a stepwise manner. We first calculatethe EMR for every possible number of faulty blocks(from 0 to the number of cache blocks), and thenwe combine this information with the probability ofthat given number of faulty blocks to occur.Equation 9, similar to Equation 2, gives the probabilityof x number of faulty blocks, for a given blockprobability failure: s · nxp x bf (1 − p bf ) s·n−x (9)This equation can be evaluated for different x valuesto obtain a probability distribution. Then, weneed to calculate the EMR for every possible numberof faults. So far, this problem has been solvedby means of random fault-maps [9].For a given number of faults, this problem is analogousto selecting at random n balls from an urnthat contains dk balls without replacement, where dis the number of unique colours and k is the numberof balls of each color. The urn represents the cache,the variable n the faults, d the number of blocks andk the number of bits in each block. The mean numberof distinct blocks, u, that contains at least onefaulty cell in a cache with n faulty cells can be approximatedwith high accuracy [19]:u = d − d(1 − p fail ) k (10)This means that we can obtain the PD MR analytically,without fault-maps, by simply using Equation10 to convert the number of faulty blocks to p fail .This, gives us the expression:p faili = 1 − k s · n − xis · n(11)This way, we can calculate which p fail results inx i faults in the cache. Then, every p faili can beused to calculate the EMR associated to each numberof faulty blocks, therefore, generating a probabilitydistribution.A. MethodologyIII. EvaluationThe input to our mo<strong>de</strong>l is a map of accesses to acache for every application. To produce these mapswe have used an algorithm called all-associativitysimulation [20], previously used in [9]. This algorithmhas a complexity or<strong>de</strong>r of O(n 2 ). However,in practice, the complexity is much lower because ofaccess locality, which limits the length of searchesdramatically. Due to space limitations, we have notdiscussed this but refer to [20] for <strong>de</strong>tails. It is importantto note, though, that the algorithm is appliedoffline and, with a single run per benchmark, is ableto produce the data our mo<strong>de</strong>l needs to evaluate any<strong>de</strong>sired cache configuration.The all-associativity algorithm takes as input atrace of memory requests which converts into a mapof cache accesses for any <strong>de</strong>sired configuration (setsand ways) following a given replacement policy (LRUin our case). This allows us to obtain the number ofaccesses per way and per set within a single run. Theoutput of the algorithm is a matrix in which each rowcorresponds to a set and each column to a position<strong>JP2011</strong>-235


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011in the LRU sequence. Each value of the matrix indicatesthe number of accesses to every position inthe LRU sequence for every set. This informationis very useful for offline analysis given that we can<strong>de</strong>termine the number of misses for a given numberof ways w in our cache by simply adding the accessesfor the last n − w columns of the matrix.We can also use this matrix to compute the misseswith faulty cells. For this purpose, and accordingto Equation 5, we need to calculate the number ofmisses if a given number of ways were disabled inthe cache due to permanent faults. First, we accumulatethe number of accesses in every position perset. Then, we perform the same operation per setto obtain a vector which indicates the exact numberof misses our cache would suffer as a consequence oflosing from 0 to w ways.For our experiments, we have simulated a processorarchitecture by means of Virtutech Simics [21]and GEMS [22]. Simics is a functional simulator executinga Solaris 10 Unix distribution simulating theUltraSPARC-III ISA. GEMS is a timing simulatorwhich, coupled to Simics, provi<strong>de</strong>s <strong>de</strong>tailed resultsfor the memory system. We have performed severalmodifications to the simulator to extract cache addresstraces. Then, these traces are used to generatethe map of accesses for every possible cache configurationby means of the all-associativity algorithm asexplained previously.We have conducted our experiments by executingdifferent applications from the SPECcpu-2000 [23](bzip2, gap, gzip, parser, twolf, vpr). Benchmarksare run for 1 billion of cycles. In all cases, the warmingup of caches has been taken into account.The different p fails used for the evaluation of thecaches are shown in Section I with the exception of6.1e-13, which produces virtually no faulty blocks inour experiments. Additionally, we have evaluatedp fail of 1e-03 which is consi<strong>de</strong>red in many relatedpapers.B. Random Fault Map MethodologyBefore proceeding to <strong>de</strong>termine the EMR usingthe proposed methodology we <strong>de</strong>termine how wellrandomly generated fault-maps approximate the expectednumber of faults obtained using Eq. 1.In Figure 1 we can see the probability distributionof the number of faulty blocks for different p fails (wehave omitted 7.3e-09 and 1.5e-06 because they offerfrom 0 to 1 and 0 to 4 faulty blocks, respectively)in a 32KB, 2-way associative cache with 558 bits perblock 3 . Results show the estimated faulty blocks obtainedanalytically (analytical line) and by differentnumbers of faulty maps (from 100 to 10 millions). Asit is observed, few faulty maps are not able to capturethe exact behaviour of the analytical mo<strong>de</strong>l. However,when the number of maps increases (1K mapsor more), the number of faulty blocks becomes moreaccurate. Nonetheless, this study cannot conclu<strong>de</strong>how well random maps approximate the expectedmisses of a cache, since misses directly <strong>de</strong>pend onthe location of faults among the different cache sets.C. EMR and SD MR for SPEC applicationsIn this section we show the calculated EMR andSD MR for several benchmarks and a 2-way 32KBL1 cache with different p fails .Surprisingly we can see in Figure 2 that a smallnumber of faulty maps, 100-1000, is enough to approximatethe EMR and SD MR provi<strong>de</strong>d by themo<strong>de</strong>l. The reason for this is the access homogeneityto the different sets of the cache. In other words, forthe applications we have evaluated, there are no particularsets that are clearly more accessed than othersduring the overall execution of the benchmark. Thismakes the EMR and SD MR virtually in<strong>de</strong>pen<strong>de</strong>ntfrom the fault locations and that is the reason whyfault maps are able to provi<strong>de</strong> such good estimations.We establish the cache access homogeneity with astudy of the correlation of accesses between all thesets in our cache by calculating the Pearson correlationcoefficient. When the Pearson coefficient is closeto 0, it means that there is no correlation betweenvariables, whereas when it is close to 1, it means acorrelation between them. We have calculated thematrix of correlations of the number of accesses for a2-way 32KB L1 cache for the evaluated benchmarks.Table II reflects the average value for the Pearson coefficientsas well as its standard <strong>de</strong>viation. As we cansee, all coefficients are very close to 1, which meansthat the accesses among sets are highly correlated.TABLE IIPearson Coefficient Matrix for each benchmark.Benchmark Mean Pearson Coeff. DEVbzip2 .993 .007gap .9 .086gzip .997 .002parser .998 .003twolf .943 .119vpr .995 .006The key insight from this study is that, becauseof the high correlation, a small number of randomfault maps is sufficient to obtain accurate expectedcache behavior with faults. If data accesses amongsets are not highly correlated, a few fault maps wouldnot be able to provi<strong>de</strong> an accurate prediction of theexpected behaviour with faults.D. PD MR for SPEC applicationsIn Section II-C, we have <strong>de</strong>veloped a method tocalculate a PD MR for the expected values of theEMR. As explained, we follow a constructive approach,calculating the different p fail from 0 to nfaulty blocks. Then, for each of these values we calculateits EMR.3 We consi<strong>de</strong>r blocks comprised of: 64 bytes for data and 11bits for its ECC, 25 bits for the tag and 7 bits for its ECC,and 3 control bits for valid, disable and dirty states.<strong>JP2011</strong>-236


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011 (a) (b) (c)Fig. 1. Probability distribution of the number of faulty blocks obtained by our mo<strong>de</strong>l and by random fault-maps in a 2-wayassociative 32KB cache. (a) (b) (c) (d) (e) (f)Fig. 2. EMR and SD MR for different applications in a 2-way associative 32KB L1 cache with different p fails . (a) (b) (c) (d) (e) (f)Fig. 3.PD MR for different applications and p fails in a 2-way associative 32KB L1 cache.<strong>JP2011</strong>-237


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011The probability distribution results in Figure 3provi<strong>de</strong>s valuable information. As a consequence ofthe increasing number of faulty blocks, the shape ofthe distribution is wi<strong>de</strong>r with higher p fails . Within asingle chart we can infer the likelihood of a miss ratein our cache to occur according to the used technologyscale. As a conclusion, this study revealsthat, in the future, the performance of caches will bemore un-predictable due to permanent errors. Thismo<strong>de</strong>l could be used by chip manufacturers to analytically<strong>de</strong>termine what is going to be the expectedpercentage of chips that should be discar<strong>de</strong>d becauseof faulty cells.IV. ConclusionsThis paper proposes an analytical mo<strong>de</strong>l to <strong>de</strong>terminethe Expected Miss Ratio (EMR) and itsStandard Deviation (SD MR) for a given applicationwhen it is executed in a cache with a randomprobability of cell failure. This analytical mo<strong>de</strong>l enables<strong>de</strong>signers to perceive the real impact of faultsin caches without the need of executing any experimentswith random fault maps. We have also presentedan analytical mo<strong>de</strong>l which provi<strong>de</strong>s the probabilitydistribution for the EMR which represents anothervaluable information for <strong>de</strong>signers about theshape of the miss-rate distribution of faulty cacheunits for a given process technology.In the evaluation we show, for the benchmarksand configurations used, that the random fault mapmethodology provi<strong>de</strong>s high accuracy when using 100-1000 maps for an L1 data cache. This is due to thehigh homogeneity of accesses to the different sets ofa cache which makes the EMR and SD MR virtuallyin<strong>de</strong>pen<strong>de</strong>nt of the allocation of faults.AcknowledgementsThis work has been jointly supported by the SpanishMEC and European Commission FEDER fundsun<strong>de</strong>r grants “Consoli<strong>de</strong>r Ingenio-2010 CSD2006-00046” and “TIN2009-14475-C04-02”. DanielSánchez is also supported by a research grant fromthe Spanish MEC un<strong>de</strong>r grant “Consoli<strong>de</strong>r Ingenio-2010 CSD2006-00046” and a mobility grant byHiPEAC (FP7 Network of Excellence). The researchleading to this paper is supported by the EuropeanCommission FP7 project “Energy-conscious3D Server-on-Chip for Green Cloud Services (ProjectNo:247779 “EuroCloud”)”.Bibliography[1] S. Borkar, “Design challenges of technology scaling,”IEEE Micro, vol. 19, no. 4, pp. 23 –29, 1999.[2] Y. Taur, “CMOS <strong>de</strong>sign near to the Limit of Scaling,”IBM Journal of Research and Development, vol. 46, no.2/3, pp. 213–222, 2002.[3] Shekhar Borkar, Tanay Karnik, Siva Narendra, JimTschanz, Ali Keshavarzi, and Vivek De, “Parameter variationsand impact on circuits and microarchitecture,” inProceedings of the 40th annual Design Automation Conference.2003, pp. 338–342, ACM.[4] Keith Bowman, James Tschanz, Chris Wilkerson, Shih-Lien Lu, Tanay Karnik, Vivek De, and Shekhar Borkar,“Circuit techniques for dynamic variation tolerance,” inProceedings of the 46th Annual Design Automation Conference.2009, pp. 4–7, ACM.[5] Sani R. Nassif, Nikil Mehta, and Yu Cao, “A resilienceroadmap,” in Design, Automation, and Test in Europe,2010, pp. 1011–1016.[6] David A. Patterson, Phil Garrison, Mark Hill, DimitrisLioupis, Chris Nyberg, Tim Sippel, and Korbin VanDyke, “Architecture of a vlsi instruction cache for arisc,” in Proceedings of the 10th Annual InternationalSymposium on Computer Architecture. 1983, pp. 108–116, ACM.[7] G. S. Sohi, “Cache memory organization to enhance theyield of high performance vlsi processors,” IEEE Transactionson Computers, vol. 38, pp. 484–492, April 1989.[8] C. McNairy and J. Mayfield, “Montecito error protectionand mitigation,” HPCRI’05: 1st Workshop on HighPerformance Computing Reliability Issues, in conjunctionwith HPCA’05, 2005.[9] A.F. Pour and M.D. Hill, “Performance implications oftolerating cache faults,” IEEE Transactions on Computers,vol. 42, no. 3, pp. 257 –267, 1993.[10] Philip P. Shirvani and Edward J. McCluskey, “Pad<strong>de</strong>dcache: A new fault-tolerance technique for cache memories,”in Proceedings of the 17TH IEEE VLSI Test Symposium.1999, pp. 440–, IEEE Computer Society.[11] Hyunjin Lee, Sangyeun Cho, and B.R. Chil<strong>de</strong>rs, “Performanceof graceful <strong>de</strong>gradation for cache faults,” inIEEE Computer Society Annual Symposium on VLSI,2007, pp. 409 –415.[12] Hyunjin Lee, Sangyeun Cho, and B.R. Chil<strong>de</strong>rs, “Exploringthe interplay of yield, area, and performance inprocessor caches,” in 25th International Conference onComputer Design, 2007, pp. 216 –223.[13] T. Ishihara and F. Fallah, “A cache-<strong>de</strong>fect-aware co<strong>de</strong>placement algorithm for improving the performance ofprocessors,” in IEEE/ACM International Conference onComputer-Ai<strong>de</strong>d Design, Nov 2005, pp. 995 – 1001.[14] D. Roberts, Nam Sung Kim, and T. Mudge, “On-chipcache <strong>de</strong>vice scaling limits and effective fault repair techniquesin future nanoscale technology,” in 10th EuromicroConference on Digital System Design Architectures,Methods and Tools, 2007, pp. 570 –578.[15] N. <strong>La</strong>das, Y. Sazei<strong>de</strong>s, and V. Desmet, “Performanceeffectiveoperation below vcc-min,” in IEEE InternationalSymposium on Performance Analysis of SystemsSoftware, 2010, pp. 223 –234.[16] A.J. Bhavnagarwala, Xinghai Tang, and J.D. Meindl,“The impact of intrinsic <strong>de</strong>vice fluctuations on cmos sramcell stability,” Solid-State Circuits, IEEE Journal of, vol.36, no. 4, pp. 658 –665, apr 2001.[17] B. Cheng, S. Roy, G. Roy, F. Adamu-Lema, andA. Asenov, “Impact of intrinsic parameter fluctuationsin <strong>de</strong>canano mosfets on yield and functionality of sramcells,” Solid-State Electronics, vol. 49, no. 5, pp. 740 –746, 2005.[18] Keith Bowman, David Brooks, Gu-Yeon Wei, and ChrisWilkerson, “Tutorial on <strong>de</strong>sign variability: Trends, mo<strong>de</strong>lsand <strong>de</strong>sign solutions,” in Tutorial at MICRO’08, Nov.2008.[19] S. B. Yao, “Approximating block accesses in databaseorganizations,” ACM Communications, vol. 20, pp. 260–261, April 1977.[20] M. D. Hill and A. J. Smith, “Evaluating associativity incpu caches,” IEEE Transactions on Computers, vol. 38,pp. 1612–1630, December 1989.[21] P. S. Magnusson, M. Christensson, J. Eskilson, D. Forsgren,G. Hallberg, J. Hogberg, F. <strong>La</strong>rsson, A. Moestedt,B. Werner, and B. Werner, “Simics: A full system simulationplatform,” Computer, vol. 35, no. 2, pp. 50–58,2002.[22] Milo M. K. Martin, Daniel J. Sorin, Bradford M. Beckmann,Michael R. Marty, Min Xu, Alaa R. Alamel<strong>de</strong>en,Kevin E. Moore, Mark D. Hill, and David A. Wood,“Multifacet’s general execution-driven multiprocessorsimulator (gems) toolset,” SIGARCH Computer ArchitectureNews, vol. 33, no. 4, 2005.[23] J.L. Henning, “Spec cpu2000: measuring cpu performancein the new millennium,” Computer, vol. 33, no.7, pp. 28 –35, July 2000.<strong>JP2011</strong>-238


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Coherencia <strong>de</strong> Caché Mediante Árbol Basadoen Proximidad y PredicciónAntonio García-Guirado 1 Ricardo Fernán<strong>de</strong>z-Pascual 1 José M. García 1Resumen— Los protocolos <strong>de</strong> coherencia <strong>de</strong>caché basados en estructuras enlazadas como listas(SCI) o árboles mantienen la información <strong>de</strong> comparticiónrepartida entre varios nodos. De esta forma, seconsigue que la memoria necesaria por nodo crezca logarítmicamentecon el número <strong>de</strong> nodos (n·log(n) paratodo el CMP) en lugar <strong>de</strong> hacerlo linealmente (n 2 paratodo el CMP) como ocurre en un directorio convector <strong>de</strong> bits, y a<strong>de</strong>más sin per<strong>de</strong>r exactitud comosuce<strong>de</strong> con otros códigos <strong>de</strong> compartición. Sin embargo,estos esquemas tienen como principal <strong>de</strong>sventajala alta latencia <strong>de</strong> las invalidaciones que provocan lasescrituras. En este artículo presentamos un protocolo<strong>de</strong> coherencia que utiliza un árbol que, como novedad,tiene en cuenta la distancia entre compartidoresy utiliza predicción <strong>de</strong> proveedor para obtener los datos.Nuestro protocolo mantiene todos los beneficios<strong>de</strong> las estructuras enlazadas a la vez que elimina susinconvenientes, e incluso presenta nuevas ventajas encomparación con otras propuestas.I. IntroducciónCONFORME aumenta el número <strong>de</strong> procesadoresintegrados en un chip, el mantenimiento <strong>de</strong> lacoherencia <strong>de</strong> caché mediante hardware se hace máscostoso. Los mecanismos basados en broadcast sonpoco escalables <strong>de</strong>bido a que necesitan un medio <strong>de</strong>comunicación totalmente or<strong>de</strong>nado y compartido portodos (por ejemplo, un bus), lo que complica su usoen chips con <strong>de</strong>cenas <strong>de</strong> procesadores. A su vez, losmecanismos basados en directorio también presentanproblemas <strong>de</strong> escalabilidad, siendo el principal problemalos altos requisitos <strong>de</strong> almacenamiento para lainformación sobre los compartidores <strong>de</strong> los bloques<strong>de</strong> memoria. En el caso <strong>de</strong>l código <strong>de</strong> comparticiónmás simple, conocido como full-map bit-vector, cadaposible compartidor se codifica como un bit queestá activo si el compartidor tiene una copia <strong>de</strong>l bloque,por lo que su sobrecarga con respecto a la capacidadtotal <strong>de</strong> la caché <strong>de</strong>l chip es proporcionalal número <strong>de</strong> procesadores. Otros códigos reducenla sobrecarga a cambio <strong>de</strong> per<strong>de</strong>r exactitud (lo quegenera tráfico <strong>de</strong> red innecesario).Hasta ahora, un CMP podía proporcionar coherencia<strong>de</strong> caché mediante un bus o un directorio simple<strong>de</strong>bido al reducido número <strong>de</strong> procesadores que contenía.Sin embargo, los chips actuales ya comienzana integrar <strong>de</strong>cenas <strong>de</strong> procesadores y, <strong>de</strong>bido a la dificultad<strong>de</strong> mantener la coherencia para tantos nodos,algunos prototipos han optado por eliminar la coherenciahardware y en su lugar recurrir al uso paso<strong>de</strong> mensajes para la comunicación entre los distintosprocesadores, lo que complica la tarea <strong>de</strong>l programador.Existen muchas propuestas que intentan solventarlos problemas <strong>de</strong> escalabilidad <strong>de</strong>l directorio. Algunasse remontan a más <strong>de</strong> veinte años atrás, comoSCI [1] (Scalable Coherence Interface), que proponía1 Departamento <strong>de</strong> Arquitectura e Ingeniería <strong>de</strong>Computadores, <strong>Universidad</strong> <strong>de</strong> Murcia, e-mail:{toni,r.fernan<strong>de</strong>z,jmgarcia}@ditec.um.esel uso <strong>de</strong> una lista enlazada <strong>de</strong> compartidores <strong>de</strong> unbloque en la que cada compartidor tenía un punteroque apuntaba al siguiente. Esto reduce la sobrecargaen almacenamiento <strong>de</strong> la información <strong>de</strong> coherencia,que en SCI es proporcional al logaritmo <strong>de</strong>l número<strong>de</strong> procesadores en el chip. Sin embargo, SCI es muyineficiente al invalidar bloques compartidos por muchosprocesadores, ya que la invalidación no se completahasta que la lista <strong>de</strong> compartidores es invalidada<strong>de</strong> manera secuencial. Para mejorar el comportamiento<strong>de</strong> SCI se propusieron esquemas basados enárboles [2, 3, 4, 5] en los que el número <strong>de</strong> saltos en elcamino crítico <strong>de</strong> las invalidaciones pasaba a ser proporcionalal logaritmo <strong>de</strong>l número <strong>de</strong> compartidores.Sin embargo, la gestión <strong>de</strong> estos árboles no es sencilla.Por ejemplo, la introducción <strong>de</strong> nuevos compartidorespue<strong>de</strong> necesitar la reestructuración <strong>de</strong>l árbol, y elreemplazo <strong>de</strong> un nodo pue<strong>de</strong> requerir la invalidación<strong>de</strong> toda la rama que hay bajo él, lo que incrementael número <strong>de</strong> fallos <strong>de</strong> caché <strong>de</strong> los nodos invalidadosinnecesariamente. A<strong>de</strong>más, las invalidaciones siguensiendo costosas ya que requieren varios saltos en elcamino crítico entre nodos que están en posicionesaleatorias <strong>de</strong>l chip.Nosotros proponemos un nuevo protocolo <strong>de</strong> coherencia<strong>de</strong> caché que, manteniendo las ventajas <strong>de</strong> laslistas y árboles, soluciona sus principales problemasy aporta nuevas e interesantes ventajas. Basándonosen la distancia entre nodos, la información <strong>de</strong> coherenciase mantiene en un árbol distribuido geográficamentepor el chip, lo que reduce la distancia entrenodos contiguos <strong>de</strong>l árbol y por tanto el tráfico necesariopara su comunicación. Esto permite que el uso<strong>de</strong> predicción en las peticiones <strong>de</strong> lectura haga queun nodo <strong>de</strong>l árbol cercano físicamente al peticionariopueda proveer el dato.<strong>La</strong>s aportaciones <strong>de</strong> nuestra propuesta son las siguientes:Dos nodos consecutivos en el árbol se encuentranpróximos físicamente en el chip. Esto haceque las comunicaciones entre nodos sean másrápidas y generen menos tráfico. Reducimos eltráfico <strong>de</strong> las escrituras en hasta un 95 % con respectoa un directorio full-map en algunos tipos<strong>de</strong> fallo.Mediante predicción <strong>de</strong> <strong>de</strong>stino <strong>de</strong> las peticiones<strong>de</strong> lectura po<strong>de</strong>mos obtener el bloque <strong>de</strong>s<strong>de</strong> unnodo cercano <strong>de</strong> manera más rápida y generandomenos tráfico. Para permitir esto, cualquiercompartidor pue<strong>de</strong> proporcionar la copia <strong>de</strong> unbloque cuando recibe una petición <strong>de</strong> un nuevocompartidor. Reducimos el camino crítico <strong>de</strong> laslecturas en hasta un 96 % y el tráfico en hastaun 95 % con respecto a un directorio full-map.<strong>JP2011</strong>-239


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Directorio SCIArbol Arbol basado en proximidadH H H HFig. 1. Información <strong>de</strong> coherencia en directorio, SCI, árbol y árbol basado en proximidad. L1s con copia <strong>de</strong>l bloque mostradasen gris. Home L2 señalado con una H. Nótese como el árbol basado en proximidad es el único que reduce la distancia entrenodos contiguos.II. Arquitectura Base.Este trabajo utiliza una arquitectura tiled-CMP.En ella, el chip se forma mediante replicación <strong>de</strong> tiles.Cada tile contiene un core, una caché L1 privaday un banco <strong>de</strong> la caché L2 compartida. Los bloques<strong>de</strong> memoria se mapean a los bancos <strong>de</strong> L2 usandovarios bits <strong>de</strong> la dirección <strong>de</strong> bloque. <strong>La</strong> L2 a la queun bloque se mapea se llama “home L2”, y contienela información <strong>de</strong> directorio <strong>de</strong>l bloque si existen copias<strong>de</strong>l mismo en las L1s. Utilizamos un esquema <strong>de</strong>estados MOESI para la coherencia <strong>de</strong> los bloques <strong>de</strong>memoria. Los tiles se comunican mediante interfaces<strong>de</strong> red formando una malla 2D. No obstante, nuestroprotocolo pue<strong>de</strong> aplicarse a cualquier otra arquitectura<strong>de</strong> memoria compartida.III. Árbol Basado en Proximidad yPredicciónEl árbol binario que contiene los compartidores <strong>de</strong>un bloque parte <strong>de</strong>l nodo home L2, que almacenaun puntero a la L1 que es raíz <strong>de</strong>l árbol. <strong>La</strong>s cachésL1 tienen tres punteros asociados a cada entrada <strong>de</strong>caché: uno para apuntar al nodo padre (pue<strong>de</strong> ser elhome L2 u otra L1) y el resto para apuntar a hastados hijos (que serán cachés L1). Inicialmente noexiste árbol para el bloque. <strong>La</strong> primera caché L1 queacce<strong>de</strong> al bloque envía su petición al home L2 y pasaa ser el nodo raíz <strong>de</strong>l árbol. Cuando aparece unnuevo compartidor (una L1 que envía una petición<strong>de</strong> lectura al home L2), la petición se reenvía a laraíz, que provee el dato y almacena la i<strong>de</strong>ntidad <strong>de</strong>lnuevo compartidor, el cual almacena la i<strong>de</strong>ntidad <strong>de</strong>lnodo que le contesta en el puntero reservado para elnodo padre en su entrada <strong>de</strong> caché. Al surgir máscompartidores se llenan los punteros <strong>de</strong>l nodo raíz,y entonces es necesario recorrer el árbol hacia abajo,eligiendo ramas aleatoriamente, hasta encontrarun puntero libre. Cada mensaje enviado hacia abajoen el árbol es asentido por su receptor para evitarcarreras <strong>de</strong> coherencia. El peticionario a<strong>de</strong>más <strong>de</strong>beesperar a recibir la i<strong>de</strong>ntidad <strong>de</strong> su padre (el nodo enel que se encontró un puntero libre) antes <strong>de</strong> po<strong>de</strong>rreemplazar el bloque. En cualquier caso, la raíz proveeel dato para mantener corto el camino crítico <strong>de</strong>los fallos <strong>de</strong> lectura.Al producirse un reemplazo no invalidamos elsubárbol bajo el nodo que reemplaza, sino que utilizamosun mecanismo <strong>de</strong> reemplazo que reestructurael árbol. En él participan un abuelo, un padre y hastados hijos <strong>de</strong>l padre. Con un intercambio <strong>de</strong> 7 mensajesse reestructura el árbol <strong>de</strong> modo que el enlaceentre el abuelo y el padre se sustituye por un enlaceentre el abuelo y uno <strong>de</strong> sus nietos, y el otro nieto pasaa formar parte <strong>de</strong>l subárbol <strong>de</strong> su hermano (lo quepue<strong>de</strong> implicar más mensajes para po<strong>de</strong>r acomodaral hermano en un puntero libre). Este reemplazo esmás costoso que un reemplazo en SCI, pero evita invalidartodo el subárbol bajo el nodo que reemplaza,y previene condiciones <strong>de</strong> carrera.El hecho <strong>de</strong> tener la información <strong>de</strong> coherencia distribuidaen un árbol presenta oportunida<strong>de</strong>s para optimizacionesque no se pue<strong>de</strong>n realizar en enfoquesque mantienen la información <strong>de</strong> coherencia <strong>de</strong> unbloque en un único punto. A continuación veremoscómo aprovechar el árbol para enlazar nodos cercanosy para obtener bloques cercanos, y las ventajasque esto nos aporta.A. Proximidad en el ÁrbolUn árbol distribuido en el chip pue<strong>de</strong> crearse <strong>de</strong>manera que cada par <strong>de</strong> nodos contiguos se encuentrenfísicamente próximos en el chip. Esto trae importantesventajas en cuanto a tráfico cuando se realizancomunicaciones entre nodos contiguos <strong>de</strong>l árbol,como pue<strong>de</strong> ser el caso <strong>de</strong> una escritura <strong>de</strong> un bloqueque <strong>de</strong>be recorrer el árbol completamente parainvalidar a todos los compartidores, o a la hora <strong>de</strong>realizar un reemplazo.Hemos optado por una opción sencilla para creary gestionar el árbol que consiste en que, cuando unnodo no tiene punteros libres para almacenar a unnuevo compartidor, envía la información <strong>de</strong>l nuevocompartidor al hijo que se encuentre más cerca físicamente<strong>de</strong>l nuevo compartidor. Esto hace que, conformebajamos por las ramas <strong>de</strong>l árbol, vayamos encontrandonodos más cercanos entre sí. Un ejemplo<strong>de</strong> la estructura <strong>de</strong> la información <strong>de</strong> coherencia enun directorio, en SCI, en un árbol y en nuestro árbolbasado en proximidad pue<strong>de</strong> verse en la Figura 1.Es posible balancear el árbol cuando se produceninserciones o reemplazos para mantener distanciasmínimas entre nodos, pero creemos que las gananciasserán mínimas en comparación con el incremento enla complejidad <strong>de</strong> la gestión <strong>de</strong>l árbol. Es por elloque hemos optado por no realizar balanceo <strong>de</strong> ningúntipo.B. PredicciónEl uso <strong>de</strong> predicción <strong>de</strong> proveedor ante un fallo<strong>de</strong> lectura en caché pue<strong>de</strong> aprovecharse <strong>de</strong> la proximidadfísica <strong>de</strong> los procesadores en el árbol. Unprocesador pue<strong>de</strong> usar a su antiguo padre en el árbolcomo proveedor si es que el padre sigue teniendo unacopia válida <strong>de</strong>l bloque. Como el padre se encuentrafísicamente próximo en el árbol gracias a nuestromecanismo <strong>de</strong> inserción, el fallo <strong>de</strong> caché se resolverácon menor latencia y generando menos tráficoque si tuviésemos que acce<strong>de</strong>r al nodo home, que pue-<strong>JP2011</strong>-240


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Sin prediccionPrediccionPrediccion en arbol basado en proximidadOwnerOwner3−Dato2−Peticion <strong>de</strong> lectura2−DatoHomeHomeHome1−Peticion <strong>de</strong> lectura1−Peticion <strong>de</strong> lectura2−Dato1−Peticion <strong>de</strong> lecturaPPPFig. 2. Resolución <strong>de</strong> un fallo <strong>de</strong> caché sin predicción (introduce un nivel <strong>de</strong> indirección para acce<strong>de</strong>r al directorio), conpredicción (elimina el nivel <strong>de</strong> indirección), y con predicción en un árbol basado en distancia (a<strong>de</strong>más se acce<strong>de</strong> al dato enun nodo cercano). L1s con copia <strong>de</strong>l bloque mostradas en gris. Nodo peticionario señalado con una P.<strong>de</strong> estar en cualquier lugar <strong>de</strong>l chip. En caso <strong>de</strong> unamala predicción (el antiguo padre ya no tiene copia<strong>de</strong>l bloque) la penalización en distancia recorrida esreducida, ya que el nodo predicho se encuentra cerca<strong>de</strong>l solicitante.El mecanismo para pre<strong>de</strong>cir es similar al <strong>de</strong> Di-Co [6]. Cada nodo tiene una pequeña caché, llamadaL1C$, que contiene predicciones in<strong>de</strong>xadas por dirección<strong>de</strong> bloque. Ante un fallo <strong>de</strong> lectura en caché L1se busca en la L1C$ una predicción para el bloqueal que se <strong>de</strong>sea acce<strong>de</strong>r. Si se encuentra, la peticiónse envía al nodo predicho. Si no es así, la petición seenvía al nodo home.Para obtener buenas predicciones la gestión <strong>de</strong> laL1C$ es fundamental. Cuando un bloque es reemplazadoen la caché L1, el puntero al padre que habíaen tag <strong>de</strong>l bloque se almacena en la L1C$ como predicciónpara un futuro acceso al bloque. <strong>La</strong> Figura 2muestra la resolución <strong>de</strong> un fallo en un directorio,usando predicción y usando predicción en el árbolbasado en distancia.Ante un fallo <strong>de</strong> escritura la petición siempre sedirige al nodo home, es <strong>de</strong>cir, no se realiza predicción.Esto es así porque el nodo home actúa como punto<strong>de</strong> serialización <strong>de</strong> todas las peticiones <strong>de</strong> escritura, yes a partir <strong>de</strong> él que se genera la invalidación <strong>de</strong> todoárbol para po<strong>de</strong>r dar permiso exclusivo <strong>de</strong> escrituraal nodo peticionario.IV. Metodología.Nuestro objetivo es probar varios protocolos <strong>de</strong>coherencia en algunos escenarios concretos. Porejemplo, es <strong>de</strong> especial interés el caso en que un bloque<strong>de</strong>l que existen muchas copias es escrito por unprocesador, provocando la invalidación <strong>de</strong> todas lascopias. El mayor problema <strong>de</strong> SCI es su mal comportamientoen ese escenario concreto, y uno <strong>de</strong> losobjetivos <strong>de</strong> nuestra propuesta <strong>de</strong> árbol es mejorarese caso.Para hacer esto hemos <strong>de</strong>sarrollado una herramientaque nos sirve para po<strong>de</strong>r hacer pruebas <strong>de</strong>este tipo manera sencilla. En ella hemos implementadoúnicamente la funcionalidad y las estadísticas<strong>de</strong>seadas <strong>de</strong> los protocolos. Ésta herramienta consi<strong>de</strong>raun único bloque <strong>de</strong> memoria sobre el que losprocesadores realizan accesos <strong>de</strong> lectura, accesos <strong>de</strong>escritura y reemplazos <strong>de</strong> caché siguiendo algún tipo<strong>de</strong> patrón o distribución estadística <strong>de</strong> interés. Porsimplicidad, sólo implementamos los fallos y reemplazos<strong>de</strong> L1, y éstos se resuelven siempre sin necesidad<strong>de</strong> ir a memoria (consi<strong>de</strong>ramos que el bloquesiempre está presente en L2).<strong>La</strong> mayor ventaja <strong>de</strong> esta herramienta es que evitamosla complejidad <strong>de</strong> las condiciones <strong>de</strong> carrera:las operaciones <strong>de</strong> memoria <strong>de</strong> todos los procesadoressobre el único bloque se ejecutan secuencialmente.Gracias a ello sólo <strong>de</strong>bemos implementar la funcionalidad<strong>de</strong> los protocolos correspondiente al casocomún y simple en que no hay ningún problema <strong>de</strong>rivado<strong>de</strong> la concurrencia entre accesos. Es por tantomuy simple implementar protocolos en la herramienta,ya que sólo hay que codificar tres operaciones <strong>de</strong>los mismos: fallo <strong>de</strong> lectura <strong>de</strong> L1, fallo <strong>de</strong> escritura<strong>de</strong> L1 y reemplazo <strong>de</strong>l bloque en L1.Esta herramienta pue<strong>de</strong> funcionar basándose enuna serie <strong>de</strong> probabilida<strong>de</strong>s. En ese caso va eligiendoprocesadores aleatoriamente, y usando estas probabilida<strong>de</strong>s<strong>de</strong>ci<strong>de</strong> si realizar una lectura (en caso <strong>de</strong>que la L1 no tenga el bloque), una escritura, o un reemplazo(en caso <strong>de</strong> sí tener el bloque). También esposible que no se realice ninguna acción. Para mo<strong>de</strong>larel escenario comentado anteriormente se hanajustado las probabilida<strong>de</strong>s <strong>de</strong> modo que estadísticamentecasi todas las L1s lean el bloque (y tambiénrealicen reemplazos) y en un momento dado se produzcauna escritura <strong>de</strong> un procesador, lo que provocauna invalidación <strong>de</strong> casi todas las L1s <strong>de</strong>l chip. Otrosescenarios pue<strong>de</strong>n codificarse <strong>de</strong> manera similar.Una gran ventaja <strong>de</strong> nuestra herramienta con respectoa simuladores como GEMS [7] es que po<strong>de</strong>mosrealizar una primera evaluación rápida <strong>de</strong> laspropuestas. <strong>La</strong> herramienta nos permite obtener estadísticas<strong>de</strong> escenarios concretos fácilmente, sin necesidad<strong>de</strong> crear checkpoints o <strong>de</strong> crear manualmentetrazas <strong>de</strong> accesos como entrada al simulador que <strong>de</strong>nlugar al tipo <strong>de</strong> escenario que nos interese probar.Esta herramienta tiene a<strong>de</strong>más otra gran ventaja:al ser tan sencilla y rápida, permite mo<strong>de</strong>lar máquinascon gran cantidad <strong>de</strong> cores. En concreto, paraeste artículo se han realizado pruebas con hasta8192 cores. Los simuladores como GEMS, <strong>de</strong>bidoa su complejidad, sólo permiten mo<strong>de</strong>lar máquinasmás mo<strong>de</strong>stas (p. ej., 64 cores) si queremos que lassimulaciones se ejecuten en un tiempo razonable (p.ej., menos <strong>de</strong> una semana) en los nodos <strong>de</strong> computación<strong>de</strong> los que se dispone actualmente.Una vez realizada una primera exploración y trashaber seleccionado los protocolos más prometedores,como trabajo futuro realizaríamos la implementación<strong>de</strong> estas propuestas en el lenguaje <strong>de</strong> especificación<strong>de</strong> protocolos SLICC para po<strong>de</strong>r realizar simulaciones<strong>de</strong>talladas en GEMS. Esta implementación escompleja y requiere un tiempo consi<strong>de</strong>rable. Nuestraherramienta nos permite <strong>de</strong>scartar propuestas pocoprometedoras evitando emplear gran<strong>de</strong>s cantida<strong>de</strong>s<strong>JP2011</strong>-241


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Links Camino Critico Lectura200180160140120100806040200dirSCItreetreePredtreeDisttreePredDist4 8 16 32 64 128 256 512 1024 2048 4096 8192Numero <strong>de</strong> Cores(a) Número medio <strong>de</strong> enlaces en elcamino crítico <strong>de</strong> una petición <strong>de</strong> lectura.Links Camino Critico Escritura50004000300020001000dirSCItreetreePredtreeDisttreePredDist04 8 16 32 64 128 256 512 1024 2048 4096 8192Numero <strong>de</strong> Cores(c) Número medio <strong>de</strong> enlaces en elcamino crítico <strong>de</strong> una petición <strong>de</strong> escritura.Flits Medios Generados por cada Lectura2000180016001400120010008006004002000dirSCItreetreePredtreeDisttreePredDist4 8 16 32 64 128 256 512 1024 2048 4096 8192Numero <strong>de</strong> Cores(b) Número medio <strong>de</strong> flits generados por una petición <strong>de</strong> lectura.Flits Medios Generados por cada Escritura700000600000500000400000300000200000100000dirSCItreetreePredtreeDisttreePredDist04 8 16 32 64 128 256 512 1024 2048 4096 8192Numero <strong>de</strong> Cores(d) Número medio <strong>de</strong> flits generados por una petición <strong>de</strong> escritura.Fig. 3. Estadísticas para el peor escenario <strong>de</strong> SCI.<strong>de</strong> tiempo en implementarlas en simuladores complejos.A. Protocolos evaluados.En nuestra herramienta hemos implementado unprotocolo <strong>de</strong> directorio básico, el protocolo <strong>de</strong> listaSCI y cuatro versiones distintas <strong>de</strong> <strong>de</strong> protocolos basadosen árboles, a saber:Tree: en lugar <strong>de</strong> tener una lista como SCI, tenemosun árbol binario. Cuando un nodo no tienepunteros para añadir a un nuevo compartidor,se envía la información por una rama aleatoria.Tree con predicción (treePred): es como el árbolanterior, pero usamos predicción similar a la <strong>de</strong>DiCo en las peticiones <strong>de</strong> lectura. <strong>La</strong>s peticionesse envían al ex-padre <strong>de</strong>l peticionario en el árbol.<strong>La</strong>s peticiones pue<strong>de</strong>n acertar o fallar (fallaránpor ejemplo si el ex-padre ya no tiene el bloque<strong>de</strong>bido a un reemplazo o a una escritura <strong>de</strong>otro nodo), por tanto no estamos utilizando <strong>de</strong>ninguna implementación tipo oráculo para laspredicciones sino una implementación relativamenterealista.Tree con uso <strong>de</strong> distancia (treeDist): es comoel protocolo tree, salvo que en caso <strong>de</strong> no tenerpunteros libres para añadir al peticionario se eligela rama con el nodo hijo más cercano al peticionariopara enviarle la información <strong>de</strong>l nuevocompartidor. <strong>La</strong> i<strong>de</strong>a es que los nodos cercanoslógicamente en el árbol sean nodos cercanos físicamente,para así reducir los flits necesarios ensus comunicaciones.Tree con predicción y distancia (treePredDist):sería la unión <strong>de</strong> los dos últimos protocolos mencionados.<strong>La</strong> i<strong>de</strong>a es que al pre<strong>de</strong>cir al proveedorusando al ex-padre <strong>de</strong>l peticionario en el árbol,tratándose ahora <strong>de</strong> nodos cercanos, po<strong>de</strong>mosreducir los flits necesarios en una petición e inclusomejorar el rendimiento.V. EvaluaciónA. Escrituras <strong>de</strong> bloques muy compartidos.En este escenario se selecciona un tile aleatorio encada acceso. Una vez elegido el tile, se pue<strong>de</strong> producirun reemplazo (en caso <strong>de</strong> estar el bloque en la L1 <strong>de</strong>ltile), una lectura <strong>de</strong>l bloque (que pue<strong>de</strong> ser local siel bloque está en L1 o traer el bloque a L1 si no loestá) o una escritura. <strong>La</strong> probabilidad <strong>de</strong> producir unreemplazo, dado que el bloque esté en la L1, la hemosfijado en un 5/(2 ∗ n) sobre 1, don<strong>de</strong> n es el número<strong>de</strong> cores en la máquina. <strong>La</strong> probabilidad <strong>de</strong> produciruna escritura la hemos fijado en un 1/(2 ∗ n) sobre 1.El resto <strong>de</strong> accesos son lecturas (locales o remotas).Estas probabilida<strong>de</strong>s aseguran que las escrituras seproducen cuando la mayoría <strong>de</strong> las L1s tienen copia<strong>de</strong>l bloque, y estas copias <strong>de</strong>ben ser invalidadas. Estepatrón es a<strong>de</strong>más bastante interesante en cuanto alas predicciones: el porcentaje <strong>de</strong> lecturas en las quese realiza predicción es <strong>de</strong> un 50 %, con un acierto <strong>de</strong>predicción <strong>de</strong> un 90 %. Estos valores entran <strong>de</strong>ntro<strong>de</strong>l rango <strong>de</strong> lo que consi<strong>de</strong>ramos normal en DiCo,que es el protocolo en el que basamos el sistema <strong>de</strong>predicciones.Como vemos en la Figura 3a, al pre<strong>de</strong>cir (tree-Pred), las lecturas se resuelven con un camino críticohasta un 11 % más corto. Esta reducción es mayorsi a<strong>de</strong>más tenemos en cuenta la distancia al montarel árbol (treePredDist), llegando hasta un 36 % <strong>de</strong>reducción, ya que <strong>de</strong> ese modo el proveedor que espredicho es un nodo cercano.En cuanto a los flits generados al realizar una lectura(Figura 3b), tenemos que los árboles aña<strong>de</strong>n flits<strong>de</strong>bido a que la i<strong>de</strong>ntidad <strong>de</strong>l solicitante <strong>de</strong>be enviarsepor el árbol hasta encontrar un nodo con punteroslibres. Nótese que estamos hablando <strong>de</strong> un caso extremoen que el árbol fuera enorme. En cualquier ca-<strong>JP2011</strong>-242


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Links Camino Critico Lectura200180160140120100806040200dirSCItreetreePredtreeDisttreePredDist4 8 16 32 64 128 256 512 1024 2048 4096 8192Numero <strong>de</strong> Cores(a) Número medio <strong>de</strong> enlaces en elcamino crítico <strong>de</strong> una petición <strong>de</strong> lectura.Flits Medios Generados por cada Lectura2500200015001000500dirSCItreetreePredtreeDisttreePredDist04 8 16 32 64 128 256 512 1024 2048 4096 8192Numero <strong>de</strong> Cores(b) Número medio <strong>de</strong> flits generados por una petición <strong>de</strong> lectura.Fig. 4. Estadísticas para el mejor caso para árbol.so, al usar distancias para formar el árbol reducimosmuchísimo el número <strong>de</strong> flits extra, ya que recorrerel árbol supone recorrer nodos cercanos y no nodosa distancia arbitraria, como suce<strong>de</strong> si no se usa ladistancia.En cuanto a las escrituras, po<strong>de</strong>mos comprobar enla Figura 3c el pésimo rendimiento <strong>de</strong> SCI. El número<strong>de</strong> enlaces en el camino crítico es proporcional alnúmero <strong>de</strong> nodos en la lista. Por el contrario, en elcaso <strong>de</strong>l directorio tenemos que el camino crítico esproporcional a la raíz cuadrada <strong>de</strong>l número <strong>de</strong> cores<strong>de</strong>l chip (ya que esa raíz cuadrada <strong>de</strong>termina ladistancia media entre cores aleatorios), lo que proporcionauna camino crítico mucho menor.Los árboles tienen un camino crítico medio proporcionala la raíz cuadrada <strong>de</strong>l número <strong>de</strong> cores<strong>de</strong>l chip multiplicada por el logaritmo <strong>de</strong>l número<strong>de</strong> compartidores. A pesar <strong>de</strong> que esto supone unamejora importante con respecto a SCI, las propuestas<strong>de</strong> árbol que no usan distancia al montar el árbolse siguen comportando mal en comparación con eldirectorio. Al usar distancia (treeDist, treePredDist)tenemos unos valores para el camino crítico que, aunqueligeramente mayores que los <strong>de</strong>l directorio, estánmucho más cerca <strong>de</strong>l directorio que <strong>de</strong> SCI o <strong>de</strong> laspropuestas <strong>de</strong> árbol que no usan distancia.En cuanto a los flits generados en las escrituras (Figura3d), el directorio, a pesar <strong>de</strong> tener un caminocrítico muy pequeño, como veíamos anteriormente,produce un número <strong>de</strong> flits similar al <strong>de</strong> SCI. <strong>La</strong>razón es que en ambos casos se necesitan dos mensajes<strong>de</strong> control con origen y <strong>de</strong>stino aleatorio porcada L1 a invalidar, por lo que la cantidad <strong>de</strong> tráficogenerado es muy similar en ambos casos. Los árbolespor sí mismos (tree, treePred) tampoco reducenen nada este número <strong>de</strong> flits. Es al usar la distanciaentre nodos al crear el árbol (treeDist, treePredDist)cuando conseguimos reducir el tráfico notablemente,y la reducción obtenida es muy consi<strong>de</strong>rable: 95 %menos <strong>de</strong> tráfico que el directorio en las invalidacionesen una máquina con 8192 cores y un 50 % menos<strong>de</strong> tráfico con tan sólo 64 cores.B. Bloques <strong>de</strong> sólo lectura.Este escenario comienza con todos los nodos leyendoel bloque. Una vez hecho esto, las hojas <strong>de</strong>l árbolrealizan reemplazos y vuelven a pedir el bloque. Enningún momento se realizan escrituras. Como vemos,el camino crítico <strong>de</strong> las lecturas (Figura 4a) se mantienecasi constante en treePredDist, ya que siemprese predice un nodo compartidor cercano físicamente,in<strong>de</strong>pendientemente <strong>de</strong>l tamaño <strong>de</strong>l chip. Esto reduceel camino crítico <strong>de</strong> las lecturas con respecto al directorio:hasta un 96 % menos <strong>de</strong> enlaces recorridospara 8192 cores. A<strong>de</strong>más, al contrario que en el escenarioanterior, gracias a la predicción treePredDistgenera notablemente menos tráfico que el directorioy SCI, un 95 % menos.C. Información <strong>de</strong> coherencia.Pasamos ahora a ver el tamaño <strong>de</strong> las estructurasutilizadas por los protocolos que estamos evaluandopara almacenar la información <strong>de</strong> coherencia. EnL2, una entrada <strong>de</strong> directorio full-map utiliza un bitpor core en cada entrada, mientras que el resto <strong>de</strong>protocolos sólo necesitan un puntero a un nodo porentrada. Un puntero tiene un tamaño igual al logaritmoen base dos <strong>de</strong>l número <strong>de</strong> nodos en el chip.En L1, el protocolo basado en directorio no necesitaalmacenar información sobre compartidores. Porsu parte, SCI necesita dos punteros en los tags <strong>de</strong>L1 para mantener la lista doblemente enlazada. <strong>La</strong>spropuestas <strong>de</strong> árbol necesitan tres punteros en lostags <strong>de</strong> L1 (dos para los hijos y uno para el padre).Teniendo en cuenta esto, el overhead <strong>de</strong>l directoriocrece linealmente con el número <strong>de</strong> cores (almacenamientoproporcional a n 2 para todo el CMP), y el<strong>de</strong>l resto <strong>de</strong> protocolos crece logarítmicamente conel número <strong>de</strong> cores (almacenamiento proporcional an · log(n) para todo el CMP).D. <strong>La</strong>tencia <strong>de</strong> escrituras.En el directorio, la latencia <strong>de</strong> las escrituras conmuchos compartidores tiene un componente que <strong>de</strong>pen<strong>de</strong>linealmente <strong>de</strong>l número <strong>de</strong> compartidores, yaque todos los ACKs se reciben en el mismo nodo.Mientras el número <strong>de</strong> compartidores sea pequeño,éste componente lineal tiene poca inci<strong>de</strong>ncia, y elcomponente dominante es la distancia atravesada enel camino crítico, que es proporcional a la raíz cuadrada<strong>de</strong>l número <strong>de</strong> cores en el chip. Sin embargo,al aumentar el número <strong>de</strong> cores y compartidores, llegaráun momento en que el componente lineal se impondrásobre el componente proporcional a la distanciaatravesada, y el nodo que recibe todos los ACKsse convertirá en un importante cuello <strong>de</strong> botella enlas escrituras a datos muy compartidos.Por otro lado, cuando se utiliza un árbol, cada nodorecibe como máximo dos ACKs, correspondientesa sus dos hijos. Con esto se elimina el componentelineal <strong>de</strong> la latencia <strong>de</strong> las escrituras, y se evita así elcuello <strong>de</strong> botella. Como consecuencia, la latencia <strong>de</strong>las escrituras <strong>de</strong>pen<strong>de</strong> <strong>de</strong>l número <strong>de</strong> niveles <strong>de</strong>l árbolmultiplicado por la distancia entre nodos adyacentes.Esta latencia es proporcional a log(n) · √n.<strong>JP2011</strong>-243


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Si a<strong>de</strong>más usamos distancia al crear el árbol, losnodos adyacentes en el árbol se encuentran cercanosfísicamente en el chip. Al aumentar el tamaño<strong>de</strong>l chip no aumenta significativamente la distanciaentre dos nodos consecutivos <strong>de</strong> una rama. Esto locomprobábamos en la Sección V-B, don<strong>de</strong> al pre<strong>de</strong>ciral antiguo padre en las lecturas el tamaño <strong>de</strong>lcamino crítico era in<strong>de</strong>pendiente <strong>de</strong>l número <strong>de</strong> cores.Por tanto, la latencia <strong>de</strong> las escrituras <strong>de</strong>pen<strong>de</strong>únicamente <strong>de</strong>l número <strong>de</strong> niveles en el árbol, que esproporcional a log(n). Al crecer el número <strong>de</strong> cores enel chip, la latencia lineal <strong>de</strong> las escrituras en el directoriopasará a ser mayor que la latencia logarítmica<strong>de</strong>l árbol que usa distancia.VI. Trabajo relacionado<strong>La</strong> propuesta más cercana a nuestro protocolo <strong>de</strong>árbol basado en proximidad y predicción es la extensiónGLOW [8] para SCI. GLOW propone situaragentes estáticos que actúan como nodos intermedios<strong>de</strong> un árbol en el que los compartidores <strong>de</strong> un bloqueson las hojas. Normalmente, los agentes se sitúan enlos nodos en los que se produce un cambio <strong>de</strong> dimensiónen el routing hacia el nodo home <strong>de</strong>l bloque (seasume un encaminamiento en or<strong>de</strong>n <strong>de</strong> dimensión)y monitorizan el tráfico que gira en ese nodo. Cadaagente mantiene una lista SCI <strong>de</strong> los compartidorescuyo tráfico hacia el nodo home gira por primera vezen el nodo <strong>de</strong>l agente. El agente también mantieneuna lista SCI <strong>de</strong> agentes cuyo tráfico hacia el nodohome gira por primera vez en el nodo <strong>de</strong>l agente,para así formar el árbol. Esto hace que, en una malla,el árbol sólo tenga un nivel intermedio <strong>de</strong> agentes,ya que sólo se produce un giro para alcanzar elnodo home. En otras topologías (p. ej., hipercubos)pue<strong>de</strong>n existir más giros y por tanto más niveles enel árbol. Los agentes se encargan <strong>de</strong> interceptar laspeticiones <strong>de</strong> memoria a bloques muy compartidospara resolverlas más rápidamente obteniendo el dato<strong>de</strong> un compartidor <strong>de</strong> su lista SCI <strong>de</strong> compartidores.Esto implica consultar el directorio en el agente paracada petición <strong>de</strong>tectada a bloque altamente compartido.Si la lista SCI local está vacía, el agente envíauna solicitud para añadirse a la lista <strong>de</strong> agentes <strong>de</strong>lnivel superior y obtener el dato; el dato es enviadoal peticionario (que a su vez pue<strong>de</strong> ser otro agente<strong>de</strong> nivel inferior), y el peticionario es añadido a lalista SCI local correspondiente <strong>de</strong>l agente (según seaun nodo hoja u otro agente). Este árbol reduce lalatencia media <strong>de</strong> las lecturas y el camino crítico <strong>de</strong>las escrituras, ya que aunque siguen existiendo listasque invalidar, estas son más cortas y están formadaspor nodos relativamente cercanos.Sin embargo, GLOW tiene numerosos inconvenientescon respecto a nuestra propuesta, <strong>de</strong> los cualesnombramos sólo algunos: requiere añadir agentesque necesitan información <strong>de</strong> directorio para mantenerlas listas SCI (en una malla necesitaríamos unagente por nodo); requiere monitorizar e intervenir eltráfico por parte <strong>de</strong> los agentes; necesita <strong>de</strong>tectar losbloques altamente compartidos <strong>de</strong> manera dinámicapara evitar que la intervención <strong>de</strong>l tráfico por parte<strong>de</strong> los agentes afecte negativamente al resto <strong>de</strong> peticiones;los bloques que no son altamente compartidossiguen usando SCI y no obtienen ningún beneficio; unnodo cercano con copia <strong>de</strong>l dato sólo pue<strong>de</strong> proveerloa un nodo solicitante en caso <strong>de</strong> que coincidan susagentes, y a<strong>de</strong>más con la indirección introducida poruno o varios agentes. En resumen, GLOW es un pasointermedio entre SCI y nuestra propuesta, pero quetiene un mayor coste y es más complejo.VII. ConclusionesHemos presentado un nuevo protocolo <strong>de</strong> coherenciabasado en árboles, predicción y proximidad, quemantiene las ventajas <strong>de</strong> los estructuras enlazadas <strong>de</strong>coherencia como SCI y evita sus principales inconvenientes.<strong>La</strong>s escrituras a bloques compartidos pormuchos nodos pasan a tener un camino crítico cuyalongitud es similar a la <strong>de</strong>l directorio. A<strong>de</strong>más, nuestroprotocolo aporta nuevas ventajas con respectoal directorio que se hacen más influyentes conformecrece el número <strong>de</strong> cores en el chip. Gracias al mecanismopara añadir nuevos compartidores en el árbol,que siempre selecciona la rama más cercana al nuevocompartidor, reducimos notablemente el tráfico generadoen la red. Éste se reduce en hasta un 95 %para las escrituras, con respecto a un directorio, enun chip con 8192 cores. Esta creación <strong>de</strong>l árbol basadaen proximidad, unida al mecanismo <strong>de</strong> predicción,también reduce el camino crítico <strong>de</strong> los fallos <strong>de</strong> lecturaen hasta un 96 %, y su tráfico en hasta un 95 %,también para 8192 cores.Agra<strong>de</strong>cimientosEste trabajo ha sido financiado por la FundaciónSéneca (Agencia Regional <strong>de</strong> Ciencia y Tecnología,Región <strong>de</strong> Murcia) mediante el proyecto00001/CS/2007, y por el MEC y la Comisión EuropeaFEDER mediante los proyectos “Consoli<strong>de</strong>rIngenio-2010 CSD2006-00046” y “TIN2009-14475-C04-02”. Antonio García-Guirado también es beneficiario<strong>de</strong> una beca <strong>de</strong> investigación <strong>de</strong>l MEC bajoel Plan Nacional <strong>de</strong> Formación <strong>de</strong> Profesorado Universitario(FPU AP2008-04387).Referencias[1] D. V. James, A. T. <strong>La</strong>undrie, S. Gjessing, and G. Sohi,“Scalable Coherent Interface,” Computer, vol. 23, no. 6,pp. 74–77, 1990.[2] Y.-C. Maa, D. K. Pradhan, and D. Thiebaut, “Two EconomicalDirectory Schemes for <strong>La</strong>rge-Scale Cache CoherentMultiprocessors,” SIGARCH Computer ArchitectureNews, vol. 19, no. 5, pp. 10–18, 1991.[3] H. Nilsson and P. Stenstrom, “The Scalable Tree Protocol- A Cache Coherence Approach for <strong>La</strong>rge-Scale Multiprocessors,”in Proceedings of the 4th International Conferenceon Parallel and Distributed Processing, pp. 498–506,1992.[4] R. E. Johnson, Extending the Scalable Coherent Interfacefor <strong>La</strong>rge-Scale Shared-Memory Mutiprocessors. PhDin Computer Science, University of Wisconsin - Madison,2003.[5] Y. Chang and L. N. Bhuyan, “An Efficient Tree CacheCoherence Protocol for Distributed Shared Memory Multiprocessors,”IEEE Transactions on Computers, vol. 48,no. 3, pp. 352–360, 1999.[6] A. Ros, M. E. Acacio, and J. M. García, “A DirectCoherence Protocol for Many-Core Chip Multiprocessors,”IEEE Transactions on Parallel and Distributed Systems(TPDS), vol. 21, pp. 1779–1792, Dec. 2010.[7] M. M. K. Martin, D. J. Sorin, B. M. Beckmann, M. R.Marty, M. Xu, A. R. Alamel<strong>de</strong>en, K. E. Moore, M. D.Hill, and D. A. Wood, “Multifacet’s general executiondrivenmultiprocessor simulator (GEMS) toolset,” SI-GARCH Comput. Archit. News, vol. 33, pp. 92–99, November2005.[8] S. Kaxiras and J. R. Goodman, “The GLOW cache coherenceprotocol extensions for wi<strong>de</strong>ly shared data,” in Proceedingsof the 10th International Conference on Supercomputing(ICS), pp. 35–43, 1996.<strong>JP2011</strong>-244


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Explotación <strong>de</strong> Técnicas <strong>de</strong> Especialización<strong>de</strong> Cores para Planificación Eficiente enProcesadores Multicore AsimétricosJuan Carlos Sáez 1 Manuel Prieto 2 Adrián Pousa 3 Alexandra Fedorova 4Resumen— Los procesadores multicore asimétricoscon repertorio común <strong>de</strong> instrucciones –AMPs (AsymmetricMulticore Processors)– han sido propuestos recientementecomo alternativa a los multicore simétricosconvencionales –SMP (Symetric Multicore Processors)–.En lugar <strong>de</strong> integrar en el chip cores <strong>de</strong>l mismotipo, como nos ofrecen actualmente Intel y AMD ensus últimos productos, la i<strong>de</strong>a consiste en combinarmúltiples cores simples con un número reducido <strong>de</strong>cores más complejos. Es una aproximación semejanteal IBM Cell/BE, el ejemplo más <strong>de</strong>stacado a nivel comercial<strong>de</strong> multicore heterogéneo, pero explícitamentese soporta un repertorio <strong>de</strong> instrucciones común entodos los cores para simplificar el <strong>de</strong>sarrollo <strong>de</strong> software.Para transladar los beneficios <strong>de</strong> los sistemas AMPdirectamente a las aplicaciones es preciso disponer <strong>de</strong>técnicas que permitan especializar cada tipo <strong>de</strong> corepara la ejecución <strong>de</strong> aquellas aplicaciones que hacen <strong>de</strong>éste un uso más eficiente. Esta especialización pue<strong>de</strong>llevarse a cabo por el planificador <strong>de</strong>l sistema operativo.Nuestro trabajo presenta el planificador CAMP(Comprehensive scheduler for AMPs), que supera lasprincipales limitaciones presentes en otros algoritmos<strong>de</strong> planificación para AMPs propuestos hasta la fecha.A diferencia <strong>de</strong> otros algoritmos, CAMP combinala información acerca <strong>de</strong> las dos características <strong>de</strong>las aplicaciones que resultan cruciales para garantizaruna planificación efectiva en AMPs: la eficiencia enla utilización <strong>de</strong> los cores complejos <strong>de</strong>l sistema y sugrado <strong>de</strong> paralelismo a nivel <strong>de</strong> hilo. Los resultadosobtenidos en un prototipo <strong>de</strong> sistema AMP diseñadopor Intel <strong>La</strong>bs revelan que CAMP es capaz <strong>de</strong> obtenerbeneficios significativos para un mayor espectro<strong>de</strong> cargas <strong>de</strong> trabajo que otros algoritmos propuestosanteriormente.Palabras clave— AMP, procesadores multicoreasimétricos, planificación, sistema operativo.I. IntroducciónLOS procesadores multicore asimétricos (AMPs)han sido recientemente propuestos como una alternativamás eficiente a los multicore simétricos actuales[1], [2]. Los AMPs integran cores que difierenen aspectos microarquitectónicos, área y consumo <strong>de</strong>energía pero exponiendo un repertorio <strong>de</strong> instruccionescomún. Este tipo <strong>de</strong> procesadores integran dostipos <strong>de</strong> core: “rápidos” y “lentos”. Los cores rápidosimplementan sofisticadas características microarquitectónicas,como ejecución fuera <strong>de</strong> or<strong>de</strong>n y especulativa,<strong>de</strong>stinadas a incrementar el rendimientosecuencial. Por el contrario, los cores lentos están caracterizadospor una microarquitectura más simple y1 ArTeCS Group, Univ. Complutense <strong>de</strong> Madrid, e-mail:jcsaezal@fdi.ucm.es.2 ArTeCS Group, Univ. Complutense <strong>de</strong> Madrid, e-mail:mpmatias@dacya.ucm.es.3 III-LIDI, Univ. Nacional <strong>de</strong> <strong>La</strong> Plata, e-mail:apousa@lidi.info.unlp.edu.ar.4 Simon Fraser University, e-mail: fedorova@cs.sfu.ca.<strong>de</strong>mandan menor área y consumo que los cores rápidosy complejos. Este hecho permite la integración<strong>de</strong> numerosos cores simples en el chip, ofreciendo unelevado paralelismo a nivel <strong>de</strong> hilo a expensas <strong>de</strong> unmenor rendimiento secuencial.El potencial <strong>de</strong> los sistemas AMPs pue<strong>de</strong> explotarsemediante la aplicación <strong>de</strong> dos técnicas <strong>de</strong> especialización<strong>de</strong> cores:Especialización <strong>de</strong> ILP: Consi<strong>de</strong>remos unacarga <strong>de</strong> trabajo constituida por aplicaciones intensivasen memoria e intensivas en CPU. <strong>La</strong>sprimeras provocan frecuentes paradas <strong>de</strong>l pipelinecomo consecuencia <strong>de</strong> numerosos accesos amemoria, y por tanto, utilizan la CPU ineficientemente.<strong>La</strong>s segundas hacen un uso más intensivo<strong>de</strong> los recursos <strong>de</strong>l procesador y experimentanun mayor speedup relativo al ejecutaren cores complejos con respecto a cores simples.<strong>La</strong> especialización <strong>de</strong> ILP permite maximizar elrendimiento en un AMP dando mayor prioridada las aplicaciones más intensivas en CPU paraejecutarse en cores complejos.Especialización <strong>de</strong> TLP: Esta técnica se basaen explotar la diversidad en el paralelismo anivel <strong>de</strong> hilo –TLP (Thread-Level Paralelism)–presente en una carga <strong>de</strong> trabajo. Consi<strong>de</strong>remosuna carga <strong>de</strong> trabajo formada por aplicacionesparalelas y secuenciales, o bien, formada exclusivamentepor aplicaciones paralelas con fases secuenciales.Los cores rápidos <strong>de</strong>l sistema AMPpue<strong>de</strong>n usarse para acelerar aplicaciones secuencialeso para mitigar los cuellos <strong>de</strong> botella secuenciales<strong>de</strong> las aplicaciones paralelas. Por elcontrario, los abundantes cores lentos pue<strong>de</strong>n reservarsepara ejecutar código paralelo.<strong>La</strong> explotación <strong>de</strong> estas técnicas <strong>de</strong> especializaciónpermite a los AMPs ofrecer un mayor rendimientopor vatio que sus equivalentes simétricos [3], [4]. Noobstante, ningún tipo <strong>de</strong> especialización pue<strong>de</strong> serexplotado directamente por el hardware, sino que estarea <strong>de</strong>l software <strong>de</strong> sistema el empleo <strong>de</strong> políticas<strong>de</strong> planificación que mapeen los distintos flujos <strong>de</strong>instrucciones en los tipos <strong>de</strong> cores que permitan ejecutarlos<strong>de</strong> manera más eficiente.Los algoritmos <strong>de</strong> planificación propuestos hasta lafecha explotan sólo una técnica <strong>de</strong> especialización (<strong>de</strong>ILP o <strong>de</strong> TLP), pero nunca ambas. Por este motivo,resultan efectivos únicamente para ciertas cargas <strong>de</strong>trabajo [5].En este trabajo presentamos CAMP, un algoritmo<strong>JP2011</strong>-245


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>de</strong> planificación para AMPs que es capaz <strong>de</strong> combinarambas técnicas. CAMP toma <strong>de</strong>cisiones <strong>de</strong> planificaciónen base al factor <strong>de</strong> utililidad <strong>de</strong> las aplicaciones,métrica que aproxima, en función <strong>de</strong>l ILP y TLP <strong>de</strong>una aplicación, el speedup global que ésta obtendríasi se permite que sus hilos <strong>de</strong> ejecución utilicen todoslos cores rápidos y complejos en el sistema, conrespecto a una ejecución don<strong>de</strong> sólo se utilizan coressimples. Para calcular el factor <strong>de</strong> utilidad <strong>de</strong> un hilo<strong>de</strong> ejecución es preciso conocer su factor <strong>de</strong> ganancia,beneficio relativo que este experimenta al ejecutaren un core rápido con respecto a uno lento. En estetrabajo proponemos una metodología para el diseñosistemático <strong>de</strong> mo<strong>de</strong>los <strong>de</strong> estimación <strong>de</strong> factores <strong>de</strong>ganancia.Para la evaluación <strong>de</strong>l planificador CAMP –implementado en el sistema operativo OpenSolaris–utilizamos un prototipo <strong>de</strong> sistema asimétrico diseñadoen Intel <strong>La</strong>bs [6]. A diferencia <strong>de</strong> la asimetríaen rendimiento que se consigue mediante la reducción<strong>de</strong> la frecuencia <strong>de</strong> trabajo en algunos cores –técnica<strong>de</strong> emulación ampliamente usada por la comunidadcientífica [7], [4], [8], [5]–, este prototipo mo<strong>de</strong>la <strong>de</strong>manera más realista el tipo <strong>de</strong> asimetría que se suponeestará presente en futuros sistemas asimétricos,don<strong>de</strong> los cores exhiben diferencias más profundas anivel microarquitectónico [6].Este artículo consta <strong>de</strong> las siguientes secciones: lasección II analiza trabajos previos sobre planificaciónen AMPs; la sección III presenta el diseño y la implementación<strong>de</strong>l algoritmo CAMP; en la sección IV<strong>de</strong>scribimos el proceso <strong>de</strong> generación <strong>de</strong> mo<strong>de</strong>los <strong>de</strong>estimación <strong>de</strong> factores <strong>de</strong> ganancia; en la sección Vse muestran los resultados experimentales obtenidos;finalmente en la sección VI se enumeran las principalesconclusiones <strong>de</strong> este trabajo.II. Antece<strong>de</strong>ntes y trabajos relacionadosEn esta sección realizamos un análisis <strong>de</strong> las propuestasprevias comenzando por aquellas que explotanespecialización <strong>de</strong> ILP. Posteriormente analizamosaquellos trabajos que estudian las capacida<strong>de</strong>s<strong>de</strong> los sistemas AMP para mitigar la ley <strong>de</strong> Amdahl.Kumar y otros [1], [2], hacen uso <strong>de</strong> los procesadoresAMP para explotar la diversidad <strong>de</strong> factores<strong>de</strong> ganancia 1 –SF (speedup factor)– presente en unacarga <strong>de</strong> trabajo multiprogramada. <strong>La</strong>s aplicacionescon SF alto usan efecientemente los recursos hardwarepresentes en los cores rápidos y complejos queestán <strong>de</strong>stinados a la extracción <strong>de</strong> ILP. Asignandolas aplicaciones con SF alto a los cores complejos ylas aplicaciones con SF bajo a los cores simples, sealcanzan incrementos en el rendimiento <strong>de</strong> hasta un63 % frente a un SMP <strong>de</strong> área similar [2].Los algoritmos propuestos por Kumar [2] y Becchi[3] requieren ejecutar las aplicaciones tanto encores simples como complejos para calcular su SF.1 El factor <strong>de</strong> ganancia (SF) <strong>de</strong> un hilo <strong>de</strong> ejecución se <strong>de</strong>fineformalmente como IPS fast /IPS slow , don<strong>de</strong> IPS fast y IPS slowson el número <strong>de</strong> instrucciones por segundo (IPS) <strong>de</strong>l hilo encores rápidos y lentos, respectivamente.El factor <strong>de</strong> ganancia <strong>de</strong> cada aplicación se aproximamediante el cociente <strong>de</strong>l número <strong>de</strong> instruccionesretiradas por segundo (IPS) <strong>de</strong> la aplicación en coresrápidos y lentos. En un trabajo previo <strong>de</strong>tectamosque esta técnica <strong>de</strong> medición directa <strong>de</strong> SFs introduceserios problemas <strong>de</strong> rendimiento, y mostramos quecalcular SFs <strong>de</strong> esta forma resulta inapropiado en lapráctica [7]. El empleo <strong>de</strong> técnicas <strong>de</strong> estimación <strong>de</strong>lfactor <strong>de</strong> ganancia a partir <strong>de</strong> medidas <strong>de</strong> rendimiento<strong>de</strong> la aplicación en un solo tipo <strong>de</strong> core permitesubsanar las limitaciones <strong>de</strong> la medición directa <strong>de</strong>lSF [9], [10]. Por este motivo, el planificador CAMPemplea mecanismos <strong>de</strong> estimación.Los sistemas AMP se han estudiado también comoplataformas para mitigar la ley <strong>de</strong> Amdahl. Hilly Marty [11] <strong>de</strong>dujeron mo<strong>de</strong>los teóricos para el speedupen arquitecturas AMP. Annavaram [4] propusoun planificador a nivel <strong>de</strong> aplicación que asigna acores rápidos las secuenciales explícitas presentes enuna aplicacion paralela, mitigando la ley <strong>de</strong> Amdahl<strong>de</strong> manera efectiva. En un trabajo previo presentamosel algoritmo PA (Paralelism-Aware), el primeralgoritmo implementado en un sistema operativo realque explota especialización <strong>de</strong> TLP [5]. A diferencia<strong>de</strong> la propuesta <strong>de</strong> Annavaram, el algoritmo PA ofrecesoporte para cargas <strong>de</strong> trabajo con múltiples aplicacionesy garantiza la aceleración <strong>de</strong> fases secuencialesen aplicaciones paralelas <strong>de</strong> forma totalmentetransparente, sin requerir modicación alguna en elcódigo fuente <strong>de</strong> la aplicación.III. Diseño e implementación<strong>La</strong>s asignaciones <strong>de</strong> hilos a cores realizadas porCAMP se llevan a cabo en base al factor <strong>de</strong> utilidad<strong>de</strong> cada hilo. Dado un sistema AMP con NFC coresrápidos, el factor <strong>de</strong> utilidad <strong>de</strong> un hilo <strong>de</strong> ejecución–UF (Utility Factor)– es una métrica que permiteaproximar el speedup que la aplicación al que el hilopertenece experimenta si NFC <strong>de</strong> sus hilos se asignana cores rápidos y el resto a cores lentos, con respectoa una ejecución don<strong>de</strong> solo se utilizan cores lentos.<strong>La</strong> fórmula para el UF, que se ha obtenido usandouna aproximación analítica <strong>de</strong>scrita en [12], es <strong>de</strong> lasiguiente forma:UF =SF − 1(⌊ N threads−1NF C⌋ + 1) 2 + 1 (1)En la fórmula, N threads es el número <strong>de</strong> hilos <strong>de</strong>ejecución activos <strong>de</strong> la aplicación. Este valor, que esvisible a nivel <strong>de</strong> sistema operativo, permite aproximareficientemente el paralelismo a nivel <strong>de</strong> hilo(TLP) <strong>de</strong> la aplicación [5]. SF es el factor <strong>de</strong> ganacia<strong>de</strong>l hilo <strong>de</strong> ejecución. <strong>La</strong> sección IV <strong>de</strong>scribe cómoCAMP aproxima el SF en tiempo <strong>de</strong> ejecución usandolos contadores hardware <strong>de</strong>l procesador.CAMP clasifica los hilos en cuatro clases <strong>de</strong> utilidad–VERY LOW, LOW, MEDIUM y HIGH– quese asignan en función <strong>de</strong> sus UFs. Esta aproximaciónbasada en clases permite mitigar algunas imprecisionesen la estimación <strong>de</strong> los factores <strong>de</strong> ganancia(SFs), usados para el cómputo <strong>de</strong>l UF, así como pa-<strong>JP2011</strong>-246


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA I: Correspon<strong>de</strong>ncia entre valores <strong>de</strong>l UF yclases <strong>de</strong> utilidad.ClaseHIGHMEDIUMLOWVERY LOWRango <strong>de</strong> UFUF ≥ upper thresholdmedium threshold ≤ UF < upper thresholdlower threshold ≤ UF < medium thresholdUF < lower thresholdra dar un mismo trato a aquellos hilos con UFs muysimilares.<strong>La</strong> asignación <strong>de</strong> hilos a las clases <strong>de</strong> utilidad serealiza en función <strong>de</strong> tres umbrales específicos <strong>de</strong> plataforma–lower, medium and upper–, que <strong>de</strong>terminanlas fronteras entre las clases. <strong>La</strong> tabla I muestra lacorrespon<strong>de</strong>ncia entre el valor <strong>de</strong>l factor <strong>de</strong> utilidad<strong>de</strong>l hilo <strong>de</strong> ejecución y su clase <strong>de</strong> utilidad. <strong>La</strong>s clasesse muestran en la tabla en or<strong>de</strong>n <strong>de</strong>scen<strong>de</strong>nte por suprioridad para ejecutarse en cores rápidos, siendo loshilos <strong>de</strong> la clase <strong>de</strong> utilidad HIGH los que gozan <strong>de</strong>mayor prioridad. Los cores rápidos se asignan a losdistintos hilos <strong>de</strong> ejecución siguiendo este or<strong>de</strong>n <strong>de</strong>prioridad. En el caso <strong>de</strong> que existan cores rápidos sinasignar a hilos <strong>de</strong> la clase HIGH, estos cores restantesse asignarán a hilos <strong>de</strong> clases <strong>de</strong> menor prioridad. Elresto <strong>de</strong> hilos se ejecutaran en cores lentos. Excepcionalmente,si el número <strong>de</strong> hilos HIGH supera alnúmero <strong>de</strong> cores rápidos, estos cores se repartirán <strong>de</strong>manera equitativa entre hilos HIGH, utilizando paraello un mecanismo round-robin basado en migracionesperiódicas <strong>de</strong> hilos propuesto en [10].CAMP reserva una clase <strong>de</strong> utilidad especial (SE-QUENTIAL BOOSTED) para los hilos <strong>de</strong> una aplicaciónparalela que ejecutan fases secuenciales <strong>de</strong> lamisma y exhiben un SF alto (clase HIGH). Estoshilos gozan temporalmente <strong>de</strong> mayor prioridad paraejecutarse en cores rápidos que el resto <strong>de</strong> hilos <strong>de</strong>clase HIGH, pertenecientes a aplicaciones monohilo.Este mecanismo ofrece mayores oportunida<strong>de</strong>s paramitigar los cuellos <strong>de</strong> botella secuenciales presentesen las aplicaciones paralelas [9].IV. Estimación <strong>de</strong> Factores <strong>de</strong> GananciaEn esta sección <strong>de</strong>tallamos el proceso <strong>de</strong> generación<strong>de</strong> un mo<strong>de</strong>lo <strong>de</strong> rendimiento que permite estimarel SF en un prototipo <strong>de</strong> sistema asimétricodiseñado en Intel <strong>La</strong>bs [6]. <strong>La</strong> sección V proporcionamás <strong>de</strong>talles acerca <strong>de</strong> esta plataforma y analizalos resultados obtenidos por el planificador CAMPen dicho prototipo.Koufaty y otros <strong>de</strong>tectaron que en este sistemaexisten dos factores que muestran una clara correlacióncon el factor <strong>de</strong> ganancia [6]. El primer factor esla intensidad en memoria que exhibe la aplicación,que pue<strong>de</strong> aproximarse mediante su tasa <strong>de</strong> fallos <strong>de</strong>cache <strong>de</strong> último nivel [9]. El segundo factor está relacionadocon las paradas producidas en el front-end<strong>de</strong>l pipeline <strong>de</strong>l procesador 2 . <strong>La</strong> figura 1 muestra lacorrelación entre el SF y estos dos factores para losbenchmarks <strong>de</strong> la suite SPEC CPU2006. Los datos2 Este factor pue<strong>de</strong> aproximarse monitorizando el número <strong>de</strong>ciclos que la cola <strong>de</strong> instrucciones está vacía.LLC misses per 1K instructionsinternal stalls per 1K cycles454035302520151050300250200150100500LLC miss rateSpeedup Factormcfastarlbmmilcsoplexgobmkbzip2leslie3dGemsFDTDgcccactusADMlibquantumsjenggromacszeusmpxalancbmksphinx3perlbenchwrfpovraynamdbwaves<strong>de</strong>alIItontoh264refgamesscalculixhmmer(a) Tasa <strong>de</strong> fallos <strong>de</strong> último nivel <strong>de</strong> cache vs. SFinternal stallsSpeedup Factormcfastarlbmmilcsoplexgobmkbzip2leslie3dGemsFDTDgcccactusADMlibquantumsjenggromacszeusmpxalancbmksphinx3perlbenchwrfpovraynamdbwaves<strong>de</strong>alIItontoh264refgamesscalculixhmmer(b) Paradas en el front-end <strong>de</strong>l pipeline vs. SFFig. 1: Correlación entre distintas métricas <strong>de</strong> rendimientoy el SF observado para los benchmarks <strong>de</strong> lasuite SPEC CPU2006 ejecutando en el prototipo <strong>de</strong>sistema asimétrico.revelan que tanto las aplicaciones intensivas en memoria(alta tasa <strong>de</strong> fallos <strong>de</strong> cache) como aquellas confrecuentes paradas en el front-end <strong>de</strong>l pipeline suelenexperimentar factores <strong>de</strong> ganancia bajos. A pesar <strong>de</strong>la relevancia <strong>de</strong> estos resultados, diseñar un mo<strong>de</strong>lobasado únicamente en esta ten<strong>de</strong>ncia daría lugara graves fallos <strong>de</strong> predicción –por ejemplo, para elbenchmark gromacs–.En la búsqueda <strong>de</strong> metodologías sistemáticas paradiseñar mo<strong>de</strong>los <strong>de</strong> estimación en escenarios complejos,como el que se estudia en este trabajo, exploramosdistintas técnicas <strong>de</strong> minería <strong>de</strong> datos usando laherramienta WEKA [13]. WEKA proporciona numerososmétodos para inferir relaciones entre un conjunto<strong>de</strong> observaciones (o atributos <strong>de</strong> entrada) y unavariable objetivo. En el problema <strong>de</strong> estimación <strong>de</strong>SFs, las observaciones se correspon<strong>de</strong>n con distintosparámetros <strong>de</strong> rendimiento y la variable objetivo esel SF. Entre los métodos explorados, <strong>de</strong>tectamos quela regresión aditiva [14] permite <strong>de</strong>rivar un mo<strong>de</strong>lo<strong>de</strong> estimación preciso para esta plataforma. A<strong>de</strong>más,los coeficientes obtenidos tras el análisis <strong>de</strong> regresión2.221.81.61.41.212.221.81.61.41.21Speedup FactorSpeedup Factor<strong>JP2011</strong>-247


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011MétricaIPCTABLA II: Métricas seleccionadasLLC miss rateL2 miss rateExecution stallsRetirement stallsDescripciónNúumero <strong>de</strong> instrucciones retiradaspor cicloNúmero <strong>de</strong> fallos <strong>de</strong> cache <strong>de</strong> últimonivel (L3) por cada mil instruccionesretiradasNúmero <strong>de</strong> fallos <strong>de</strong> cache <strong>de</strong> L2por cada mil instrucciones retiradasNumero <strong>de</strong> ciclos por cada mil ciclos<strong>de</strong> procesador en los ningunainstrucción ha finalizado su fase <strong>de</strong>ejecuciónNumero <strong>de</strong> ciclos por cada mil ciclos<strong>de</strong> procesador en los que no seretira ninguna instrucciónaditiva permiten establecer un ranking <strong>de</strong> las métricasexploradas en base a su relevancia. Esta informaciónfacilita la selección <strong>de</strong>l subconjunto <strong>de</strong> métricasque contribuyen en mayor medida a la aproximación<strong>de</strong>l SF, permitiendo una utilización efectiva <strong>de</strong> loscontadores hardware <strong>de</strong>l procesador.El proceso completo para la generación <strong>de</strong>l mo<strong>de</strong>lo<strong>de</strong> estimación pue<strong>de</strong> resumirse en los siguientespasos:1. Seleccionar un conjunto AP <strong>de</strong> aplicaciones secuencialesrepresentativas y un conjunto M <strong>de</strong>métricas <strong>de</strong> rendimiento.2. Ejecutar las aplicaciones <strong>de</strong> AP en ambos tipos<strong>de</strong> core para obtener su SF y monitorizar lasmétricas <strong>de</strong> rendimiento en M usando los contadoreshardware <strong>de</strong>l procesador.3. Construir el mo<strong>de</strong>lo <strong>de</strong> estimación para aproximarel SF <strong>de</strong>s<strong>de</strong> cada core <strong>de</strong> la siguiente forma:a) Aplicar regresión aditiva para aproximar el SFusando como training set los SFs obtenidospara las aplicaciones en AP junto con los valores<strong>de</strong> las métricas en M.b) Obtener el subconjunto <strong>de</strong> métricas SM ⊆ Mcon mayores coeficientes <strong>de</strong> regresión obtenidosen el paso anterior, tal que los contadoreshardware necesarios para monitorizar esasmétricas no exceda el número <strong>de</strong> contadoreshardware en la plataforma.c) Aplicar regresión aditiva <strong>de</strong> nuevo para obtenerel mo<strong>de</strong>lo <strong>de</strong> estimación final usando únicamentelas métricas en SM.Como conjunto AP <strong>de</strong> aplicaciones representativaspara construir el mo<strong>de</strong>lo en nuestra plataformaseleccionamos los benchmarks <strong>de</strong> las suites SPECCPU2006 y CPU2000. <strong>La</strong> tabla II <strong>de</strong>scribe el conjuntoSM <strong>de</strong> métricas, usado para la construcción <strong>de</strong>los mo<strong>de</strong>los finales en ambos cores. <strong>La</strong>s figuras 2ay 2b muestran la comparación entre el SF observadoy el estimado en cores rápidos y lentos, respectivamente.Los resultados revelan una mayor precisiónen los SFs predichos <strong>de</strong>s<strong>de</strong> el core rápido que <strong>de</strong>s<strong>de</strong>el lento. No obstante, este no es un comportamientoinesperado, ya que, intuitivamente, resulta muchomás sencillo pre<strong>de</strong>cir qué aplicaciones sufrirían másal reducir ciertas capacida<strong>de</strong>s microarquitectónicasestimated SFestimated SF2.221.81.61.41.2mgrid00 applu00wupwise00perlbmk00crafty00galgel00sixtrack0011 1.2 1.4 1.6 1.8 2 2.2observed SF2.221.81.61.41.2lbm06(a) Estimación en el core rápidogobmk06mgrid00tonto06wupwise00hmmer06calculix0611 1.2 1.4 1.6 1.8 2 2.2observed SF(b) Estimación en el core lentoFig. 2: SFs observados y predichos para losbenchmarks <strong>de</strong> las suites SPEC CPU2000 y SPECCPU2000. Se proporciona el nombre <strong>de</strong> aquellas aplicacionescon peores resultados <strong>de</strong> predicción.en un core (estimación <strong>de</strong> SF <strong>de</strong>s<strong>de</strong> el core rápido),que i<strong>de</strong>ntificar <strong>de</strong> manera precisa qué programas experimentaríanlos mayores beneficios al añadir hardwareadicional (estimación <strong>de</strong> SF <strong>de</strong>s<strong>de</strong> el core lento).Durante el proceso <strong>de</strong> diseño <strong>de</strong> CAMP <strong>de</strong>tectamosque las imprecisiones presentes en el mo<strong>de</strong>lo <strong>de</strong>estimación <strong>de</strong> SF pue<strong>de</strong>n mitigarse utilizando intervalos<strong>de</strong> SFs, en lugar <strong>de</strong> emplear directamente elvalor numérico proporcionado por la estimación. <strong>La</strong>sfronteras entre los intervalos <strong>de</strong> SF mencionados semuestran en las figuras 2a y 2b como líneas rojashorizontales.Finalmente, cabe <strong>de</strong>stacar que para realizar unaevaluación más exhaustiva <strong>de</strong> la efectividad <strong>de</strong> nuestromo<strong>de</strong>lo, hemos incluido experimentos con cargas<strong>de</strong> trabajo que incluyen aplicaciones que no han estadoinvolucradas en la generación <strong>de</strong> los mo<strong>de</strong>los <strong>de</strong>estimación (sección V).V. ExperimentosPara el análisis <strong>de</strong>l planificador CAMP hemos empleadoun prototipo <strong>de</strong> sistema asimétrico diseñado<strong>JP2011</strong>-248


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA III: Cargas <strong>de</strong> trabajo multiaplicación constituidaspor aplicaciones secuencialesCT Categorías BenchmarksSR1 2H-2L calculix, gamess, gobmk,milcSR2 2H-2L hmmer, calculix, soplex,astarSR3 1H-1M-2L hmmer, perlbench, soplex,mcfSR4 1H-1M-2L gamess, namd, astar, gobmkSR5 3H-1L hmmer, calculix, gamess,gobmkSR6 1H-3L gamess, sjeng, GemsFDTD,leslie3dSR7 4H hmmer, hmmer, calculix,gamessSR8 4H calculix, calculix, gamess,gamessSR9 2M-2L povray, gromacs, milc, mcfSR10 4L gobmk, gobmk, astar, astarTABLA IV: Cargas <strong>de</strong> trabajo multiaplicación constituidaspor aplicaciones paralelas y secuencialesCT Categorías BenchmarksMR1 2STH-2STL-1HPH hmmer, calculix,gobmk, astar,wupwise m(8)MR2 2STH-2STL-1HPL hmmer, gamess,soplex, bzip2,EP(8)MR3 2STH-1PSL-1HPH calculix,gamess, BLAST(5),wupwise m(5)MR4 1STH-1STL-1PSM-1HPM hmmer,gobmk, semphy(5),fma3d m(5)MR5 1STH-1STL-1PSM-1PSL calculix, bzip2,semphy(5),BLAST(5)MR6 1STH-1STL-1PSL-1HPH hmmer, astar,bodytrack(5),wupwise m(5)MR7 2STH-1PSM-1PSL calculix,gamess,bodytrack(5),FFTW(5)MR8 2STM-1PSL-1HPH wrf, namd, FFTW(5),wupwise m(5)MR9 3STH-3STL-1PSL hmmer, hmmer,gamess, gobmk,astar, BLAST(6)en Intel <strong>La</strong>bs [6]. Esencialmente, este prototipo esuna plataforma tipo NUMA con dos procesadoresIntel Xeon E5645 hex-core (Westmere) –doce coresen total–. Cada procesador tiene una cache L3 <strong>de</strong>6MB compartida por los seis cores <strong>de</strong> cada chip. Elprimer y segundo nivel <strong>de</strong> cache son privados a cadacore. <strong>La</strong> asimetría ha sido introducida en este sistemareduciendo el número máximo <strong>de</strong> microinstruccionesque pue<strong>de</strong>n retirarse por ciclo en algunos cores. Másconcretamente, los cores “lentos” son capaces <strong>de</strong> retiraruna microinstrucción por ciclo, mientras que loscores “rápidos” utilizan la configuración <strong>de</strong> fábrica –pudiendo retirar hasta cuatro microoperaciones porciclo–.En nuestra evaluación hemos empleado dos configuracionesAMP, (1) 2FC-2SC – dos cores rápidos ydos lentos distribuidos en dos chips <strong>de</strong> tal forma quecada chip incluye un core rápido y uno lento compartiendoun último nivel <strong>de</strong> cache – y (2) 2FC-10SC –dos cores rápidos y diez lentos en dos chips, don<strong>de</strong>cada chip contiene un core rápido y cinco lentos –.En esta sección comparamos el rendimiento <strong>de</strong>CAMP con el <strong>de</strong> otros tres algoritmos <strong>de</strong> planificaciónpropuestos previamente. Se trata <strong>de</strong> los algoritmosPA (Parallelism-Aware) [5] –que explota únicamenteespecialización <strong>de</strong> TLP–, SFD (SF-Driven)) 3 –que explota especialización <strong>de</strong> ILP– y RR (roundrobin)[8] –que realiza un reparto equitativo <strong>de</strong> loscores rápidos <strong>de</strong>l sistema entre todos los hilos–. Todoslos algoritmos evaluados en este trabajo se hanimplementado en el sistema operativo OpenSolaris.Para llevar a cabo un estudio exhaustivo <strong>de</strong> lasdistintas propuestas, construimos diversas cargas <strong>de</strong>trabajo multiprogramadas constituidas por aplicacionessecuenciales y paralelas <strong>de</strong> distintas suites <strong>de</strong>benchmarks – SPEC CPU2006, SPEC OMP2011,NAS Parallel, Minebench y PARSEC– así comoBLAST –aplicación utilizada en bioinformática– yFFTW –un benchmark científico que realiza la transformadarápida <strong>de</strong> Fourier–. <strong>La</strong>s cargas <strong>de</strong> trabajoestudiadas se divi<strong>de</strong>n en dos grupos. El primero incluyeúnicamente conjuntos <strong>de</strong> aplicaciones secuenciales(tabla III). El segundo grupo está constituidopor cargas <strong>de</strong> trabajo con aplicaciones paralelas ysecuenciales (tabla IV).En el proceso <strong>de</strong> construcción <strong>de</strong> cargas <strong>de</strong> trabajorepresentativas, clasificamos las distintas aplicacionesteniendo en cuenta su grado <strong>de</strong> paralelismo -ST (single-threa<strong>de</strong>d), PS (partially sequential 4 ) o HP(highly parallel) – así como en función <strong>de</strong> sus factores<strong>de</strong> ganancia – H (high), M (medium) o L (low)-. <strong>La</strong>columna central <strong>de</strong> las tablas III y IV especifica lacomposición <strong>de</strong> la carga <strong>de</strong> trabajo, indicando la clase<strong>de</strong> cada aplicación en el mismo or<strong>de</strong>n en el que seenumera en la tabla. Por ejemplo, la carga <strong>de</strong> trabajoSR1 (2H-2L) en la tabla III está compuesta por dosaplicaciones secuenciales con SF alto (calculix ygamess) y dos con SF bajo (gobmk, milc). Del mismomodo, la carga <strong>de</strong> trabajo MR4 (1STH-1STL-1PSM-1HPM) en la tabla IV incluye dos aplicacionessecuenciales, una con SF alto (STH) y la otracon SF bajo (STL), y dos aplicaciones paralelas <strong>de</strong>SF medio, siendo la primera <strong>de</strong> ellas parcialmente secuencial(PSM) y la segunda muy paralela (HPM).<strong>La</strong> figura 3 muestra la media geométrica <strong>de</strong> losspeedups obtenidos para las aplicaciones <strong>de</strong> las cargas<strong>de</strong> trabajo por cada planificador SFD, PA yCAMP, normalizados con respecto a los tiempos <strong>de</strong>ejecución obtenidos por el algoritmo RR. En un trabajoprevio mostramos que usar RR como baselineproporciona resultados más fiables a la hora <strong>de</strong> cuantificarel beneficio <strong>de</strong> los distintas propuestas que utilizarel planificador por <strong>de</strong>fecto <strong>de</strong> OpenSolaris, queno es consciente <strong>de</strong> la asimetría en la plataforma [10].A simple vista, po<strong>de</strong>mos apreciar que CAMP consiguemayores beneficios que los otros algoritmos pa-3 Este algoritmo es una variación <strong>de</strong>l algoritmo HASS-D [10].4 Esta clase <strong>de</strong> aplicaciones abarca aquellas aplicaciones paralelascon fases <strong>de</strong> ejecución secuencial que constituyen almenos un 20 % <strong>de</strong> su tiempo <strong>de</strong> ejecución total.<strong>JP2011</strong>-249


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 201130%25%SINGLE-THREADED APPS. (2FC-2SC)SFD CAMP PASINGLE- AND MULTI- THREADED APPS. (2FC-10SC)gmean speedup over RR (%)20%15%10%5%0%-5%-10%SR1 SR2 SR3 SR4 SR5 SR6 SR7 SR8 SR9 SR10 MR1 MR2 MR3 MR4 MR5 MR6 MR7 MR8 MR9Fig. 3: Speedup medio obtenido por SFD, PA y CAMP con respecto a RR.ra todas las cargas <strong>de</strong> trabajo. Este resultado es laprincipal contribución <strong>de</strong> este trabajo.Analizando más <strong>de</strong>tenidamente los resultados obtenidos(figura 3), po<strong>de</strong>mos observar que para cargas<strong>de</strong> trabajo constituidas por aplicaciones secuenciales(SRx) SFD logra un rendimiento similar a CAMP. <strong>La</strong>razón <strong>de</strong> este comportamiento es que en ausencia <strong>de</strong>aplicaciones paralelas en la carga <strong>de</strong> trabajo, la únicamétrica relevante para llevar a cabo la planificaciónes el SF. Tanto SFD como CAMP tienen en cuentaeste factor y ambos se basan en el mismo mecanismo<strong>de</strong> estimación. El algoritmo PA, que no es consciente<strong>de</strong> los SFs, se comporta como RR –reparte equitativamentelos cores rápidos entre todos los hilos– ypor tanto no ofrece beneficios significativos en esteescenario.Para aquellas cargas <strong>de</strong> trabajo que incluyen aplicacionesparalelas (MRx), el algoritmo PA es capaz<strong>de</strong> ofrecer mejores resultados en promedio que SFD,llegando a obtener en algunos casos un speedup similara CAMP (MR3, MR4 y MR6). No obstante,PA no es capaz <strong>de</strong> ofrecer un rendimiento comparablea CAMP para cargas <strong>de</strong> trabajo que incluyenaplicaciones parcialmente secuenciales (PS) y don<strong>de</strong>a<strong>de</strong>más exista una gran diversidad <strong>de</strong> factores <strong>de</strong> gananciaen las distintas aplicaciones. Para cargas <strong>de</strong>trabajo que exhiben estas características, como MR7y MR9, po<strong>de</strong>mos observar diferencias más significativasentre ambos algoritmos <strong>de</strong> planificación, don<strong>de</strong>CAMP supera a PA hasta en un 16 %.VI. ConclusionesEn este trabajo hemos presentado el algoritmo<strong>de</strong> planificación CAMP para procesadores multicoreasimétricos (AMPs), cuya implementación en Open-Solaris ha sido evaluada en profundidad en un prototipo<strong>de</strong> AMP diseñado por Intel <strong>La</strong>bs. Los resultadosobtenidos muestran que tener en cuenta tanto el paralelismoa nivel <strong>de</strong> hilo <strong>de</strong> una aplicación como sufactor <strong>de</strong> ganancia (SF) resulta esencial a la hora <strong>de</strong>diseñar una estrategia <strong>de</strong> planificación que maximiceel rendimiento en AMPs. Estos dos factores permitena CAMP ofrecer un mayor rendimiento que otros algoritmospreviamente propuestos, como SFD y PA,que tienen en cuenta sólo uno <strong>de</strong> los factores.Los elementos que contribuyen en mayor medida aléxito <strong>de</strong> CAMP son el factor <strong>de</strong> utilidad y la técnicaempleada para estimar los factores <strong>de</strong> ganancia (SFs)<strong>de</strong> los distintos hilos <strong>de</strong> ejecución. Este trabajo proponepor primera vez una metodología sistemáticapara facilitar el proceso <strong>de</strong> <strong>de</strong>sarrollo <strong>de</strong> mo<strong>de</strong>los <strong>de</strong>estimación <strong>de</strong> SF específicos <strong>de</strong> plataforma.Agra<strong>de</strong>cimientosEl presente trabajo ha sido financiado por el proyectoTIN2008-00508. Agracecemos al Dr. DavidKoufaty el habernos permitido experimentar con elsistema asimétrico diseñado en Intel <strong>La</strong>bs.Referencias[1] Rakesh Kumar, Keith I. Farkas, Norman Jouppi, et al.,“Single-ISA Heterogeneous Multi-Core Architectures: thePotential for Processor Power Reduction,” in Proc. ofMICRO 36, 2003.[2] Rakesh Kumar, Dean M. Tullsen, Parthasarathy Ranganathan,et al., “Single-ISA Heterogeneous Multi-CoreArchitectures for Multithrea<strong>de</strong>d Workload Performance,”in Proc. of ISCA ’04, 2004.[3] Michela Becchi and Patrick Crowley, “Dynamic ThreadAssignment on Heterogeneous Multiprocessor Architectures,”in Proc. of Computing Frontiers ’06, 2006.[4] Murali Annavaram, Ed Grochowski, and John Shen, “MitigatingAmdahl’s <strong>La</strong>w through EPI Throttling,” in Proc.of ISCA’05, 2005, pp. 298–309.[5] Juan Carlos Saez, Alexandra Fedorova, Manuel Prieto,et al., “Operating System Support for Mitigating SoftwareScalability Bottlenecks on Asymmetric MulticoreProcessors,” in Proc. of ACM CF’ 10, 2010.[6] David Koufaty, Dheeraj Reddy, and Scott Hahn, “BiasScheduling in Heterogeneous Multi-core Architectures,”in Proc. of Eurosys ’10, 2010.[7] Daniel Shelepov, Juan Carlos Saez, Stacey Jeffery, et al.,“HASS: a Scheduler for Heterogeneous Multicore Systems,”Operating System Review, vol. 43, no. 2, 2009.[8] Tong Li, Dan Baumberger, David Koufaty, et al., “EfficientOperating System Scheduling for Performance-Asymmetric Multi-Core Architectures,” in Proc. of SC’07, 2007, pp. 1–11.[9] Juan Carlos Saez, Alexandra Fedorova, Manuel Prieto,et al., “A Comprehensive Scheduler for Asymmetric MulticoreSystems,” in Proc. of ACM Eurosys ’10, 2010.[10] Juan Carlos Saez, Daniel Shelepov, Alexandra Fedorova,and Manuel Prieto, “Leveraging workload diversity throughos scheduling to maximize performance on singleisaheterogeneous multicore systems,” J. Parallel Distrib.Comput., vol. 71, pp. 114–131, January 2011.[11] M. D. Hill and M. R. Marty, “Amdahl’s <strong>La</strong>w in theMulticore Era,” IEEE Computer, vol. 41, no. 7, 2008.[12] Juan Carlos Saez, Thread Scheduling on AsimmetricMulticore Systems (Ph.D. dissertation), UCM, 2011.[13] Mark Hall, Eibe Frank, Geoffrey Holmes, Bernhard Pfahringer,Peter Reutemann, and Ian H. Witten, “The WE-KA data mining software: an update,” SIGKDD Explor.Newsl., vol. 11, pp. 10–18, November 2009.[14] Jerome H Friedman, “Stochastic gradient boosting,”http: // www-stat. stanford. edu/ ~ jhf/ ftp/stobst. pdf , 1999.<strong>JP2011</strong>-250


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Optimización MapReduce para uso <strong>de</strong> losrecursos en las arquitecturas multi-coreTharso Ferreira, Aprigio Bezerra, Antonio Espinosa, Porfidio Hernán<strong>de</strong>z y Juan Carlos Moure 1Resumen— Este artículo presenta una evaluaciónMapReduce y cómo se utilizan los recursos en lasarquitecturas multi-core. Hemos explorado las estructura<strong>de</strong> datos internas <strong>de</strong> MapReduce para la creación <strong>de</strong> datosintermedios, que apuntan a un cuello <strong>de</strong> botella <strong>de</strong>rendimiento en los procesadores multi-core <strong>de</strong> memoriacompartida.Presentamos situaciones problemáticas y posibles puntos<strong>de</strong> mejora, proponiendo una aportación diferente <strong>de</strong> lasabordadas actualmente en las arquitecturas multi-core.Nos basamos en las i<strong>de</strong>as originales propuestas por elparadigma MapReduce utilizadas en Hadoop.Nuestro objetivo es <strong>de</strong>finir un mo<strong>de</strong>lo para ejecutareficientemente el paradigma MapReduce en arquitecturasmulti-core. Para lograr este objetivo, la i<strong>de</strong>a es <strong>de</strong>finir unaestrategia para optimizar el uso <strong>de</strong> la memoria compartidaentre los threads que se ejecutan sobre el mismo ydiferentes conjunto <strong>de</strong> datos.Palabras clave—MapReduce, Multi-core, Threads,Phoenix, Hadoop, Memoria compartida.LI. INTRODUCCIÓNa gestión <strong>de</strong> recursos en los procesadores multicoreha ganado importancia con la evolución <strong>de</strong> lasaplicaciones y arquitecturas. Pero esta gestión es muycompleja. Por ejemplo, una misma aplicación paralelaejecutada múltiples veces con los mismos datos <strong>de</strong>entrada, en un único nodo multi-core, pue<strong>de</strong> tenertiempos <strong>de</strong> ejecución muy variables. Hay múltiplesfactores hardware y software que afectan alrendimiento. <strong>La</strong> forma en que los recursos hardware(cómputo y memoria) se asignan a los procesos othreads, posiblemente <strong>de</strong> varias aplicaciones quecompiten entre sí, es fundamental para <strong>de</strong>terminar esterendimiento. <strong>La</strong> diferencia entre hacer la asignación<strong>de</strong> recursos sin conocer la verda<strong>de</strong>ra necesidad <strong>de</strong> laaplicación, frente a asignación con una meta específicaes cada vez mayor. <strong>La</strong> mejor manera <strong>de</strong> realizar la esresolverlos automáticamente, con una mínimaintervención <strong>de</strong>l programador resolver el problema <strong>de</strong> lagestión <strong>de</strong> recursos.Es importante <strong>de</strong>stacar, que la forma en que laaplicación se ejecuta en una arquitectura nonecesariamente es la más a<strong>de</strong>cuada, y esta situaciónpue<strong>de</strong> mejorarse a través <strong>de</strong> la gestión a<strong>de</strong>cuada <strong>de</strong> losrecursos disponibles. Una apropiada gestión <strong>de</strong> recursospue<strong>de</strong> ofrecer ventajas tanto al <strong>de</strong>sarrollador <strong>de</strong> lasaplicaciones, como al entorno informático don<strong>de</strong> ésta seejecuta, permitiendo un mayor número <strong>de</strong> aplicacionesen ejecución con la misma cantidad <strong>de</strong> recursos. Asímismo, esta gestión <strong>de</strong> recursos no requeriría introducir1 Departamento <strong>de</strong> Arquitectura <strong>de</strong> Computadores y SistemasOperativos, <strong>Universidad</strong> Autónoma <strong>de</strong> Barcelona, España, e-mail:tharso.souza, Aprigio.Bezerra, antonio.espinosa@caos.uab.esporfidio.hernan<strong>de</strong>z, juancarlos.moure@uab.es<strong>JP2011</strong>-251cambios a la aplicación, o a su estrategia operativa.MapReduce [1] es un paradigma creado por Google,originalmente dirigido a los Data Centers. MapReducees un paradigma <strong>de</strong> programación, <strong>de</strong>sarrollado paraapoyar el procesamiento <strong>de</strong> gran<strong>de</strong>s conjuntos <strong>de</strong> datos ycómputo paralelo. <strong>La</strong> simplicidad <strong>de</strong> este paradigmaradica en que el programador sólo necesita proporcionaruna implementación secuencial <strong>de</strong> la aplicación,expresando las funciones Map y Reduce. El siguientepseudocódigo muestra la estructura básica <strong>de</strong> unaaplicación MapReduce, que cuenta el número <strong>de</strong>ocurrencias <strong>de</strong> cada palabra en un <strong>de</strong>terminadodocumento. <strong>La</strong> función EmitIntermediate <strong>de</strong> Map asignael valor 1 para cada ocurrencia <strong>de</strong> cada palabra en eldocumento. <strong>La</strong> función Reduce suma todos los valoresasociados a una <strong>de</strong>terminada clave emitida por lafunción Map.// input: a document// intermediate output: key=word; value=1Map(void *input){for each word w in inputEmitIntermediate(w, 1);}// output: key=word; value=occurencesReduce(String key, Iterator values){int result = 0;for each v in valuesresult += v;Emit(w, result);}El funcionamiento <strong>de</strong> una aplicación MapReduce tienecomo inicio la ejecución <strong>de</strong> la fase Map, que distribuyeel procesamiento a aplicar a los datos <strong>de</strong> entrada <strong>de</strong> laaplicación. Mediante la partición <strong>de</strong>l archivo <strong>de</strong> entradaen un número <strong>de</strong> M bloques, cada tarea Map recibe uno<strong>de</strong> esos M bloques <strong>de</strong> datos, por lo que la entrada pue<strong>de</strong>ser procesada <strong>de</strong> forma simultánea en cada uno <strong>de</strong> losnodos <strong>de</strong> ejecución.Después <strong>de</strong> la fase Map, se ejecuta la fase Reduce,don<strong>de</strong> los Workers utilizan los datos intermediosgenerados por la fase Map. En esta fase también todo elcómputo se realiza en paralelo, sin tener ninguna<strong>de</strong>pen<strong>de</strong>ncia <strong>de</strong> datos entre tareas. Los Workers <strong>de</strong> lafase Reduce suelen realizar algún tipo <strong>de</strong> operación <strong>de</strong>reducción, como una suma o clasificación. El resultado<strong>de</strong> la fase Reduce es escrito en una estructura <strong>de</strong> datoslocales, produciendo una sola salida. El funcionamiento<strong>de</strong>l paradigma MapReduce se muestra en la figura 1.Actualmente, los chips multi-core se han convertido enmucho más que un procesador, es cada vez más


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011importante explorar toda su capacidad <strong>de</strong> cómputo. <strong>La</strong>sactuales técnicas <strong>de</strong> programación paralela, hacen usoprincipalmente <strong>de</strong>l envío <strong>de</strong> mensajes y <strong>de</strong> la memoriacompartida. Sin embargo estas técnicas son bastantelaboriosas para la mayoría <strong>de</strong> los <strong>de</strong>sarrolladores, ya quees necesaria la gestión <strong>de</strong> la concurrencia y el accesocompartido a las estructuras <strong>de</strong> datos. Dando comoresultado la necesidad <strong>de</strong> sincronizar la ejecución <strong>de</strong> losthreads.En la sección II se presentan los trabajos relacionadoscon la ejecución <strong>de</strong> aplicaciones MapReduce enentornos <strong>de</strong> memoria compartida. <strong>La</strong> sección IIIpresenta las principales características <strong>de</strong> uso <strong>de</strong>recursos <strong>de</strong> las aplicaciones MapReduce en entornos <strong>de</strong>ejecución. En la sección IV, se presenta una propuesta<strong>de</strong> gestión <strong>de</strong>l almacenamiento <strong>de</strong> las claves intermediasgeneradas por las aplicaciones para mejorar surendimiento. Finalmente, la sección V proporciona unabreve <strong>de</strong>scripción <strong>de</strong> las conclusiones <strong>de</strong>l presentetrabajo.línea funciona como una tabla hash. Phoenix pone cadaclave generada en la fase Map en una estructura enforma <strong>de</strong> matriz. Hay una fila para división <strong>de</strong> los datos<strong>de</strong> entrada y una columna para cada reducer, resultado<strong>de</strong> aplicar una función hash a cada clave. Esta estructurase muestra en la figura 2 y 3.Durante la fase Reduce, los workers utilizan losvalores generados por la fase Map, separadas porcolumnas [6]. <strong>La</strong> ventaja <strong>de</strong> esta forma <strong>de</strong> distribución<strong>de</strong> los datos, es que son utilizadas diferentes regiones <strong>de</strong>la memoria, evitando así la necesidad <strong>de</strong> sincronización.Fig. 2. Uso <strong>de</strong> la matriz por el Map y el Reduce.Fig. 1. Flujo <strong>de</strong> datos <strong>de</strong> una aplicación MapReduce.II.TRABAJO RELACIONADOHay diferentes implementaciones <strong>de</strong>l mo<strong>de</strong>loMapReduce en diferentes tipos <strong>de</strong> arquitecturas. A partir<strong>de</strong>l mo<strong>de</strong>lo presentado por Google [1], han aparecidoimplementaciones para clusters como Hadoop[2], paraGPUs como MARS[3], o para sistemas con memoriacompartida como Phoenix[4] o Metis[5].A. PhoenixComo una contribución en las arquitecturas multi-corey multi-procesador <strong>de</strong> memoria compartida, hay sido<strong>de</strong>sarrollado Phoenix [4]. Phoenix maneja el uso <strong>de</strong>threads para la ejecución <strong>de</strong> tareas Map y Reduce,utilizando la memoria compartida como vía para lacomunicación entre los threads, evitando la copia <strong>de</strong>datos[6]. El Scheduler dinámicamente evalúa losprocesadores disponibles y hace la distribución ybalanceo <strong>de</strong> carga, maximizando la utilización <strong>de</strong> losrecursos entre las tareas.Phoenix utiliza dos buffers temporales asignados en lamemoria compartida para almacenar los datosintermedios. Inicialmente estos buffers tienen untamaño por <strong>de</strong>fecto, que cambia dinámicamente segúnsea necesario.Para almacenar valores intermedios generados por lafase <strong>de</strong> Map, Phoenix utiliza una matriz don<strong>de</strong> cada<strong>JP2011</strong>-252Fig. 3. Aplicación <strong>de</strong> la función hash sobre un conjunto <strong>de</strong> datos.El problema principal <strong>de</strong> este mo<strong>de</strong>lo, se producedurante la creación <strong>de</strong> los datos intermedios en la faseMap, don<strong>de</strong> se pue<strong>de</strong> llegar a necesitar más <strong>de</strong>l espaciodisponible en memoria para almacenar todas las clavesy valores intermedios.B. METISUtilizando Phoenix como base, se <strong>de</strong>sarrolló Metis[6]como una librería <strong>de</strong> MapReduce con una mejorapropuesta para almacenar los datos intermedios en unaestructura que tiene un buen <strong>de</strong>sempeño con la mayoría<strong>de</strong> las cargas <strong>de</strong> trabajo.<strong>La</strong> i<strong>de</strong>a <strong>de</strong> Metis es utilizar una estructura"Hash+tree". De esta forma, po<strong>de</strong>mos aprovechar lasventajas <strong>de</strong> cada una <strong>de</strong> estas estructuras. Todos losworkers <strong>de</strong> la fase Map utilizan el mismo tamaño <strong>de</strong>tabla hash, y la misma función hash. Cuando el Map


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011hace la emisión <strong>de</strong> un par clave/valor, la librería utilizala clave para encontrar la entrada en la tabla hash y lamisma clave para bajar en el árbol. Si la clave ya existe,la librería agrega un nuevo valor a la misma clave, <strong>de</strong> locontrario una nueva entrada es creada para la clave.III.UTILIZACIÓN DE RECURSOSHemos usado la API <strong>de</strong> Phoenix, y una aplicación <strong>de</strong>contar palabras, evaluando el uso <strong>de</strong> la memoria y elrendimiento en tiempo <strong>de</strong> ejecución en dos entornosinformáticos diferentes.En el entorno 1, se dispone <strong>de</strong> un or<strong>de</strong>nador con unIntel Core 2 Duo <strong>de</strong> 3.00 GHz en una arquitectura64bits, con 6 GB <strong>de</strong> memoria. El entorno 2 estácompuesto por una máquina que utiliza 2 Dual-CoreIntel Xeon <strong>de</strong> 3.00GHz en una arquitectura 64Bits y con12 GB <strong>de</strong> memoria. También hemos utilizado 6 archivos<strong>de</strong> entrada, <strong>de</strong> 1GB hasta 6GB, basándonos en lacantidad <strong>de</strong> memoria que nuestros entornos teníandisponibles.En la figura 4, se muestra que el uso <strong>de</strong> la memoria eslínea ascen<strong>de</strong>nte, don<strong>de</strong> los dos principales factores queinfluyen en la curva <strong>de</strong> la línea son los tamaños <strong>de</strong> laentrada y la cantidad <strong>de</strong> memoria disponible. Mientrasque la memoria está disponible, las estructuras creadastienen una magnitud <strong>de</strong> 2,3 veces el tamaño <strong>de</strong> laentrada.Fig. 5. Rendimiento <strong>de</strong> aplicaciones bajo Phoenix.Fig. 6. Requerimientos <strong>de</strong> memoria <strong>de</strong> la aplicacion WordCount bajoPhoenix.<strong>La</strong> estructura en Phoenix para almacenar los datosintermedios está formada por una matriz, don<strong>de</strong> cadalínea representa una tabla hash. El principal problema <strong>de</strong>utilizar esta tabla hash, es la imposibilidad <strong>de</strong> <strong>de</strong>finir <strong>de</strong>forma estática el tamaño idóneo <strong>de</strong> esta tabla. Es <strong>de</strong>cir,es difícil pre<strong>de</strong>cir cuánto espacio se necesita a priori. Noes posible saber cuál es la ocurrencia <strong>de</strong> una<strong>de</strong>terminada clave. <strong>La</strong> misma clave pue<strong>de</strong> aparecervarias veces; el número <strong>de</strong> claves únicas pue<strong>de</strong> sergran<strong>de</strong>. Y a<strong>de</strong>más el tamaño <strong>de</strong> las claves es difícil <strong>de</strong>pre<strong>de</strong>cir, ya que <strong>de</strong>pen<strong>de</strong> <strong>de</strong>l diseño <strong>de</strong> la aplicación.IV.SOLUCIÓN PROPUESTAFig. 4. Uso <strong>de</strong> memoria por la aplicación MapReduce WordCount.<strong>La</strong> gran ventaja <strong>de</strong> las aplicaciones MapReduce paralas arquitecturas multi-core es que todas las estructuras<strong>de</strong> datos intermedios están en los buffers <strong>de</strong> memoria.El uso <strong>de</strong> MapReduce en las arquitecturas multi-coretiene un buen <strong>de</strong>sempeño mientras un factor importantees contemplado: memoria disponible.Cuando este factor no se contempla, ninguna estrategiaespecífica es adoptada. El sistema operativo gestiona losdatos y empieza a utilizar el Swap para suplir la falta <strong>de</strong>memoria. Esta situación claramente perjudica elrendimiento <strong>de</strong> la aplicación como se muestra en lafigura 5.Se concluye que la estructura <strong>de</strong> datos intermedioscreada por las aplicaciones MapReduce se convierte enun cuello <strong>de</strong> botella como se muestra en la figura 6. Estasituación no favorece el rendimiento <strong>de</strong> las aplicacioneshaciendo uso ineficiente <strong>de</strong>l espacio.<strong>JP2011</strong>-253MapReduce propone como i<strong>de</strong>a inicial que todas lastareas sean in<strong>de</strong>pendientes y que trabajen sobreconjuntos <strong>de</strong> datos disjuntos. Mientras que laspropuestas <strong>de</strong> soluciones para las arquitecturas multicoreproponen índices, nosotros proponemos utilizar lai<strong>de</strong>a original <strong>de</strong> MapReduce y substraer el uso <strong>de</strong> índice,que pue<strong>de</strong> optimizar el uso <strong>de</strong> los recursos en tiempo yespacio.Nos basamos en Hadoop[2] para proponer unaoptimización que utiliza la memoria <strong>de</strong> modo que noafecte al rendimiento ofrecido por el paradigmaMapReduce.Durante la ejecución <strong>de</strong> la fase Map, los workersreciben los datos divididos por una función <strong>de</strong> división(splitter) y los almacena en un buffer <strong>de</strong> memoria cuyotamaño sea configurable por el usuario. Cada Mapprocesa estos datos que están en el buffer <strong>de</strong> memoria ygenera una serie <strong>de</strong> tuplas clave/valor. En cada nuevaiteración <strong>de</strong> las tareas Map, se hace una llamada a lafunción combiner, que realiza una pre-agregación <strong>de</strong>


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011valores para cada clave, con el fin <strong>de</strong> disminuir lacantidad <strong>de</strong> datos para procesar y ahorrar espacio enmemoria. Cuando el buffer <strong>de</strong> la memoria alcanza un<strong>de</strong>terminado umbral <strong>de</strong> utilización disponible <strong>de</strong>finidopor el usuario, estos datos <strong>de</strong>ben ser enviados al disco,como se muestra en la figura 7. Antes <strong>de</strong> enviar los datosal disco se realizará una or<strong>de</strong>nación en las claves.Fig. 7. Flujo <strong>de</strong> datos en la fase Map.En la ejecución <strong>de</strong> la fase Reduce, cargamos los datosque están en el disco en los buffers <strong>de</strong> memoria <strong>de</strong> lastareas reduce. Cuando los datos están en la memoria, serealiza una agregación <strong>de</strong> todos los datos a través <strong>de</strong> unafunción merge. Si la cantidad <strong>de</strong> datos ocupa másespacio que la cantidad <strong>de</strong> memoria disponible, se envíanuevamente al disco <strong>de</strong>spués <strong>de</strong> la fusión.Después <strong>de</strong> combinar los datos en un conjunto, losdatos son enviados a las tareas Reduce, como se muestraen la figura 8. Los datos <strong>de</strong> entrada <strong>de</strong> las tareas Reduceestán or<strong>de</strong>nados por clave. <strong>La</strong> salida final <strong>de</strong> esta fase seescribe directamente en el disco.AGRADECIMIENTOSEl presente trabajo ha sido financiado por el MEC(Ministerio <strong>de</strong> Educación y Ciencia) mediante elproyecto con referencia TIN2007-64974.REFERENCIAS[1] J. Dean, S. Ghemawat, “MapReduce: simplified data processingon large clusters”, Commun. ACM, 2008.[2] T. White, “Hadoop: The Definitive Gui<strong>de</strong>”, 2009.[3] B. He, W. Fang, Q. Luo, N. K. Govindaraju, T. Wang, “Mars: aMapReduce framework on graphics processors”, Proceedings ofthe 17th international conference on Parallel architectures andcompilation techniques, 2008.[4] R.M. Yoo, A. Romano, C. Kozyrakis, “Phoenix Rebirth:Scalable MapReduce on a <strong>La</strong>rge-Scale Shared-Memory System”,Proceedings of the IEEE International Symposium on WorkloadCharacterization (IISWC), 2009.[5] Y. Mao, R. Morris, M.F. Kaashoek, “Optimizing MapReduce forMulticore Architectures”, MIT technical report MIT-CSAIL-TR-2010-020, 2010.[6] C. Ranger, R. Raghuraman, A. Penmetsa, G. Bradski,C.Kozyrakis, “Evaluating MapReduce for Multi-core andMultiprocessor Systems”, Proceedings of the 13th InternationalSymposium on High-Performance Computer Architecture, 2007.Fig. 8. Flujo <strong>de</strong> datos en la fase Reduce.V. CONCLUSIONESHemos propuesto un mo<strong>de</strong>lo que tiene como i<strong>de</strong>aprincipal el uso <strong>de</strong> los recursos en aplicacionesMapReduce bajo una arquitectura multi-core.<strong>La</strong> i<strong>de</strong>a <strong>de</strong> este mo<strong>de</strong>lo, es evitar la saturación <strong>de</strong>lrecurso <strong>de</strong> memoria, utilizando el disco comodispositivo auxiliar para el almacenamiento yor<strong>de</strong>nación <strong>de</strong> las claves intermedias. Sabiendo que paraun conjunto <strong>de</strong> datos muy gran<strong>de</strong>s, no siempre haymemoria disponible, la i<strong>de</strong>a <strong>de</strong> utilizar el acceso al disco<strong>de</strong> manera or<strong>de</strong>nada se convierte en una solución a teneren cuenta y a ser contrastada con el resto <strong>de</strong> alternativasexistentes.<strong>JP2011</strong>-254


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Análisis <strong>de</strong> los datos privados/compartidos enaplicaciones paralelas sobre CMPsAlfonso Ramos 1 Antonio García-Guirado 1 José M. García 1Resumen— En los últimos años se han realizado numerososestudios para mejorar el rendimiento <strong>de</strong>l sistema<strong>de</strong> memoria <strong>de</strong> los procesadores <strong>de</strong>bido a la graninfluencia que tiene en el tiempo <strong>de</strong> ejecución <strong>de</strong> lasaplicaciones. En este artículo presentamos un estudio<strong>de</strong> las necesida<strong>de</strong>s <strong>de</strong> memoria para datos privados ycompartidos en aplicaciones paralelas sobre CMPs anivel <strong>de</strong> la caché L1 <strong>de</strong> datos. A<strong>de</strong>más, realizamos unanálisis <strong>de</strong> un subconjunto <strong>de</strong> los datos compartidosque tiene un comportamiento especial: se escriben alcomienzo <strong>de</strong> la aplicación y ya no vuelven a ser escritos.Por último, estudiamos el potencial <strong>de</strong> mejora<strong>de</strong> las aplicaciones con un manejo especial <strong>de</strong> estosdatos, mostrando que, si se tratan a<strong>de</strong>cuadamente, sepodrían obtener mejoras importantes en el tiempo <strong>de</strong>ejecución <strong>de</strong> las aplicaciones.Palabras clave— Chip Multiprocessor, Caché L1, DatosCompartidos.I. IntroducciónDURANTE los últimos años, los tiled CMPs hancobrado protagonismo <strong>de</strong>bido a su capacidadpara mantener los avances en rendimiento esperados<strong>de</strong>ntro <strong>de</strong> unos límites <strong>de</strong> consumo y complejidad <strong>de</strong>diseño aceptables. Estos chips están formados por variostiles compuestos por un core, una caché privada,parte <strong>de</strong> una caché mayor que suele ser compartida yuna interfaz <strong>de</strong> red que sirve para unir a todos los tilesmediante una red <strong>de</strong> interconexión. Actualmentese están llevando a cabo numerosas propuestas queresuelven algunos <strong>de</strong> los retos que plantean estos sistemas.Por un lado, se preten<strong>de</strong> reducir al máximoel consumo <strong>de</strong> energía en el chip, y por otro, mejorarel rendimiento <strong>de</strong> las aplicaciones en la medida <strong>de</strong> loposible.Uno <strong>de</strong> los mayores retos es que sigue existiendouna gran diferencia <strong>de</strong> velocidad entre el procesadory la memoria en los sistemas multiprocesadoractuales. Esto hace que el rendimiento <strong>de</strong>l sistema <strong>de</strong>memoria tenga un impacto muy gran<strong>de</strong> en el rendimiento<strong>de</strong> las aplicaciones, aportando entre un 60 %y un 80 % <strong>de</strong>l tiempo total <strong>de</strong> ejecución.Por esta razón, el a<strong>de</strong>cuado manejo <strong>de</strong> la jerarquía<strong>de</strong> memoria es uno <strong>de</strong> los aspectos cruciales para optimizarel rendimiento <strong>de</strong> un CMP, especialmente enlos niveles más cercanos al procesador que amortiguanel efecto <strong>de</strong> los costosos accesos a niveles máslejanos. Por este motivo, aspectos como el aprovechamiento<strong>de</strong>l espacio, las políticas <strong>de</strong> reemplazo y, en<strong>de</strong>finitiva, el aumento <strong>de</strong>l rendimiento <strong>de</strong> las cachés(principalmente la caché L1 <strong>de</strong> datos) han sido algunos<strong>de</strong> los gran<strong>de</strong>s objetivos en el campo <strong>de</strong> laarquitectura <strong>de</strong> computadores en los últimos años.1 Departamento <strong>de</strong> Arquitectura e Ingeniería <strong>de</strong> Computadores,<strong>Universidad</strong> <strong>de</strong> Murcia, e-mail: alfonso.ramos@um.es,{toni,jmgarcia}@ditec.um.esPor otro lado, es conocido que las necesida<strong>de</strong>s <strong>de</strong>la sociedad hacen que cada vez se <strong>de</strong>sarrollen aplicacionesque requieren sistemas más potentes, talescomo aplicaciones intensivas en gráficos, servidoresweb con mayores funcionalida<strong>de</strong>s o aplicaciones confines científicos. De esta forma, la carga <strong>de</strong> trabajo<strong>de</strong> las aplicaciones se encuentra en continuo cambio,y con ello sus necesida<strong>de</strong>s <strong>de</strong> memoria.Todo esto nos hace llegar a la conclusión <strong>de</strong> queel estudio <strong>de</strong>l comportamiento <strong>de</strong> los bloques en lacaché L1 <strong>de</strong> datos pue<strong>de</strong> permitir una mayor comprensión<strong>de</strong> las necesida<strong>de</strong>s <strong>de</strong> memoria <strong>de</strong> las aplicacionesactuales, lo que abre vías <strong>de</strong> estudio interesantespara mejorar el rendimiento <strong>de</strong> dichas aplicaciones.Así pues, las aportaciones <strong>de</strong> este artículo son lassiguientes:Realizamos un estudio <strong>de</strong> las necesida<strong>de</strong>s <strong>de</strong>memoria <strong>de</strong> una serie <strong>de</strong> aplicaciones <strong>de</strong> variosámbitos a nivel <strong>de</strong> la caché L1 <strong>de</strong> datos.Analizamos un subconjunto <strong>de</strong> los datos compartidosque tienen un comportamiento especial:se escriben al comienzo <strong>de</strong> la aplicación y novuelven a ser escritos en el resto <strong>de</strong> la ejecución.Estudiamos el potencial <strong>de</strong> mejora en el tiempo<strong>de</strong> ejecución <strong>de</strong> las aplicaciones que pue<strong>de</strong>proporcionar a<strong>de</strong>cuado manejo <strong>de</strong> estos datos.Ofrecemos posibles vías <strong>de</strong> investigación paramejorar el rendimiento <strong>de</strong> las aplicaciones medianteuna mejor gestión <strong>de</strong> los distintos tipos<strong>de</strong> datos.El resto <strong>de</strong> este artículo se organiza <strong>de</strong> la siguientemanera: en la Sección 2 comentamos algunos trabajos<strong>de</strong> interés relacionados con el tratamiento diferenciado<strong>de</strong> los datos según su tipo; en la Sección3 presentamos un análisis <strong>de</strong> las necesida<strong>de</strong>s <strong>de</strong> memoria<strong>de</strong> los distintos tipos <strong>de</strong> datos para una serie<strong>de</strong> aplicaciones; la Sección 4 ahonda en las características<strong>de</strong> los datos compartidos <strong>de</strong> sólo lecturay el potencial <strong>de</strong> mejora <strong>de</strong> rendimiento que pue<strong>de</strong>proporcionar su tratamiento específico; para finalizar,presentamos nuestras conclusiones.II. Trabajo relacionadoEn los últimos años han aparecido varios estudiossobre los distintos tipos <strong>de</strong> datos presentes en unaaplicación paralela. Los resultados han sido aprovechadosparar realizar varias propuestas que adaptanel funcionamiento <strong>de</strong> la caché al patrón <strong>de</strong> comportamiento<strong>de</strong> los tipos <strong>de</strong> datos observados. Así se obtienenventajas en rendimiento, se consigue reducir elconsumo, o se simplifica el protocolo <strong>de</strong> coherencia.<strong>JP2011</strong>-255


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Reactive NUCA [1] trata <strong>de</strong> forma diferenciada losdatos privados, los datos compartidos y las instrucciones,y les asigna distintos mapeos a los bancos <strong>de</strong>caché. Los datos privados se almacenan en el banco<strong>de</strong> caché local para proporcionar una mejor latencia<strong>de</strong> acceso. Los datos compartidos se distribuyen entretodos los bancos <strong>de</strong> caché para evitar réplicas ymaximizar así la capacidad efectiva <strong>de</strong> la caché. <strong>La</strong>sinstrucciones utilizan un nuevo mapeo con centro fijoque proporciona un equilibrio entre replicación ylatencia <strong>de</strong> acceso. <strong>La</strong> distinción entre tipos <strong>de</strong> datosse realiza mediante nuevos campos en la tabla <strong>de</strong>páginas y el TLB. El resultado es una importantemejora <strong>de</strong>l rendimiento con respecto a usar un únicomapeo.SWEL [2] simplifica la coherencia mediante el tratamientodiferenciado <strong>de</strong> datos, aprovechando el hecho<strong>de</strong> que los datos que realmente necesitan coherenciasuponen un porcentaje pequeño <strong>de</strong> los accesos.Los datos privados son traídos a las cachés L1 <strong>de</strong> losprocesadores. Los datos compartidos <strong>de</strong> sólo lecturapue<strong>de</strong>n tener copia en todas las cachés L1 <strong>de</strong>l chip.Estas copias son invalidadas mediante broadcast encaso <strong>de</strong> una escritura. Por último, los datos compartidos<strong>de</strong> lectura/escritura sólo mantienen una copiaen L2, evitando tener que mantener coherencia, y todoslos accesos <strong>de</strong> los procesadores provocan el envío<strong>de</strong> una petición <strong>de</strong> memoria por la red para acce<strong>de</strong>ra la L2. El resultado es que sólo se necesitan tresbits <strong>de</strong> estado por bloque en L2 y dos bits en L1para mantener el sistema coherente. El rendimientoes similar al <strong>de</strong> un directorio pero añadiendo muchamenor complejidad al diseño <strong>de</strong>l chip.<strong>La</strong> arquitectura Nahalal [3] aprovecha la gran cantidad<strong>de</strong> accesos a datos compartidos para colocarun banco <strong>de</strong> L2 central para esos datos alre<strong>de</strong>dor<strong>de</strong>l cual se colocan los procesadores. El acceso a estebanco central es muy rápido para todos. Al ladocontrario, cada procesador tiene su propio banco <strong>de</strong>L2 privada.ASR [4] aplica políticas <strong>de</strong> replicación <strong>de</strong> bloquesen caché L2 compartida adaptadas al hecho <strong>de</strong> quelos datos compartidos son muy accedidos. Así consigueaprovechar tanto la mayor capacidad efectiva<strong>de</strong> un esquema <strong>de</strong> caché compartida como la menorlatencia <strong>de</strong> acceso a las réplicas creadas para los bloquesque más beneficio producen por ser muy accedidos.III. Análisis <strong>de</strong> las necesida<strong>de</strong>s <strong>de</strong> memoria<strong>La</strong>s necesida<strong>de</strong>s <strong>de</strong> memoria <strong>de</strong> las aplicacionesestán en constante cambio. Por ello, creemos quei<strong>de</strong>ntificar criterios que permitan clasificar los datosrequeridos por las aplicaciones pue<strong>de</strong> convertirse enun elemento diferenciador a la hora <strong>de</strong> mejorar elrendimiento <strong>de</strong> las mismas. En este apartado se <strong>de</strong>scribeen primer lugar la metodología empleada en laspruebas realizadas. Tras ello, se presenta una clasificación<strong>de</strong> los bloques solicitados por el procesadora la caché L1 <strong>de</strong> datos. Finalmente, se analiza la in-TABLA IParámetros <strong>de</strong>l sistema.Procesadores 16 UltraSPARC-III+ 3 GHz. 2-vías, in-or<strong>de</strong>r.Cache L1Dividida I&D. Tamaño: 16KB.Asociatividad: 4-vías. 64 bytes/bloque.<strong>La</strong>tencia <strong>de</strong> acceso: 1 (tag) + 1 (datos) ciclos.Cache L2Tamaño: 512KB cada banco. 8MB total.Asociatividad: 16-vías. 64 bytes/bloque.<strong>La</strong>tencia <strong>de</strong> acceso: 12 ciclos.RAMTamaño: 4 GB DRAM.<strong>La</strong>tencia Memoria 156 ciclos + on-chip <strong>de</strong>lay.Tamaño <strong>de</strong> Página: 4 KB.Red interconexión Malla bidimensional 4x4. enlaces <strong>de</strong> 16 bytes.<strong>La</strong>tencia: 4 ciclos/enlace + 1 ciclo/switch +1 ciclo/router (en ausencia <strong>de</strong> contención)Tamaño Flit: 16 bytes.Tamaño paquete <strong>de</strong> control: 1 flit.Tamaño <strong>de</strong>l paquete <strong>de</strong> datos: 5 flits.TABLA IIConfiguración <strong>de</strong> los benchmarks.Workload Dominio aplicacion Tamañofft Procesamiento <strong>de</strong> señales 16K puntosradiosity Gráfica large roomvolrend Gráfica Headblackscholes Análisis financiero simsmallfluidanimate Animación simsmallswaptions Análisis financiero simsmallapache Servidor web 500 clientesjbb Servidor web 1.5 warehouses por tilefluencia <strong>de</strong> los distintos tipos <strong>de</strong> datos en el tiempo<strong>de</strong> ejecución <strong>de</strong> las aplicaciones.A. Metodología <strong>de</strong> las pruebas.Todas las pruebas han sido realizadas usando elsimulador funcional Simics [5] extendido por el simulador<strong>de</strong> temporización GEMS [6]. Para este trabajose ha utilizado una arquitectura NUCA sobreCMPs. <strong>La</strong> coherencia <strong>de</strong> caché se mantiene medianteun protocolo <strong>de</strong> directorio que sigue un esquema<strong>de</strong> estados MOESI. En la Tabla I se pue<strong>de</strong> apreciaruna <strong>de</strong>scripción más <strong>de</strong>tallada <strong>de</strong> los parámetros <strong>de</strong>lsistema.<strong>La</strong> mayoría <strong>de</strong> las aplicaciones utilizadas pertenecena las suites SPLASH-2 [7] y PARSEC [8] sugeridasen [9]. A<strong>de</strong>más, se han añadido dos aplicacionescomerciales para servidores: apache y jbb. Enla Tabla II se pue<strong>de</strong>n observar con más <strong>de</strong>talle lasaplicaciones utilizadas, su dominio <strong>de</strong> aplicación y eltamaño <strong>de</strong> la entrada.B. Clasificación <strong>de</strong> los tipos <strong>de</strong> datos.Si tenemos en cuenta los accesos a la caché L1 <strong>de</strong>datos, po<strong>de</strong>mos distinguir claramente dos tipos <strong>de</strong>bloques. Aquellos que son accedidos por un únicoprocesador para realizar lecturas y escrituras (datosprivados), y los que son accedidos por varios procesadorespara realizar lecturas y escrituras (datoscompartidos).No obstante, hemos comprobado que existen algunosdatos compartidos que tienen un comportamientopeculiar. Y es que, a partir <strong>de</strong> un instante<strong>de</strong>terminado cercano al comienzo <strong>de</strong> la ejecución <strong>de</strong>la aplicación, no vuelven a ser escritos por ningúnprocesador. Si nos fijamos, estos bloques se comportan<strong>de</strong> forma similar a los bloques <strong>de</strong>l código <strong>de</strong> la<strong>JP2011</strong>-256


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011100908070Tiempo <strong>de</strong>dicado a CPU y MemoriaComp_Lect_EscComp_LectPrivadosCPU% of total6050403020100FluidanimateBlackscholesSwaptionsRadiosityVolrendApacheFFTJBBMediaFig. 1. Porcentaje <strong>de</strong>l tiempo <strong>de</strong> ejecución empleado en accesos a memoria (dividido por tipos <strong>de</strong> datos) y cpu.aplicación que son tratados en la caché L1 <strong>de</strong> instrucciones,pero sólo a partir <strong>de</strong> un cierto momento.Este momento coinci<strong>de</strong> con el fin <strong>de</strong> la inicialización<strong>de</strong> las estructuras <strong>de</strong> datos <strong>de</strong> la aplicaciones, y estosdatos ya no cambian <strong>de</strong> valor durante el resto <strong>de</strong>ltiempo <strong>de</strong> ejecución <strong>de</strong> las mismas.Llamaremos a estos datos “datos compartidos <strong>de</strong>sólo lectura” <strong>de</strong> aquí en a<strong>de</strong>lante, y analizaremos sucomportamiento junto al <strong>de</strong>l resto <strong>de</strong> tipos <strong>de</strong> datos.De esta forma, los bloques manejados por lacaché L1 <strong>de</strong> datos quedan clasificados la siguientemanera:Datos privados: son accedidos solamente por unprocesador para lectura y/o escritura.Datos compartidos:• Datos compartidos <strong>de</strong> sólo lectura: son accedidospor varios procesadores para lectura trasla inicialización <strong>de</strong> las estructuras <strong>de</strong> datos.• Datos compartidos <strong>de</strong> lectura/escritura: sonaccedidos por varios procesadores para lecturay escritura.C. Estudio <strong>de</strong>l peso en el tiempo <strong>de</strong> ejecución <strong>de</strong> losdistintos tipos <strong>de</strong> datos.Pasamos ahora a estudiar qué importancia adquierenlos tipos <strong>de</strong> datos en el tiempo <strong>de</strong> ejecución <strong>de</strong>las aplicaciones, teniendo en cuenta la clasificaciónestablecida en la sección anterior. En la Figura 1 semuestra el porcentaje <strong>de</strong>l tiempo <strong>de</strong> ejecución empleadopor la CPU y por los accesos a memoria segúnel tipo <strong>de</strong> dato.Como se pue<strong>de</strong> observar en dicha figura, el tiempoempleado en accesos a memoria es <strong>de</strong> más <strong>de</strong> un 70 %<strong>de</strong> media. Si nos centramos en los distintos tipos <strong>de</strong>datos vemos como, <strong>de</strong> media, cerca <strong>de</strong> un 35 % <strong>de</strong>ltiempo es empleado en accesos a los datos privados.En torno a un 20 % <strong>de</strong>l tiempo es <strong>de</strong>dicado a los datoscompartidos <strong>de</strong> lectura/escritura y más <strong>de</strong> un 15 %<strong>de</strong> media <strong>de</strong>l tiempo <strong>de</strong> ejecución coinci<strong>de</strong> con losaccesos a los datos compartidos <strong>de</strong> sólo lectura. Vemoscomo estos últimos, datos que tras inicializarseno vuelven a ser escritos, tienen un impacto bastantesignificativo en el tiempo <strong>de</strong> ejecución <strong>de</strong> las aplicaciones.Esto es especialmente notable en aplicacionescomo blackscholes o radiosity, en las que aportan más<strong>de</strong>l 20 % <strong>de</strong>l tiempo <strong>de</strong> ejecución, y siendo totalmente<strong>de</strong>terminantes en jbb, don<strong>de</strong> prácticamente la mitad<strong>de</strong>l tiempo <strong>de</strong> ejecución se consume en accesos a bloques<strong>de</strong> este tipo.Así pues, aunque hay aplicaciones como fft o fluidanimateen las cuales representan un porcentaje pequeño<strong>de</strong>l tiempo <strong>de</strong> ejecución, alre<strong>de</strong>dor <strong>de</strong>l 5 %, pareceque los datos compartidos <strong>de</strong> sólo lectura pue<strong>de</strong>ntener un gran impacto en el tiempo <strong>de</strong> ejecución <strong>de</strong>algunas aplicaciones. En las siguientes secciones seestudiaran minuciosamente.IV. Estudiando en profundidad los datoscompartidos <strong>de</strong> sólo lecturaEn este momento, nos preguntamos si los datoscompartidos <strong>de</strong> sólo lectura podrían tener algún tratamientoespecial que ayudara a mejorar el tiempo <strong>de</strong>ejecución <strong>de</strong> las aplicaciones. Para respon<strong>de</strong>r a estapregunta se <strong>de</strong>ben conocer algunos <strong>de</strong>talles más acerca<strong>de</strong>l comportamiento <strong>de</strong> los mismos. Esta seccióntratará estas cuestiones.A. Número <strong>de</strong> bloques y número <strong>de</strong> accesos.En primer lugar analizaremos la cantidad <strong>de</strong> bloquesque son compartidos <strong>de</strong> sólo lectura y el númerototal <strong>de</strong> peticiones <strong>de</strong> memoria que generan. En la Figura2 se muestran el número <strong>de</strong> accesos y el espacioocupado por los bloques <strong>de</strong> memoria en la caché L1<strong>de</strong> datos según el tipo <strong>de</strong> dato al que pertenecen.Si nos fijamos <strong>de</strong>tenidamente en la Figura 2a po<strong>de</strong>moscomprobar que el número <strong>de</strong> bloques <strong>de</strong> sólolectura representa <strong>de</strong> media sólo un 10 % <strong>de</strong>l total <strong>de</strong>bloques accedidos durante la ejecución <strong>de</strong> las aplicaciones.Es más, excepto en volrend y jbb, el número<strong>de</strong> bloques <strong>de</strong> sólo lectura no llega ni al 5 % <strong>de</strong>l totalen ninguna aplicación. Esto es un dato tremendamenteinteresante, ya que, aunque el espacio ocupadopor los datos compartidos <strong>de</strong> sólo lectura es muypequeño, su peso en el tiempo <strong>de</strong> ejecución <strong>de</strong> lasaplicaciones es bastante <strong>de</strong>terminante, como se pudoapreciar en la Figura 1. Por ejemplo, en radiosity yblackscholes el espacio que ocupan estos bloques nollega al 3 %, y sin embargo el impacto que tienen en<strong>JP2011</strong>-257


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 201110090Porcentaje <strong>de</strong>l espacio ocupadoComp_Lect_EscComp_LectPrivado10090Porcentaje accesos a memoriaComp_Lect_EscComp_LectPrivado808070706060% of total5040% of total504030302020101000FluidanimateBlackscholesSwaptionsRadiosityVolrendApacheBlackscholesSwaptionsFluidanimateRadiosityVolrendApacheFFTMediaJBBFFTMediaJBB(a) Porcentaje <strong>de</strong>l tamaño <strong>de</strong> memoria (número <strong>de</strong> bloques)según tipo <strong>de</strong> dato.(b) Porcentaje <strong>de</strong>l número <strong>de</strong> accesos segúntipo <strong>de</strong> dato.Fig. 2. Estadísticas <strong>de</strong>l número <strong>de</strong> accesos y espacio ocupado por los bloques <strong>de</strong> memoria en la caché L1 <strong>de</strong> datos según el tipo<strong>de</strong> dato.el tiempo <strong>de</strong> ejecución supera el 20 %. De forma parecida,en jbb ocupan un 20 % y tienen un peso <strong>de</strong>casi el 50 % en el tiempo <strong>de</strong> ejecución.En cuanto al número <strong>de</strong> accesos, en la Figura 2bvemos que, <strong>de</strong> media, en torno a un 20 % son <strong>de</strong>stinadosa bloques compartidos <strong>de</strong> sólo lectura. Porsu parte, los datos privados y compartidos <strong>de</strong> lecturay escritura son accedidos en torno a un 40 % <strong>de</strong>media cada uno. Si comparamos estos datos con losresultados mostrados en la Figura 1, y centrándonosen los datos compartidos <strong>de</strong> sólo lectura, vemos comopara la mayoría <strong>de</strong> aplicaciones la frecuencia conque se acce<strong>de</strong> a ellos explica el impacto que tienen enel tiempo <strong>de</strong> ejecución. Sin embargo, hay dos casosque merece la pena mencionar. En blackscholes, elporcentaje <strong>de</strong> accesos a los datos es muy superior alimpacto que tienen los mismos en el tiempo <strong>de</strong> ejecución(50 % frente a 20 % aproximadamente). Estopue<strong>de</strong> <strong>de</strong>berse a una buena gestión <strong>de</strong> los mismos enla caché L1 <strong>de</strong> datos. Por el contrario, si nos fijamosen JBB, el porcentaje <strong>de</strong> accesos, <strong>de</strong> cerca <strong>de</strong>l 25 %,tiene un impacto <strong>de</strong> en torno al 50 % en el tiempo<strong>de</strong> ejecución. En este caso parece que la caché L1 <strong>de</strong>datos no gestiona bien los datos compartidos <strong>de</strong> sólolectura, para los cuales <strong>de</strong>ben producirse numerososfallos en caché.Parece, por tanto, interesante estudiar la influencia<strong>de</strong> los datos compartidos <strong>de</strong> sólo lectura en la tasa <strong>de</strong>fallos <strong>de</strong> la caché L1. El siguiente apartado estudiaeste aspecto.B. Impacto <strong>de</strong> los datos compartidos <strong>de</strong> sólo lecturaen la tasa <strong>de</strong> fallos <strong>de</strong> la caché L1 <strong>de</strong> datos.<strong>La</strong> Figura 3 muestra la tasa <strong>de</strong> fallos <strong>de</strong> la caché L1<strong>de</strong> datos <strong>de</strong>scompuesta para mostrar la aportación <strong>de</strong>cada tipo <strong>de</strong> datos en ella. Como po<strong>de</strong>mos observaren esta figura, en torno a un 25 % <strong>de</strong> los fallos enla caché L1 <strong>de</strong> datos son producidos por los datoscompartidos <strong>de</strong> sólo lectura, lo que unido a su granfrecuencia <strong>de</strong> acceso justifica que estos datos tenganun peso importante en el tiempo <strong>de</strong> ejecución <strong>de</strong> lamayoría <strong>de</strong> las aplicaciones, a pesar <strong>de</strong>l poco espacioque ocupan.Por lo tanto, vemos que las suposiciones sobre elcomportamiento <strong>de</strong> la L1 hechas en el apartado anteriorson ciertas. En blackscholes hay muchos accesosa datos compartidos <strong>de</strong> sólo lectura (50 % aproximadamente)pero no tienen tanta importancia en eltiempo <strong>de</strong> ejecución (sólo un 20 %) porque suponenmuy pocos fallos en caché. En jbb, por el contrario,estos datos tienen un peso tan <strong>de</strong>terminante (50 %)en el tiempo <strong>de</strong> ejecución, a pesar <strong>de</strong> que el númerototal <strong>de</strong> accesos a ellos no es tan gran<strong>de</strong> (20 %),porque la inmensa mayoría <strong>de</strong> los fallos <strong>de</strong> L1 se producenen los accesos a estos datos.C. Estudio <strong>de</strong>l potencial <strong>de</strong> los datos compartidos <strong>de</strong>sólo lectura.Hemos comprobado como los datos compartidos <strong>de</strong>sólo lectura tienen una gran influencia en el tiempo<strong>de</strong> ejecución <strong>de</strong> las aplicaciones a pesar <strong>de</strong> su escasotamaño. A continuación vamos a comprobar si, efectivamente,tratando estos datos a<strong>de</strong>cuadamente sepue<strong>de</strong> conseguir una mejora consi<strong>de</strong>rable en el tiempo<strong>de</strong> ejecución <strong>de</strong> las aplicaciones. Para ello hemosejecutado <strong>de</strong> nuevo las aplicaciones suponiendo quetodos los accesos a los datos compartidos <strong>de</strong> sólo lecturaproducen acierto en la caché L1 <strong>de</strong> datos.Para hacer esto, al lanzar las ejecuciones originalesguardamos las direcciones <strong>de</strong> memoria <strong>de</strong> los bloques<strong>de</strong>tectados como compartidos <strong>de</strong> sólo lectura. En laejecución posterior, para calcular el potencial, <strong>de</strong>tectamoslos accesos a estos bloques y directamente asumimosun acierto en L1, e introducimos la latencia<strong>de</strong> acceso a la caché L1 <strong>de</strong> datos.Este método pue<strong>de</strong> producir efectos colaterales, yaque en el cálculo <strong>de</strong>l potencial estos bloques no entranrealmente en la caché. Por tanto, el tamaño efectivo<strong>de</strong> la misma se ve ligeramente aumentado <strong>de</strong>bidoa que estos bloques no “ocupan espacio” y los fallospor conflicto con otros bloques se ven ligeramentereducidos. Esto pue<strong>de</strong> provocar cierta mejora adicional.<strong>JP2011</strong>-258


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011% of total109.598.587.576.565.554.543.532.521.510.50RadiosityVolrendTasa <strong>de</strong> fallos L1 DatosBlackscholesFluidanimateSwaptionsComp_Lect_EscComp_LectPrivadosApacheFFTJBBMediaFig. 3. Tasa <strong>de</strong> fallos en caché L1 <strong>de</strong> datos <strong>de</strong>scompuesto por tipos <strong>de</strong> datos.% of total10095908580757065605550454035302520151050RadiosityVolrendCota Superior SpeedupBlackscholesRealCota% of total10095908580757065605550454035302520151050Cota Superior SpeedupFluidanimateSwaptionsRealCotaApacheMediaJBBFFTMedia(a) Aplicaciones con un buen potencial.(b) Aplicaciones con un potencial reducido.Fig. 4. Cota superior <strong>de</strong>l tiempo <strong>de</strong> ejecución <strong>de</strong> las aplicaciones reduciendo la tasa <strong>de</strong> fallos en L1 a 0 para los datos compartidos<strong>de</strong> sólo lectura.No obstante, nuestra intención es mostrar una cotasuperior <strong>de</strong> la mejora que podríamos obtener siaplicásemos mecanismos para reducir la tasa <strong>de</strong> fallos<strong>de</strong> L1 para los escasos bloques compartidos <strong>de</strong>sólo lectura <strong>de</strong> las aplicaciones.A<strong>de</strong>más, hemos clasificado las aplicaciones segúnsu potencial para explicar qué características <strong>de</strong> lasestudiadas anteriormente pue<strong>de</strong>n proporcionar unamejora consi<strong>de</strong>rable en el tiempo <strong>de</strong> ejecución ycuáles no. <strong>La</strong> comparación entre la ejecución normaly la cota superior, suponiendo aciertos en L1 paralos datos compartidos <strong>de</strong> sólo lectura, pue<strong>de</strong> verse enla Figura 4.En primer lugar, como po<strong>de</strong>mos ver en la Figura4a, podríamos alcanzar hasta un 25 % <strong>de</strong> mejora<strong>de</strong> media en aplicaciones con buen potencial: volrend,blackscholes, jbb y radiosity. En algunas <strong>de</strong> ellas, comojbb, la cota superior es sorpren<strong>de</strong>nte, <strong>de</strong> casi el50 %. Así pues, vemos que existe un margen <strong>de</strong> mejorabastante amplio, que nos hace pensar que tratando<strong>de</strong> una manera a<strong>de</strong>cuada los datos compartidos<strong>de</strong> sólo lectura se pue<strong>de</strong>n conseguir mejoras importantesen estas aplicaciones, incluso aunque no nosacerquemos <strong>de</strong>masiado a la cota superior.Sin embargo, en la Figura 4b po<strong>de</strong>mos comprobarque no todas las aplicaciones tienen un margen<strong>de</strong> mejora tan amplio. En las aplicaciones fft, fluidanimate,swaptions y apache podríamos alcanzar entorno a un 6 % <strong>de</strong> mejora media. No obstante, hemos<strong>de</strong> <strong>de</strong>stacar un hecho relevante, y es que, si observamos<strong>de</strong> nuevo la Figura 2a, po<strong>de</strong>mos comprobarque el espacio ocupado por los datos compartidos <strong>de</strong>sólo lectura en estas aplicaciones es casi <strong>de</strong>spreciable.En ninguno <strong>de</strong> los casos supera el 3 % <strong>de</strong>l total.Esto hace pensar que aunque la cota superior no es<strong>de</strong>masiado buena, será más fácil acercarse a ella siconseguimos tratar estos datos <strong>de</strong> forma a<strong>de</strong>cuadagracias a su poca cantidad.Este estudio nos permite analizar cuáles son las característicascomunes que tienen las aplicaciones conun potencial parecido, lo que nos ayudará a i<strong>de</strong>ntificarlas condiciones que favorecen la existencia <strong>de</strong>dicho potencial para una aplicación concreta. Comocabía esperar, si miramos <strong>de</strong> nuevo la Figura 3, vemosque las aplicaciones con un potencial más altoson aquéllas en las cuáles los datos compartidos <strong>de</strong>sólo lectura tienen una influencia mayor en su tasa<strong>de</strong> fallos en L1, in<strong>de</strong>pendientemente <strong>de</strong>l número <strong>de</strong>accesos a este tipo <strong>de</strong> datos. A simple vista podríaparecer que apache <strong>de</strong>bería tener un potencial mayorsegún esta afirmación. Sin embargo, si nos fijamos<strong>de</strong>tenidamente, vemos que aunque el porcentaje <strong>de</strong><strong>JP2011</strong>-259


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011fallos que generan dichos datos es alto en comparacióncon otras aplicaciones, queda eclipsado por elgran número <strong>de</strong> fallos que producen los datos compartidos<strong>de</strong> lectura y escritura en dicha aplicación.V. ConclusionesHemos analizado la necesidad <strong>de</strong> memoria para datosprivados/compartidos en aplicaciones paralelassobre CMPs. A<strong>de</strong>más, hemos estudiado en profundidadlos datos compartidos <strong>de</strong> sólo lectura. Hemoscomprobado que a pesar <strong>de</strong> que estos datos ocupan<strong>de</strong> media un porcentaje pequeño <strong>de</strong>l espacio totalusado por la aplicación, inferior al 5 % en la mayoría<strong>de</strong> aplicaciones, estos bloques se acce<strong>de</strong>n frecuentementey tienen un peso muy importante en el tiempo<strong>de</strong> ejecución <strong>de</strong> las aplicaciones: en torno a un 15 %<strong>de</strong> media. Este porcentaje es incluso mayor en aplicacionescomo radiosity o blackscholes, don<strong>de</strong> superael 20 %, y totalmente <strong>de</strong>terminante en JBB, don<strong>de</strong>supone cerca <strong>de</strong>l 50 %.Por otro lado, hemos presentado una cota superior<strong>de</strong> la posible mejora <strong>de</strong>l tiempo <strong>de</strong> ejecución <strong>de</strong> lasaplicaciones suponiendo que los datos compartidos<strong>de</strong> sólo lectura no fallan en la caché L1, mostrandoque el margen <strong>de</strong> mejora es amplio. Hemos comprobadoque para las aplicaciones con un buen potencialse obtiene <strong>de</strong> media un 25 % <strong>de</strong> mejora como cotasuperior. Esto sugiere que con un buen manejo <strong>de</strong>estos datos se podría conseguir una mejora real enel tiempo <strong>de</strong> ejecución notable, aun sin acercarnos<strong>de</strong>masiado a la cota. A<strong>de</strong>más, aunque en las aplicacionescon un potencial más bajo se obtiene un 6 %medio <strong>de</strong> cota superior, hemos comprobado que elespacio ocupado para esos bloques no supera en ninguna<strong>de</strong> ellas el 3 %, lo que nos hace pensar que lamejora real podría acercarse bastante a la cota superior.Hemos visto a<strong>de</strong>más que, como cabía esperar,cuanto mayor es el peso en la tasa <strong>de</strong> fallos en L1<strong>de</strong> los datos compartidos <strong>de</strong> sólo lectura, mayor es elpotencial <strong>de</strong> mejora <strong>de</strong> la aplicación.Estos resultados nos permiten plantear varias lineas<strong>de</strong> investigación futuras entre las que se encuentran:El estudio <strong>de</strong>l patrón temporal <strong>de</strong> acceso a losdatos compartidos <strong>de</strong> sólo lectura para dar untratamiento especial a<strong>de</strong>cuado a dichos datos.<strong>La</strong> i<strong>de</strong>ntificación en el código <strong>de</strong> la aplicación<strong>de</strong> las estructuras <strong>de</strong> datos que correspon<strong>de</strong>n alos bloques compartidos <strong>de</strong> sólo lectura. De estaforma se podría evitar la necesidad <strong>de</strong> <strong>de</strong>tectardichos bloques en tiempo <strong>de</strong> ejecución, y en sulugar hacerlo en tiempo <strong>de</strong> compilación, o inclusodarle al programador la posibilidad <strong>de</strong> marcardichas estructuras <strong>de</strong> datos en el momento quesea consciente <strong>de</strong> que ya no se van a volver aescribir.El tratamiento especial en una estructura distintaa la caché L1 <strong>de</strong> los datos compartidos <strong>de</strong>sólo lectura.Agra<strong>de</strong>cimientosEste trabajo ha sido financiado por la FundaciónSéneca (Agencia Regional <strong>de</strong> Ciencia y Tecnología,Región <strong>de</strong> Murcia) mediante el proyecto00001/CS/2007, y por el MEC y la Comisión EuropeaFEDER mediante los proyectos “Consoli<strong>de</strong>rIngenio-2010 CSD2006-00046” y “TIN2009-14475-C04-02”. Alfonso Ramos Can<strong>de</strong>l es beneficiario <strong>de</strong>una beca <strong>de</strong> colaboración en el curso 2010/2011 (Or<strong>de</strong>nEDU/1799/2010 <strong>de</strong> 29 <strong>de</strong> junio <strong>de</strong> 2010) <strong>de</strong>lMinisterio <strong>de</strong> Educación (B.O.E. <strong>de</strong> 05 <strong>de</strong> julio <strong>de</strong>2010). Antonio García-Guirado también es beneficiario<strong>de</strong> una beca <strong>de</strong> investigación <strong>de</strong>l MEC bajoel Plan Nacional <strong>de</strong> Formación <strong>de</strong> Profesorado Universitario(FPU AP2008-04387).Referencias[1] N. Hardavellas, M. Ferdman, B. Falsafi, and A. Ailamaki,“Reactive nuca: near-optimal block placement and replicationin distributed caches,” in Proceedings of the 36thannual International Symposium on Computer Architecture,pp. 184–195, 2009.[2] S. H. Pugsley, J. B. Spjut, D. W. Nellans, and R. Balasubramonian,“Swel: hardware cache coherence protocolsto map shared data onto shared caches,” in Proceedings ofthe 19th international conference on Parallel Architecturesand Compilation Techniques, pp. 465–476, 2010.[3] Z. Guz, I. Keidar, A. Kolodny, and U. C. Weiser, “Utilizingshared data in chip multiprocessors with the Nahalalarchitecture,” in SPAA ’08: Proceedings of the twentiethannual Symposium on Parallelism in Algorithms and Architectures,pp. 1–10, 2008.[4] B. M. Beckmann, M. R. Marty, and D. A. Wood,“ASR: Adaptive selective replication for CMP caches,” inIEEE/ACM international Symposium on Microarchitecture,pp. 443–454, 2006.[5] P. S. Magnusson, M. Christensson, J. Eskilson, D. Forsgren,G. Hallberg, J. Hogberg, F. <strong>La</strong>rsson, A. Moestedt,B. Werner, and B. Werner, “Simics: A full system simulationplatform,” Computer, vol. 35, no. 2, pp. 50–58, 2002.[6] M. M. K. Martin, D. J. Sorin, B. M. Beckmann, M. R.Marty, M. Xu, A. R. Alamel<strong>de</strong>en, K. E. Moore, M. D.Hill, and D. A. Wood, “Multifacet’s general executiondrivenmultiprocessor simulator (GEMS) toolset,” SI-GARCH Comput. Archit. News, vol. 33, pp. 92–99, November2005.[7] S. C. Woo, M. Ohara, E. Torrie, J. P. Singh, and A. Gupta,“The SPLASH-2 Programs: Characterization and MethodologicalConsi<strong>de</strong>rations,” in Proceedings of the 22th InternationalSymposium on Computer Architecture, (SantaMargherita Ligure, Italy), pp. 24–36, 1995.[8] C. Bienia and K. Li, “Parsec 2.0: A new benchmark suitefor chip-multiprocessors,” in Proceedings of the 5th AnnualWorkshop on Mo<strong>de</strong>ling, Benchmarking and Simulation,2009.[9] C. Bienia, S. Kumar, and K. Li, “Parsec vs. splash-2: Aquantitative comparison of two multithrea<strong>de</strong>d benchmarksuites on chip-multiprocessors.,” in IISWC’08, pp. 47–56,2008.<strong>JP2011</strong>-260


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Reconfiguración <strong>de</strong> la NoC en la Virtualización<strong>de</strong> CMPsFrancisco Triviño 1 , Francisco J. Alfaro 1 , José L. Sánchez 1 , José Flich 2 y Santos González 3Resumen— Debido al gran número <strong>de</strong> nodos que incorporanlos actuales sistemas en chip y el escaso grado<strong>de</strong> escalabilidad que las aplicaciones logran alcanzar,se espera que aumente el número <strong>de</strong> aplicacionesque se podrán ejecutar <strong>de</strong> forma concurrente en unmismo sistema. De esta forma, es posible aprovechargran cantidad <strong>de</strong> los recursos disponibles. Como consecuencia,se produce un aumento <strong>de</strong> las interferenciasentre las diferentes aplicaciones y por tanto el rendimiento<strong>de</strong> cada aplicación por separado pue<strong>de</strong> verseseriamente afectado. A nivel <strong>de</strong> red <strong>de</strong> interconexión,es posible reducir las interferencias mediante mecanismos<strong>de</strong> virtualización. Una posible estrategia <strong>de</strong>virtualización consiste en dividir la red en diferentesparticiones tal que cada una pue<strong>de</strong> ejecutar diferentesaplicaciones.En este trabajo se propone un mecanismo <strong>de</strong> reconfiguración<strong>de</strong> la red para ofrecer soporte <strong>de</strong> virtualizaciónbajo escenarios realistas. En dichos escenarios,múltiples aplicaciones entran y salen <strong>de</strong>l sistema continuamente.En este caso, el sistema <strong>de</strong>be proporcionarmecanismos <strong>de</strong> reasignación dinámica <strong>de</strong> recursoscon el fin <strong>de</strong> satisfacer las necesida<strong>de</strong>s <strong>de</strong> las aplicaciones.Los resultados <strong>de</strong> evaluación muestran un buenentorno <strong>de</strong> virtualización que permite reducir el tiempo<strong>de</strong> ejecución <strong>de</strong> las aplicaciones.Palabras clave— Chip Multiprocesador, Re<strong>de</strong>s enChip, Virtualización, Reconfiguración.I. IntroducciónCon el fin <strong>de</strong> aumentar la velocidad <strong>de</strong> computación,las técnicas actuales <strong>de</strong> fabricación permitenincluir múltiples nodos <strong>de</strong> procesamiento en un únicochip. Aunque estos nodos no alcanzan la velocidadque proporciona un único y potente procesador <strong>de</strong> unnodo, varios <strong>de</strong> ellos mejoran las prestaciones <strong>de</strong> formaglobal. Los chip multiprocesador (CMPs) son unexcelente ejemplo <strong>de</strong> estos sistemas [1], [2].El éxito <strong>de</strong> los sistemas CMP no sólo <strong>de</strong>pen<strong>de</strong> <strong>de</strong>lnúmero <strong>de</strong> nodos que incorporan sino también <strong>de</strong>pen<strong>de</strong><strong>de</strong> otros recursos tales como el sistema <strong>de</strong> memoria(caches, memoria principal, protocolo <strong>de</strong> coherencia,etc.), y el sistema <strong>de</strong> comunicación. Debido alalto número <strong>de</strong> componentes a interconectar y parapermitir una configuración eficiente entre los recursos,es necesaria una red <strong>de</strong> interconexión <strong>de</strong> altasprestaciones. Este es el caso <strong>de</strong> las re<strong>de</strong>s en chip (Networkson chip, NoCs) capaces <strong>de</strong> reducir a valoresaceptablemente bajos los tiempos <strong>de</strong> transmisión <strong>de</strong>la información [4].Por otra parte, las aplicaciones actuales muestranbajo grado <strong>de</strong> escalabilidad. Como ejemplo, el estudiorealizado en [5] revela el poco grado <strong>de</strong> escalabilidadobtenido por las aplicaciones PARSEC cuando seconsi<strong>de</strong>ran todos los componentes involucrados en la1 Grupo <strong>de</strong> Re<strong>de</strong>s y Arquitecturas <strong>de</strong> Altas Prestaciones(RAAP), <strong>Universidad</strong> <strong>de</strong> Castilla-<strong>La</strong> Mancha, e-mail:{ftrivino,falfaro,jsanchez}@dsi.uclm.es.2 Grupo <strong>de</strong> Arquitecturas Paralelas (GAP), Universitat Politècnica<strong>de</strong> València, e-mail: jflich@disca.upv.es.3 Departamento <strong>de</strong> Informática, <strong>Universidad</strong> Peruana CayetanoHeredia,santos.gonzalez.t@upch.pe.arquitectura <strong>de</strong> un CMP. Del estudio realizado en [5]se pue<strong>de</strong> observar que estas aplicaciones no escalanbien a partir <strong>de</strong> 16 hilos. Por lo tanto, para aprovechargran parte <strong>de</strong> los recursos que ofrecen los CMPs,se espera que varias aplicaciones se ejecuten <strong>de</strong> manerasimultánea. A<strong>de</strong>más, a medida que aumenta elnúmero <strong>de</strong> nodos, se espera que el número <strong>de</strong> aplicacionesque se ejecutan <strong>de</strong> forma simultánea tambiénaumente. Dichas aplicaciones pue<strong>de</strong>n ser <strong>de</strong> diversaíndole (visión por computador, procesamiento multimedia,animación, simulación, etc.) provocando quelos patrones <strong>de</strong> tráfico sean completamente impre<strong>de</strong>cibles.En este escenario, múltiples aplicaciones compartentodos los recursos que forman el CMP. Comoconsecuencia, se produce un aumento <strong>de</strong> las interferenciasentre las diferentes aplicaciones. Así, es evi<strong>de</strong>nteque si los recursos no se asignan <strong>de</strong> forma eficiente,el rendimiento <strong>de</strong> cualquier aplicación pue<strong>de</strong>verse seriamente afectado.A nivel <strong>de</strong> red, las interferencias se pue<strong>de</strong>n reducirdrásticamente mediante el uso <strong>de</strong> mecanismos <strong>de</strong> virtualización.Una red virtualizada consiste en dividirla red en diferentes particiones don<strong>de</strong> cada particiónpue<strong>de</strong> ser utilizada para diferentes aplicaciones y flujos<strong>de</strong> tráfico. No obstante, la clave <strong>de</strong> esta propuestaes el hecho <strong>de</strong> no permitir que el tráfico proce<strong>de</strong>nte<strong>de</strong> una aplicación pueda afectar al <strong>de</strong> otras aplicaciones.En [6] se ha propuesto un mecanismo <strong>de</strong>virtualización capaz <strong>de</strong> reducir los efectos negativosque producen las interferencias. En concreto, el mecanismose analizó bajo un escenario estático don<strong>de</strong>cuatro aplicaciones comparten un CMP en el mismointervalo <strong>de</strong> tiempo.No obstante, en un sistema real, las aplicacionesentran y salen <strong>de</strong>l sistema continuamente. En un escenariodinámico, se <strong>de</strong>be permitir la reasignación <strong>de</strong>recursos <strong>de</strong> red a diferentes particiones con el objetivo<strong>de</strong> adaptarse a las necesida<strong>de</strong>s <strong>de</strong> las aplicaciones.Por esta razón, en este trabajo, se propone un mecanismoeficiente <strong>de</strong> reconfiguración <strong>de</strong> la red paraofrecer soporte <strong>de</strong> virtualización bajo escenarios realistas,que tiene por objetivo readaptar la NoC parapermitir la creación <strong>de</strong> particiones <strong>de</strong> forma dinámica.Este artículo está organizado <strong>de</strong> la siguiente manera:la sección II muestra el trabajo relacionado. Enla sección III se <strong>de</strong>scribe, en primer lugar, la propuestapara aislar el tráfico <strong>de</strong> aplicaciones en unaNoC. En segundo lugar, se <strong>de</strong>talla el mecanismo <strong>de</strong>reconfiguración <strong>de</strong> red propuesto. <strong>La</strong> sección IV presentala evaluación <strong>de</strong> prestaciones y los resultadosobtenidos. Finalmente, en la sección V se presentanlas conclusiones.<strong>JP2011</strong>-261


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011II. Trabajo RelacionadoEl concepto <strong>de</strong> virtualización no es nuevo y ha sidoaplicado <strong>de</strong> una forma u otra en los sistemas <strong>de</strong> lacomputación <strong>de</strong>s<strong>de</strong> principios <strong>de</strong> 1960. Por ejemplo,actualmente múltiples servidores se implementan enmáquinas virtuales (VM), que se ejecutan en un únicoservidor <strong>de</strong> altas prestaciones. De esta forma, numerosascargas <strong>de</strong> trabajo <strong>de</strong> diferente índole se consolidanen un mismo sistema don<strong>de</strong> aislar el rendimientohardware se convierte en una necesidad parala ejecución <strong>de</strong> aplicaciones con ciertas priorida<strong>de</strong>s,que generalmente vienen marcadas por el usuario oadministrador.En el contexto <strong>de</strong> los CMPs, el diseño <strong>de</strong>l mo<strong>de</strong>lo<strong>de</strong> virtualización es un proceso en el que intervienenvarios elementos. Por ejemplo, la virtualización involucraal sistema operativo y a las aplicaciones quese ejecutan en un mismo sistema. El sistema <strong>de</strong> memoria<strong>de</strong>be ser optimizado para minimizar la interferenciaentre las distintas máquinas virtuales paraaislar mejor la carga <strong>de</strong> las aplicaciones. Para solucionareste problema, Michael R. et al. proponenuna variedad <strong>de</strong> técnicas [7], todas ellas centradasen las jerarquías <strong>de</strong> memoria que implementan losCMPs. Otro ejemplo pue<strong>de</strong> encontrarse en [8] don<strong>de</strong>los autores abordan la problemática <strong>de</strong> compartirlos recursos <strong>de</strong> cache y su utilización para diferentesaplicaciones basándose en parámetros <strong>de</strong> calidad <strong>de</strong>servicio. Por <strong>de</strong>sgracia, en todos estos estudios no setiene en cuenta la red <strong>de</strong> interconexión.En cuanto al sistema <strong>de</strong> interconexión, en [9] losautores introducen el concepto <strong>de</strong> NoC virtualizaday presentan algunas ventajas basadas en maximizarlas prestaciones <strong>de</strong> la red <strong>de</strong> interconexión, en mejorarla capacidad <strong>de</strong> tolerancia a fallos, y en reducir elconsumo <strong>de</strong> energía. <strong>La</strong>mentablemente, en este estudiolos autores no <strong>de</strong>tallan una metodología <strong>de</strong> cómoconseguir una NoC virtualizada y, por tanto, no serealiza ningún estudio <strong>de</strong> evaluación <strong>de</strong> prestaciones.En [6], se ha propuesto el uso <strong>de</strong>l mecanismo Logic-Based Distributed Routing (LBDR) [10] como unmétodo eficiente para dividir una NoC en particiones.Concretamente, en este trabajo se analiza unasituación estática don<strong>de</strong> cuatro aplicaciones se ejecutaal mismo tiempo compartiendo un mismo CMP.Esta situación sólo se correspon<strong>de</strong> con el inicio <strong>de</strong>lsistema don<strong>de</strong> se asignan el máximo número <strong>de</strong> aplicacionesposible en función <strong>de</strong> los recursos disponibles.En una situación real, las aplicaciones entrany salen <strong>de</strong>l sistema continuamente a medida que losrecursos son liberados <strong>de</strong> nuevo. Por tanto, en el estudio[6] no se tuvo en cuenta ningún mecanismo <strong>de</strong>reconfiguración <strong>de</strong> la red que permita readaptar lasparticiones a nuevas aplicaciones.A. Aislar el TráficoPor lo general, un sistema CMP homogéneoestá compuesto por nodos. Cada nodo contiene unelemento <strong>de</strong> proceso, memoria cache <strong>de</strong> diferentes nivelesy el conmutador local que conecta dicho nodoa los nodos vecinos a través <strong>de</strong> la NoC. Los mensajesgenerados en el procesador se envían al conmutadora través <strong>de</strong> una interfaz <strong>de</strong> red. A continuación, elmensaje se mueve al siguiente conmutador en su caminoen función <strong>de</strong>l algoritmo <strong>de</strong> encaminamiento.El proceso se repite hasta que el mensaje consiguealcanzar su <strong>de</strong>stino. Bajo una situación normal, losenlaces están multiplexados en el tiempo usados porlos mensajes pertenecientes a diferentes aplicacionesque se están ejecutando en un mismo instante. Por lotanto, las aplicaciones compiten por los recursos <strong>de</strong>red en un entorno caótico don<strong>de</strong> se producen interferenciasa nivel <strong>de</strong> red. Este hecho reduce consi<strong>de</strong>rablementelas prestaciones obtenidas. Por lo tanto, esmuy importante aislar el tráfico <strong>de</strong> diferentes aplicacionespara mejorar las prestaciones.En [6] se presenta una NoC virtualizada capaz <strong>de</strong>separar el tráfico generado por diferentes aplicacionesmediante la división <strong>de</strong> la red en diferentes particiones.En esta situación, los enlaces no están multiplexadosentre mensajes pertenecientes a diferentesaplicaciones.Para conseguir una NoC completamente virtualizadase propuso el uso <strong>de</strong>l mecanismo LBDR [10] quepermite la creación <strong>de</strong> diferentes particiones en unamalla 2D con muy pocos recursos hardware. El mecanismoLBDR está formado por dos conjuntos <strong>de</strong> bitspor puerto <strong>de</strong> salida en cada conmutador. Se utilizauna lógica simple a nivel <strong>de</strong> bloque que contiene variaspuertas lógicas. El primer conjunto consiste enun bit por puerto y permite <strong>de</strong>finir el patrón <strong>de</strong> conexión<strong>de</strong> la partición. Cada puerto <strong>de</strong> salida tiene unbit, Cx, que indica si un conmutador está conectadoa través <strong>de</strong>l puerto x. Por tanto, los bits <strong>de</strong> conectividadCn, Ce, Cw, y Cs representan la conectividad<strong>de</strong> un conmutador con los puertos norte, este, oestey sur, respectivamente. El segundo conjunto consisteen dos bits por puerto y <strong>de</strong>fine el conjunto <strong>de</strong> restricciones<strong>de</strong> encaminamiento <strong>de</strong>bido al algoritmo <strong>de</strong>encaminamiento finalmente implementado. Los bitspara el puerto <strong>de</strong> salida este son etiquetados comoRen y Res. Indican si los mensajes encaminados através <strong>de</strong>l puerto este pue<strong>de</strong>n tomar la salida por elpuerto norte o por el puerto sur en el siguiente con-III. Virtualización Dinámica <strong>de</strong> una NoCEn esta sección mostramos como se pue<strong>de</strong> aislarel tráfico <strong>de</strong> diferentes aplicaciones mediante el uso<strong>de</strong>l mecanismo LBDR. También se <strong>de</strong>talla la metodología<strong>de</strong> reconfiguración capaz <strong>de</strong> adaptar el mecanismo<strong>de</strong> encaminamiento a las necesida<strong>de</strong>s <strong>de</strong> lasaplicaciones.Fig. 1. Ejemplo <strong>de</strong>l mecanismo LBDR.<strong>JP2011</strong>-262


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011(a)Fig. 2. (a) Segmentación en zig-zag, y (b) bits LBDR para el algoritmo SR en una malla 2D 4x4 con 9 segmentos.(b)mutador, respectivamente. En otras palabras, estosbits indican si los mensajes pue<strong>de</strong>n o no cambiar <strong>de</strong>dirección en el siguiente conmutador. Para el puerto<strong>de</strong> salida norte los bits son etiquetados como Rne yRnw, para el puerto <strong>de</strong> salida oeste: Rwn y Rws, yfinalmente para el puerto <strong>de</strong> salida sur: Rse y Rsw.<strong>La</strong> figura 1 muestra un ejemplo <strong>de</strong>l mecanismoLBDR don<strong>de</strong> un CMP <strong>de</strong> 16 nodos se ha divididoen dos particiones, cada una <strong>de</strong> 8 nodos. A modo <strong>de</strong>ejemplo, en esta figura se <strong>de</strong>tallan los bits <strong>de</strong> conectividady <strong>de</strong> encaminamiento para el conmutador 6.<strong>La</strong> figura representa con flechas las restricciones <strong>de</strong>encaminamiento, es <strong>de</strong>cir, el conjunto <strong>de</strong> dos enlacesconsecutivos que no pue<strong>de</strong>n atravesar los mensajes.En este ejemplo se ha aplicado el algoritmoSegment-Based Routing (SR) [11] en cada particiónpor separado.Nótese que las rutas <strong>de</strong> comunicación <strong>de</strong> cada partición<strong>de</strong>pen<strong>de</strong>n <strong>de</strong>l algoritmo <strong>de</strong> encaminamientousado en la red. Dicho algoritmo <strong>de</strong>be ser lo suficientementeflexible para permitir particiones irregularesy <strong>de</strong>be ser diseñado teniendo en cuenta los estrictosrequisitos aplicados a arquitecturas CMP en cuantoa latencia, consumo <strong>de</strong> energía y área. El algoritmoSR cumple con dichas restricciones.B. Mecanismo <strong>de</strong> ReconfiguraciónEn esta sección se <strong>de</strong>scribe un método efectivo,práctico y rápido para reconfigurar los bits <strong>de</strong> encaminamientoen una NoC y permitir así la virtualización<strong>de</strong> los recursos <strong>de</strong> red (mediante la división<strong>de</strong> la red en diferentes particiones) en un entornodinámico.En primer lugar hay que tener en cuenta que eltamaño y forma <strong>de</strong> las particiones son elegidas porun gestor <strong>de</strong> recursos que, por regla general, se ejecutabajo el sistema operativo. El gestor <strong>de</strong> recursospue<strong>de</strong> tener en cuenta diferentes requisitos a la hora<strong>de</strong> asignar recursos a las aplicaciones tales como: laminimización <strong>de</strong> la latencia <strong>de</strong> red entre los elementos<strong>de</strong> proceso, la posición <strong>de</strong> los controladores <strong>de</strong>memoria, la reducción <strong>de</strong> la fragmentación <strong>de</strong> red,posibles fallos en la red, ahorro <strong>de</strong> energía, etc. Ennuestro caso, únicamente se tiene en cuenta el número<strong>de</strong> hilos que componen las aplicaciones, don<strong>de</strong> unhilo requiere un nodo. A nivel <strong>de</strong> red, hay que teneren cuenta que el gestor <strong>de</strong> recursos es in<strong>de</strong>pendiente<strong>de</strong>l mecanismo <strong>de</strong> reconfiguración.Se parte <strong>de</strong>l hecho <strong>de</strong> que el algoritmo <strong>de</strong> encaminamientoes SR [11]. Con el algoritmo SR, es posiblepre-configurar un conjunto <strong>de</strong> bits LBDR parauna malla 2D completa y totalmente conectada. Porejemplo, la figura 2.(a) muestra el resultado <strong>de</strong> aplicarel algoritmo SR a una malla 4 × 4 1 . Aunque haynumerosas instancias que se pue<strong>de</strong>n obtener <strong>de</strong>l algoritmoSR, se ha elegido segmentar la red y asignarlas restricciones en forma <strong>de</strong> Zig-Zag <strong>de</strong> izquierda a<strong>de</strong>recha empezando <strong>de</strong> arriba hacia abajo. Este métodoha sido analizado obteniendo buenas prestacionescon respecto a otras segmentaciones alternativas [17].Una vez que se ha obtenido el conjunto <strong>de</strong> restricciones<strong>de</strong> encaminamiento (representadas por flechasen la figura 2.(a)), se calculan los bits <strong>de</strong>l LBDR encada conmutador. Estos bits pue<strong>de</strong>n ser <strong>de</strong>ducidos<strong>de</strong> forma sencilla teniendo en cuenta la localización<strong>de</strong> las restricciones <strong>de</strong> encaminamiento y <strong>de</strong> conectivida<strong>de</strong>n la red. A modo <strong>de</strong> ejemplo, la figura 2.(b)muestra los bits para la topología <strong>de</strong> la figura 2.(a).Teniendo en cuenta la configuración <strong>de</strong> encaminamientoanterior, y una vez que el sistema operativocomienza a ejecutar aplicaciones, se necesita i<strong>de</strong>ntificarlas nuevas formas que resultan <strong>de</strong> la creación <strong>de</strong>nuevas particiones. Por ejemplo, la figura 3.(a) muestrauna situación don<strong>de</strong> tres aplicaciones han sidoasignadas en el CMP don<strong>de</strong> los bits <strong>de</strong>l mecanismoLBDR se han adaptado consecuentemente. Primero,los bits <strong>de</strong> conectividad establecen los limites <strong>de</strong> lasparticiones (por ejemplo, se configura a 0 el bit <strong>de</strong>conectividad sur <strong>de</strong> los conmutadores 2 a 7, mientrasque el puerto norte <strong>de</strong> los conmutadores 6 al11 se configuran también a 0). A<strong>de</strong>más, las restricciones<strong>de</strong> encaminamiento se <strong>de</strong>ben configurar paraevitar ciclos en las particiones. Dichos bits <strong>de</strong> encaminamientose configuran <strong>de</strong> forma in<strong>de</strong>pendiente encada partición. Por ejemplo, el conmutador 5 tieneuna restricción bidireccional en las direcciones estenortey norte-oeste.Cuando se crea una nueva partición, los bits LBDRse revisan y se actualizan acor<strong>de</strong> con la forma <strong>de</strong> lanueva partición. <strong>La</strong> figura 3.(b) muestra un ejemploa partir <strong>de</strong> la situación inicial <strong>de</strong> la figura 3.(a)don<strong>de</strong> las aplicaciones App1 y App3 han completadosu ejecución. Después, una nueva aplicación (App4)solicita 8 nodos y el sistema operativo le asigna los1 No confundir los segmentos SR (líneas punteadas) con lasparticiones (líneas continuas) <strong>de</strong>l mecanismo <strong>de</strong> virtualización.<strong>JP2011</strong>-263


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20110 1 2 3App1App34 5 6 70 1 2 34 5 6 70 1 2 3App44 5 6 78 9 10 11App212 13 14 158 9 10 11App212 13 14 158 9 10 11App212 13 14 15(a) (b) (c)Fig. 3. (a) Situación inicial, (b) finalizan las aplicaciones App1 y App3 , y (c) comienza la ejecución <strong>de</strong> la aplicación App4.nodos <strong>de</strong> 0 al 7 (Figura 3.(c)). En esta situación, losbits <strong>de</strong>l LBDR para los conmutadores 0 a 7 se <strong>de</strong>benreconfigurar antes <strong>de</strong> comenzar con la ejecución <strong>de</strong> laaplicación App4. Como se pue<strong>de</strong> <strong>de</strong>ducir fácilmente,los bits <strong>de</strong> conectividad norte <strong>de</strong> los conmutadores6 y 7 se <strong>de</strong>ben reconfigurar para permitir la comunicacióncon todos los nodos <strong>de</strong> la nueva partición.Lo mismo suce<strong>de</strong> con los bits <strong>de</strong> conectividad sur <strong>de</strong>los conmutadores 2 y 3. Por último, se computan lasrestricciones <strong>de</strong> encaminamiento para la nueva partición.Téngase en cuenta que este proceso <strong>de</strong> reconfiguraciónse basa en una reconfiguración estática (nohay tráfico circulando por la red) y afecta sólo a laspartes <strong>de</strong> la red don<strong>de</strong> no hay mensajes circulandoa través <strong>de</strong> los conmutadores ya que las aplicacionesque los estaban usando han terminado su ejecución.Esto es muy importante porque en otro caso podríanaparecer bloqueos. En ese caso, para evitar los bloqueos,se tendría que <strong>de</strong>tener todo el tráfico <strong>de</strong> la redantes <strong>de</strong> reconfigurar la función <strong>de</strong> encaminamiento,o si se quiere evitar drenar la red previamente, se <strong>de</strong>beríaconsi<strong>de</strong>rar otro mecanismo <strong>de</strong> reconfiguraciónmás complejo que no afecte el resto <strong>de</strong> particiones <strong>de</strong>la red. Gracias al hecho <strong>de</strong> que no hay interferenciasentre el tráfico perteneciente a diferentes particiones,es posible realizar una reconfiguración local sin queafecte al resto <strong>de</strong> particiones <strong>de</strong> la red. En el ejemploanterior, sólo se <strong>de</strong>ben configurar los bits <strong>de</strong>l LBDR<strong>de</strong> los nodos libres 0 al 7. Por esta razón, el mecanismo<strong>de</strong> reconfiguración siempre asegura una situaciónlibre <strong>de</strong> bloqueo.IV. Evaluación <strong>de</strong> PrestacionesEn esta sección, se evalúa mediante simulación elentorno <strong>de</strong> virtualización, que incluye el mecanismo<strong>de</strong> reconfiguración <strong>de</strong>scrito anteriormente. Para llevara cabo la evaluación hemos utilizado un entorno<strong>de</strong> simulación [3] basado en herramientas existentes yorientado a la evaluación <strong>de</strong> re<strong>de</strong>s en chip. Dicho entornomo<strong>de</strong>la <strong>de</strong> forma lo suficientemente <strong>de</strong>talladauna NoC, así como los diferentes componentes queforman una arquitectura CMP completa (procesadores,sistema <strong>de</strong> memoria, sistema operativo, aplicacionesreales, etc.).El sistema simulado es un CMP homogéneo <strong>de</strong>16 nodos. Dicho CMP se estructura en una serie <strong>de</strong>nodos; cada uno contiene un procesador en or<strong>de</strong>n(UltraSparc III), una cache L1 privada para datos yotra para instrucciones, una cache L2 compartida, unconmutador para comunicarlo con el resto <strong>de</strong> nodos,unidos con una red <strong>de</strong> interconexión con topología <strong>de</strong>malla <strong>de</strong> dos dimensiones. <strong>La</strong> coherencia entre los diferentesniveles <strong>de</strong> cache se preserva mediante el protocoloMOESI. En cuanto al acceso fuera <strong>de</strong>l chip seusa la técnica 3D-Stacking [12] por lo que cada nodotiene acceso fuera <strong>de</strong>l chip. Para la red <strong>de</strong> interconexiónse asume conmutación wormhole con tamaños<strong>de</strong> colas <strong>de</strong> 4 bits. El tamaño <strong>de</strong> flit <strong>de</strong>finido es <strong>de</strong> 4bytes. Por otra parte, se utiliza el mecanismo LBDRque permite la creación <strong>de</strong> particiones junto con elalgoritmo <strong>de</strong> encaminamiento SR [11]. A<strong>de</strong>más, lared opera a la misma velocidad que los procesadores.Por último, para reducir las interferencias entrela cache L2 <strong>de</strong> diferentes particiones, se obliga a quelos bloques <strong>de</strong> L2 pertenecientes a una partición seanutilizados por la aplicación que ocupa dicha partición[13]. De esta forma, se consigue aislar el contexto <strong>de</strong>las aplicaciones a nivel <strong>de</strong> sistema <strong>de</strong> memoria.Como carga <strong>de</strong> trabajo se han utilizado aplicacionesincluidas en los benchmarks SPLASH-2 [14] yPARSEC v2,1 [15]. <strong>La</strong> suite SPLASH-2 contiene unconjunto <strong>de</strong> programas que representan una ampliavariedad <strong>de</strong> aplicaciones científicas y <strong>de</strong> ingeniería.<strong>La</strong> suite PARSEC posee una amplia variedad <strong>de</strong> patrones<strong>de</strong> computación y comunicación que permitenevaluar las actuales tecnologías <strong>de</strong> CMP con mayoreficacia.A. EscenariosA fin <strong>de</strong> evaluar el mecanismo <strong>de</strong> reconfiguraciónse han consi<strong>de</strong>rado diferentes escenarios. En cada escenariose ejecutan 5 conjuntos <strong>de</strong> aplicaciones diferentes.Cada conjunto <strong>de</strong> aplicaciones contiene 20aplicaciones seleccionadas <strong>de</strong> forma aleatoria <strong>de</strong> losrepositorios <strong>de</strong> aplicaciones SPLASH-2 y PARSECv2,1. Los requisitos <strong>de</strong> las aplicaciones están basadosúnicamente en el número <strong>de</strong> hilos. Se ha consi<strong>de</strong>radoque cada hilo solicita un nodo diferente. Losrequisitos <strong>de</strong> cada aplicación son elegidos <strong>de</strong> formaaleatoria <strong>de</strong>s<strong>de</strong> 2 hasta 8 hilos. El gestor <strong>de</strong> recursosasigna automáticamente los recursos <strong>de</strong>l CMP alas aplicaciones <strong>de</strong> forma secuencial. <strong>La</strong>s aplicacionesson almacenadas en una cola FIFO hasta que elgestor <strong>de</strong> recursos tiene suficientes recursos para comenzarla ejecución <strong>de</strong> la siguiente aplicación. Losescenarios se diferencian en el uso que se hace <strong>de</strong> losrecursos <strong>de</strong>l CMP.<strong>JP2011</strong>-264


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011El primero consiste en un escenario base (EB) don<strong>de</strong>cada aplicación utiliza todos los recursos que formanel CMP. En este escenario los hilos que formancada aplicación son distribuidos <strong>de</strong> forma aleatoria.En este caso no se consi<strong>de</strong>ra ningún mecanismo <strong>de</strong>virtualización, y por tanto, el mecanismo <strong>de</strong> reconfiguraciónno es necesario. Así, el tráfico generado poruna aplicación en concreto se verá afectado por eltráfico generado por otras aplicaciones.El segundo caso evaluado (RV, regiones virtuales)parte <strong>de</strong>l escenario base, pero en este caso, la redse divi<strong>de</strong> para crear regiones <strong>de</strong> forma dinámica. Eneste escenario, los mensajes generados por diferentesaplicaciones sólo pue<strong>de</strong>n usar los recursos <strong>de</strong> redpertenecientes a dicha región, por lo tanto, las aplicacionesposeen sus propios recursos <strong>de</strong> forma <strong>de</strong>dicadadon<strong>de</strong> el tráfico <strong>de</strong> una región no pue<strong>de</strong> cruzarotras regiones. Como el tráfico <strong>de</strong> las aplicaciones<strong>de</strong>be ser aislado, los recursos <strong>de</strong>ben ser asignados <strong>de</strong>forma contigua. Por esta razón, se utiliza la estrategia<strong>de</strong> asignación <strong>de</strong> recursos presentada en [16].Hay que tener en cuenta que el gestor <strong>de</strong> recursoses in<strong>de</strong>pendiente <strong>de</strong>l mecanismo <strong>de</strong> reconfiguración.En este escenario cada aplicación es asignada a unaregión virtual <strong>de</strong> forma similar que en el ejemplo <strong>de</strong>la figura 3. Cada partición tendrá diferente tamaño<strong>de</strong>pendiendo <strong>de</strong> los requisitos <strong>de</strong> la aplicación a ejecutar(número <strong>de</strong> hilos).Por último, hemos consi<strong>de</strong>rado un escenario adicionalcon el objetivo <strong>de</strong> mostrar el efecto negativoque producen las interferencias en el tráfico <strong>de</strong> red.Este escenario (DV, dominios virtuales) parte <strong>de</strong>l escenarioRV. Sin embargo, los mensajes pertenecientesa un dominio pue<strong>de</strong>n cruzar los límites <strong>de</strong> otros dominiospara alcanzar sus <strong>de</strong>stinos. En este escenario,la carga <strong>de</strong> red se distribuye a lo largo <strong>de</strong> todo elCMP <strong>de</strong>pendiendo <strong>de</strong>l algoritmo <strong>de</strong> encaminamientousado y suponiendo, en todo momento, caminosmínimos. Como cabe esperar, en el escenario DV nose aplica el mecanismo <strong>de</strong> reconfiguración <strong>de</strong> la redpuesto que no es necesario. En lugar <strong>de</strong> eso se haaplicado el algoritmo <strong>de</strong> encaminamiento SR en lamalla completa tal y como muestra la figura 2.(a).Por ultimo, cabe <strong>de</strong>stacar que únicamente se aplicael mecanismo <strong>de</strong> reconfiguración en el escenarioRV. En este caso, se ha consi<strong>de</strong>rado el tiempo <strong>de</strong>ejecución adicional cada vez que se ha aplicado elmecanismo <strong>de</strong> reconfiguración, el cual <strong>de</strong>pen<strong>de</strong> principalmente<strong>de</strong>l tamaño <strong>de</strong> la partición. Con respectoal gestor <strong>de</strong> recursos, no se ha tenido en cuenta laposible sobrecarga en tiempo <strong>de</strong> ejecución <strong>de</strong> dichaestrategia.B. ResultadosEn esta sección se presentan los resultados obtenidosen el proceso <strong>de</strong> evaluación. Se han ejecutado 5conjuntos <strong>de</strong> 20 aplicaciones en cada escenario. Puestoque en el escenario EB los hilos son asignados alos nodos <strong>de</strong> forma aleatoria, cada valor obtenido coneste escenario es el resultado <strong>de</strong> treinta simulacionesdiferentes, don<strong>de</strong> el intervalo <strong>de</strong> confianza se ha establecidoal 95 %.110105100959085807570EB RV DVSet1 Set2 Set3 Set4 Set5Fig. 4. Tiempo <strong>de</strong> ejecución normalizado.<strong>La</strong> figura 4 muestra el tiempo <strong>de</strong> ejecución para losdiferentes conjuntos <strong>de</strong> aplicaciones (eje-x). El eje-yrepresenta la diferencia en el tiempo <strong>de</strong> ejecución totalentre los diferentes escenarios (EB, RV y DV). Parailustrar la variación <strong>de</strong> rendimiento, los resultadosse muestran en términos normalizados comparadoscon el tiempo <strong>de</strong> ejecución para el caso EB.Para el escenario EB, las aplicaciones compartenla totalidad <strong>de</strong> los recursos <strong>de</strong>l CMP. En este sentido,se obtiene un comportamiento caótico don<strong>de</strong> las interferenciasentre el tráfico <strong>de</strong> diferentes aplicacionesocurren constantemente, lo que termina afectando alrendimiento individual <strong>de</strong> las aplicaciones.Por otra parte, en el escenario DV se producenmenos interferencias <strong>de</strong> tráfico que en el escenarioEB y por tanto las prestaciones son mucho mejores.En concreto, el tiempo <strong>de</strong> ejecución <strong>de</strong>crece en un14 % (para el conjunto Set3) comparado con el casoEB como se pue<strong>de</strong> ver en la figura 4. Si comparamosRV con DV, a pesar <strong>de</strong> tener la misma asignación<strong>de</strong> recursos, se obtienen mayores beneficios con RV,puesto que el tiempo <strong>de</strong> ejecución <strong>de</strong>crece otro 10 %comparado con el escenario DV (en el conjunto Set3).Aunque el tiempo <strong>de</strong> ejecución es la métrica másimportante cuando se utilizan aplicaciones reales, enel ámbito <strong>de</strong> las re<strong>de</strong>s <strong>de</strong> interconexión son interesantestambién otras métricas como la latencia <strong>de</strong> redy el uso medio <strong>de</strong> los enlaces. <strong>La</strong> figura 5 muestrala latencia media producida en la red (a) y la cargamedia <strong>de</strong> los enlaces (b) para el conjunto Set1 <strong>de</strong>aplicaciones, <strong>de</strong> nuevo en términos normalizados encomparación con el valor obtenido para el caso EB.En este caso, la latencia obtenida para el escenarioEB se incrementa en un 22 % comparada con la<strong>de</strong>l escenario RV, así como un 13 % para el escenarioDV. <strong>La</strong> razón principal por la que el escenarioRV obtiene mejores prestaciones se encuentra en elhecho <strong>de</strong> que el mecanismo <strong>de</strong> reconfiguración divi<strong>de</strong>la red en diferentes regiones y la distancia media<strong>de</strong> los mensajes generados por las aplicaciones se reduce<strong>de</strong> forma significativa. Por tanto, el tráfico <strong>de</strong>cada aplicación tiene muy baja latencia, lo cual estambién una <strong>de</strong> las razones por las que se obtienemejores tiempos <strong>de</strong> ejecución. Cuando los orígenesy <strong>de</strong>stinos <strong>de</strong> los mensajes no están muy próximos,un mensaje <strong>de</strong>be atravesar nodos intermedios paraalcanzar su <strong>de</strong>stino. Cuando se incrementa el número<strong>de</strong> saltos, la probabilidad <strong>de</strong> interferir con otros<strong>JP2011</strong>-265


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20111051009590858075EB RV DV(a)Fig. 5. (a) <strong>La</strong>tencia media normalizada y (b) uso <strong>de</strong> enlaces.mensajes se incrementa también, lo cual se convierteen un aumento <strong>de</strong> la latencia. Si se comparan losescenarios RV y DV, y teniendo en cuenta que loshilos han sido asignados a los mismos nodos, las diferenciasson únicamente <strong>de</strong>bidas a las interferenciasentre mensajes.Por otra parte, el uso medio <strong>de</strong> los enlaces representael uso <strong>de</strong> la red. Esta métrica se ha calculadoteniendo en cuenta la carga <strong>de</strong> todos los enlaces <strong>de</strong>s<strong>de</strong>el principio <strong>de</strong> la simulación hasta que todas las aplicacioneshan finalizado su ejecución. Como se pue<strong>de</strong>observar, el escenario RV consigue reducir la sobrecarga<strong>de</strong> comunicación y el tráfico producido puestoque aisla completamente el tráfico <strong>de</strong> las aplicaciones.Por tanto, se reduce significativamente la cargamedia <strong>de</strong> los enlaces cuando se utiliza el mecanismo<strong>de</strong> virtualización. El escenario RV muestra una reducción<strong>de</strong>l 5 % sobre el escenario DV. Por último,aunque únicamente se muestran resultados para elconjunto Set1 <strong>de</strong> aplicaciones, la ten<strong>de</strong>ncia para lalatencia y carga <strong>de</strong> la red es similar para todos losconjuntos <strong>de</strong> aplicaciones evaluados.(b)V. ConclusionesEste artículo trata <strong>de</strong> mejorar el rendimiento <strong>de</strong>las aplicaciones que se ejecutan <strong>de</strong> forma simultáneamediante el concepto <strong>de</strong> virtualización. El mecanismo<strong>de</strong> virtualización permite aislar el tráfico generadopor cada aplicación para reducir la sobrecarga <strong>de</strong>comunicación <strong>de</strong>bida a interferencias entre mensajespertenecientes a diferentes aplicaciones. En un sistemareal, las aplicaciones entran y salen <strong>de</strong>l sistemacontinuamente. En este caso, la red <strong>de</strong>be ser capaz<strong>de</strong> asignar recursos <strong>de</strong> red a diferentes particiones <strong>de</strong>forma dinámica. Por esta razón, en este trabajo se<strong>de</strong>scribe un mecanismo <strong>de</strong> reconfiguración para ofrecersoporte <strong>de</strong> virtualización bajo escenarios realistasdon<strong>de</strong> los recursos <strong>de</strong>l sistema son asignados <strong>de</strong> formadinámica.Se han evaluado tres casos: un mo<strong>de</strong>lo base (EB)sin soporte <strong>de</strong> virtualización y dos mo<strong>de</strong>los basadosen virtualización (RV y DV) don<strong>de</strong> el primero (RV)aisla completamente el tráfico <strong>de</strong> las diferentes aplicacionesmientras que el segundo (DV) no aisla eltráfico. Se ha observado que el escenario RV pue<strong>de</strong>suponer una importante mejora en las prestacionesque el sistema obtiene. En concreto, se ha observadoque el escenario RV reduce (para todos los conjuntos<strong>de</strong> aplicaciones que hemos simulado) entre un 5 %y un 12 % el tiempo <strong>de</strong> ejecución comparado con elescenario DV (don<strong>de</strong> no se aisla el tráfico <strong>de</strong> aplicaciones).A<strong>de</strong>más, la latencia y carga media <strong>de</strong> la redsiguen la misma ten<strong>de</strong>ncia que el tiempo <strong>de</strong> ejecución.Este hecho se <strong>de</strong>be a la eliminación <strong>de</strong> las interferencias<strong>de</strong> tráfico entre mensajes pertenecientesa diferentes aplicaciones puesto que en ambos casosel resto <strong>de</strong>l CMP (principalmente nodos y cache) seha particionado <strong>de</strong> la misma forma.Agra<strong>de</strong>cimientosEste trabajo ha sido cofinanciado por el MEC yMICINN <strong>de</strong>l gobierno <strong>de</strong> España, y por fondos FE-DER <strong>de</strong> la Comisión Europea, con las subvencionesConsoli<strong>de</strong>r Ingenio-2010 CSD2006-00046 y TIN2009-14475-C04-03, respectivamente; por la Consejería <strong>de</strong>Educación y Ciencia <strong>de</strong> la JCCM con los proyectosPEII11-0229-2343 y POII10-0289-3724, y por el proyectoNaNoC (referencia 248972) que está financiadopor la Comisión Europea <strong>de</strong>ntro <strong>de</strong>l programa <strong>de</strong> investigaciónFP7.Referencias[1] “Tilera Tile-Gx Product Brief,” 2010. Available:http://www.tilera.com/pdf/PB025-TILE-Gx-Processor-A-v3.pdf[2] S. R. Vangal, et al., “An 80-tile sub-100-W TeraFLOPSprocessor in 65-nm CMOS,” IEEE JSSC, 2008.[3] F. Triviño, F. J. Andujar, F. J. Alfaro, J. L. Sánchez,and A. Ros, “Self-Related Traces: An Alternative to Full-System Simulation for NoCs,” in HPCS, 2011.[4] F. Gilabert, F. Silla, M. E. Gomez, M. Lod<strong>de</strong>, A. Roca,J. Flich, J. Duato, C. Hernán<strong>de</strong>z, and S. Rodrigo, DesigningNetwork On-Chip Architectures in the NanoscaleEra, J. B. D. Flich, Ed. CRC Press, 2010. Available:http://www.crcpress.com/product/isbn/9781439837108[5] F. Triviño, J. L. Sánchez, and F. J. Alfaro, “Effect of theCMP Network on the PARSEC v2.1 Benchmark Suite Scalability,”INAOCMC, 2010.[6] F. Triviño, J. L. Sánchez, F. J. Alfaro, and J. Flich,“Virtualizing network-on-chip resources in chipmultiprocessors,”MICPRO, vol. 35, pp. 230–245,2011.[7] M. R. Marty and M. D. Hill, “Virtual hierarchies to supportserver consolidation,” in ISCA, 2007.[8] F. Guo, et al., “From Chaos to QoS: Case Studies inCMP Resource Management,” SIGARCH Comput. Archit.News, 2007.[9] J. Flich, J. Duato, T. Sødring, Å. G. Solheim, T. Skeie,O. Lysne, and S. Rodrigo, “On the Potential of NoC Virtualizationfor Multicore Chips,” in MuCoCoS, 2008.[10] J. Flich and J. Duato, “Logic-Based Distributed Routingfor NoCs,” IEEE Comput. Archit. Lett., 2008.[11] A. Mejia, J. Flich, and J. Duato, “On the Potentials ofSegment-Based Routing for NoCs,” in ICPP, 2008.[12] B. Black, et al., “Die Stacking (3D) Microarchitecture,”in MICRO, 2006.[13] S. Cho and L. Jin, “Managing Distributed, Shared L2Caches through OS-Level Page Allocation,” in MICRO,2006.[14] S. C. Woo, et al., “The SPLASH-2 programs: characterizationand methodological consi<strong>de</strong>rations,” in ISCA, 2005.[15] C. Bienia and K. Li, “PARSEC 2.0: A New BenchmarkSuite for Chip-Multiprocessors,” in MoBS, 2009.[16] A. G. Solheim, O. Lysne, T. Sødring, T. Skeie, andJ. A. Libak, “Routing-contained virtualization based onUp*/Down* forwarding,” in HiPC, 2007.[17] A. Mejia, “Design and Implementation of Efficient TopologyAgnostic Routing Algorithms for InterconnectionNetworks”, PhD dissertation, University of Valencia, 2008.<strong>JP2011</strong>-266


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Beneficios <strong>de</strong>l uso <strong>de</strong> la Red <strong>de</strong> Interconexiónen la Aceleración <strong>de</strong> la CoherenciaLucía G. Menezo, Adrián Colaso, Pablo Prieto, Pablo Abad, Valentín Puente, José Ángel GregorioResumen—A lo largo <strong>de</strong> este trabajo se realiza un análisis<strong>de</strong>l comportamiento <strong>de</strong> diversas aplicaciones con el fin <strong>de</strong>evaluar los beneficios que supondría hacer partícipe a lared <strong>de</strong> interconexión en el protocolo <strong>de</strong> coherencia <strong>de</strong> unCMP. <strong>La</strong> colaboración <strong>de</strong> la red <strong>de</strong> interconexión en lagestión <strong>de</strong> las peticiones que realizan los cores podríaacelerar la resolución <strong>de</strong> las fases <strong>de</strong> sincronización <strong>de</strong> lasaplicaciones, suponiendo <strong>de</strong> este modo una mejora en elrendimiento global <strong>de</strong> este tipo <strong>de</strong> sistemas. Utilizando unentorno basado en el simulador funcional Simics, junto conel simulador <strong>de</strong> sistemas multiprocesador GEMS y elsimulador <strong>de</strong>tallado <strong>de</strong> re<strong>de</strong>s <strong>de</strong> interconexión SICOSYS,se ha <strong>de</strong>terminado el nivel <strong>de</strong> compartición <strong>de</strong> los datosatendiendo fundamentalmente a la coinci<strong>de</strong>ncia temporal<strong>de</strong> las peticiones realizadas. Los resultados para unconjunto significativo <strong>de</strong> aplicaciones muestran unosvalores muy bajos <strong>de</strong> simultaneidad al enviar peticiones alresto <strong>de</strong> los procesadores. <strong>La</strong> media <strong>de</strong> todas lasaplicaciones analizadas muestra que cuando ocurre unmiss en una cache L1 y se envía una petición al resto <strong>de</strong>controladores <strong>de</strong> coherencia, en promedio, tan solo en un1% <strong>de</strong> los casos se encuentran una o más peticionespendientes <strong>de</strong> otros procesadores a la misma dirección y enese intervalo <strong>de</strong> tiempo.Palabras clave—Coherencia, Re<strong>de</strong>s <strong>de</strong> interconexión,Sincronización, Sistemas multiprocesadorEI. INTRODUCCIÓNN la actualidad, los avances en la tecnología porsí solos no son suficientes para incrementar elrendimiento <strong>de</strong> los sistemas <strong>de</strong> forma notable. Elconsumo limitado <strong>de</strong> energía o el ancho <strong>de</strong> bandadisponible hacia el exterior <strong>de</strong>l chip son algunos <strong>de</strong> losfactores que provocan que las mejoras en muchos casossean casi inapreciables. Por esta razón, los arquitectos <strong>de</strong>computadores han optado por conseguir mejoras en elrendimiento mediante la inclusión <strong>de</strong> varios cores en elinterior <strong>de</strong>l chip (CMPs) fundamentando las mejoras <strong>de</strong>rendimiento en el paralelismo a nivel <strong>de</strong> thread.Sin embargo, la paralelización <strong>de</strong> tareas no está libre <strong>de</strong>problemas. Es necesaria la sincronización y lacomunicación entre todos los procesadores en el accesoa los recursos compartidos. Dentro <strong>de</strong> estos recursoscompartidos, uno <strong>de</strong> los mayores obstáculos en esteaspecto es la multiplicidad <strong>de</strong> copias que, para unadirección <strong>de</strong> memoria, se pue<strong>de</strong> encontrar a lo largo <strong>de</strong>la jerarquía <strong>de</strong> cache. Esto obliga a disponer en elsistema <strong>de</strong> algún tipo <strong>de</strong> mecanismo que garantice unavisión coherente <strong>de</strong> la jerarquía <strong>de</strong> memoria. <strong>La</strong> opciónmás viable, <strong>de</strong>s<strong>de</strong> el punto <strong>de</strong> vista <strong>de</strong> laprogramabilidad <strong>de</strong>l sistema, es optar por unaaproximación hardware. Los controladores <strong>de</strong>coherencia <strong>de</strong> cada uno <strong>de</strong> los niveles <strong>de</strong> la jerarquía <strong>de</strong>memoria son los encargados <strong>de</strong> implementar protocolosGrupo <strong>de</strong> Arquitectura y Tecnología <strong>de</strong> Computadores<strong>Universidad</strong> <strong>de</strong> Cantabria, Facultad <strong>de</strong> Ciencias, Santan<strong>de</strong>r{gregoriol, acolaso, prietop, abadp, vpuente, monaster}@unican.es<strong>JP2011</strong>-267<strong>de</strong> coherencia precisos para garantizar la visióncoordinada <strong>de</strong> la jerarquía <strong>de</strong> memoria por parte <strong>de</strong>todos los cores.El comportamiento <strong>de</strong> los protocolos <strong>de</strong> coherenciapue<strong>de</strong> llegar a marcar una gran diferencia en elrendimiento <strong>de</strong> los sistemas multiprocesador. Son losresponsables directos <strong>de</strong> resolver las peticiones querealizan los procesadores y evitan los conflictos quepue<strong>de</strong>n surgir entre ellas <strong>de</strong>bido a las posibles carreraspor el acceso a los datos compartidos.El número <strong>de</strong> cores integrados en el chip y la topologíautilizada para conectarlos entre sí, son dos parámetrosclave para <strong>de</strong>cidir qué metodología emplear paramantener la coherencia. Por un lado, cuando el número<strong>de</strong> procesadores es pequeño, la red <strong>de</strong> interconexión máseficaz es el bus. Este tipo <strong>de</strong> re<strong>de</strong>s permite laimplementación <strong>de</strong> protocolos <strong>de</strong> coherencia basados enla técnica snoopy. Cuando el número <strong>de</strong> procesadores esmás alto, la nula escalabilidad en el ancho <strong>de</strong> banda <strong>de</strong>lbus hace necesario utilizar re<strong>de</strong>s <strong>de</strong> interconexión comolos crossbars. Sin embargo, si el número <strong>de</strong>procesadores sigue creciendo se requieren re<strong>de</strong>s con unaescalabilidad más elevada, como las re<strong>de</strong>s punto a puntotales como mallas, toros, etc.De la misma manera que la red <strong>de</strong> interconexión <strong>de</strong>beser diferente según el número <strong>de</strong> procesadores y ladistribución <strong>de</strong>l sistema <strong>de</strong> memoria, los protocolos <strong>de</strong>coherencia también <strong>de</strong>ben implementarse pensando en elsistema en el que van a funcionar. Básicamente, existendos variantes diferenciadas <strong>de</strong> protocolos <strong>de</strong> coherencia.Por una parte se encuentran los basados en directorio,don<strong>de</strong> existe una estructura lógicamente centralizadaque arbitra los accesos a los bloques compartidos entrelos distintos procesadores, serializándolos cuando sonincompatibles, para evitar los conflictos. <strong>La</strong> ventaja <strong>de</strong>estos protocolos es que el tráfico escala, pero cuando elnúmero <strong>de</strong> procesadores es elevado requieren muchoespacio para almacenar la información sobre lacoherencia <strong>de</strong>l sistema o tienen problemas <strong>de</strong>inclusividad entre los diferentes niveles <strong>de</strong> la jerarquía.A<strong>de</strong>más, la serialización <strong>de</strong> las peticiones supone unaumento consi<strong>de</strong>rable en la latencia total <strong>de</strong> laspeticiones <strong>de</strong>bido sobre todo a la indirección que suponeacce<strong>de</strong>r al directorio. Por otra parte, se encuentran losprotocolos <strong>de</strong> coherencia basados en broadcast. Estetipo <strong>de</strong> protocolos no requieren <strong>de</strong> una estructuracentralizada y mantienen la coherencia <strong>de</strong> maneradistribuida entre todos los controladores. Cuando seutilizan en re<strong>de</strong>s <strong>de</strong> interconexión no or<strong>de</strong>nadas comolas mallas o los toros, la aparición <strong>de</strong> carreras <strong>de</strong>peticiones y datos son probables, por lo que es necesarioincluir en el protocolo algún mecanismo <strong>de</strong> evitación o<strong>de</strong> <strong>de</strong>tección <strong>de</strong> conflictos.En cualquiera <strong>de</strong> los dos casos, surge la duda <strong>de</strong> si lared <strong>de</strong> interconexión pue<strong>de</strong> contribuir a acelerar laresolución <strong>de</strong> los conflictos en los accesos a los datoscompartidos. Este trabajo, usando un entorno <strong>de</strong>evaluación preciso y próximo a la realidad, evalúa


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011cuáles son las posibilida<strong>de</strong>s reales <strong>de</strong> tal aproximación.Aunque <strong>de</strong> los datos obtenidos se <strong>de</strong>spren<strong>de</strong> que elvolumen <strong>de</strong> contención en el acceso a los datoscompartidos no es lo suficientemente intenso como paraque soluciones <strong>de</strong> este tipo conlleven un beneficiotangible en el rendimiento <strong>de</strong>l sistema, espotencialmente utilizable <strong>de</strong>s<strong>de</strong> el punto <strong>de</strong> vista <strong>de</strong>simplificación <strong>de</strong>l diseño <strong>de</strong>l protocolo <strong>de</strong> coherencia.El trabajo está estructurado como sigue: la sección 2repasará el trabajo relacionado, la sección 3 presentará elentorno y metodología <strong>de</strong> evaluación, la sección 4presentará los resultados más significativos y la sección5 mostrará las conclusiones más relevantes.II. TRABAJO RELACIONADOPara obtener alto rendimiento en los sistemas, losprotocolos <strong>de</strong> coherencia han <strong>de</strong> ser capaces <strong>de</strong> permitirmúltiples peticiones pendientes por procesador yposibilitar la ejecución <strong>de</strong> operaciones concurrentes.Esto supone la aparición <strong>de</strong> numerosos estadostransitorios y <strong>de</strong> un comportamiento altamente complejo<strong>de</strong> <strong>de</strong>terminar que dificulta enormemente el trabajo <strong>de</strong>los arquitectos que los diseñan y verifican, conduciendoocasionalmente a comportamientos imprevisibles <strong>de</strong> lossistemas, que tienen un alto impacto económico.Por esta razón, van apareciendo trabajos dirigidos asimplificar el diseño y la verificación <strong>de</strong> dichosprotocolos, incluso a costes elevados. En atomiccoherence [1] por ejemplo, las peticiones simultáneas auna misma dirección <strong>de</strong> memoria se serializan con unmutex óptico antes <strong>de</strong> ser emitidas. De esta manera seasegura la eliminación <strong>de</strong> carreras y por lo tanto seconsigue simplificar consi<strong>de</strong>rablemente el protocolo <strong>de</strong>coherencia. También con el fin <strong>de</strong> facilitar la validación<strong>de</strong> los protocolos, en fractal coherence [2] se proponeuna nueva metodología en el diseño <strong>de</strong> arquitecturas,para así po<strong>de</strong>r manejar protocolos <strong>de</strong> coherenciafácilmente verificables mediante un comportamientofractal.Es precisamente esta necesidad <strong>de</strong> optimización <strong>de</strong> losprotocolos <strong>de</strong> coherencia la que está llevando a muchosarquitectos a hacer partícipe a la red <strong>de</strong> interconexiónen el protocolo <strong>de</strong> una u otra manera.Por un lado es posible añadir nuevas funcionalida<strong>de</strong>s alos routers o encaminadores tal y como hacen enSwitchMSHR [3] don<strong>de</strong> se aña<strong>de</strong>n varios registros parapeticiones pendientes (Miss Status Holding Registers) encada router <strong>de</strong> la red, con el fin <strong>de</strong> mantener unseguimiento <strong>de</strong> las lecturas y conseguir repartir el dato aleer cuando hay más <strong>de</strong> una petición pendientesimultánea.Otro papel que pue<strong>de</strong> llevar a cabo la red es la <strong>de</strong>realizar en ella la or<strong>de</strong>nación <strong>de</strong> mensajes. Ejemplostales como timestamp snooping [4] o INSO [5],consiguen or<strong>de</strong>nar los mensajes en los routerspermitiendo la evitación <strong>de</strong> carreras y por lo tantosimplificando el protocolo, aunque obviamente a costa<strong>de</strong>l rendimiento.En in-network cache coherence [6], los encaminadoresmantienen una estructura lógica que va uniendo loscompartidores <strong>de</strong> un dato con el fin <strong>de</strong> redireccionar lasnuevas peticiones hacia don<strong>de</strong> está dicho dato. Estapropuesta es <strong>de</strong>pendiente <strong>de</strong>l recorrido que realizan laspeticiones. Eliminando esta <strong>de</strong>pen<strong>de</strong>ncia, virtual treecoherence [7] también mantiene un seguimiento <strong>de</strong> loscompartidores <strong>de</strong> un dato pero sólo los <strong>de</strong> una regiónamplia y empleando las propieda<strong>de</strong>s <strong>de</strong>l árbol virtualpara forzar el or<strong>de</strong>n entre las peticiones. De las mismasautoras que el anterior trabajo, también proviene lapropuesta <strong>de</strong> emplear la red <strong>de</strong> interconexión para filtrarlos mensajes enviados en broadcast por el protocolo <strong>de</strong>coherencia. Aña<strong>de</strong>n en los routers filtros quedinámicamente rastrean patrones <strong>de</strong> compartición entrevarios cores. De esta forma, es posible eliminarpeticiones redundantes que se están dirigiendo haciazonas don<strong>de</strong> no hay compartidores, consiguiendo conello una reducción en la energía consumida [8].En <strong>de</strong>finitiva, cada vez parece más claro que, dada laenorme sinergia existente entre la red <strong>de</strong> interconexión yel resto <strong>de</strong> la jerarquía <strong>de</strong> memoria, resultaráimprescindible hacerla participe en las tareas propias <strong>de</strong>lprotocolo con el fin <strong>de</strong> mejorar el rendimiento <strong>de</strong>lsistema completo o simplificar el proceso <strong>de</strong> diseño <strong>de</strong>los protocolos <strong>de</strong> coherencia. No obstante, previamentees imprescindible <strong>de</strong>tallar los aspectos sobre los que lared podría incidir para obtener dicha mejora.III. ENTORNO Y METODOLOGÍA DE EVALUACIÓNComo ya se ha mencionado anteriormente, el análisispresentado en este trabajo preten<strong>de</strong> ayudar a compren<strong>de</strong>rmejor el comportamiento real <strong>de</strong> las aplicacionesejecutadas en un CMP con el fin <strong>de</strong> encontrar el modoen el que la red <strong>de</strong> interconexión pueda colaborar <strong>de</strong> unamanera directa en el protocolo <strong>de</strong> coherencia. Dentro <strong>de</strong>este análisis se pue<strong>de</strong>n distinguir dos visiones condiferentes perspectivas. Por una parte se ha analizado <strong>de</strong>qué manera son vistas las peticiones <strong>de</strong> los procesadorespor la red <strong>de</strong> interconexión, centrándonos especialmenteen la simultaneidad temporal <strong>de</strong> esas peticiones. Por otraparte, parece necesario conocer el comportamiento <strong>de</strong>las aplicaciones estudiadas <strong>de</strong>s<strong>de</strong> el punto <strong>de</strong> vista <strong>de</strong> lasinstrucciones <strong>de</strong> sincronización y comprobar que dichocomportamiento es coherente con los resultadosanteriores.El sistema con el que trabajaremos, a lo largo <strong>de</strong> todoel análisis, es un CMP con 8 procesadores conectadosmediante una red <strong>de</strong> interconexión en malla 4×4. <strong>La</strong>jerarquía <strong>de</strong> memoria tiene 2 niveles <strong>de</strong> cache. Unprimer nivel privado para cada procesador con L1 <strong>de</strong>datos y <strong>de</strong> instrucciones, <strong>de</strong> 128 KB cada uno. A<strong>de</strong>más,se dispone <strong>de</strong> un segundo nivel <strong>de</strong> cache compartidadividida en 16 bancos <strong>de</strong> 512 KB cada uno. El protocolo<strong>de</strong> coherencia empleado es un protocolo basado entokens [9] optimizado. En la Fig. 1 se muestra unesquema <strong>de</strong>l sistema simulado.<strong>JP2011</strong>-268


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 1 Esquema general <strong>de</strong>l sistema simulado compuesto por 8 coresy 16 bancos <strong>de</strong> L2 interconectados mediante routers (R) en unamalla 4×4.El entorno <strong>de</strong> simulación en el que hemos trabajadoconsta <strong>de</strong> tres simuladores: Simics [10], GEMS [11] ySICOSYS [12]. Con GEMS es posible simular elsistema <strong>de</strong> memoria completo. Por su parte, SICOSYSnos permite simular, <strong>de</strong> manera <strong>de</strong>tallada, elcomportamiento <strong>de</strong> la red <strong>de</strong> interconexión.Con el primer conjunto <strong>de</strong> pruebas se ha <strong>de</strong>terminadola cantidad <strong>de</strong> peticiones a la misma dirección <strong>de</strong>memoria que se realizan <strong>de</strong> forma simultánea por dos omás procesadores y cuáles se realizan <strong>de</strong> forma única.Para conocer este dato, se han implementado enSICOSYS dos estructuras globales y accesibles paratodos los componentes <strong>de</strong> la red. Su cometido principales mantener anotadas todas las peticiones que tienenpendientes los procesadores <strong>de</strong>l sistema, <strong>de</strong> manerasimilar a lo que hace un MSHR <strong>de</strong>ntro <strong>de</strong>l procesador,pero a nivel <strong>de</strong> red. Una <strong>de</strong> estas estructuras se utilizapara anotar las peticiones <strong>de</strong> lectura pendientes y la otrapara mantener las peticiones <strong>de</strong> escritura. Nosreferiremos a cada una <strong>de</strong> ellas como pending_reads_map y pending_writes_map para las lecturas yescrituras respectivamente. Cada entrada <strong>de</strong> estas dosestructuras contiene la dirección <strong>de</strong> memoria a la que sequiere acce<strong>de</strong>r y un contador que indica el número <strong>de</strong>procesadores con esa petición pendiente por resolver.Cuando un procesador <strong>de</strong>sea hacer una operación <strong>de</strong>lectura o <strong>de</strong> escritura se comprueba en la L1 privada siexiste el bloque necesario. Si no está presente, elcontrolador <strong>de</strong> L1 envía un broadcast <strong>de</strong> la peticiónincluyendo como <strong>de</strong>stinatarios <strong>de</strong>l mensaje al resto <strong>de</strong>controladores <strong>de</strong> L1, al controlador <strong>de</strong> L2 y alcontrolador <strong>de</strong> memoria principal. En el momento en elque se inyecta el mensaje en la red, se aña<strong>de</strong> la direcciónque está siendo solicitada en el pending_mapcorrespondiente según el tipo <strong>de</strong> petición y seincrementa el número <strong>de</strong> peticiones pendientes.Posteriormente se almacena en un histograma el número<strong>de</strong> peticiones pendientes <strong>de</strong>l mismo tipo (lectura oescritura) que ha encontrado en la red y, en otro<strong>JP2011</strong>-269histograma, cuántas peticiones pendientes hay a esadirección <strong>de</strong> memoria global (tanto <strong>de</strong> lectura como <strong>de</strong>escritura). En el momento en el que una petición seresuelve, es <strong>de</strong>cir, el controlador <strong>de</strong> L1 recibe el bloqueque había solicitado y por lo tanto el procesador pue<strong>de</strong>llevar a cabo la operación pendiente, se <strong>de</strong>crementa elcontador correspondiente a esa dirección en elpending_map. De esta manera cuantificamos lasincronicidad en el acceso a los datos compartidos porparte <strong>de</strong> los diversos procesadores.Con estos cálculos, se preten<strong>de</strong> saber cuánto podríaayudar la red <strong>de</strong> interconexión a resolver peticionessimultáneas si se dispusiese <strong>de</strong> la información necesariaalmacenada en los encaminadores.Por otra parte, en paralelo con la monitorización <strong>de</strong> lared <strong>de</strong> interconexión, se ha llevado a cabo un análisissobre el comportamiento <strong>de</strong> sincronización <strong>de</strong> lasaplicaciones bajo estudio para tener un conocimientomás <strong>de</strong>tallado sobre las instrucciones que se ejecutan enlas aplicaciones empleadas y comprobar que losresultados que “ve” la red son coherentes con dichoscomportamientos <strong>de</strong> las aplicaciones. Para llevar caboesta tarea se ha analizado el código <strong>de</strong> sincronizaciónque se ejecuta en cada una <strong>de</strong> las aplicaciones,entendiendo como código <strong>de</strong> sincronización el conjunto<strong>de</strong> instrucciones atómicas ejecutadas e instrucciones <strong>de</strong>acceso a las secciones criticas (Test and Test-and-Set).Esta simplificación es <strong>de</strong>bida a que, <strong>de</strong>terminar el total<strong>de</strong> código <strong>de</strong> sincronización es una tarea compleja, yaque los bloques <strong>de</strong> sincronización tienen estructuras muydiferentes en función <strong>de</strong> si se ejecutan en modo usuarioo supervisor. Por esta razón es necesario aplicar distintastécnicas conjuntamente. Para realizar la instrumentación<strong>de</strong> dichas aplicaciones se ha utilizado el módulo tracer<strong>de</strong>l simulador Simics. Este módulo nos permite acce<strong>de</strong>ra los 32 bits que componen cualquier instrucción <strong>de</strong> laarquitectura SPARC y clasificarla para su posterioranálisis. A<strong>de</strong>más, Simics proporciona una función paradiscernir entre las instrucciones ejecutadas en modosupervisor y las ejecutadas en modo usuario.TABLA 1. CONFIGURACIÓN DEL SISTEMA EMPLEADO.Núm. <strong>de</strong> procesadores8 @3GHzNúm. peticiones pendientes 16Ventana <strong>de</strong> instrucción /Issue Width128/4-wayTamaño <strong>de</strong>l bloque 64 BTamañoL1 (instrucciones y datos)128 KBAsociatividad 4Tiempo <strong>de</strong> acceso (ciclos) 2Tamaño 512 KBx16banksL2 Asociatividad 16Tiempo <strong>de</strong> acceso (ciclos) 5Red Topología Malla 4×4En la arquitectura SPARC [13] se pue<strong>de</strong>n distinguirdos tipos <strong>de</strong> instrucciones atómicas utilizadas para lasincronización y la actualización <strong>de</strong> memoria llevada a


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011cabo por procesos concurrentes: Load-Store UnsignedByte (LdStUB) y Compare-and-Swap (CaS) 1 . <strong>La</strong>primera instrucción es la primitiva atómica originalempleada en el sistema operativo Solaris paraimplementar los locks exclusivos. Básicamente es laclásica instrucción test-and-set que recoge el valor <strong>de</strong> unbyte <strong>de</strong> una dirección <strong>de</strong> memoria en un registro yescribe 0xFF en dicha dirección. Como es sabido, lalimitación <strong>de</strong> esta instrucción es que, <strong>de</strong> forma wait-free,únicamente pue<strong>de</strong> resolver la contención <strong>de</strong> dosprocesos. Por el contrario, la instrucción CAS lo pue<strong>de</strong>hacer con un número ilimitado <strong>de</strong> ellos. Esta instrucciónemplea una dirección <strong>de</strong> memoria y dos registros. Alejecutarse compara una palabra en memoria con uno <strong>de</strong>los registros, si son iguales, la instrucción intercambia elcontenido <strong>de</strong> la palabra <strong>de</strong> memoria con el segundoregistro. Ambas instrucciones han sido rastreadasdurante la ejecución.A<strong>de</strong>más <strong>de</strong> estas instrucciones atómicas, es necesarioi<strong>de</strong>ntificar el resto <strong>de</strong> código <strong>de</strong>dicado a lasincronización para el acceso único a las seccionescríticas. Debido a la complejidad que supone diferenciartodas las instrucciones <strong>de</strong>dicadas a sincronización,contabilizaremos únicamente como tales, las lecturas auna dirección física <strong>de</strong> memoria que es accedida por unainstrucción atómica.IV.EVALUACIÓN DE LOS RESULTADOSA. Cargas <strong>de</strong> trabajoComo se ha mencionado, para la obtención <strong>de</strong> losresultados se ha utilizado un entorno <strong>de</strong> simulaciónbasado en el simulador funcional Simics, junto conGEMS y Sicosys.Los resultados han sido obtenidos <strong>de</strong> la ejecución <strong>de</strong> 18cargas <strong>de</strong> trabajo diferentes, que son las mostradas en laTabla 2. Correspon<strong>de</strong>n a tres benchmarks <strong>de</strong>l tipocliente-servidor, que forman parte <strong>de</strong> la WisconsinCommercial Workload Suite [14]; las aplicacionesnuméricas <strong>de</strong> enteros <strong>de</strong> los NAS ParalellBenchmarks[15]; cuatro <strong>de</strong> las aplicaciones <strong>de</strong> la suitePARSEC [16]; y, por último, tres aplicacionesmultiprogramadas <strong>de</strong> la suite SPEC CPU2006 [17]. Estenúmero alto <strong>de</strong> aplicaciones proporciona una granvariedad <strong>de</strong> comportamientos, consiguiendo analizar lasimultaneidad <strong>de</strong> las peticiones en aplicaciones muyCliente-servidor(WisconsinCommercial Suite)NUMÉRICASCargasmultiprogramadasTABLA 2. CARGAS DE TRABAJO UTILIZADASApache Jbb ZeusNAS BT CGFTISLU MGSP UAPARSECBlackscholes CannealFluidanimate SwaptionsAstar Hmmer Lbmdiferentes, con distinto grado <strong>de</strong> compartición,contención, tamaño <strong>de</strong>l problema, etc.B. ResultadosA continuación se muestran los resultados obtenidos.En la Fig. 2 se representa el porcentaje <strong>de</strong> peticiones <strong>de</strong>lectura (GETS) y <strong>de</strong> escritura (GETX) que realizan doso más procesadores simultáneamente en cada una <strong>de</strong> lasaplicaciones consi<strong>de</strong>radas.Lo primero que llama la atención <strong>de</strong> estos resultadoses la poca simultaneidad temporal que existe, es <strong>de</strong>cir,en la gran mayoría <strong>de</strong> las aplicaciones, prácticamente el100% <strong>de</strong> las peticiones sobre una dirección <strong>de</strong> memoriaque se realizan son únicas y no hay ningún otroprocesador que necesite también acce<strong>de</strong>r a ella al mismotiempo. <strong>La</strong> aplicación que tiene este porcentaje más bajo<strong>de</strong> peticiones únicas es swaptions, don<strong>de</strong> el 94 % <strong>de</strong> laslecturas son únicas y el 96% <strong>de</strong> las escrituras también.En esta aplicación, el 4% <strong>de</strong> los misses en L1, provocanuna petición al resto cuando hay otro procesador másque también quiere el mismo dato. En menor medida, un1%, otros misses coinci<strong>de</strong>n en la red con otros dosprocesadores. De las PARSEC también <strong>de</strong>staca, sobrelas <strong>de</strong>más, las escrituras simultáneas entre dosprocesadores <strong>de</strong> la aplicación fluidanimate que tambiénalcanzan el 2% <strong>de</strong> las escrituras globales. En el ladocontrario se encuentra canneal, don<strong>de</strong> la ejecución <strong>de</strong>cada procesador se mantiene in<strong>de</strong>pendiente <strong>de</strong> los <strong>de</strong>mása pesar <strong>de</strong> que su gran working set es activamentecompartido. Esto ocurre <strong>de</strong>bido a que tan solo unapequeña porción <strong>de</strong> él entra en la cache haciendo que laprobabilidad <strong>de</strong> que una línea sea accedida por más <strong>de</strong>un procesador antes <strong>de</strong> ser reemplazada sea muy baja.En cuanto a las aplicaciones numéricas, todasmuestran también muy poca simultaneidad en cuanto alas direcciones <strong>de</strong> memoria accedidas. Esto ocurreporque a pesar <strong>de</strong> ser aplicaciones muy <strong>de</strong>mandantes<strong>de</strong>s<strong>de</strong> el punto <strong>de</strong> vista <strong>de</strong> la red <strong>de</strong> interconexión, cadauna <strong>de</strong> las peticiones realizadas son in<strong>de</strong>pendientes <strong>de</strong>lresto. Se aprecia alguna excepción como mg o cg don<strong>de</strong>hay un porcentaje mayor <strong>de</strong> escrituras simultáneas pero,<strong>de</strong> nuevo, no llegan a alcanzar ni el 2% <strong>de</strong> todas laspeticiones que se realizan a lo largo <strong>de</strong> la ejecución.También bt por su parte muestra un número elevado <strong>de</strong>lecturas simultáneas, indicando que sí existen datosaccedidos por más <strong>de</strong> un procesador en el mismointervalo <strong>de</strong> tiempo.Los datos no resultan nada sorpren<strong>de</strong>ntes en lasaplicaciones multiprogramadas, don<strong>de</strong> el grado <strong>de</strong>compartición es prácticamente nulo y por lo tanto sí eraesperable obtener valores cercanos a cero en estosbenchmarks.Los que sí resultan algo más sorpren<strong>de</strong>ntes son losresultados obtenidos <strong>de</strong> la ejecución <strong>de</strong> las aplicacionescliente-servidor. Estas son aplicaciones con un altogrado <strong>de</strong> compartición y se podría esperar queapareciesen muchas operaciones simultáneas <strong>de</strong> losdistintos procesadores. Sin embargo, la Fig. 2 muestraclaramente como el acceso a las direcciones <strong>de</strong> memoriallevado a cabo por los distintos procesadores, nocoinci<strong>de</strong>n en el tiempo en el sistema analizado.1 Existe una tercera instrucción atómica Swap pero que está obsoleta yse mantiene por compatibilidad.<strong>JP2011</strong>-270


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011%65432108 7 6 5 4 3 2GETSGETXGETSGETXastar hmmer lbm bt cg ft is lu mg sp ua apache jbb zeus blacks cann fluid swapt AVGFig. 2 Porcentaje <strong>de</strong> peticiones <strong>de</strong> lectura y escritura que se realizan simultáneamente en el tiempo.%10.1AtómicasSincronización0.010.0010.00010.00001Fig. 3 Porcentaje <strong>de</strong> instrucciones <strong>de</strong> sincronización y atómicas <strong>de</strong>l total <strong>de</strong> instrucciones ejecutadas. (Porcentaje en eje Y en escala logarítmica)Si cambiamos el punto <strong>de</strong> vista y pasamos a analizarlas instrucciones <strong>de</strong> sincronización ejecutadas por cadaprocesador po<strong>de</strong>mos comprobar que son totalmentecoherentes con los resultados mostrados anteriormente.En la Fig. 3 se muestran los porcentajes <strong>de</strong>instrucciones atómicas e instrucciones <strong>de</strong> sincronizaciónejecutadas en cada aplicación. Nótese que losporcentajes <strong>de</strong>l eje Y están en escala logarítmica con elfin <strong>de</strong> po<strong>de</strong>r ver los valores mínimos <strong>de</strong> sincronizaciónque tienen algunas <strong>de</strong> las aplicaciones. Los valores sonla media <strong>de</strong> los 8 procesadores. En el caso <strong>de</strong> lasaplicaciones numéricas, las instrucciones <strong>de</strong>sincronización son muy bajas, excepto en el caso <strong>de</strong> cg y<strong>de</strong> mg que sí se muestra algo más <strong>de</strong> sincronización perono se llega a alcanzar ni el 0.1% <strong>de</strong>l total <strong>de</strong>instrucciones ejecutadas. Para las aplicaciones clienteservidorse pue<strong>de</strong> ver como en todas ellas hay unporcentaje bastante más alto <strong>de</strong> instrucciones <strong>de</strong>sincronización y atómicas. Esto parece no concordar conlos datos <strong>de</strong> las peticiones simultáneas <strong>de</strong> la Fig. 1,don<strong>de</strong> no se veía simultaneidad en la petición. Sinembargo, la cantidad <strong>de</strong> instrucciones atómicas esprácticamente la misma que la cantidad <strong>de</strong> instrucciones<strong>de</strong> sincronización, lo que significa que, durante laejecución <strong>de</strong> las aplicaciones, hay muy poca contenciónen el acceso a las secciones críticas. Igualmente, estecomportamiento se pue<strong>de</strong> comprobar en el caso <strong>de</strong> lasPARSEC, don<strong>de</strong> también se llega a apreciar un númeroalto, en comparación con la mayoría, <strong>de</strong> instrucciones<strong>de</strong> sincronización. En el caso <strong>de</strong> canneal, la proporción<strong>de</strong> instrucciones <strong>de</strong> sincronización y atómicas esprácticamente la misma, indicando que apenas hayconflictos en los accesos a la entrada <strong>de</strong> las seccionescríticas y, por lo tanto, sin simultaneidad en las<strong>JP2011</strong>-271direcciones <strong>de</strong> memoria a las que se acce<strong>de</strong>n. En el ladoopuesto se encuentra swaptions, don<strong>de</strong> casi el 90% <strong>de</strong> lasincronización está <strong>de</strong>dicada a los intentos <strong>de</strong> acceso alas secciones críticas, indicando que sí existen másocasiones en las que hay operaciones simultáneas entremás <strong>de</strong> un procesador siendo coherente con lo observado<strong>de</strong>s<strong>de</strong> el punto <strong>de</strong> vista <strong>de</strong> simultaneidad <strong>de</strong> lasoperaciones en memoria.In<strong>de</strong>pendientemente <strong>de</strong> los casos individuales <strong>de</strong> cadaaplicación, lo más importante <strong>de</strong> los resultadosmostrados en este trabajo es la escasa coinci<strong>de</strong>nciatemporal en el acceso a los datos. Des<strong>de</strong> el punto <strong>de</strong>vista <strong>de</strong>l protocolo <strong>de</strong> coherencia, <strong>de</strong> media, el 99% <strong>de</strong>las peticiones que se envían, lo hacen <strong>de</strong> forma única ysin existir otro procesador que quiera acce<strong>de</strong>r a la mismadirección <strong>de</strong> memoria.V. CONCLUSIONES Y TRABAJO FUTUROAnalizados los resultados obtenidos, parece claro que,al no producirse solapamiento en el momento <strong>de</strong> enviarlas peticiones, implementar cualquier mecanismo en lared <strong>de</strong> interconexión con el objetivo <strong>de</strong> resolver posiblesconflictos <strong>de</strong> acceso a datos compartidos que ocurran enese momento, no parece que vaya a tener ningún efectoen el rendimiento <strong>de</strong> los sistemas puesto que esassituaciones son muy escasas.Por esta razón, y viendo que la mayoría <strong>de</strong> laspeticiones son únicas, la participación <strong>de</strong> la red en elprotocolo <strong>de</strong> coherencia <strong>de</strong>berá dirigirse hacia laaceleración en la localización <strong>de</strong>l dato, minimizando conella la latencia <strong>de</strong> los misses. Si se aña<strong>de</strong> información alos encaminadores sobre la distribución <strong>de</strong> los datos queestán siendo compartidos sería posible redireccionar


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011peticiones hacia don<strong>de</strong> la red conoce bien la últimaubicación <strong>de</strong>l dato o bien la más cercana, <strong>de</strong>pendiendo<strong>de</strong> la acción a realizar.Por último, sigue abierta la posibilidad <strong>de</strong> añadirfuncionalida<strong>de</strong>s <strong>de</strong> filtrado, evitando el envío <strong>de</strong>mensajes hacia regiones don<strong>de</strong> la red podría conocer queno se encuentra el dato requerido.[17] SPEC Standard Performance Evaluation Corporation, “SPEC2006.”AGRADECIMIENTOSEl presente trabajo ha sido financiado mediante elproyecto MICINN TIN2010-18159 y la red <strong>de</strong>excelencia europea HiPEAC.REFERENCIAS[1] D. Vantrease and N. Binkert, “Atomic Coherence : LeveragingNanophotonics to Build Race-Free Cache CoherenceProtocols,” HPCA - 17 2011 The Seventeenth InternationalSymposium on High-Performance Computer Architecture, 2011,pp. 132-143.[2] M. Zhang, A.R. Lebeck, and D.J. Sorin, “Fractal Coherence:Scalably Verifiable Cache Coherence,” 2010 43rd AnnualIEEE/ACM International Symposium on Microarchitecture,Dec. 2010, pp. 471-482.[3] L.N. Bhuyan and H. Wang, “Switch MSHR : A Technique toReduce Remote Read Memory Access Time in CC-NUMAMultiprocessors,” IEEE Comput. Soc, vol. 52, 2003, pp. 1-16.[4] M.M.K. Martin, D.J. Sorin, A. Ailamaki, A.R. Alamel<strong>de</strong>en,R.M. Dickson, C.J. Mauer, K.E. Moore, M. Plakal, M.D. Hill,and D.A. Wood, “Timestamp Snooping : An Approach forExtending SMPs,” ASPLOS-IX - Architetural Support forProgramming <strong>La</strong>nguages and Operating Systems, 2000, pp. 1-12.[5] N. Agarwal, L.-S. Peh, and N.K. Jha, “In-Network SnoopOr<strong>de</strong>ring (INSO): Snoopy coherence on unor<strong>de</strong>redinterconnects,” 2009 IEEE 15th International Symposium onHigh Performance Computer Architecture, Feb. 2009, pp. 67-78.[6] N. Eisley, L.-S. Peh, and L. Shang, “In-Network CacheCoherence,” International Symposium on Microarchitecture,2006.[7] N.D. Enright Jerger, L.-S. Peh, and M.H. Lipasti, “Virtual treecoherence: Leveraging regions and in-network multicast treesfor scalable cache coherence,” 2008 41st IEEE/ACMInternational Symposium on Microarchitecture, Nov. 2008, pp.35-46.[8] N. Agarwal, L.-shiuan Peh, and N.K. Jha, “In-NetworkCoherence Filtering : Snoopy Coherence without Broadcasts,”Ieee Micro, 2009.[9] M.M.K. Martin, M.D. Hill, and D.A. Wood, “Token Coherence:a new framework for shared-memory multiprocessors,” IeeeMicro, vol. 23, 2003, pp. 108-116.[10] Virtutech, “Simics : A Full System Simulation Platform,” IEEE,2002.[11] M.M.K. Martin, D.J. Sorin, B.M. Beckmann, M.R. Marty, M.Xu, A.R. Alamel<strong>de</strong>en, K.E. Moore, M.D. Hill, and D.A. Wood,“Multifacet’s General Execution-driven MultiprocessorSimulator (GEMS) Toolset,” Computer Architecture News,2005.[12] V. Puente, J.A. Gregorio, and R. Beivi<strong>de</strong>, “SICOSYS: AnIntegrated Framework for Studying Interconnection NetworkPerformance in Multiprocessor Systems,” IEEE Comput. Soc,2002, pp. 15-22.[13] D.L. Weaver, “The SPARC Architecture Manual,” Control,1994.[14] A.R. Alamel<strong>de</strong>en, M.M.K. Martin, C.J. Mauer, K.E. Moore, M.Xu, M.D. Hill, D. Wood, and D.J. Sorin, “Simulating a $2MCommercial Server on a $2K PC,” Computer, vol. 36, 2003, pp.50-57.[15] H. Jin, M. Frumkin, and J. Yan, “The OpenMP Implementationof NAS Parallel Benchmarks and its Performance,” NASTechnical Report NAS-99-011, NASA Ames Research Center,Moffett Field, CA, 1999.[16] C. Bienia and K. Li, “PARSEC 2 . 0 : A New Benchmark Suitefor Chip-Multiprocessors,” MoBS, 2009.<strong>JP2011</strong>-272


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Conversion between DPD and RBCD foron-line arithmetic computationSonia González, Carlos García, Julio Villalba. 1Summary— In recent years <strong>de</strong>cimal arithmetic hasgained renewed interest with the ratification of theIEEE 754-2008 Floating-point Standard. It specifiesformats for Decimal Floating-point (DFP) numbersand uses Densely Packed Decimal (DPD) encoding tostore the significand of a DFP number. However, toperform <strong>de</strong>cimal arithmetic operations, DPD conversionsto Binary Co<strong>de</strong>d Decimal (BCD) are nee<strong>de</strong>d. Inor<strong>de</strong>r to <strong>de</strong>al with on-line arithmetic it is necessaryto use redundant number representation which preventsthe carry propagation and allows the computationstarting from the most significant digit (MSD). Inthis paper we consi<strong>de</strong>r the Redundant Binary Co<strong>de</strong>dDecimal (RBCD) encoding and presents the <strong>de</strong>sign ofa DPD converter to RBCD representation for <strong>de</strong>cimalon-line arithmetic units. The direct conversionproposed in this paper (DPD to RBCD) supposes animprovement over the two steps conversion requiredby a regular computation (DPD to BCD and BCD toRBCD).Keywords— conversion, <strong>de</strong>cimal floating-point, onlinearithmetic, <strong>de</strong>nsely packed <strong>de</strong>cimal, redundantbinary co<strong>de</strong>d <strong>de</strong>cimal.I. IntroductionDECIMAL arithmetic is present nowadaysthanks to the ratification of the IEEE 754-2008Floating-point Standard. During last years therehave been a lot of activities in the <strong>de</strong>sign of specific<strong>de</strong>cimal arithmetic units. In fact, processors suchas IBM Power6, Power7, z9 and z10 [10], [5], [11]inclu<strong>de</strong> <strong>de</strong>cimal floating-point units.The standard inclu<strong>de</strong>s two basic formats for DecimalFloating-point (DFP) numbers and specifies twoencodings for DFP significands known as the <strong>de</strong>cimaland the binary encoding. The <strong>de</strong>cimal encoding usesthe Densely Packed Decimal (DPD) [3] encoding toenco<strong>de</strong> the significand. The main drawback of DPDencoding is that it is not easy to perform computationswith it. To resolve this problem, a DPDnumber is converted to Binary Co<strong>de</strong>d Decimal representation(BCD) and the operations are carried outusing this representation. Most of the recent proposed<strong>de</strong>cimal arithmetic units based on DPD encoding[4], [14], [15], [16], [8], [9], [7] are <strong>de</strong>signedassuming this conversion. On the other hand, onlinearithmetic is based on serial computation startingfrom the Most Significant Digit (MSD). To avoidthe chain of carries a redundant representation of thenumbers is used in on-line arithmetic [6]. RedundantBinary Co<strong>de</strong>d Decimal (RBCD) [13] is a redundant<strong>de</strong>cimal representation where the BCD digits from 0to 9 are represented with the digit set is {-7,...,7}.In or<strong>de</strong>r to work with <strong>de</strong>cimal on-line units twosteps are nee<strong>de</strong>d to convert from DPD to RBCD:1 Dept. Computer Architecture, University of Málaga, e-mail: sonia,cgarcia,julio@ac.uma.esa conversion from DPD to BCD and from BCD toRBCD. Although the DPD to BCD conversion is fastin hardware, the BCD to RBCD conversion impliesthe chain of a carry between digits. In this paper,we propose a direct conversion DPD to RBCD by thefusion of the tables and equations involved by the twosteps conversion, achieving a faster algorithm.The rest of the paper is organized as follows. SectionII <strong>de</strong>scribes the DFP formats specified in theIEEE 754-2008 standard. Section III <strong>de</strong>als with theRedundant Binary Co<strong>de</strong>d Decimal numbers and theon–line arithmetic requirements. Section IV presentsthe direct conversion from DPD to RBCD. SectionV examines the implementation results, and finally,Section VI presents the summary and conclusions ofthis work.II. Decimal Floating-Point formatDue to the importance of DFP arithmetic, IEEE<strong>de</strong>veloped its standard for floating-point arithmetic[1] by including specifications for DFP formats andoperations [1]. With IEEE 754-2008, the value of afinite DFP number, x, is:(−1) Sx × C x × 10 Ex−biaswhere S x is the sign bit, E x is a biased exponent,bias is a constant value that makes E x non-negative,and C x is the significand, which is also referred toas the coefficient. IEEE 754-2008 <strong>de</strong>fines two basicDFP formats, <strong>de</strong>cimal64 and <strong>de</strong>cimal128, withencodings lengths of 64 and 128 bits, respectively.These formats are used to represent a finite subset ofreal numbers including finite numbers, signed infinitiesand two different types of Not-a-Numbers (qNaNand sNaN). In addition, the Standard specifies twoencodings for DFP significands; (1) a binary encoding,known as Binary Integer Decimal (BID), and(2) a <strong>de</strong>cimal encoding, known as Densely PackedDecimal (DPD). With the BID encoding, the significandis represented using an unsigned binary integer.With the DPD encoding the significand is representedusing an unsigned <strong>de</strong>cimal integer, in which three<strong>de</strong>cimal digits are encoding using ten bits [3]. Witheither encoding, the significand of a DFP number isnot normalized, which means that a single DFP numbermay have multiple representations. More <strong>de</strong>tailson the DFP formats and operations are provi<strong>de</strong>d in[1].III. Redundant Binary Co<strong>de</strong>d DecimalnumbersOn–line arithmetic <strong>de</strong>fines algorithms for serialarithmetic operators that receive the inputs and ge-<strong>JP2011</strong>-273


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011nerate the output starting from the most-significantdigit (MSD first). The serial approach is advantageousbecause of the simplicity of the hardware andthe reduction in number and length of connectionsamong modules. Moreover, the MSD first alternativeallows the implementation of operations, such asdivision and square root, which are difficult to implementleast-significant digit first. The drawback ofthe serial approach is the number of cycles required;however, this can be compensated by the overlap ofthe execution of <strong>de</strong>pen<strong>de</strong>nt operations. Thanks toall these characteristics, on-line arithmetic is suitablefor VLSI implementation.vwxstp·q·r (abcd) C out0---- 0100-- 0 a=0 0101-- 0 (bcd) = (pqr) + C in011110 00---- 1100-- 1 a = 1, b = 1 1101-- 1 c = C in0 , d = C in011110 1110-- -11000 - a = r · C in0 , b = r · C in0 111101 - c = r · C in0 , d = r ⊕ C in011111 -TABLE IObtaining (abcd)Xvwxst p·q·u s·t·u (efgh) C out0---- - 0e = 0100-- - 0 (fgh) = (stu) + Cin1110-- - 0011101 0 -e = 0(fgh) = (pqu) + C in100---- - 1100-- - 1 e = 1, f = 1110-- - 1 g = C in1 , h = C in1111101 1 -101-- - - e = u · C in111100 - - f = u · C in111110 - - g = u · C in1111111 - - h = u ⊕ C in1VVxvTABLE IIObtaining (efgh)vstu11Cin140 0 Cin1 s t umux+0+4pqumuxmux1 1Cin1u Cin140 0 Cin1 p q umux+0+uCin1TWWTVVVSXFig. 1.pqr1 1 Cin0Cout140 0 Cin0 p q rmux+0muxabcd+r Cin0Implementation obtaining abcdrCin0To <strong>de</strong>al with on-line arithmetic it is necessary tohave a number representation system with no carrypropagation. In this way, it is possible to performthe computation starting from the Most SignificantDigit (MSD). This is achieved by carry-save or signeddigit representations.Therefore, to <strong>de</strong>al with <strong>de</strong>cimal on-line arithmetica <strong>de</strong>cimal redundant number systems is required.The BCD co<strong>de</strong> involved in the DPD format does notfulfill this condition. Thus, a conversion step fromBCD to a redundant <strong>de</strong>cimal system is nee<strong>de</strong>d. Aco<strong>de</strong> that meets the required condition and which isSVFig. 2.Cout2efghImplementation obtaining efghdirectly related to BCD co<strong>de</strong> is the Redundant BinaryCo<strong>de</strong>d Decimal (RBCD) <strong>de</strong>fined in [2].A RBCD number is composed by digits of 4bits which represent 15 numbers in the range{−7, −6, ...0...6, 7}. It is a signed digit representationsuch as a positive number is co<strong>de</strong>d as naturalbinary whereas a negative number is co<strong>de</strong>d as two‘scomplement. This co<strong>de</strong> allows the computation withno carry propagation for the <strong>de</strong>cimal addition [2],substraction, multiplication and division [12].The conversion between BCD and RBCD can beperformed with no carry propagation whereas theopposite conversion involves a borrow propagation.Fortunately for the on–line arithmetic computation,the most critical conversion is BCD to RBCD sincethe MSD is required as soon as possible. DPD co<strong>de</strong>is only used for storage purposes and the conversionfrom RBCD to DPD is performed only when the on–line processing has finished.The conversion from BCD to RBCD is performedby a two steps algorithm [2]. In the first step we<strong>de</strong>tect if a number is greater or equal to 7 and we<strong>JP2011</strong>-274


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011vwxst w·x·y s·t·y p·q·y (ijkm) C out0---- 0 - -i = 0(jkm) = (wxy) + C in20101-- - 0 -i = 0(jkm) = (sty) + C in20110-- - - 0 i = 011100 - - 0 (jkm) = (pqy) + C in200---- 1 - -101-- - 1 - i = 1, j = 1 1110-- - - 1 k = C in2 , m = C in211100 - - 1100-- - - - i = y · C in211101 - - - j = y · C in2 111110 - - - k = y · C in211111 - - - m = y ⊕ C in2SWXTVVXVwxyST11WVXFig. 3.Cin24muxvTABLE IIIObtaining (ijkm)0 0 Cin2 w x y0 0 Cin2+1 1 Cin20 0VW+stymux4muxCout3+4muxs t y+muxijkmpqyy Cin2Implementation obtaining ijkm11Cin24yCin20 0 Cin2add the amount of 6 in such a case. This provokesan output carry. In the second step we add the inputcarry to the result of the previous operation.Let (abcd) a generic BCD digit of a BCD-co<strong>de</strong>dnumber, and C in and C out the input and outputcarries respectively. The condition for a carrygeneration is c out = a‖(b · c · d) (see [2]), where thesymbol ‖ means the logic OR operation and · is thelogical AND (notice that the carry only <strong>de</strong>pends onthe current digit bits). Thus, the conversion is:Cin0abcdCout1Fig. 4.Cin1efghCout2Cin2ijkmGlobal structure of the conversionmux+0Cout3p q y+First step:c out = a‖(b · c · d) (1){ (abcd) if cout = 0(abcd) =(2)(abcd) + (0110) if c out = 1Second step:(abcd) = (abcd) + c in (3)IV. Direct conversion from DPD to RBCDLet (pqrstuvwxy) the ten bits corresponding to aDPD co<strong>de</strong>. This co<strong>de</strong> is converted to three BCDdigits (abcd)(efgh)(ijkm), in such a way that eachbit of the three BCD digits is obtained as a booleanfunction of the DPD bits. In [1] a table conversion isprovi<strong>de</strong>d. On the other hand, conversion from BCDto RBCD is performed by implementation of equations(1) through (3). What we propose is the combinationof the table and the equations to provi<strong>de</strong> adirect table conversion, which is presented in tablesI, II and III. The resulting BCD co<strong>de</strong> is composed bythree digits namely (abcd)(efgh)(ijkm) and they aredirectly obtained from the DPD co<strong>de</strong> (pqrstuvwxy).In the tables the symbol · means the logical ANDoperation, the symbol ⊕ corresponds to the logicalEXOR operation and the symbol + is the arithmeticaddition.From these tables we can see that only logical operationsare required as well as, for some cases, onelevel of 3-bit arithmetic addition to add the inputcarry (for example, in table I for the first case, thebits (bcd) are obtained by the addition of the bits(pqr) and a carry, whereas the bit a=0. Notice thatthe maximum value of (bcd) is 6 and thus the additionof a carry never provokes an output carry). Nevertheless,the BCD to RBCD conversion proposedin [2] involves two additions.The implementation of the direct conversion isshown in Fig. 1,Fig. 2 and Fig. 3 which are relatedto Tables I, II and III respectively. The implementationof Table I requires the use of only twomultiplexers and one 3-bit ad<strong>de</strong>r, while the implementationof Table II uses four multiplexers and two3-bit parallel ad<strong>de</strong>rs, and the implementation of TableIII uses six multiplexers and three 3-bit parallelad<strong>de</strong>rs.Fig. 4 shows the global structure of the full conversion.The C in0 is the carry input coming fromthe previous conversion, and the C out3 is the carryoutput produced by the current conversion.V. Experimental resultsThe DPD to RBCD <strong>de</strong>sign presented in this paperhave been implemented in Verilog, simulated usingMo<strong>de</strong>lSim 6.0, and synthesized using Synopsys DesignCompiler and the TSMC 65nm library in whichone cell unit has an area equal to 1 µm 2 . Also,we have implemented the conversion using two steps(conversion from DPD to BCD [1] plus conversionfrom BCD to RBCD [2]). Table IV shows the implementationresults. Our approach is close to 27%<strong>JP2011</strong>-275


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011faster than the two steps algorithm. Nevertheless,our <strong>de</strong>sign requires about 58% more area than thetwo step processing.The improvement in the time of our algorithm isdue to the fact that we use only one 3-bit paralleladdition operation in comparison with the two serial4-bit additions required by the standard conversion.Notice that the table conversion from DPD to BCDinvolves only logical operations, in such a way thataddition has a high influence in the total computationtime.DPD to RBCDTime AreaTwo steps 0.0744 913Our <strong>de</strong>sign 0.0546 1449TABLE IVImplementation resultsVmx and dfu. IBM Journal of Research and Development,51:1–21, November 200u.[11] E. M. Schwarz, J. S. Kapernick, and M. F. Cowlishaw.Decimal floating-point support on the ibm system z10processor. IBM Journal of Research and Development,53(1):4:1 –4:10, 2009.[12] S.Gorgin and G. Jaberipur. Fully redundant <strong>de</strong>cimalarithmetic. In Proc. of 19th IEEE Symposium on ComputerArithmetic (ARITH 2009). IEEE Computer SocietyPress, 2009.[13] B. Shirazi, D.Y.Y. Yun, and C.N. Zhang. Rbcd: redundantbinary co<strong>de</strong>d <strong>de</strong>cimal ad<strong>de</strong>r. Computers and DigitalTechniques, IEE Proceedings E, 136(2):156 – 160, March1989.[14] L.-K. Wang and M. J. Schulte. Decimal floating-pointsquare root using Newton-Raphson iteration. In Proceedingsof IEEE International Conference on Application-Specific System, Architectures and Processors, pages309–315, July 2005.[15] L.-K. Wang and M. J. Schulte. Decimal floating-pointad<strong>de</strong>r and multifunction unit with injection-based rounding.In Proceedings of the 18th IEEE Symposium onComputer Arithmetic, Montpellier, France, June 2007.[16] L.-K. Wang and M. J. Schulte. A <strong>de</strong>cimal floating-pointdivi<strong>de</strong>r using Newton-Raphson iteration. The Journal ofVLSI Signal Processing, pages 727–739, 2007.VI. Summary and ConclusionIn this paper we have presented a direct conversionbetween DPD and RBCD which makes the computationin an on–line arithmetic system possible. Theproposed system obtains directly the RBCD digitsfrom a DPD data stream starting from the MSD.The fusion of the two steps into one reduces significativelythe computation time of the conversion with amo<strong>de</strong>rate increase of hardware.The fast conversion proposed in this paper canbenefit to all the potential <strong>de</strong>cimal on–line arithmeticalgorithms if these algorithms involve IEEE 754-2008<strong>de</strong>cimal floating point numbers.References[1] American National Standards Institute and Institute ofElectrical and Electronic Engineers. 754-2008 IEEE standardfor floating-point arithmetic,. IEEE Standard, Std754-2008, 2008.[2] D.Y.Y. Yun B. Shirazi and C.N. Zhang. RBCD: redundantbinary co<strong>de</strong>d <strong>de</strong>cimal ad<strong>de</strong>r. IEE Proceedings Computerand Digital Techniques, 136:156–160, March 1989.[3] M. F. Cowlishaw. Densely packed <strong>de</strong>cimal encoding. InIEE Proceedings - Computers and Digital Techniques,volume 149, pages 102–104, May 2002.[4] M. F. Cowlishaw. Decimal floating-point: Algorism forcomputers. In Proceedings of the 16th IEEE Symposiumon Computer Arithmetic, pages 104–111, June 2003.[5] A. Y. Duale, M. H. Decker, H.-G. Zipperer, M. Aharoni,and T. J. Bohizic. Decimal floating-point in z9: An implementationand testing perspective. IBM Journal ofResearch and Development, 51(1/2), 2007.[6] M.D. Ercegovac and T. <strong>La</strong>ng. Digital Arithmetic. MorganKaufmann, 2004.[7] Steven R. Carlough Eric M. Schwarz. Power6 <strong>de</strong>cimaldivi<strong>de</strong>. In Proceedings of the 18th IEEE Symposium onApplication-specific Systems, Architectures and Processors,2007.[8] M. A. Erle, M. J. Schulte, and B. J. Hickmann. Decimalfloating-point multiplication via carry-save addition. InProceedings of the 18th IEEE Symposium on ComputerArithmetic, 2007.[9] B. Hickmann, A. Krioukov, M. A. Erle, and M. Schulte.A parallel ieee p754 <strong>de</strong>cimal floating-point multiplier. InInternational Conference on Computer Designs, pages296–303, October 2007.[10] J. Leenstra, S. M. Mueller, C. Jacobi, J. Preiss, E. M.Schwarz, and S. R. Carlough. Ibm power6 accelerators:<strong>JP2011</strong>-276


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Multiples Puertos <strong>de</strong> Inyección en una Red enChipJesús Camacho, José Flich y José Duato 1Resumen—Presentamos una nueva topología <strong>de</strong> red en chipflexible: la NR-Mesh (Nearest neighboR Mesh). Estatopología pue<strong>de</strong> inyectar y recibir mensajes a través<strong>de</strong> varios puertos mediante diferentes conmutadores,con lo que pue<strong>de</strong> reducirse el número <strong>de</strong> saltos, asícomo el tiempo <strong>de</strong> apagado <strong>de</strong> componentes inutilizadosen la red con el ahorro <strong>de</strong> consumo que ello conlleva.A<strong>de</strong>más otros beneficios que ofrece la toplogíason: reducción <strong>de</strong> la congestión, soporte eficiente paracomunicación colectiva o tolerancia a fallos.Así mismo proponemos una técnica para ahorrarconsumo mediante un algoritmo <strong>de</strong> encaminamientoadaptativo, apagando puertos y enlaces inutilizados.Usando la topología NR-Mesh con encaminamientoadaptativo (comparado con la topología 2D-Mesh conencaminamiento <strong>de</strong>terminista) se obtiene una media<strong>de</strong> un 7% <strong>de</strong> reducción en tiempo <strong>de</strong> ejecución y unamedia <strong>de</strong> un 75% <strong>de</strong> reducción en energía consumidapara una red con 16 nodos. Resultados similares sehan obtenido para 32 nodos.Palabras clave— Re<strong>de</strong>s en chip, Topologías, Consumo,Inyección <strong>de</strong> mensajes, Tolerancia a fallos.I. IntroducciónLos chip multiprocesador <strong>de</strong> hoy día optan habitualmentepor la conexión entre sus diferentes nodosmediante una malla 2D. Cada nodo se conectaa sus vecinos en las direcciones norte, este, oestey sur. Este diseño es fácil <strong>de</strong> implementar pues sepue<strong>de</strong> obtener simplemente replicando cada tile enuna superficie plana. El problema aparece cuando eltamaño <strong>de</strong> los sistemas aumenta y por tanto la distanciaentre nodos distantes se incrementa notablementeen la malla 2D.En una malla 2D, el algoritmo <strong>de</strong> encaminamientomás eficiente (teniendo en cuenta la complejidad yel consumo) es DOR (Dimension Or<strong>de</strong>r Routing).DOR se utiliza en cada conmutador y no requiereuna lógica excesiva. Los mensajes primero se muevenen una dirección y <strong>de</strong>spués en la otra. Por ejemplo,primero X y luego Y, siempre siguiendo ruta mínima.<strong>La</strong> reducida complejidad <strong>de</strong> este algoritmo hace queesté muy extendido entre los diseñadores <strong>de</strong> re<strong>de</strong>s enchip. El problema <strong>de</strong>l mismo resi<strong>de</strong> en la poca flexibilidadque posee, ya que no es capaz <strong>de</strong> tolerarningún fallo al ofrecer una única ruta entre cada par<strong>de</strong> nodos, no siendo capaz tampoco <strong>de</strong> aliviar unasituación <strong>de</strong> congestión.Una alternativa a DOR es el uso <strong>de</strong> encaminamientoadaptativo, es <strong>de</strong>cir, los diferentes conmutadorespue<strong>de</strong>n elegir diferentes puertos <strong>de</strong> salida <strong>de</strong>pendiendo<strong>de</strong>l estado <strong>de</strong> los mismos (ocupados o no).De esta forma es posible aliviar la congestión local.Normalmente se soportan también rutas mínimas1 Grupo <strong>de</strong> Arquitecturas Paralelas, Universitat Politècnica<strong>de</strong> València, e-mail: {jecavil,jflich,jduato}@gap.upv.es.para el encaminamiento adaptativo, haciendo quecada mensaje esté cada vez más cerca <strong>de</strong> su <strong>de</strong>stino.Sin embargo ahora, la dimensión por la que se muevecada mensaje pue<strong>de</strong> cambiar más <strong>de</strong> una vez. Paraevitar ciclos es necesario proveer a la red <strong>de</strong> un canalvirtual adicional que llamamos vía <strong>de</strong> escape [5].En este artículo proponemos una topología flexiblellamada NR-Mesh (Nearest neighboR Mesh).Dicha topología permite utilizar varias rutas alternativaspara enviar cada mensaje utilizando DOR.<strong>La</strong> topología NR-Mesh es capaz <strong>de</strong> enviar y recibirmensajes a través <strong>de</strong> 4 conmutadores distintos graciasa un interfaz <strong>de</strong> red modificado que se estudia<strong>de</strong>talladamente más a<strong>de</strong>lante. A<strong>de</strong>más, la topologíaNR-Mesh posee un menor diámetro que la malla 2Dy proporciona a<strong>de</strong>más un soporte eficiente para la comunicacióncolectiva (<strong>de</strong>bido a que un mismo mensajepue<strong>de</strong> ser recibido por 4 nodos distintos <strong>de</strong>s<strong>de</strong>un mismo conmutador) y para la tolerancia a fallos(<strong>de</strong>bido a que el interfaz <strong>de</strong> red es capaz <strong>de</strong> inyectarmensajes a través <strong>de</strong> diferentes puertos hacia distintosconmutadores).<strong>La</strong> segunda propuesta que realizamos es la implementación<strong>de</strong> un algoritmo capaz <strong>de</strong> gestionarel encendido y apagado <strong>de</strong> puertos y enlaces en lared cuando no es necesario utilizarlos. El algoritmoen cuestión maximiza el tiempo en que los componentesse mantienen apagados para po<strong>de</strong>r ahorrarel máximo consumo posible sin per<strong>de</strong>r prestaciones.Para ello, se utiliza encaminamiento adaptativo ayudadopor la función <strong>de</strong> selección <strong>de</strong>l interfaz <strong>de</strong> red.El resto <strong>de</strong>l artículo se organiza <strong>de</strong> la siguienteforma. En la sección II, se <strong>de</strong>scribe el estado <strong>de</strong>l arte.Después, en la sección III, se <strong>de</strong>scribe la topologíaNR-Mesh. <strong>La</strong> sección IV <strong>de</strong>scribe el algoritmo parala gestión <strong>de</strong>l consumo. A continuación, en la secciónV, se evalua la nueva topología y los algoritmos <strong>de</strong>scritosanteriormente. Finalmente, en la sección VI seconcluye el artículo.II. Estado <strong>de</strong>l ArteDiferentes topologías han sido propuestas durantelos últimos años. Inicialmente, los diseños y propuestasmás extendidas eran los anillos [15] y las mallas2D [20], [18], [19]. Los esfuerzos por reducir elnúmero <strong>de</strong> saltos entre fuente y <strong>de</strong>stino se centraronen las mallas concentradas [2] y las re<strong>de</strong>s ’flattenedbutterfly’ [10]. Otros trabajos [6] también han conseguidoreducir el número <strong>de</strong> saltos mediante ’expresschannels’ [4]. Un análisis completo <strong>de</strong> variastopologías se muestra en [6].Power gating (’gated-Vdd’) es una conocidatécnica para reducir el consumo estático. En [16] se<strong>JP2011</strong>-277


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011propone una técnica para <strong>de</strong>sconectar el suministro<strong>de</strong> componentes (’transistor gating’). Power gatingse pue<strong>de</strong> aplicar a diferentes niveles, <strong>de</strong>s<strong>de</strong> unida<strong>de</strong>s<strong>de</strong> ejecución completas [8] hasta celdas <strong>de</strong> memoriaSRAM [3]. Para las re<strong>de</strong>s en chip, existen diferentestrabajos que aplican estas técnicas. En [3], powergating se utiliza para apagar los ’buffers’ mediantediferentes políticas. En [13, 14], power gating se utilizaa nivel <strong>de</strong> canales virtuales. En [17] se utilizapara el apagado <strong>de</strong> enlaces. En [7], se reduce el consumoestático utilizando el concepto <strong>de</strong> encendidoy apagado <strong>de</strong> enlaces [17] con ’power-aware’ en losbuffers [3, 13, 14]. El algoritmo <strong>de</strong> gestión <strong>de</strong> consumoen este artículo usa este último concepto. <strong>La</strong>sdiferentes propuestas <strong>de</strong>scritas anteriormente cuentannormalmente con la malla 2D, aunque pue<strong>de</strong>naplicarse potencialmente a la topología NR-Mesh.III. NR-Mesh<strong>La</strong> Figura 1 muestra en su parte <strong>de</strong>recha el patrón<strong>de</strong> conexión entre los nodos finales y los conmutadores<strong>de</strong> la topología NR-Mesh. <strong>La</strong> red utiliza 4 enlacespara conectar cada nodo con 4 conmutadoresdistintos, siempre que sea posible. Esto ofrece mayorconectividad si realizamos una comparación con lamalla 2D <strong>de</strong>bido al mayor número <strong>de</strong> enlaces internospor los cuáles pue<strong>de</strong>n inyectarse y recibirse mensajesa través <strong>de</strong> hasta 4 conmutadores distintos. Cabe<strong>de</strong>stacar que los mensajes en tránsito nunca cruzaránlos nodos finales.Cada nodo final incluye un procesador, una caché<strong>de</strong> primer nivel y un bloque <strong>de</strong> caché <strong>de</strong> segundonivel. Cómo el nodo final está conectado a cuatroconmutadores diferentes, se necesita una lógica adicionalen el interfaz <strong>de</strong> red para <strong>de</strong>cidir que puerto<strong>de</strong> salida se va a utilizar. Dicha lógica ha sido implementaday testada (ver sección III-B) obteniendolatencias <strong>de</strong>spreciables excepto para los enlaces internosen la NR-Mesh, dón<strong>de</strong> se requiere un enlacemás largo. Esta lógica se implementa en el nodo final(ver Figura 1). Más a<strong>de</strong>lante, <strong>de</strong>scribiremos elalgoritmo <strong>de</strong> selección que utiliza el interfaz <strong>de</strong> red.Una propiedad a <strong>de</strong>stacar <strong>de</strong> la NR-Mesh es su reducidodiámetro. En concreto se reduce un salto pordimensión al utilizar una ruta mínima comparadocon una malla 2D. Esta propiedad permite reducir lalatencia media <strong>de</strong> los mensajes, así como el tiempo<strong>de</strong> ejecución en aplicaciones reales y el consumo.A. Diseño T ile<strong>La</strong> NR-Mesh pue<strong>de</strong> adaptarse fácilmente a undiseño tile, cómo pue<strong>de</strong> observarse en la Figura 1.El conmutador se coloca en la parte inferior <strong>de</strong>recha<strong>de</strong>l tile y se conecta a 4 nodos distintos, cada uno<strong>de</strong> ellos en un tile diferente. Cada nodo final incluyeuna función <strong>de</strong> selección. <strong>La</strong> figura muestra laconexión <strong>de</strong> los enlaces internos y externos. Cómo sepue<strong>de</strong> apreciar los enlaces externos se conectan <strong>de</strong> lamisma forma que en una malla 2D.El diseño seguido contiene el mismo número <strong>de</strong> nodosy conmutadores que una malla 2D. También, talFig. 1.Diseño tile para la topología NR-Mesh.y como muestra la figura no todos los nodos pue<strong>de</strong>nconectarse a 4 conmutadores, ésto <strong>de</strong>pen<strong>de</strong> <strong>de</strong> suubicación en la malla. A<strong>de</strong>más, cabe <strong>de</strong>stacar quese podría prescindir <strong>de</strong> la última fila y columna <strong>de</strong>conmutadores en la NR-Mesh. Sin embargo, estosconmutadores proporcionan flexibilidad a la hora <strong>de</strong>encaminar mensajes <strong>de</strong>ntro <strong>de</strong> la red, aunque estaránapagados la mayor parte <strong>de</strong>l tiempo en condiciones<strong>de</strong> poco tráfico.B. Algoritmo <strong>de</strong> InyecciónEl algoritmo <strong>de</strong> inyección es un componente clave<strong>de</strong> la topología. Un mensaje pue<strong>de</strong> ser inyectado ala red a través <strong>de</strong> hasta 4 puertos diferentes. Cabe<strong>de</strong>stacar que no siempre los mensajes inyectados ala red seguirán una ruta mínima. Ésto <strong>de</strong>pen<strong>de</strong>rá<strong>de</strong> la disponibilidad <strong>de</strong> cada puerto, aunque siempreserán prioritarios los puertos <strong>de</strong> ruta mínima. Éstoproporciona una gran flexibilidad a la red.El algoritmo primero crea un conjunto <strong>de</strong> puertoscon rutas mínimas, y <strong>de</strong>spués otro conjunto conrutas no mínimas. Pue<strong>de</strong> ocurrir que todos los puertosestén ocupados, en dicho caso esperaremos al siguienteciclo. En caso contrario el puerto escogidoserá el que inyecte el mensaje a la red hacia el conmutadormás cercano al <strong>de</strong>stino final entre los puertosdisponibles.<strong>La</strong> Figura 2.(a) muestra 2 ejemplos. En S1, paralos mensajes que van hacia D1, 2 puertos son incluidosen el conjunto <strong>de</strong> puertos con ruta mínimay 2 en el conjunto <strong>de</strong> puertos con ruta no mínima,respectivamente. En cambio, para los mensajes quevan <strong>de</strong>s<strong>de</strong> S2 a D2, sólo un puerto es incluido en elconjunto <strong>de</strong> puertos con ruta mínima y el resto en elconjunto <strong>de</strong> puertos con ruta no mínima. Si ningúnpuerto estuviese disponible, se esperaría al siguienteciclo y así sucesivamente hasta encontrar al menosun puerto libre.Una vez uno <strong>de</strong> los conjuntos mencionados contieneal menos un puerto libre, el algoritmo <strong>de</strong> selección<strong>de</strong>ci<strong>de</strong>, según lo explicado anteriormente,cual es el mejor enlace para inyectar el mensaje encuestión. Si hay más <strong>de</strong> una ruta para escoger conel mismo número <strong>de</strong> saltos, se selecciona uno <strong>de</strong> lospuertos aleatoriamente. Hay que <strong>de</strong>stacar que la inyección<strong>de</strong> mensajes a la red pue<strong>de</strong> realizarse <strong>de</strong>s<strong>de</strong> elmismo nodo durante el mismo ciclo a través <strong>de</strong> 4 conmutadoresdiferentes, siempre que la red lo requieray todos los puertos <strong>de</strong> inyección estén disponibles.<strong>JP2011</strong>-278


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011(a) Puertos <strong>de</strong> inyección (b) Ruta no mínimaFig. 2. Diferentes características <strong>de</strong> la topología NR-Mesh.function encaminamiento <strong>de</strong>teminista(puerto ent, conm actual,conm <strong>de</strong>st) : puertovar p: puertovar cp: conjunto <strong>de</strong> puertosbeginp = puerto minimo xy(conm actual, conm <strong>de</strong>st)if (libre[p]) return pif (puerto ent==W & y(conm <strong>de</strong>st)y(conm actual) &x(conm <strong>de</strong>st)==x(conm actual)+1) cp+=ESif (puerto ent==E & y(conm <strong>de</strong>st)y(conm actual) &x(conm <strong>de</strong>st)==x(conm actual)-1) cp+=WSif (puerto ent==S & conm <strong>de</strong>st en N) cp+=Nif (puerto ent==N & conm <strong>de</strong>st en S) cp+=Sreturn selecciona libre prioritario(cp)end functionComponente Consumo Cámino crítico Área (µm 2 )Inyección 2.5 µW 0.21 ns 57.40Conm. 3P 34.63 mW 1.00 36,417.96Conm. 4P 49.57 mW 1.00 49,954.71Conm. 5P 63.11 mW 1.00 64,354.10Conm. 6P 76.42 mW 1.00 71,827.22Conm. 7P 88.37 mW 1.00 95,188.55Conm. 8P 102.13 mW 1.00 ns 111,724.72TABLA IResultados <strong>de</strong> consumo y latencias para el interfaz <strong>de</strong>red y conmutadores <strong>de</strong> distinto número <strong>de</strong> puertos (P).Fig. 3. Algoritmo <strong>de</strong> encaminamiento <strong>de</strong>terminista para latopología NR-Mesh.function encaminamiento adaptativo(puerto ent, conm actual,conm <strong>de</strong>st) : puerto, canal virtualvar cp: conjunto <strong>de</strong> puertosbegincp = puertos disponibles ruta minima(conm actual,conm <strong>de</strong>st)if (vacio(cp)) return encaminamiento <strong>de</strong>terminista(puerto ent,conm actual, conm <strong>de</strong>st), canal virtual <strong>de</strong>terministaelse return aleatorio(cp), canal virtual adaptativoend functionC. Resultados <strong>de</strong> ImplementaciónFig. 4. Algoritmo <strong>de</strong> encaminamiento adaptativo para latopología NR-Mesh.El interfaz <strong>de</strong> red así como un conmutador <strong>de</strong> 5etapas ha sido diseñado y sintetizado con la librería<strong>de</strong> código abierto 45nm Nangate en Verilog. Conmutadorescon diferente número <strong>de</strong> puertos se handiseñado también, todos ellos a la frecuencia <strong>de</strong> 1GHz. El consumo total se ha obtenido usando laherramienta P owerCompiler <strong>de</strong> Synopsys <strong>de</strong>spués<strong>de</strong> utilizar la herramienta Place&Route <strong>de</strong> Ca<strong>de</strong>nce.Los resultados para el interfaz <strong>de</strong> red y conmutadores<strong>de</strong>s<strong>de</strong> 3 a 8 puertos (NR-Mesh) están reflejados en laTabla I. El consumo dinámico también se ha medidopara diferentes cargas, sin embargo los resultadosno varian significativamente puesto que el consumoestático es el principal componente. Los resultadosobtenidos han sido comparados con el mo<strong>de</strong>lo<strong>de</strong> consumo Orion-2 [9].Como pue<strong>de</strong> apreciarse, el área y el consumo adicionalen el interfaz <strong>de</strong> red <strong>de</strong>bido al algoritmo <strong>de</strong>inyección es <strong>de</strong>spreciable. A<strong>de</strong>más el consumo paraun conmutador <strong>de</strong> 8 puertos (NR-Mesh) es casi eldoble que para uno <strong>de</strong> 5 (malla 2D) <strong>de</strong>bido principalmenteal número <strong>de</strong> buffers. Aun así, este consumose aplica cuando el conmutador está totalmente encendido.De este modo, la nueva topología NR-Meshcombinada con un algoritmo adaptativo, será capaz<strong>de</strong> apagar puertos y enlaces disminuyendo el consumoactual. También cabe <strong>de</strong>cir que la latencia <strong>de</strong>los mensajes al ser inyectados está muy por <strong>de</strong>bajo <strong>de</strong>los límites impuestos por los <strong>de</strong>l conmutador, lo quequiere <strong>de</strong>cir que el algoritmo <strong>de</strong> inyección no representaun cuello <strong>de</strong> botella a lo largo <strong>de</strong> la ruta crítica<strong>de</strong>l mensaje inyectado.D. Algoritmo <strong>de</strong> EncaminamientoEl algoritmo <strong>de</strong> encaminamiento <strong>de</strong>terminista(Figura 3) con soporte para rutas no mínimas se<strong>de</strong>scribe a continuación. El algoritmo se ejecutaen cada conmutador para cada mensaje entranteteniendo en cuenta <strong>de</strong> don<strong>de</strong> proviene el mensaje,don<strong>de</strong> está y hacia don<strong>de</strong> va. Se prioriza la rutamínima, pero si esta está ocupada y un salto extraes posible (<strong>de</strong>bido a que el mensaje pue<strong>de</strong> serrecibido a través <strong>de</strong> hasta 4 conmutadores distintosen cada nodo final) y el enlace está libre se tomauna ruta no mínima (ver figura 2.(b)). Nótese queaunque varias rutas pue<strong>de</strong>n ser utilizadas como semuestra en dicha figura el encaminamiento utilizadosigue siendo DOR, por lo tanto no es posible que selleven ciclos a cabo. Si ninguno <strong>de</strong> los puertos posiblesestá libre, entonces la función <strong>de</strong> selección <strong>de</strong>puerto <strong>de</strong> salida se volverá a ejecutar en el siguienteciclo.<strong>La</strong> topología NR-Mesh también pue<strong>de</strong> utilizar encaminamientoadaptativo (Figura 4). En este caso,al menos 2 canales virtuales son necesarios para <strong>de</strong>sacoplarrutas adaptativas y vias <strong>de</strong> escape. En nuestrocaso utilizamos un canal virtual para cada caso.El algoritmo primero intenta utilizar el canal adaptativo.Si los posibles puertos que llevan a estoscanales están ocupados, entonces se pasará a encaminamiento<strong>de</strong>terminista mediante la vía <strong>de</strong> escape. Enel siguiente salto se pue<strong>de</strong> volver a utilizar encaminamientoadaptativo (asumimos conmutación virtualcut-trough).<strong>JP2011</strong>-279


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011(a) tolerancia a fallos (b) comunicacióncolectivaFig. 5. Propieda<strong>de</strong>s adicionales en la topología NR-Mesh.E. Propieda<strong>de</strong>s <strong>de</strong> la Topología NR-Mesh<strong>La</strong> primera propiedad y más importante es la flexibilidadal inyectar y recibir mensajes hacia / <strong>de</strong>s<strong>de</strong>diferentes conmutadores basado en el algoritmo <strong>de</strong>inyección implementado. Esta propiedad será <strong>de</strong>gran utilidad cuando gestionemos el consumo paraapagar componentes inutilizados, sobretodo al utilizarencaminamiento adaptativo. A<strong>de</strong>más, la congestión<strong>de</strong>ntro <strong>de</strong> la red <strong>de</strong>saparecerá en gran medida.Otra propiedad es la reducción <strong>de</strong>l diámetro, <strong>de</strong>hasta un salto por coor<strong>de</strong>nada. Ésto conlleva unamenor latencia y el consiguiente ahorro <strong>de</strong> consumo.A<strong>de</strong>más, la topología NR-Mesh soporta un altogrado <strong>de</strong> tolerancia a fallos <strong>de</strong>bido al algoritmo <strong>de</strong>inyección y el algoritmo <strong>de</strong> encaminamiento (Figura5.(a)). También soporta la comunicación colectiva<strong>de</strong> una forma muy eficiente gracias a que un mensajepue<strong>de</strong> ser entregado <strong>de</strong>s<strong>de</strong> el mismo conmutador hacia4 <strong>de</strong>stinos distintos (figura 5.(b)).IV. Algoritmo <strong>de</strong> gestión <strong>de</strong>l consumoEl algoritmo <strong>de</strong> encaminamiento se modificarápara evitar, en la medida <strong>de</strong> lo posible, los puertosque estén apagados. El algoritmo <strong>de</strong> gestión <strong>de</strong>lconsumo se pue<strong>de</strong> dividir en tres partes diferenciadas.<strong>La</strong> primera es <strong>de</strong>cidir cuando un puerto <strong>de</strong>beapagarse. <strong>La</strong> segunda es evitar en la medida <strong>de</strong> loposible los puertos apagados. Por último, queda <strong>de</strong>cidircuando <strong>de</strong>ben encen<strong>de</strong>rse los puertos y enlacesque se encuentran apagados.A. Algoritmo para Apagar un PuertoCada conmutador en la red incluirá una nuevalógica <strong>de</strong> control (ver Figura 6) que llamaremos PML(’Power Management Logic’), la cual estará a cargo<strong>de</strong> encen<strong>de</strong>r y apagar puertos en los conmutadores.Para apagar un puerto se tiene en cuenta el tráficoentrante en el mismo. El PML mi<strong>de</strong> la utilización<strong>de</strong> cada puerto, calculada como el número <strong>de</strong> ciclosdurante el cuál no se utiliza. Cuando se llega a ciertoumbral, dicho puerto <strong>de</strong>berá ser apagado.Para ello, una señal <strong>de</strong> control se enviará al puertoasociado para notificar al PML que el puerto ha <strong>de</strong>ser apagado mediante ’power gating’. Si todos lospuertos <strong>de</strong> un conmutador están apagados entoncesFig. 6. Lógica utilizada para el algoritmo <strong>de</strong> gestión <strong>de</strong>l consumo(PML).la lógica apagará completamente el conmutador, incluyendoel reloj mediante ’clock gating’.El proceso <strong>de</strong> apagar un puerto tiene un consumoque es compensado por el número <strong>de</strong> ciclos en que elconmutador está apagado. Sin embargo, para ahorrarconsumo es necesario que el puerto esté apagadoal menos durante 10 ciclos, aunque no existeninguna penalización en el consumo por <strong>de</strong>spertarloantes. Para más <strong>de</strong>talles ver [8].B. Algoritmo para Encaminar MensajesEl algoritmo <strong>de</strong> encaminamiento <strong>de</strong>scrito en lasección III-D se modifica en este caso para evitar,siempre cuando sea posible, los componentes apagadosen la red. Para ello, dos cambios son necesarios:el primero es qué el algoritmo ha <strong>de</strong> saber que puertosen el conmutador están activos y cuáles no (yasea porqué se esté transmitiendo un mensaje o sencillamenteporqué están apagados). El PML mantieneal arbitro actualizado en cada momento.El segundo requerimiento consi<strong>de</strong>ra el volver a encen<strong>de</strong>run puerto. Si el algoritmo no encuentra unpuerto disponible, entonces una ruta <strong>de</strong>terminista esnecesaria y el PML notificará mediante la señal ’IPon signal’ al siguiente conmutador que ha <strong>de</strong> encen<strong>de</strong>rel puerto <strong>de</strong> entrada correspondiente. Una vezéste haya sido encendido, el mensaje será trasmitidopor la vía <strong>de</strong> escape.C. Algoritmo para Encen<strong>de</strong>r un PuertoEl PML encien<strong>de</strong> los puertos <strong>de</strong> entrada cuando lellega la señal ’IP on signal’ <strong>de</strong>l conmutador previo.Hay una pequeña penalización <strong>de</strong> 1 ciclo al encen<strong>de</strong>rlos enlaces en el conmutador previo, puesto que senecesitan 3 ciclos para ello y no se pue<strong>de</strong> enviar unaseñal al enlace antes <strong>de</strong> la etapa routing.V. EvaluaciónEn esta sección evaluamos la nueva topología NR-Mesh comparándola con la malla 2D usando encaminamiento<strong>de</strong>terminista y adaptativo para ambastopologías. <strong>La</strong> evaluación se realiza en términos<strong>de</strong> tiempo <strong>de</strong> ejecución y energía consumida. Esteúltimo parámetro correspon<strong>de</strong> al consumo empleadodurante todo el tiempo <strong>de</strong> ejecución <strong>de</strong> una aplicación.Hay que <strong>de</strong>stacar que el uso <strong>de</strong>l PML seutiliza únicamente con encaminamiento adaptativopara ambas topologías.<strong>JP2011</strong>-280


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Los umbrales para apagar un puerto son 100 y 200ciclos para 16 y 32 nodos respectivamente. Diferentesumbrales se han estudiado y se han elegido losindicados anteriormente ya que ofrecen una buenarelación entre prestaciones y ahorro <strong>de</strong> energía.A. Herramienta <strong>de</strong> Simulación<strong>La</strong>s herramientas <strong>de</strong> simulación empleadas sonSIMICS [12] y GEMS [11], las cuáles son capaces <strong>de</strong>mo<strong>de</strong>lar un sistema completo. Sin embargo, hemosreemplazado el simulador <strong>de</strong> red <strong>de</strong> GEMS por elsimulador gNoCsim, un simulador propio, dón<strong>de</strong> elconmutador y el interfaz <strong>de</strong> red han sido diseñadosen Verilog. En la tabla II se muestran los principalesparámetros <strong>de</strong> simulación. Varias aplicacionesSplash-2 [21] y cargas <strong>de</strong> trabajo [1] han sido evaluadas.Parámetro Valor Parámetro ValorTamaño L1 128 KB privada <strong>La</strong>tencia L1 3 ciclosTamaño L2 8MB compartida <strong>La</strong>tencia L2 6 ciclosProtocolo Directorio Re<strong>de</strong>s virtuales 5Procesadores 16 y 32Parámetros <strong>de</strong> redConmutadoresTamaño flit 8 bytes Tamaño buffer 10 flitsEnlaces exts 1 ciclo VCs 2Enlaces ints 1 ciclo (2D) Etapas 5Enlaces ints 2 ciclos (NR) Duración etapa 1 cicloTABLA IIParámetros <strong>de</strong> simulación.En las siguientes subsecciones se analiza el tráficoaceptado y el consumo en régimen <strong>de</strong> tráficosintético, así como el tiempo <strong>de</strong> ejecución (en ciclos)y la energía consumida en GEMS, respectivamente.B. Tráfico Sintético<strong>La</strong> Figura 7 muestra las prestaciones (a) y consumo(b) para un sistema <strong>de</strong> 16 nodos (4 × 4) simuladocon tráfico sintético uniforme.En primer lugar se pue<strong>de</strong> observar en (a) la grancantidad <strong>de</strong> tráfico aceptada por la topología NR-Mesh en altas cargas. Ésto es <strong>de</strong>bido a que poseeuna bisección mayor y un diámetro menor. A<strong>de</strong>más,en el encaminamiento <strong>de</strong>terminista el tráfico aceptadoes mayor <strong>de</strong>bido a que no hay penalización porencen<strong>de</strong>r componentes ni uso <strong>de</strong> rutas no mínimas,aunque, el objetivo principal <strong>de</strong> la NR-Mesh es reducirel consumo. En (b) pue<strong>de</strong> observarse comola NR-Mesh consigue un consumo mucho menor ensu versión adaptativa, también superando a la malla2D, excepto para cargas <strong>de</strong> tráfico muy altas al bor<strong>de</strong><strong>de</strong> la saturación.Viendo los resultados <strong>de</strong> ambos gráficos quedaclaro pues que la mejor combinación es la NR-Meshcon encaminamiento adaptativo, puesto que consiguebuenas prestaciones a bajo consumo.Para 32 (4 × 8) nodos (no mostrado por razones<strong>de</strong> espacio), el comportamiento es similar, aunquela NR-Mesh consume algo más sobretodo en el caso<strong>de</strong>terminista. No es así para el caso adaptativo, queconsigue beneficios similares al sistema <strong>de</strong> 16 nodos.Fig. 7.(a) tráfico aceptado (flits/ciclo/tile)(b) consumo por flit (W)Comparación con tráfico sintético para 16 nodos.C. Tiempo <strong>de</strong> Ejecución en GEMS<strong>La</strong> Figura 8.(a) muestra el tiempo <strong>de</strong> ejecuciónpara sistemas <strong>de</strong> 16 y 32 nodos, respectivamente,para cada topología y algoritmo <strong>de</strong> encaminamiento.Los resultados se han normalizado al caso <strong>de</strong>terministapara la malla 2D en cada aplicación. Los resultadosson similares para ambos sistemas (16 y 32nodos).El tiempo <strong>de</strong> ejecución para el encaminamientoadaptativo aumenta ligeramente <strong>de</strong>bido al uso <strong>de</strong>rutas no mínimas y a la penalización introducidacuando se toma la vía <strong>de</strong> escape. Sin embargo, esteaumento en el tiempo <strong>de</strong> ejecución está claramentecompensado por el bajo consumo alcanzado, tal ycomo observaremos en la siguiente subsección.Fijándonos en la NR-Mesh, se pue<strong>de</strong>n apreciargran<strong>de</strong>s reducciones en el tiempo <strong>de</strong> ejecución comparándolocon la malla 2D para ambos algoritmos<strong>de</strong> encaminamiento (<strong>de</strong>terminista y adaptativo).Por ejemplo, Raytrace consigue una reducción en eltiempo <strong>de</strong> ejecución <strong>de</strong> hasta un 12%. A<strong>de</strong>más, in<strong>de</strong>pendientemente<strong>de</strong>l algoritmo utilizado, la topologíaNR-Mesh consigue un tiempo <strong>de</strong> ejecución menor al<strong>de</strong> la malla 2D.D. Energía Consumida en GEMS<strong>La</strong> Figura 8.(b) compara la energía consumida.Los resultados <strong>de</strong> nuevo se muestran normalizadosal caso <strong>de</strong> la malla 2D para cada aplicación.Si comparamos la topología NR-Mesh utilizando elalgoritmo adaptativo propuesto contra la tradicionalmalla 2D utilizando DOR, el ahorro <strong>de</strong> energía llegahasta un 75% <strong>de</strong> media para 16 nodos y hasta un69% para un sistema <strong>de</strong> 32 nodos.<strong>JP2011</strong>-281


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011(a) Tiempo <strong>de</strong> ejecución(b) Energía consumidaFig. 8. Tiempo <strong>de</strong> ejecución y energía consumida en aplicaciones reales. Resultados normalizados para la malla 2D <strong>de</strong>terminista.VI. ConclusionesEn este artículo presentamos la topología NR-Mesh, dón<strong>de</strong> cada nodo se conecta a 4 conmutadoresdiferentes, consiguiendo gran<strong>de</strong>s beneficios enel ahorro <strong>de</strong> consumo. A<strong>de</strong>más, la latencia media sereduce así como la contención. Otros beneficios sonla tolerancia fallos, a<strong>de</strong>más <strong>de</strong> un soporte eficientepara la comunicación colectiva. Los beneficios <strong>de</strong> laNR-Mesh explorados en este artículo son la gran flexibilidadque otorga la red para inyectar y extraermensajes habilitando para ello algoritmos <strong>de</strong> gestión<strong>de</strong>l consumo.<strong>La</strong> nueva topología rin<strong>de</strong> al máximo cuando el encaminamientoadaptativo se combina con el mecanismo<strong>de</strong> power gating, que se utiliza para habilitar/ <strong>de</strong>shabilitar componentes. Debido a la baja utilización<strong>de</strong> la red y la flexibilidad <strong>de</strong> la topología NR,la energía consumida y la reducción en el tiempo <strong>de</strong>ejecucción es <strong>de</strong> un 75% y un 7% respectivamentepara un sistema <strong>de</strong> 16 nodos, comparado con unamalla 2D sin gestión <strong>de</strong>l consumo (encaminamiento<strong>de</strong>terminista sin apagado <strong>de</strong> componentes). Resultadossimilares se han obtenido para 32 nodos.Como trabajo futuro queremos evaluar nuevastopologías siguiendo la filosofía <strong>de</strong> inyección múltipleen el interfaz <strong>de</strong> red.Agra<strong>de</strong>cimientosEste trabajo ha sido financiado por el Ministerio<strong>de</strong> Educación, el Ministerio <strong>de</strong> Ciencia e Innovación,y con fondos FEDER <strong>de</strong> la Comisión Europea, conel proyecto TIN2009-14475-C04-01.Referencias[1] Alamel<strong>de</strong>en, Alaa R. et al. ”Evaluating Non-<strong>de</strong>terministicMulti-threa<strong>de</strong>d Commercial Workloads,” in Workshopon Computer Architecture Evaluation Using CommercialWorkloads.[2] J.D. Balfour and W. J. Dally, ”Design Tra<strong>de</strong>offs for TiledCMP On-Chip Networks,” in International Conference onSupercomputing, June 2006.[3] X. Chen and L.-S. Peh, ”Leakage Power Mo<strong>de</strong>ling and Optimizationin Interconnection Networks,” in InternationalSymposium on Low Power Electronics and Design, pages90-95, August 2003.[4] W. J. Dally, ”Express Cubes: Improving the Performanceof k-ary n-cube Interconnection Networks,” in IEEETransactions on Computers, 40(9):1016-1023, September1991.[5] J. Duato, ”A New Theory of Deadlock-Free AdaptiveRouting in Wormhole Networks,” in IEEE Transactionson Parallel and Distributed Systems, 1993.[6] B. Grot, et. al, ”Express Cube Topologies for On-ChipInterconnects,” in International Symposium on High-Performance Computer Architecture, 2009.[7] K. C. Hale, B. Grot, S. W. Keckler, ”Segment Gatingfor Static Energy Reduction in Networks-on-Chip,” in InternationalWorkshop on Network-on-Chip Architectures,December 2009.[8] Z. Hu at al, ”Microarchitectural Techniques for PowerGating of Execution Units,” in International Symposiumon Low Power Electronics and Design, pages 32-37, August2004.[9] Andrew Kahng, et al, ”ORION 2.0: A Fast and AccurateNoC Power and Area Mo<strong>de</strong>l for Early-Stage Design SpaceExploration,” in Design Automation and Test in Europe(DATE), Nice, France, April 2009.[10] J. Kim et al, ”Flattened Butterfly Topology for On-chipnetworks,” in International Symposium on Microarchitecture,December 2007.[11] M. Martin et al, ”Multifacet, a general execution-drivenmultiprocessor simulator (GEMS) toolset,” in ComputerArchitecture News, September 2005.[12] Peter S. Magnusson et al., ”Simics: A full system simulationplatform,” in Computer, 35(2):50-58, 2002.[13] H. Matsutani et al, ”Run-time Power Gating of On-ChipRouters Using Look-Ahead Routing.,” in Asia and SouthPacific Design Automation Conference, pages 55-60, January2008.[14] H. Matsutani et al., ”Adding Slow-Silent Virtual Channelsfor Low-Power On-Chip Networks,” in InternationalSymposium on Networks-on-Chip, pages 23-32, April2008.[15] D. Pham et al., ”Overview of the Architecture, CircuitDesign, and Physical Implementation of a First-Generation Cell Processor,” in IEEE Journal of Solid-State Circuits, 41(1):179-196, January 2006.[16] M. Powell et al, ”Gated-Vdd: a Circuit Technique toReduce Leakage in Deep-Submicron Cache Memories,” inInternational Symposium on Low Power Electronics andDesign, pages 90-95, July 2000.[17] V. Soteriou and L.-S. Peh, ”Dynamic Power Managementfor Power Optimization of Interconnection Networks UsingOn/Off Links,” in International Symposium on HighPerformance Interconnects, pages 15-20, August 2003.[18] S. Vangal et al., ”An 80-Tile 1.28 TFLOPS Network-on-Chip in 65nm CMOS,” in International Solid-State CircuitsConference, pages 98-99, February 2007.[19] E. Waingold et al., ”Baring It All to Software: RAWMachines,”in IEEE Computer, 30(9):86-93, September 1997.[20] D. Wentzlaff et al., ”On-Chip Interconnection Architectureof the Tile Processor,” in IEEE Micro, 27(5):15-31,September/October 2007.[21] S. C. Woo, M. Ohara, E. Torrie, J. P. Singh, A.Gupta, A., ”The SPLASH-2 programs: characterizationand methodological consi<strong>de</strong>rations,” in 22nd Annual Int.Symposium on Computer Architecture, Italy, June 22 - 24,pp. 24-36, 1995.<strong>JP2011</strong>-282


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011A Flexible Hybrid Transactional MemoryMulticore on FPGAOriol Arcas 1 , Nehir Sonmez 1 , Osman S. Unsal 2 , Adrián Cristal 3 and Mateo Valero 1Abstract— In this paper we present the <strong>de</strong>sign andimplementation of an MPSoC built to explore tra<strong>de</strong>offsin multicore <strong>de</strong>sign space and to evaluate parallelprogramming proposals such as Transactional Memory(TM). Our flexible system, comprised of MIPSR3000-compatible cores is easily modifiable to studydifferent architecture, library and operating systemextensions. For this paper we evaluate a 16-core HybridTransactional Memory implementation based onthe TinySTM-ASF proposal on a Virtex-5 FPGA andwe accelerate three benchmarks written to investigateTM.I. IntroductionA recent alternative for exploring new generationsof multicores is based on building a multiprocessorsystem-on-chip (MPSoC). This approach enables theemulation of large parallel architectures on top ofa reconfigurable FPGA platform whose speed andprocess technology (currently 28 nm) are evolvingfaster than ASIC. Today’s FPGA systems can integratemultiple hard/soft processor cores, multiportedSRAM blocks, high-speed DSP units, andprogrammable I/O interfaces with configurable fabricof logic cells.With the abundance of pre-tested IntellectualProperty (IP) cores available, nowadays it is possibleto prototype large architectures in a full-systemenvironment which allows for faster and more productivehardware research than software simulation.Over the past <strong>de</strong>ca<strong>de</strong>, the RAMP project has alreadyestablished a well-accepted community visionand various novel FPGA architecture <strong>de</strong>signs [4], [6],[8], [13], [17], [22]. Another advantage of FPGA emulationover software simulation is the reduced profilingoverhead and the possibility for a variety of<strong>de</strong>bugging options.One direction is to choose a well-known architecturelike MIPS and utilize the commonly-availabletoolchains and library support. Although runninga minimal OS might be acceptable, a <strong>de</strong>eper softwarestack could have many advantages by providingmemory protection, performing scheduling, aiding<strong>de</strong>bugging and file system support. Full OS supportcan also be accomplished with a nearby hostcomputer which serves system calls and handles exceptions,instead of implementing them in the FPGAmo<strong>de</strong>l [6].A proposal that has drawn consi<strong>de</strong>rable attentionfor programming shared-memory Chip Multi-Processors (CMP) has been the use of Transactional1 Universitat Politècnica <strong>de</strong> Catalunya, Barcelona SupercomputingCenter2 Barcelona Supercomputing Center3 Barcelona Supercomputing Center, CSIC - Spanish NationalResearch CouncilMemory (TM), an attractive paradigm for <strong>de</strong>adlockfreeexecution of parallel co<strong>de</strong> without using locks.Locks are prone to <strong>de</strong>adlock or priority inversionwhile TM provi<strong>de</strong>s optimistic concurrency by executingatomic transactions in an all-or-none manner.The programmer encapsulates critical sections insi<strong>de</strong>the atomic{} construct and the un<strong>de</strong>rlying TMmechanism automatically <strong>de</strong>tects data inconsistenciesand aborts and restarts one or more transactions.If there are no inconsistencies, all si<strong>de</strong> effectsof a transaction are committed as a whole.Transactional Memory can be implemented inhardware (HTM) [3], [16], which is fast but resourceboun<strong>de</strong>dwhile usually requiring changes to thecaches and the Instruction Set Architecture (ISA),or software (STM) [9] which can be flexible, runon off-the-shelf hardware, albeit at the expense oflower performance. To have the best of two worlds,there are intermediate Hybrid TM (HyTM) proposalswhere transactions first attempt to run on hardware,but are backed off to SW when HW resourcesare excee<strong>de</strong>d, and Hardware-assisted STM (HaSTM)which aims to accelerate a software-controlled TMimplementation by architectural means [7], [2].Despite the fact that FPGA emulators of manycomplex architectures of various ISAs have been proposed,only a few of these are on TM research, andonly up to a small number of cores. Furthermore, themajority of these proposals are based on proprietaryor hard processor cores, which imply rigid pipelinesthat can prevent an architect from modifying the ISAand the microarchitecture of the system.In this paper, we present TMbox, a sharedmemoryCMP prototype with Hybrid TM support.More specifically, our contributions are as follows:• A <strong>de</strong>scription of the first 16-core implementationof a Hybrid TM that is completely modifiablefrom top to bottom. This implies convenienceto study HW/SW tra<strong>de</strong>offs in topics like TM.• We <strong>de</strong>tail on how we construct a multicore withMIPS R3000-compatible cores, interconnect thecomponents in a bi-directional ring with backwardsinvalidations and adapt the TinySTM-ASF Hybrid TM proposal to our infrastructure.• Experimental results and performance comparisonsof STM, HTM and Hybrid TM on threebenchmarks <strong>de</strong>signed to investigate tra<strong>de</strong>-offs inTM. We also discuss the strengths and weaknessesof our approach.The next section presents the TMbox architecture,Section 3 explains the Hybrid TM implementation,Section 4 discusses the limitations and the results of<strong>JP2011</strong>-283


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011running three benchmarks on TMbox. Related workis in Section 5 and Section 6 conclu<strong>de</strong>s the paper.II. The TMbox ArchitectureThe basic processing element of TMbox is theHoneycomb CPU core, a heavily modified and exten<strong>de</strong>dversion of the Plasma soft core [20]. Thesynthesizable MIPS R2000-compatible soft processorcore Plasma was <strong>de</strong>signed for embed<strong>de</strong>d systemsand written in VHDL. It has a configurable 2/3 stagepipeline, a 4 KB direct-mapped write-through L1cache, and can address up to 64 MB of RAM. Itwas <strong>de</strong>signed to run at a clock speed of 25 MHz,and it inclu<strong>de</strong>s UART and Ethernet IP cores. Wechose it because it is based on the popular MIPSarchitecture, it is complete and it has a relativelysmall area footprint on the FPGA. Such RISC architectureswith simpler pipelines are more easily customizableand require fewer FPGA resources comparedto a <strong>de</strong>eply-pipelined superscalar processor, sothey are more appropriate to be integrated into alarger multiprocessor SoC.To effectively upgra<strong>de</strong> the MIPS R2000-compatible Plasma to our MIPS R3000-compatibleHoneycomb, we <strong>de</strong>signed and implemented twocoprocessors: CP0 that provi<strong>de</strong>s support for virtualmemory using a Translation Lookasi<strong>de</strong> Buffer(TLB), and CP1 encapsulating an FPU. We optimizedthe cores to make better use of the resourceson our Virtex-5 FPGAs where it can run at twicethe frequency (50 MHz); we modified the memoryarchitecture to enable virtual memory addressingfor 4 GB and caches of 8 KB; we implemente<strong>de</strong>xtra instructions to better support exceptionsand thread synchronization (load-linked and storeconditional) and we <strong>de</strong>veloped system libraries formemory allocation, I/O and string functions [21].The Honeycomb core (without an FPU and theDDR controller) occupies 5827 LUTs (Table I) on aVirtex-5 FPGA including the ALU, MULT/DIV andShifter units, the coherent L1 cache and the UARTcontroller, a comparable size to the Microblaze core.The Virtex5-155T FPGA contains 98K LUTs, 212BRAMs, and 128 DSP blocks. The DDR2 controllerthat occupies a small portion of the FPGA (around2%) performs calibration and serves requests [23].Using one controller provi<strong>de</strong>s sequential consistencyfor our multicore since there is only one addressbus, and loads are blocking and stall the processorpipeline.A. InterconnectionTo interconnect the cores, we <strong>de</strong>signed and implementeda bi-directional ring as shown in Figure1. Arranging the components on a ring rather thana bus requires shorter wires which eases placementon the chip, relaxing constraints, and is a simpleand efficient <strong>de</strong>sign choice to diminish the complexitiesthat arise in implementing a large crossbar onFPGA fabric. Apart from increased place and routetime, longer wires would lead to more capacitance,Table ILUT occupation of componentsComponent 5-LUTs Component 5-LUTsPC next 138 Mem ctrl 156Control 139 Reg File 147Bus mux 155 ALU 157Shifter 201 MULT 497Pipeline 112 Cache 1985TLB 202 TM unit 1242Bus no<strong>de</strong> 619 DDR ctrl 1119UART 77 TOTAL 6946longer <strong>de</strong>lay and higher dynamic power dissipation.Using a ring will also enable easily adding and removingshared components such as an FPU or anyapplication-specific module, however this is out ofthe scope of this work.CPU requests move counterclockwise; they gofrom the cores to the bus controller, eg. CP U i -CP U i−1 - ... - CP U 0 - Bus Ctrl. Requests may bein form of read or write, carrying a type field, a 32-bitaddress, a CPU ID and a 128-bit data field, which isthe data word size in our system. Memory responsesalso move in the same direction; from the bus controllerto the cores, eg. Bus Ctrl - CP U n - CP U n−1- ... - CP U i+1 - CP U i . They use the same channelas requests, carrying responses to the read requestsserved by the DDR Ctrl. On the other hand, movingclockwise are backwards invalidations caused bythe writes to memory which move from the Bus Ctrltowards the cores in the opposite direction, eg. BusCtrl - CP U 0 - ... - CP U i−1 - CP U i . These carry onlya 32-bit address and a CPU ID field. When a writerequest meets an invalidation to the same address onany no<strong>de</strong>, it gets cancelled. Moreover, the caches oneach core snoop and discard the lines correspondingto the invalidation address. We <strong>de</strong>tail how we extendthis protocol for supporting HTM in the nextsection.III. Hybrid TM Support for TMboxTinySTM [9] is a lightweight and efficient wordbasedSTM library implementation in C and C++.It differentiates from other STMs such as TL2 andIntel STM mainly by its time-based algorithm andlock-based <strong>de</strong>sign. By <strong>de</strong>fault, it compiles andruns on 32 or 64-bit x86 architectures, using theatomic ops library to implement atomic operations,which we modified to inclu<strong>de</strong> Compare and Swap(CAS) and Fetch and Add (FAA) primitives for theMIPS architecture using load-linked and store conditional(LL/SC) instructions. TinySTM-ASF is ahybrid port that enables TinySTM to be used withAMD’s HTM proposal, ASF [5], which we modifiedto work with TMbox. This version starts the transactionsin hardware mo<strong>de</strong> and jumps to software if(i) hardware capacity is excee<strong>de</strong>d, (ii) there is toomuch contention or (iii) the application explicitly requiresit. Our hardware <strong>de</strong>sign closely follows the<strong>JP2011</strong>-284


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 1.An 8-core TMbox infrastructure showing the ring bus, the TM Unit and the processor core.InstructionXBEGIN (addr)XCOMMITTable IIHTM instructions for TMboxDescriptionStarts a transaction and saves the abort address (addr) in TMregister $TM0. Also saves the contents of the $sp (stack pointer)to TM register $TM1.Commits a transaction. If it succeeds, it continues execution. Ifit fails, it rolls back the transaction, sets TM register $TM2 toABORT CONFLICT, restores the $sp register and jumps to theabort address.XABORT (20-bit co<strong>de</strong>) Used by software to explicitly abort the transaction. Sets TMregister $TM2 to ABORT SOFTWARE, restores the $sp registerand jumps to the abort address. The 20-bit co<strong>de</strong> is stored in theTM register $TM3.XLB, XLH, XLW, XSB, XSH, XSW Transactional load/store of bytes, halfwords (2 bytes) or words (4bytes).MFTM (reg), (TM reg)Move From TM: Reads from a TM register and writes to a generalpurpose register.ASF proposal with the exception of nesting support.A new processor mo<strong>de</strong>l (-march=honeycomb) wasad<strong>de</strong>d by modifying GCC and GAS (the GNU Assembler).This new ISA inclu<strong>de</strong>s all the R3000 instructionsplus RFE (Return from Exception), LL,SC and the transactional instructions in Figure II.All GNU tools (GAS, ld, objdump) were modified towork with these new instructions.To enable hardware transactions, we exten<strong>de</strong>d our<strong>de</strong>sign with a per-core TM Unit that contains atransactional cache that only admits transactionalloads and stores. By <strong>de</strong>fault it has a capacity of 16data lines (256 bytes). If the TM cache capacity isexcee<strong>de</strong>d, the transaction aborts and sets the TMregister $TM2 to ABORT FULL (explained in thenext section) after which the transaction reverts tosoftware and restarts.A transactional LD/ST causes a cache line to bewritten to the TM Unit. An invalidation of any ofthe lines in the TM Unit causes the current transactionto be aborted. Modifications ma<strong>de</strong> to thetransactional lines are not sent to memory until thewhole transaction successfully commits. The TMUnit provi<strong>de</strong>s single-cycle operations on the transactionalread/writeset stored insi<strong>de</strong>. A Content AddressableMemory (CAM) is built using LUTs bothto enable asynchronous reads and since BRAM-basedCAMs grow superlinearly in resources. Two BRAMsstore the data that is accessed by an in<strong>de</strong>x provi<strong>de</strong>dby the CAM. Additionally, the TM Unit can serveLD/ST requests on an L1 miss if the line is found onthe TM cache.A. Instruction Set Architecture ExtensionsTo support HTM, we augmented the MIPS R3000ISA with the new transactional instructions listed inTable II. We have also exten<strong>de</strong>d the register file withfour new transactional registers, which can only be<strong>JP2011</strong>-285


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011LI $11, 5 //set max. retries = 5LI $13, HW_OFLOW //reg 13 has err. co<strong>de</strong>J $TX$ABORT:MFTM $12, $TM2 //check error co<strong>de</strong>BEQ $12, $13, $ERR //jump if HW overflowADDIU $10, $10, 1 //retries++SLTU $12, $10, $11 //max. retries?BEQZ $12, $ERR2 //jump if max. retriesRDdoneRD hitRDcheckRD reqUncachedRDRD MissReadyUncachedRD reqRD reqWR reqRD MissFor WRWRcheckUncachedWR reqRD reqfor WRUncachedWRWR done$TX:XBEGIN($ABORT) //provi<strong>de</strong> abort addressXLW $8, 0($a0) //transactional LD wordADDi $8, $8, 1 //a++XSW $8, 0($a0) //transactional ST wordXCOMMIT//if abort go to $ABORTFig. 2. TMbox MIPS assembly for atomic{a++} (NOPs andbranch <strong>de</strong>lay slots are not inclu<strong>de</strong>d).Abort?Commit/abortTMbusCheckCommit?TMlockBusLock_busFailWaitMemRDRD doneWRbackNo invalidates,MemWriteWaitMemWRWR cancel on invalidateCommit/abortdoneread with the MFTM (move from TM) instruction.$TM0 register contains the abort address, $TM1 hasa copy of the stack pointer for restoring when atransaction is restarted, $TM2 contains the bit fieldfor the abort (overflow, contention or explicit) and$TM3 stores a 20-bit abort co<strong>de</strong> that is provi<strong>de</strong>d byTinySTM, eg. abort due to malloc/syscall/interruptinsi<strong>de</strong> a transaction, or maximum number of retriesreached etc.Aborts in TMbox are processed like an interrupt,but they do not cause any traps, instead they jump tothe abort address and restore the $sp (stack pointer)in or<strong>de</strong>r to restart the transactions. Regular loadsand stores should not be used with addresses previouslyaccessed in transactional mo<strong>de</strong>, therefore it isleft to the software to provi<strong>de</strong> isolation of transactionaldata if <strong>de</strong>sired. LL/SC can be used simultaneouslywith TM provi<strong>de</strong>d that they do not accessthe same address.Figure 2 shows an atomic increment in TMboxMIPS assembly. In this simple example, the abortco<strong>de</strong> is responsable for checking if the transactionhas been retried a maximum number of times, and ifthere is a hardware overflow (the TM cache is full),and in this case jumps to an error handling co<strong>de</strong> (notshown).B. Bus ExtensionsTo support HTM, we ad<strong>de</strong>d a new type of request,namely COMMIT REQ, and a new response type,LOCK BUS. When a commit request arrives to theDDR, it causes a backwards LOCK BUS message onthe ring which <strong>de</strong>stroys any incoming write requestsfrom the opposite direction, and locks the bus togrant exclusive access to perform a serialized commitaction. All writes are then committed through the“channel” created, after which the bus is unlockedwith another LOCK BUS message, resuming normaloperation. More efficient schemes can be supportedin the future to enable parallel commits [3].C. Cache ExtensionsThe cache state machine reuses the same hardwarefor transactional and non-transactional loadsand stores, however a transactional bit dictates ifLock_bus OKTMwriteInvalidate all writeset entries in cacheWR Commit DoneStart WR commitFig. 3. Cache state diagram. Some transitions (LL/SC) arenot shown for visibility.the line should go to the TM cache or not. Apartfrom regular cached RD/WR, uncached accesses arealso supported, as shown in Figure 3. Cache missesfirst make a memory read request to bring the lineand wait in WaitMemRD state. In case of a store,the WRback and WaitMemWR states manage thememory write operations. While in these two states,if an invalidation arrives to the same address, thewrite will be cancelled. In case of a store-conditionalinstruction, the write will not be re-issued, and theLL/SC will have failed. Otherwise, the cache FSMwill re-issue the write after such a write-cancellationon invalidation.While processing a transactional store insi<strong>de</strong> of anatomic block, an incoming invalidation to the sameaddress causes an abort and possibly the restart ofthe transaction. Currently our HTM system supportslazy version management: the memory is updatedat commit-time at the end of transactions, asopposed to having in-place updates and keeping anundo log for aborting. We also provi<strong>de</strong> lazy conflict<strong>de</strong>tection which implies that data inconsistenciesare <strong>de</strong>tected only after the speculative data iscommitted to the memory. Each transactional writesuccessfully committed causes an invalidation signal,which aborts the transactions that already havethose lines in the TM cache. So a transaction canonly be aborted due to data conflicts during transactionexecution (between XBEGIN and XCOM-MIT/XABORT).To support HTM, the cache state machine is exten<strong>de</strong>dwith three new states, TMbusCheck, TMlockBusand TMwrite. One ad<strong>de</strong>d functionalityis to dictate the locking of the bus prior to committing.Another duty is performing burst writesin case of a successful commit which runs throughthe TMwrite-WRback-WaitMemWR-TMwrite loop.The TMwrite state is also responsible for the gang<strong>JP2011</strong>-286


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011clearing of all entries in the TM cache and the writesetentries that are also found in L1 cache after acommit/abort. To enable this, address entries thatare read from the TM Unit are sent to L1 cache asinvalidation requests, after which the TM cache iscleared in preparation for a new transaction.IV. Experimental EvaluationTMbox can fit 16 cores in a Virtex-5 FPGA, occupying86,797 LUTs (95% of total slices) and 105BRAMs (49%). In this section, we first examine thetra<strong>de</strong>-offs of our implementation, we then discuss theresults of three TM benchmarks.A. Architectural Benefits and DrawbacksOn the TM si<strong>de</strong>, the performance of our best-effortHybrid TM is boun<strong>de</strong>d by the size of the transactionalcache of the TM unit. Although for this workwe chose to use a small, 16-entry TM cache, largercaches can certainly be supported on the TMbox onlarger FPGAs (keeping in mind the extra area overheadintroduced).In pure HTM mo<strong>de</strong>, all 16 lines of the TM cachecan be used for running the transaction in hardware,however the benchmark can not run to completionif there are larger transactions that do not fit in theTM cache, since there is no hardware or softwaremechanism to <strong>de</strong>ci<strong>de</strong> what to do in this case. Thelargest overhead related to STM is due to keepingtrack of transactional loads and stores in software.The situation can worsen when the transactions arelarge and there are many aborts in the system.In Hybrid TM mo<strong>de</strong> it is <strong>de</strong>sired to commit asmany transactions as possible on <strong>de</strong>dicated hardware,however when this is not possible, it is also importantto provi<strong>de</strong> an alternative path using softwaremechanisms. All transactions that overflow the TMcache will be restarted in software, implying all workdone in hardware TM mo<strong>de</strong> to be wasted in the end.Furthermore to enable hybrid execution, TinySTM-ASF additionally keeps the lock variables insi<strong>de</strong> theTM cache. This results in allowing a maximum of 8variables in the read/writesets of each transaction asopposed to 16 for pure HTM. Of course this is trueprovi<strong>de</strong>d that neither the transactional variables, northe lock variables share a cache line, in which case,in some executions we observed some transactionshaving a read/writeset of 9 or 10 entries successfullycommitting in hardware TM mo<strong>de</strong>.On the network si<strong>de</strong>, the ring is an FPGA-friendlyoption: we have reduced the place and route timeof an 8-core <strong>de</strong>sign to less than an hour using thering network, whereas it took more than two hoursusing a shared crossbar for interconnection and wecould not fit more than 8 cores. However, each memoryrequest has to travel as many cycles as the totalnumber of no<strong>de</strong>s on the ring plus the DDR2 latency,during which the CPU is stalled. This is clearly a systembottleneck: using write-back caches or relaxedmemory consistency mo<strong>de</strong>ls might be key in reducingthe number of messages that travel on the ringto improve system performance.On the processor si<strong>de</strong>, the shallow pipeline negativelyaffects the operating frequency of the CPU.Furthermore larger L1 caches can not fit on ourFPGA, however they could be supported on larger,newer generation FPGAs, which would help the systemto better exploit locality. Having separate cachesfor instructions and data would also be a profitableenhancement.B. Experimental ResultsEigenbench is a synthetic benchmark that can betuned to discover TM bottlenecks. As Figure 4shows, the transactions in EigenBench with 2R+8Wvariables overflow (since TinySTM-ASF keeps thelock variables in the transactional cache) and getrestarted in software, exhibiting worse performancethan STM. However, the 4 read-4 write variable versionfits in the cache and shows a clear improvementover STM.In the SSCA2 results presented in Figure 5, weget an 1-8% improvement over STM because thisbenchmark contains small transactions that fit in thetransactional cache. Although Intru<strong>de</strong>r (Figure 6) isa benchmark that is frequently used for TM, it isnot a TM-friendly benchmark, causing a high rateof aborts and non-scalable performance. However,especially with 16-cores, our scheme achieves in (i)discovering conflicts early and (ii) committing 48.7%of the total transactions in hardware, which results inalmost 5x superior performance compared to directupdateSTM, which has to undo all changes on eachabort. We were unable to run this benchmark onpure HTM because it contains memory operationslike malloc/free insi<strong>de</strong> transactions that are complexto run un<strong>de</strong>r HTM and are not supported yet onTMbox.These three benchmarks can benefit from our hybridscheme because they do not run very large transactions,so most of the fallbacks to software causedare due to repeated aborts or mallocs insi<strong>de</strong> transactions.For SSCA2, we see good scalability for up to 8cores, and for Intru<strong>de</strong>r for up to 4 cores. The performance<strong>de</strong>gradations in STM for Intru<strong>de</strong>r are causedby the fact that the STM directly updates the memoryand as the abort rates increase, its performancedrastically <strong>de</strong>creases. Furthermore the system performanceis benchmark-<strong>de</strong>pen<strong>de</strong>nt: compared to sequentialversions, the TM versions can perform in therange of 0.2x (Intru<strong>de</strong>r) to 2.4x (SSCA2). We willbe looking more into overcoming the limitations ofthe ring bus, improving on the TM implementation(serialized commits) and the coherency mechanism.V. Related WorkFew mostly initial work has been published in thecontext of studying Transactional Memory on FPGAprototypes. ATLAS is the first full-system prototypeof an 8-way CMP system with PowerPC hard processorcores, buffers for read/write sets and per-CPU<strong>JP2011</strong>-287


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Table IIITM Benchmarks UsedTM BenchmarkEigenbench[11]Intru<strong>de</strong>r[15]SSCA2[15]DescriptionHighly tunable microbenchmark for TM with orthogonal characteristics. We haveused this benchmark (2000 loops) with (i) r1=8, w1=2 to overflow the TM cacheand vary contention (by changing the parameters a1 and a2) from 0–28%, and (ii)r1=4 and w1=4 to fit in the TM cache and vary the contention between 0–35%.Network intrusion <strong>de</strong>tection. A high abort rate benchmark, contains many transactions<strong>de</strong>queuing elements from a single queue. We have used this benchmark with128 attacks.An efficient and scalable graph kernel construction algorithm. We have used problemscale = 12Execution time (seconds)Execution time (seconds)Normalized speedupNormalized speedup98765432100,0265432100,0254,543,532,521,510,50,030,03Fig. 4.Eigenbench - 2R/8W variables0,04 0,06 0,11Contention (%)0,04 0,06 0,11Contention (%)0,21Eigenbench - 4R/4W variables0,210,380,38Eigenbench results (16 cores).01 2 4 8 162,521,510,5Fig. 5.Number of threadsSSCA2 benchmark results.01 2 4 8 16Number of threadsFig. 6.Intru<strong>de</strong>r benchmark results.Hybrid HTMSTMPure HTMSTMHybrid HTMPure HTMHTMHyTMSTMSTMHyTMcaches augmented with transactional read-write bitsand TCC-type HTM support, with a ninth core forrunning Linux and serving OS requests from othercores [17].Kachris and Kulkarni <strong>de</strong>scribe a TM implementationfor embed<strong>de</strong>d systems which can work withoutcaches, using a central transactional controlleron four Microblaze cores[12]. TM is used as a simplesynchronization mechanism that can be used withhigher level CAD tools like EDK for non-cache coherentembed<strong>de</strong>d MPSoC. The proposal occupies asmall area on chip, but it is a centralized solutionthat would not scale as we move up to tens of cores.Similarly, the compact TM proposal, composed byoff-the-shelf cores with a software API managingtransactions, can be useful for early validation of programsto TM [19].Recent work that also utilizes MIPS soft cores focuseson the <strong>de</strong>sign of the conflict <strong>de</strong>tection mechanismthat uses Bloom filters for an FPGA-basedHTM [14]. Application-specific signatures are comparedto <strong>de</strong>tect conflicts in a single pipeline stage.The <strong>de</strong>sign takes little area, reducing false conflicts.The un<strong>de</strong>rlying bit-level parallelism used for signaturesmakes this approach a good match for FPGAs.This proposal was the first soft core prototype withHTM albeit only with 2 cores; it is not clear whatis done in case of overflow or how the <strong>de</strong>sign wouldscale. Another approach that uses Bloom filters onFPGAs to accelerate STMs on commodity cores waspresented by Casper et al. [2].Ferri et al. proposed an energy-efficient HTM on acycle-accurate SW simulator, where transactions canoverflow to a nearby victim cache [10]. It is a realisticsystem with cache coherence, and non-centralizedTM support, running a wi<strong>de</strong> range of benchmarkson various configurations, however bus-based snoopyprotocol would not scale with more cores, the simulatoris not scalable and would suffer from mo<strong>de</strong>llinglarger numbers of processors, and no ISA changes arepossible to the ARM hard CPU core.Recently, an HTM was proposed by C. Thacker forthe Beehive system [24]. In case of overflow the entiretransaction is run un<strong>de</strong>r a commit lock withoutusing the transactional hardware. We believe thatsoftware transactions might have more to offer. TheBeehive <strong>de</strong>sign also uses a uni-directional ring where<strong>JP2011</strong>-288


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011messages are ad<strong>de</strong>d to the head of a train with thelocomotive at the end [24]. Ring networks are suggestedas a better architecture for shared memorymultiprocessors by Barroso et al. [1] and a cachecoherent bi-directional ring was presented by Oi etal. [18], but as far as we know, using backwardspropagatingwrite-<strong>de</strong>structive invalidations is a novelapproach. Unlike some of the proposals above, oursystem features a large number of processors andis completely modifiable which enables investigatingdifferent interconnects, ISA extensions or coherencymechanisms.VI. ConclusionsWe have presented a Hybrid TM <strong>de</strong>sign, where wefit 16 cores on an FPGA providing hardware supportand accelerating a mo<strong>de</strong>rn TM implementationrunning benchmarks that are wi<strong>de</strong>ly used in TM research.The results agree with our insights and findingsfrom other works [15]: Hybrid TM works well whenhardware resources are sufficient, providing betterperformance than software TM. However, whenhardware resources are excee<strong>de</strong>d, the performancecan fall below the pure software scheme in certainbenchmarks. The good news is that Hybrid TM isflexible; a smart implementation should be able to<strong>de</strong>ci<strong>de</strong> what is best by dynamic profiling. We believethat this is a good direction for further research.We have also shown that a ring network fits well onFPGA fabric and using smaller cores can help buildinglarger prototypes. Newer generations of FPGAswill continue to present multicore researchers withinteresting possibilities, having become so mature asto permit investigating credible largescale systemsarchitecture. We are looking forward to extendingthe TMbox with a memory directory and to usemultiple-FPGAs.References[1] L. A. Barroso and M. Dubois. Cache coherence on a slottedring. In International Conference on Parallel Processing,1991.[2] J. Casper, T. Oguntebi, S. Hong, N. G. Bronson,C. Kozyrakis, and K. Olukotun. Hardware acceleration oftransactional memory on commodity systems. ASPLOS’11, pages 27–38, 2011.[3] H. Chafi, J. Casper, B. D. Carlstrom, A. McDonald,C. C. Minh, W. Baek, C. Kozyrakis, and K. Olukotun.A scalable, non-blocking approach to transactional memory.HPCA ’07, pages 97–108, 2007.[4] D. Chiou, H. Sunjeliwala, H. Sunwoo, J. D. Xu, andN. Patil. FPGA-based Fast, Cycle-Accurate, Full-SystemSimulators. Number UTFAST-2006-01, 15(5):795–825,November Austin, TX, 2006.[5] D. Christie, J.-W. Chung, S. Diestelhorst, M. Hohmuth,M. Pohlack, C. Fetzer, M. Nowack, T. Riegel, P. Felber,P. Marlier, and E. Rivière. Evaluation of AMD’s advancedsynchronization facility within a complete transactionalmemory stack. In EuroSys ’10, pages 27–40,2010.[6] E. S. Chung, E. Nurvitadhi, J. C. Hoe, B. Falsafi, andK. Mai. A complexity-effective architecture for acceleratingfull-system multiprocessor simulations using FPGAs.In FPGA ’08, pages 77–86, 2008.[7] P. Damron, A. Fedorova, Y. Lev, V. Luchangco, M. Moir,and D. Nussbaum. Hybrid transactional memory. ASP-LOS ’06, 2006.[8] N. Dave, M. Pellauer, and J. Emer. Implementing a functional/timingpartitioned microprocessor simulator withan FPGA. WARFP, 2006.[9] P. Felber, C. Fetzer, and T. Riegel. Dynamic performancetuning of word-based software transactional memory. InPPoPP, pages 237–246, 2008.[10] C. Ferri, S. Wood, T. Moreshet, R. Iris Bahar, andM. Herlihy. Embed<strong>de</strong>d-TM: Energy and complexityeffectivehardware transactional memory for embed<strong>de</strong>dmulticore systems. J. Parallel Distrib. Comput., 70:1042–1052, October 2010.[11] S. Hong, T. Oguntebi, J. Casper, N. Bronson,C. Kozyrakis, and K. Olukotun. EigenBench: A simpleexploration tool for orthogonal TM characteristics.In IISWC’10, 2010.[12] C. Kachris and C. Kulkarni. Configurable transactionalmemory. In FCCM ’07, pages 65–72, April 2007.[13] A. Krasnov, A. Schultz, J. Wawrzynek, G. Gibeling, andP. yves Droz. RAMP Blue: A message-passing manycoresystem in FPGAs. In FPL 2007, pages 27–29, 2007.[14] M. <strong>La</strong>brecque, M. Jeffrey, and J. Steffan. Applicationspecificsignatures for transactional memory in soft processors.In ARC 2010, pages 42–54. 2010.[15] C. C. Minh, J. W. Chung, C. Kozyrakis, and K. Olukotun.STAMP: Stanford transactional applications formulti-processing. In IISWC, 2008.[16] K. E. Moore, J. Bobba, M. J. Moravan, M. D. Hill, andD. A. Wood. LogTM: Log-based transactional memory.In HPCA 2006, pages 254–265, 2006.[17] N. Njoroge, J. Casper, S. Wee, Y. Teslyar, D. Ge,C. Kozyrakis, and K. Olukotun. ATLAS: A chipmultiprocessorwith TM support. In DATE’07, pages3–8, 2007.[18] H. Oi and N. Ranganathan. A cache coherence protocolfor the bidirectional ring based multiprocessor. InPDCS’99, pages 3–6, 1999.[19] M. Pusceddu, S. Ceccolini, G. Palermo, D. Sciuto, andA. Tumeo. A compact TM multiprocessor system onFPGA. FPL’10, pages 578–581, 2010.[20] S. Rhoads. Plasma soft core. http://opencores.org/project,plasma.[21] N. Sonmez, O. Arcas, G. Sayilar, O. S. Unsal, A. Cristal,I. Hur, S. Singh, and M. Valero. From Plasma to Bee-Farm: Design experience of an FPGA-based multicoreprototype. In ARC’11, March 23-25 2011.[22] Z. Tan, A. Waterman, R. Avizienis, Y. Lee, H. Cook,D. Patterson, and K. Asanović. RAMP gold: An FPGAbasedarchitecture simulator for multiprocessors. In DAC’10, pages 463 – 468, 2010.[23] C. Thacker. A DDR2 controller for BEE3. MicrosoftResearch, 2009.[24] C. Thacker. Hardware Transactional Memoryfor Beehive. In http://research.microsoft.com/enus/um/people/birrell/beehive/hardwaretransactionalmemory for beehive3.pdf. MSR Silicon Valley, 2010.<strong>JP2011</strong>-289


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-290


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011An Adaptive Controller to Save DynamicEnergy in LP-NUCADarío Suárez Gracia 1 , Teresa Monreal Arnal 2 , and Víctor Viñals Yúfera 1Abstract— Portable <strong>de</strong>vices often <strong>de</strong>mand powerfulprocessors to run computing intensive applications,such as vi<strong>de</strong>o playing or gaming, and ultra low energyconsumption to extend <strong>de</strong>vice uptime. Such conflictingrequirements are hard to fulfil and appeal foradaptive hardware that only consumes energy whenrequired.LP-NUCA is a tiled cache organization aimedat high-performance low-power embed<strong>de</strong>d processorsthat sequentially looks up for blocks or<strong>de</strong>red by temporallocality in groups of small tiles. Unfortunately,LP-NUCA has two main dynamic energy wastingsources: (a) blocks are continuously migrating amongtiles even in low locality phases, (b) to reduce cachelatency, the tag and data arrays of the tiles are alwaysaccessed in parallel.This paper proposes a learning-based controllerthat dynamically tunes block migration and cache accesspolicy between parallel and serial. During lowtemporal locality phases the controller drops blocksfrom the LP-NUCA root tile, L1, and forces a serialaccess to the tag and data arrays in the tiles, thusreducing the energy waste. Using a cycle-accuratesimulator and energy estimations <strong>de</strong>rived from an LP-NUCA layout, the proposed controller reduces dynamicenergy by 20% on average for single and multithreadworkloads.Keywords— Cache Hierarchy, Multithreading, Energy,Power, Embed<strong>de</strong>d, NUCAI. IntroductionTHE way people use computers is partially shiftingfrom personal computers with local data tomobile <strong>de</strong>vices with data on the cloud. This “platform”displacement has not carried along “application”changes. Users almost <strong>de</strong>mand the same performancein mobile <strong>de</strong>vices that they used to experiment in <strong>de</strong>sktopcomputers. Giving the same performance levelwith the tight energy constraints of mobile environmentsappeals for adaptive hardware that judiciously<strong>de</strong>tects whether it is profitable to invest energy inor<strong>de</strong>r to satisfy the user.One of the most energy-efficient mechanisms toachieve high-performance is the memory hierarchy [1],where several small caches pretend to be an unboundand fast storage thanks to the locality of programs.Non-Uniform Cache Architecture, NUCA, exploits localityat a finer granularity than conventional cachesbecause they enable inter bank block migrations [2].Light Power NUCA, LP-NUCA, is a variant of LightNUCA (L-NUCA) for high-performance low-powerembed<strong>de</strong>d processors, such as those of mobile <strong>de</strong>vices,that conveys blocks through three specialized1 Computer Architecture Group (gaZ). Dpto. <strong>de</strong> Informáticae Ingeniería <strong>de</strong> Sistemas. Instituto <strong>de</strong> Investigación en Ingeniería<strong>de</strong> Aragón. <strong>Universidad</strong> <strong>de</strong> Zaragoza. e-mail {dario,victor}@unizar.es2 Department of Computer Architecture. Universitat Politécnica<strong>de</strong> Catalunya (UPC). e-mail: teresa@ac.upc.eduNetworks-in-Cache as L-NUCA does [3], [4], but alsoinclu<strong>de</strong>s two static techniques for saving dynamicenergy, Miss Wave Stopping and Sectoring. Thesetechniques together with LP-NUCA ad-hoc networkmechanism enable to outperform conventional andstatic NUCA organizations in terms of energy andperformance.The organization of LP-NUCA consists of manysmall tiles behaving as a very large distributed victimcache [5]. Blocks remain or<strong>de</strong>red by temporallocality (TL), so the L1, renamed root-tile (r-tile),recently evicted blocks have a lower service latencythan those previously evicted. The LP-NUCA <strong>de</strong>signrelies on the temporal locality of programs alongall their execution; hence, when the r-tile evicts ablock, it triggers a chain of dominoes replacement formaintaining the TL block or<strong>de</strong>ring. But an energywasting problem can arise during low TL phases. Duringthem, the r-tile floods the rest of tiles with blocksthat will be seldom requested. Besi<strong>de</strong>s, these blocks<strong>de</strong>gra<strong>de</strong> ol<strong>de</strong>r ones that may be re-referenced in thenear future. Moreover, LP-NUCA always accesses inparallel tag and data arrays to reduce cache latency.Since a data array access roughly consumes morethan 5× the energy of the tag in LP-NUCA [4], thisparallel access is a major waste of energy for requestswith high likelihood of being a miss. I<strong>de</strong>ally, we wouldlike to <strong>de</strong>tect low locality phases to prevent the r-tilefor evicting low locality blocks and to dynamicallyswitch between parallel and serial access in the restof tiles.LP-NUCAs were conceived for single-thread processors;however, to increase their performance ⁄energy ratio,current advanced embed<strong>de</strong>d processors rely onextracting parallelism from multiple threads ratherthan from a single one. For example, the Intel XeonLC3528, the MIPS MIPS32-1004K, or the NetlogicXLP832 simultaneously execute between 2 and 4threads [6], [7], [8]. Traditionally, multi-threa<strong>de</strong>dprocessors (MT) have shared all the cache hierarchy[9] increasing the chances of polluting the cachewith useless blocks and evicting useful blocks fromother threads. LP-NUCA in MT environments wouldsuffer from this problem and would benefit from acontroller able to drop low locality blocks and toretain high locality ones. Finally, in this case wecan expect little performance improvements becausehigh locality threads will experiment more hits in theLP-NUCA.This paper extends LP-NUCA in several significantways. First, we i<strong>de</strong>ntify that LP-NUCA wastesdynamic energy during low locality phases by continuously<strong>de</strong>grading blocks among tiles and by accessing<strong>JP2011</strong>-291


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011the tag and data arrays in parallel even when thelikelihood of miss is high. Second, we propose a learningbased mechanism based on local search methodsthat dynamically selects when dropping blocks fromthe cache will harm neither performance nor energy.Third, we employ the same controller to dynamicallyadjust between parallel and serial access to the cachetag and data arrays leveraging from the congestionmanagement support from L-NUCA. Fourth, we showthat the proposed controller requires minimal hardwarefor improving energy consumption with smallgains in performance.The rest of the paper is organized as follows. SectionII presents the adaptive controller. Section III<strong>de</strong>scribes our methodology and simulation environment.Section IV evaluates the results. Section Vcomments on the related work, and Section VI conclu<strong>de</strong>sthe paper.II. Adaptive Drop Ratio ControllerFigure 1 shows the LP-NUCA cache organization.Misses in LP-NUCA operate as follows: when the r-tile misses, it allocates an empty way for the incomingblock. When necessary, it evicts a victim block to aneighbour tile with the minimum latency difference.The <strong>de</strong>stination tile, with a transport latency of 3,will repeat the operation to a tile with transportlatency of 4, and this dominoes operation continuesuntil a tile has an empty way or a block is evictedfrom the whole LP-NUCA.to nextcache7 6 5 6 76 4 3 4 65 3 1 3 5ROOTTILEfrom nextL-NUCA levelscache1 2 3processorFig. 1. LP-NUCA basic organization with its three Networksin-Cache:Search in blue, Transport in red, and Replacementin black. The number in the right upper corner ofeach tile represents its service latency assuming single-cycletilesThis chain of evictions keeps blocks or<strong>de</strong>red by temporallocality but wastes a lot of energy when blocksare not requested before leaving the LP-NUCA. Besi<strong>de</strong>s,in their way out, these blocks pollute the tilesand force the evictions of other blocks that may be requestedin the near future causing additional damage.The goal of this work is to find a controller minimizingthe insertion of these polluted blocks from the r-tileinto the rest of tiles. To do so, we propose an AdaptiveDrop Ratio controller able to dynamically <strong>de</strong>tectlow locality phases of programs and choose the optimaldrop rates for all threads in execution. Besi<strong>de</strong>s,when dropping all r-tile eviction blocks, the likelihoodof a request becoming a cache miss increases, so thecontroller will switch the access policy of the dataand tag arrays insi<strong>de</strong> tiles from parallel to serial tosave extra power.Now, we explain the controller operation. It keepsa reference state with the drop rates of all the threadsand its value in the <strong>de</strong>sired target function (cachehits, IPC, . . . ). At regular periods, named epochs,the controller changes the drop rate of a single thread(trial), and after N epochs have completed, whereN is the number of threads, it ranks the drop ratetrials accordingly to the target function. The besttrial superse<strong>de</strong>s the reference when its target valueis better than the reference one. To simplify theimplementation, the drop rate changes at regularsteps, named ∆, and ranges between 0 and 1. A droprate of 0 means all blocks are evicted to the rest oftiles and of 1 means all blocks are dropped 1 . From agiven drop rate, we can move either upwards, adding∆, or downwards, subtracting ∆. To avoid the trial ofboth, we add a variable specifying the direction, andrestrict the trial to this direction. This variable takestwo values, −1 for downwards (↓) and 1 for upwards(↑), making straightforward the implementation ofthe controller. In round-robin fashion, the controllerselects one thread and computes its trial drop rate asdritrial + dir i ∆ where dritrial , and dir irepresent the trial drop rate, the reference drop rate,and the direction of thread i, respectively. At theend of thread i trial epoch, dir i reverts if the reachedtarget is lower than the reference one.= dr refi, dr refiAlgorithm 1: Hill-Climbing algorithm of theADR controllercomputeEpochStatistics();if n epoch % n threads == 0 thenforeach thread doif not isExempted(thread) thenif ifTrialBetterThanRef(thread) thenref[thread].dir = trial[thread].dir;elseref[thread].dir = !trial[thread].dir;en<strong>de</strong>n<strong>de</strong>ndif bestTrialBetterThanRef() ormaxEpochsWoutChange() thenrefSt.dr = bestTrialSt.dr;en<strong>de</strong>ndn epoch++;setTrialState();Algorithm 1 shows the proposed implementation ofthe ADR controller based on hill climbing with two additionalimprovements: the exemption of threads andthe update of the reference state to avoid temporarymaximums. The penalty of dropping useful blockscan be very high because they can cause processorstalls. So when a thread experiences a few number of1 Dirty blocks require to be sent to the next cache level incopy-back configurations.<strong>JP2011</strong>-292


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011misses, it is counterproductive his evaluation becausewe will be moving the controller in a flat zone andnot towards the steep areas 2 . Regarding the latter,temporary maximums, we observe from the experimentsthat it is worthy its update either when a trialperforms better or after a given number of epochswithout change. In this work, we empirically fixedthis value to 4× the number of threads in execution.drop rates LP-NUCA# hitsthread 0 thread 1referencestatetrialstatereference# hits0001.00.51.00.5[[1.0,â],[0.5,á]]controllerevaluationepoch i epoch i+1 epoch i+2[[0.5,â],[0.5,á]][[1.0,â],[1.0,á]][[0.5,â],[0.5,â]][[0.0,â],[0.5,â]]drop ratereferencetrialtimeFig. 2. Temporal behaviour of the Adaptive Drop RatioController with an step, ∆, of 0.5For example, Figure 2 shows a controller for a 2thread machine in which the number of LP-NUCAhits is the target function. We assume that thecontroller state is <strong>de</strong>fined as a list of tuples ST =[[dr 0 , dir 0 ], ..., [dr n−1 , dir n−1 ]]. During epoch i, thread0 is the trial thread and is in trial downwards directionstate. Alike, thread 1 is evaluated in epoch i+1with trial upward state. At the end of this epoch, thecontroller observes the target function, LP-NUCAnumber of hits, and epoch i results better than thereference one. So in epoch i+2, dr 1 remains equaland dr 0 reduces in one step keeping the direction.Thread 1 reverses its direction because in epoch i+1the number of hits was lower than in the referenceepoch.TABLE IPossible organizations for the Adaptive DropRatio ControllerEvaluation TriggerTime 1-512K cycles# misses 1 ⁄4-5× r-tile blocksStep Size From 0.1 to 1Target Metric IPC, # hits, reuse rateAuxiliary Tags, m From 0 to 128 entriesExemption Threshold From 5 to 100 MPKITo suggest a good ADR controller <strong>de</strong>sign based onhill-climbing, we evaluated the various parameterssummarized in Table I.The first big choice is how to trigger a new epoch,either at fixed intervals of time or after a fixed numberof r-tile misses. On the former, we have experimented2 We could also reevaluate after a number of epochs equalsto the no exempted threads, but the hardware complexity willbe higher.with epochs from 1K to 512K cycles and, on the laterfrom 1 ⁄4 to 5× the number of blocks the r-tile stores 3 .The second big choice is step size; i.e., with an step of0.5 a thread can drop all, half, or none of the evictedblocks. Finally, when a thread reaches the “all drop”state, dr j = 1, the controller requires an heuristic forreturning the injection of evicted blocks into the restof LP-NUCA tiles, dr j = 0. One option is to force thereturn to a state that does not drop all the blocks aftera given number of epochs. Another smarter optionis the introduction of a small auxiliary tags trackingthe last m dropped blocks and lookup for misses inthis structure. When updating the controller state ifseveral requests have matched in the auxiliary tags,automatically that thread leaves the “all drop” state.Also, we can fix the misses per epoch that we requireto evaluate a thread.Finally, Figure 3 shows the behaviour of the controllerexecuting 255.vortex with 179.art during 2millions of cycles. ADR synchronously reevaluatesafter 4096 cycles, has 3 dropping states, and whenthe drop ratio is 1, cache arrays are serially accessed.It inclu<strong>de</strong>s an auxiliary tag array of 512 entries. Thisconfiguration was the best among all the test of thiswork. The plot inclu<strong>de</strong>s from top to bottom the numberof committed instructions, the drop ratio in<strong>de</strong>xes,the number of rest of tiles hits, the number of evicted(inserted) blocks into the rest of tiles, and the numberof dropped blocks. 255.vortex, red lines, is anexample of a benchmark that is better to exemptfrom the controller. Its miss rate is very low, and bydropping blocks we could only reduce its performanceand increase the accesses to the next cache level. Onthe contrary, 179.art experiences program phases inwhich it pollutes the cache. For example, before the54M point, the controller drop blocks and keeps usefulblocks insi<strong>de</strong> the cache that are serviced to the r-tile,and then when the miss rate drops again below theexemption threshold, it evicts all the blocks insi<strong>de</strong>the rest of tiles.A. Hardware CostThe hardware implementation of the AdaptiveDrop Ratio controller requires minimal overhead.Most current processors already inclu<strong>de</strong> the performancecounters for the target function and we onlyrequire to store the reference state for all the threads,1 bit for the direction plus log 2 (drop ratios), and thetrial configuration. The partial tags only require ansmall SRAM array, consuming little energy, and ifnecessary it could be easily replaced by a bloom filter.Other novelty of this work is the proposal of switchingbetween parallel and serial access to the cachearrays. At first glance, this feature could be hard toimplement, just the opposite is true. The key observationis that when the likelihood of cache miss ishigh only the tag array is accessed. So we can add anextra bit in the Search Network disabling the accessesto the data arrays in the tiles. Misses will propagate3 Assuming a 32KB r-tile organized in blocks of 32B, thereare 1024 blocks in total.<strong>JP2011</strong>-293


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011CommittedKInstructions42052.5 53 53.5 54 54.5Drop Ratio1.000.500.0052.5 53 53.5 54 54.5Hits900600300052.5 53 53.5 54 54.5R-TILEevicted blocksADR droppedblocksFig. 3.800600400200052.5 53 53.5 54 54.58006004002000vortexart52.5 53 53.5 54 54.5Cycles (Millions)SMT execution of 255.vortex and 179.art with an ADR of 4Kcycles epochs and 3 drop ratiosback-to-back over the fabric. Nevertheless, in the rarecase that a tile hits during a serial access, the dataarray have to be accessed. Since we can not stop therequest propagation in the Search network because itdoes not have any control flow mechanism, we needto re-inject the request in parallel mo<strong>de</strong>. This reinjectionfeature is already supported by LP-NUCAto cope with congestion of the Transport network,when a tile hits and does not have any output transportlink available. Therefore, a serial request hittingin a tile will reset the serial and set the congestionbits, so that the request be reinserted.III. Methodology and SimulationEnvironmentWe employ the same simulation environment,energy estimations, and cache hierarchy organizationsthat previous LP-NUCA work [4]. The baselineprocessor resembles the IBM/LSI PowerPC476FP [10], [11] and executes 1 or 2 threads simultaneously.Table II summarizes the main parameters forthe reference processor and cache hierarchy, includingthe same L1 and L3 caches and either a conventionalL2, a S-NUCA, or an L-NUCA. All caches use LRUreplacement except L-NUCA that employs LRF, leastrecently-filled,and they all have a single read/writeport.Our workload comprises the same embed<strong>de</strong>d domainoriented application than previous work [4].Nevertheless, to get <strong>de</strong>eper insights from the results,we divi<strong>de</strong> the benchmarks in two groups: low MPKIand high MPKI as table III shows. For the two SMTexperiments we present the results in three groups:low MPKI, medium MPKI, and high MPKI whenboth, one, and none benchmarks of the combinationexhibit a low misses per kilo instruction rate.TABLE IISimulator Micro-architectural parameters. BS, AM,lat, and init stand for block size, access mo<strong>de</strong>, latency,and initiation rate, respectivelyClock Frequency1 GHz Fetch/Deco<strong>de</strong>/ 2Commit widthIssue width 2(IN+ME) ROB / LSQ entries32 / 16+2FPINT/FP/MEM 8 / 8 / 8 branch predictor bimodal +IW entriesgshare, 16 bitMiss. branch 6 Instruction perfectpenaltyCacheL1/L2/L3 8 / 8 / 4 TLB miss latency 30MSHR entriesMSHR secon. 4 Store Buffer/ L2/missesL3 WB size a 8 / 4 / 4L1/r-tile b 32KB–4Way–32B BS, write-through, 2-cyclelat, 1-cycle initL2512KB–8Way–32B BS, serial AM, 4-cyclelat, 2-cycle init, copy-backS-NUCA 2×2 128KB–2Way–32BS, parallel AM, 3-cycle lat, 3-cycle init, copy-backL-NUCA rest 32KB–2Way–32B BS, parallel AM, copyback,levels: 3, total size: of tiles448KBL34MB eDRAM–16Way–128B BS, 14-cycle lat,7-cycle init, copy-backMain Memory 100 cycles/4 cycle inter chunk, 16 Byte busa L2, S-NUCA, L-NUCA, and L3 Write Buffers coalesceentriesb In r-tile, copy-back and write-aroundWe used a similar energy estimations than the previouswork for the battery powered domain in 32nm [4]. In the single thread execution, the simulatorwarms-up caches and branch-predictor for 200Minstructions before starting the cycle-accurate simulation.We follow the same approach that Li et al.for energy and <strong>de</strong>lay measurements in SMT environments[12], and account for all the energy consumed<strong>JP2011</strong>-294


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLE IIIWorkload selection. I, F, 0, 6 refer to Integer,Floating Point, SPEC CPU2000, and SPEC CPU2006,respectivelyLow MPKI a 186.crafty I0, 255.vortex I0, 177.mesa F0,458.sjeng I6, 482.sphinx3 F6High MPKI 164.gzip I0, 179.art F0, 187.facerec F0,401.bzip2 I6, 445.gobmk I6, 464.h264refI6, 473.astar I6, 453.povray F6a L1 MPKI rate lower than 20 in the baseline processoruntil the last thread commits 100M instructions.IV. Results EvaluationThis section compares the cache organizations presentedin previous section, namely, conventional L2(L2), Static NUCA (SN), LP-NUCA (LP), and twoLP-NUCAs enhanced with two adaptive drop ratiocontrollers: one with synchronous epochs (ADR C)and another with epoch based on the number ofrequest for evictions (ADR R). Both ADR C andADR R have been selected after exhaustively exploringthe controlling <strong>de</strong>sign space with the optionsshown in Table I. ADR C re-evaluates the drop ratiosand directions every 4096 cycles, while in ADR Roccurs after 1024 attempts of r-tile evictions (or r-tileprimary misses). Both controllers share the rest ofparameters, namely, 3 dropping states, 512-entry auxiliarytags, and an exemption threshold of 50 MPKIin the rest of tiles.First, we compare the energy consumption, then wecontinue with the execution time, and we finish withenergy-<strong>de</strong>lay results. For the sake of brevity, we onlyshow overall and averaged results, but the individualbehaviours do not differ from the presented one.A. EnergyFigure 4 shows the total energy consumed by allconfigurations. LP-NUCA with the ADR have thebest results regardless the benchmark group and thenumber of threads.If we focus on the last three bars to compare theperformance of the ADR controller we observe thatthe synchronous one performs slightly better thanthe based on the number of replacements. In themore energy <strong>de</strong>manding benchmarks, high MPKI,the controller reduces energy by 20% on average.B. Execution TimeDropping blocks may reduce LP-NUCA hit ratesand increase execution time, EX. To verify that theproposed ADRs do not affect EX Figure 5 shows thetotal execution time.LP-NUCA shows performance improvements overL2 and SN, and both controllers slightly reduce executiontime because they keep insi<strong>de</strong> the cache usefulblocks that otherwise would be expelled. ADR C andADR R reduces total execution time by 2.14% and2.29%, respectively, in the single-thread environment.Improvements become marginal in the 2 SMT andTotal Energy (mJ)Total Energy (mJ)Fig. 5.7060504030201006005004003002001000Dynamic L2/SN/RESTTDynamic L1/RTStatic L2/SN/RESTTStatic L1/RTL2 SN LP ADR_C ADR_R L2 SN LP ADR_C ADR_RLow MPKIHigh MPKIDynamic L2/SN/RESTTDynamic L1/RTStatic L2/SN/RESTTStatic L1/RTL2SNLPLow MPKIFig. 4.Total Cycles (M)Total Cycles (M)1000800600400200ADR_C0900080007000600050004000300020001000(a) Single ThreadADR_RL2SNLPMed. MPKI(b) 2 SMTADR_CADR_RL2SNLPHigh MPKIEnergy consumption comparisonL2SNLPADR_RADR_CLow MPKIHigh MPKI(a) Single ThreadL2SNLPADR_RADR_CLow MPKI Med. MPKI High MPKI(b) 2 SMTADR_CADR_RTotal Execution Time for the different configurationsreduce to 0.62% and 0.89% for ADR R and ADR C,respectively, because the multi-threading executioncovers the memory stalls.C. Overall System ImpactFinally, we present the sum of the energy-<strong>de</strong>layof the tested benchmarks. Figure 6 inclu<strong>de</strong>s the L3energy to show that dropped blocks are not requestedto the L3 increasing the overall energy.Again ADR R and ADR C are the winners in allcategories. LP-NUCA improvements in executiontime reduces the static component with regards toL2 and SN, and the controllers reduce on averagedynamic energy-<strong>de</strong>lay, their target, 7.6% for all butlow MPKI workloads.V. Related WorkArchitects have proposed a plethora of <strong>de</strong>signs tosave cache energy through reconfigurable caches that<strong>JP2011</strong>-295


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Energy-Delay (mJ x s)Energy-Delay (mJ x s)35302520151050500450400350300250200150100500Dynamic EDStatic EDL2 SN LP ADR_C ADR_R L2 SN LP ADR_C ADR_RLow MPKIHigh MPKIDynamic EDStatic EDL2SNLPLow MPKIADR_C(a) Single ThreadADR_RL2SNLPMed. MPKI(b) 2 SMTADR_CADR_RL2SNLPHigh MPKIFig. 6. Energy-Delay. This figure inclu<strong>de</strong>s L3 cache consumptionas wellchange their number of ways, sets, or both at runtime [13], [14], [15], [16]. For an updated state ofthe art please refer to Sundararajan et al. [16]. Previousworks adapt the cache at a finer granularitythan this work, and most proposed techniques canbe easily applied to the LP-NUCA. Contrary to theoriginal LP-NUCA <strong>de</strong>sign [4], this work proposes aproactive dynamic technique to save energy while previousones, Sectoring and Miss Wave Stopping, werecompletely static and application agnostic. Besi<strong>de</strong>s,this work analyzes SMT workloads which have notbeen extensively studied.Regarding the learning based approach, the HillClimbing algorithm has been employed for distributingresources in SMT processors [17], but not forcache reconfiguration.VI. ConclusionsUltra-portable mobile <strong>de</strong>vices <strong>de</strong>mand quasi<strong>de</strong>sktopperformance with a fraction of energy consumption.Since application behaviour changes duringexecution, processors require adaptive mechanismwasting the minimum amount of energy when necessary.This paper proposes an adaptive controller for LP-NUCA, a tiled organization for high-performance lowpowerprocessors, that automatically <strong>de</strong>ci<strong>de</strong>s whencache blocks are not reused and can be dropped reducingthe cache activity. Besi<strong>de</strong>s, during high droppingphases, the controller is able to change the cachearray access from parallel to serial further reducingthe energy consumption.With representative workloads, a cycle-accuratesimulator, and implementation based energy estimations,we observe that the proposed controller reducesdynamic energy on average by 20% for single-threadand 2-threa<strong>de</strong>d workloads without increasing the executiontime.ADR_CADR_RAcknowledgementThe authors would like to thank Luis Montesano<strong>de</strong>l Campo for his helpful comments on the learningstrategies. This work was supported in part by grantsTIN2010-21291-C02-01 and TIN2007-60625 (SpanishGovernment), gaZ: T48 research group (Aragon Governmentand European ESF), Consoli<strong>de</strong>r CSD2007-00050 (Spanish Government), and HiPEAC-2 NoE(European FP7/ICT 217068).References[1] Shekhar Borkar and Andrew A. Chien, “The future ofmicroprocessors,” Commun. ACM, vol. 54, pp. 67–77,May 2011.[2] Changkyu Kim, Doug Burger, and Stephen W. Keckler,“An adaptive, non-uniform cache structure for wire-<strong>de</strong>laydominated on-chip caches,” in Proc. of ASPLOS-X, 2002.[3] Darío Suárez, Teresa Monreal, Fernando Vallejo, RamónBeivi<strong>de</strong>, and Víctor Viñals, “Light NUCA: a proposalfor bridging the inter-cache latency gap,” in Proc. ofDATE’09, 2009.[4] Darío Suárez Gracia, Giorgos Dimitrakopoulos,Teresa Monreal Arnal, Manolis G.H. Katevenis, andVíctor Viñals Yúfera, “LP-NUCA: Networks-in-Cache forhigh-performance low-power embed<strong>de</strong>d processors,” toappear in IEEE Trans.on VLSI Systems, 2011.[5] Norman P. Jouppi, “Improving direct-mapped cacheperformance by the addition of a small fully-associativecache and prefetch buffers,” in Proc. of ISCA’90, 1990.[6] Intel Embed<strong>de</strong>d, “Intel® Xeon® processor C5500/C3500series. Datasheet–Volume 1,” February 2010.[7] MIPS Technologies, “MIPS32® 1004Kcoherent processingsystem (CPS),” 2010.[8] Tom R. Halfhill, “Netlogic broa<strong>de</strong>ns XLP family,” MicroprocessorReport, vol. 24, no. 7, pp. 1–11, 2010.[9] D.M. Tullsen, S.J. Eggers, and H.M. Levy, “Simultaneousmultithreading: Maximizing on-chip parallelism,” in Proc.of ISCA’95, 1995.[10] Tom R. Halfhill, “The rise of licensable SMP,” MicroprocessorReport, vol. 24, no. 2, pp. 11–18, 2010.[11] LSI Corporation, “PowerPC processor (476FP)embed<strong>de</strong>d core product brief, http://www.lsi.com/DistributionSystem/AssetDocument/PPC476FP-PB-v7.pdf,” January 2010.[12] Yingmin Li, David Brooks, Zhigang Hu, Kevin Skadron,and Pradip Bose, “Un<strong>de</strong>rstanding the energy efficiencyof simultaneous multithreading,” in Proc. ISLPED’04,2004.[13] David H. Albonesi, “Selective cache ways: on-<strong>de</strong>mandcache resource allocation,” in Proc. of MICRO’32, 1999.[14] Rajeev Balasubramonian, David Albonesi, Alper Buyuktosunoglu,and Sandhya Dwarkadas, “Memory hierarchyreconfiguration for energy and performance in generalpurposeprocessor architectures,” in Proc. of MICRO’33,2000.[15] Chuanjun Zhang, Frank Vahid, and Walid Najjar, “Ahighly configurable cache architecture for embed<strong>de</strong>d systems,”in Proc. of ISCA’03, 2003.[16] Karthik T. Sundararajan, Timothy M. Jones, and NigelTopham, “Smart cache: A self adaptive cache architecturefor energy efficiency,” in Proc. of SAMOS’11, 2011.[17] Seungryul Choi and Donald Yeung, “Hill-climbing smtprocessor resource distribution,” ACM Trans. Comput.Syst., vol. 27, no. 1, pp. 1–47, 2009.<strong>JP2011</strong>-296


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Acelerando las simulaciones <strong>de</strong> sistemacompleto usando Simics en sistemasmultiprocesadorS. González 1 , F. Triviño 2 , F. J. Andujar 2 , J. L. Sánchez 2 , F. J. Alfaro 2Resumen—El uso <strong>de</strong> simuladores <strong>de</strong> sistema completopara evaluar el <strong>de</strong>sarrollo <strong>de</strong> un <strong>de</strong>terminado componenteen un sistema <strong>de</strong> computación, es una prácticafrecuente. Esto permite obtener mejores resultadosy conclusiones en comparación a una simulación parcialdon<strong>de</strong> solo se mo<strong>de</strong>la una parte <strong>de</strong>l sistema y se<strong>de</strong>scarta su interacción con el resto <strong>de</strong>l sistema.Sin embargo, realizar una simulación <strong>de</strong> sistemacompleto trae consigo inconvenientes como un mayortiempo para realizar las pruebas y un mayor consumo<strong>de</strong> recursos. Esto pue<strong>de</strong> generar una <strong>de</strong>mandacreciente proporcional a la complejidad <strong>de</strong>l mo<strong>de</strong>lo aanalizar, como se da en la investigación <strong>de</strong> sistemasmultiprocesador al aumentar el número <strong>de</strong> procesadoreso al realizar simulaciones en paralelo.En este trabajo se <strong>de</strong>scriben las mejoras <strong>de</strong> rendimientoen términos <strong>de</strong> tiempo <strong>de</strong> simulación queofrece la versión 4 <strong>de</strong>l simulador Simics, con la incorporación<strong>de</strong> nuevas tecnologías pensadas para mejorarel uso <strong>de</strong> sistemas multiprocesador, como es SimicsAccelerator. Se realizan pruebas con el benchmarkPARSEC, midiendo el tiempo <strong>de</strong> simulación ycomparando el rendimiento con la versión 3 <strong>de</strong> Simics,analizando las ventajas y <strong>de</strong>sventajas en optar por laactualización <strong>de</strong> versión.Palabras clave— Simulación, rendimiento, Simics4.I. IntroducciónLA simulación es un método muy usado en la investigacióny diseño <strong>de</strong> propuestas <strong>de</strong> arquitectura<strong>de</strong> computadores al permitir evaluar una variedad<strong>de</strong> arquitecturas sin tener que construirlas, permitiendola reducción en coste y tiempo <strong>de</strong> <strong>de</strong>sarrollo<strong>de</strong> un proyecto. A<strong>de</strong>más, con ello se mejoran los procedimientos<strong>de</strong> validación <strong>de</strong> nuevos mo<strong>de</strong>los graciasa la sistematización <strong>de</strong> pruebas, las cuales pue<strong>de</strong>n serreplicadas fácilmente y ejecutadas en paralelo, así comola obtención <strong>de</strong> resultados.Muchas veces será útil realizar un análisis <strong>de</strong>l comportamiento<strong>de</strong>l sistema en su totalidad incluyendo elprocesador, la memoria, los dispositivos <strong>de</strong> entrada ysalida, buses, re<strong>de</strong>s y otras interconexiones. Todo ellose pue<strong>de</strong> evaluar <strong>de</strong> forma conjunta permitiendo laejecución <strong>de</strong> un sistema operativo y otras aplicacionescomerciales como benchmarks. Esa es la finalidadcon la que surgen los simuladores <strong>de</strong> sistema completo[1]. Un inconveniente <strong>de</strong> este tipo <strong>de</strong> simulacioneses que requieren <strong>de</strong> mucho tiempo para completarse,<strong>de</strong>bido al gran nivel <strong>de</strong> <strong>de</strong>talle <strong>de</strong>l sistema mo<strong>de</strong>lado.Así pues, un reto importante es po<strong>de</strong>r reducir almáximo el tiempo <strong>de</strong> simulación.1 Dpto. <strong>de</strong> Informática, Univ. Peruana Cayetano Heredia, e-mail: santos.gonzalez.t@upch.pe2 Dpto. <strong>de</strong> Sistemas Informáticos,Univ. Castilla-<strong>La</strong> Mancha, e-mail: {ftrivino, fandujar, jsanchez,falfaro}@dsi.uclm.esSimics [4] es una herramienta <strong>de</strong> simulación <strong>de</strong> sistemacompleto, capaz <strong>de</strong> mo<strong>de</strong>lar diferentes tipos <strong>de</strong>arquitecturas. Sin embargo, cuando el sistema es muycomplejo las simulaciones pue<strong>de</strong>n requerir horas o inclusodías en completarse.En este trabajo se revisa la versión 4 <strong>de</strong> Simicsanalizando sus nuevas características. Éstas surgencomo resultado <strong>de</strong> las nuevas ten<strong>de</strong>ncias en el uso <strong>de</strong>máquinas multiprocesador y clusters. Una <strong>de</strong> las másimportantes es la inclusión <strong>de</strong> Simics Accelerator [2],que permite reducir el tiempo <strong>de</strong> ejecución haciendoun uso más eficiente <strong>de</strong>l hardware don<strong>de</strong> se realiza lasimulación.Para <strong>de</strong>terminar cómo influyen las nuevas características<strong>de</strong> Simics 4, se realizarán diversas simulacionesusando el benchmark PARSEC [3], el cualagrupa un largo y variado conjunto <strong>de</strong> aplicacionesque han sido correctamente paralelizadas con diferentestécnicas. Se trata <strong>de</strong> ofrecer argumentos parapo<strong>de</strong>r <strong>de</strong>cidir sobre la actualización o no <strong>de</strong>l sistemay <strong>de</strong>pendiendo <strong>de</strong>l mo<strong>de</strong>lo a simular po<strong>de</strong>r tomar una<strong>de</strong>cisión.Este artículo está organizado <strong>de</strong> la siguiente manera:en la Sección II se incluye una breve <strong>de</strong>scripción<strong>de</strong>l simulador Simics 4.2 y <strong>de</strong> sus características másimportantes. En la Sección III se <strong>de</strong>scribe el proceso<strong>de</strong> pruebas para obtener los tiempos <strong>de</strong> simulación.Finalmente, en la Sección IV se presentan las conclusionesy trabajo futuro.II. SIMICS 4Simics [4] es una plataforma que permite simularun sistema completo lo cual facilita tanto el <strong>de</strong>sarrollo<strong>de</strong> hardware como <strong>de</strong> software proporcionando lonecesario para la simulación <strong>de</strong> ambos componentes<strong>de</strong>ntro <strong>de</strong> un mismo contexto. Como se pue<strong>de</strong> observaren la Figura 1 tanto los requerimientos hardwarecomo los <strong>de</strong>l sistema, cuyo mo<strong>de</strong>lado mantieneuna estructura modular, son completamente simuladosen una máquina (host) [1].También se pue<strong>de</strong>n tener varias arquitecturas tantomonoprocesador como multiprocesador y ejecutaren ellas sistemas operativos convencionales, benchmarks,aplicaciones <strong>de</strong> escritorio, entre otras aplicacionescomerciales. Una <strong>de</strong> las ventajas que se tienees que se pue<strong>de</strong>n usar cargas <strong>de</strong> trabajo reales, algoque no se pue<strong>de</strong> hacer con otros simuladores.<strong>La</strong> versión utilizada para el presente trabajo es laversión 4.2. Entre las principales características conlas que cuenta esta versión se pue<strong>de</strong>n <strong>de</strong>stacar:<strong>JP2011</strong>-297


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Mejoras en rendimiento y escalabilidad <strong>de</strong>bidoa la inclusión <strong>de</strong> Simics Accelerator 2.0. Permiteejecutar simulaciones <strong>de</strong> sistemas distribuidosy máquinas multiprocesador acelerando el <strong>de</strong>sarrollo<strong>de</strong> software y hardware ayudados tambiéncon las herramientas <strong>de</strong> <strong>de</strong>puración y checkpointing.Mejoras en los mo<strong>de</strong>los a simular, permitiendola comprensión <strong>de</strong> los programas a través <strong>de</strong>un visualizador <strong>de</strong> rendimiento y facilitando eldiagnóstico <strong>de</strong> errores.Mejoras en la interfaz <strong>de</strong> usuario logrando integrarsecon Eclipse a través <strong>de</strong> plugins parainiciar y controlar las sesiones <strong>de</strong> Simics. Estohace útil las herramientas y flujos <strong>de</strong> trabajo <strong>de</strong>Eclipse.Conectividad a través <strong>de</strong> telnet, un visor <strong>de</strong> memoriay soporte unico<strong>de</strong>.TABLA INuevas arquitecturas soportadas por Simics 4.Mo<strong>de</strong>los Procesadores ComponentesIBM PowerPCPPC464FP AMCC464PPC440GXSoC, MemoriaDDR,FLASH,Conectividadserial yEthernetFreescale PowerMPC8347, MemoriaQUICC MPC8360E DDR,II ProFLASH,MPC83xxConectividadserial yEthernetARM Integrator/CPARM926,ARM1136,ARM1176ARM Basic Intel StrongARMMemoriaDDR,FLASH,Conectividadserial yEthernetRAM, ConectividadserialFig. 1. Simulador <strong>de</strong> sistema completo.Simics 4 soporta nuevos tipos <strong>de</strong> arquitecturas. Enla Tabla I se pue<strong>de</strong>n observar los nuevos mo<strong>de</strong>los incorporadospara esta versión [4]. Simics, <strong>de</strong>ntro <strong>de</strong>sus nuevas características, también permite realizarsimulaciones híbridas logrando unir mo<strong>de</strong>los <strong>de</strong> procesadores<strong>de</strong> distintos niveles <strong>de</strong>ntro <strong>de</strong> un sistemasimulado sirviendo tanto para el <strong>de</strong>sarrollo rápidocomo para su validación, y luego po<strong>de</strong>r obtener unanálisis <strong>de</strong>tallado <strong>de</strong> rendimiento. Este tipo <strong>de</strong> simulacioneshíbridas están disponibles en los mo<strong>de</strong>los <strong>de</strong>microprocesador Freescale QorIQ P4080, y en próximasversiones se podrá tener un API genérico paraque pueda ser aplicado a otras microarquitecturas.De igual forma, pue<strong>de</strong>n usarse nuevas extensionespara Simics como es el soporte en tiempo real <strong>de</strong>lsistema operativo. Así, se permite que Simics pueda<strong>de</strong>tectar cuándo un proceso se inicia, termina yse mantiene activo en el sistema simulado, sirviendocomo herramienta para la <strong>de</strong>tección <strong>de</strong> errores.Otra <strong>de</strong> las características que incorpora Simicses la <strong>de</strong> lograr un puente con los mo<strong>de</strong>los <strong>de</strong> SystemCpermitiendo que éstos sean incluidos como parte<strong>de</strong>l sistema <strong>de</strong> simulación <strong>de</strong> Simics. De esta forma,será posible construir una plataforma virtual quepermita ser ejecutada a través <strong>de</strong> la interacción <strong>de</strong>mo<strong>de</strong>los en DML, C, Python y SystemC lograndoque los usuarios puedan construir <strong>de</strong> manera rápidauna plataforma completa, al facilitar la reutilización<strong>de</strong> estructuras previamente realizadas sin necesidad<strong>de</strong> tener que hacer cambios.También es posible trabajar con TLM(Transaction-level mo<strong>de</strong>ling) [5] que tiene lapropiedad <strong>de</strong> realizar la comunicación a través <strong>de</strong>llamadas a funciones directamente entre los módulossimulados sin tener que interactuar con el kernelsimulado. Esto se realiza en unida<strong>de</strong>s que seanlo más largas posibles, para reducir el número <strong>de</strong>comunicaciones, y con la menor frecuencia posible.<strong>La</strong>s versiones anteriores <strong>de</strong> Simics basaban el rendimientoy escalabilidad con el módulo llamado SimicsCentral [6]. Este módulo administraba la conexión<strong>de</strong> nodos heterogéneos <strong>de</strong> distintas máquinassimuladas, las cuales podían encontrarse en distintoshosts. Así pues, dicho módulo tenía que encargarse<strong>de</strong> sincronizar el tiempo virtual entre el simuladory el tráfico simulado entre las máquinas. Ahora lanueva versión <strong>de</strong> Simics reemplaza este módulo <strong>de</strong> simulacióndistribuida incorporando Simics Accelerator2.0. Este nuevo módulo trae consigo otras venta-<strong>JP2011</strong>-298


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 2. Simulación Multihilo[2]jas adicionales que repercuten en el rendimiento <strong>de</strong>lsistema. A continuación se resumen las principalesventajas que mejoran la velocidad en la simulación.A. Simics Accelerator 2.0Uno <strong>de</strong> los principales requisitos al realizar simulacioneses que éstas, a<strong>de</strong>más <strong>de</strong> precisas, puedan serrealizadas en el menor tiempo posible. Esto <strong>de</strong>beríacumplirse incluso simulando sistemas y cargas <strong>de</strong> trabajogran<strong>de</strong>s sacando provecho <strong>de</strong>l uso <strong>de</strong> servidoresy clusters.Simics busca este objetivo a través <strong>de</strong> este nuevomódulo don<strong>de</strong> se implementan mejoras relacionadascon la <strong>de</strong>cisión en el nivel correcto <strong>de</strong> abstracción <strong>de</strong>ltiempo, en la metodología <strong>de</strong> mo<strong>de</strong>lado basada entransacciones entre los distintos dispositivos, creación<strong>de</strong> mo<strong>de</strong>los <strong>de</strong> procesadores rápidos y simulacionesmultihilo [1]. Estas últimas están orientadasa ser aplicadas en la ejecución <strong>de</strong> mo<strong>de</strong>los más complejos,como se muestra en la Figura 2. Empezandocon un mo<strong>de</strong>lo sencillo se simula una máquina en unacomputadora <strong>de</strong> un solo núcleo. El host provee ciertoporcentaje <strong>de</strong> procesamiento, lo que equivale a lavelocidad <strong>de</strong> simulación en términos <strong>de</strong>l rendimiento<strong>de</strong>l sistema global y <strong>de</strong> cómo es percibido por elusuario.Cuando se realiza un mo<strong>de</strong>lo más complejo, <strong>de</strong> 4máquinas simuladas en el mismo host con el mismopo<strong>de</strong>r <strong>de</strong> procesamiento, el rendimiento esta vez tieneque ser dividido por la cantidad <strong>de</strong> máquinas simuladas.Esta vez el usuario percibirá una reducción<strong>de</strong> cuatro veces la velocidad <strong>de</strong> simulación. UsandoSimics Accelerator y un host con cuatro núcleos,el mismo mo<strong>de</strong>lo complejo <strong>de</strong> cuatro máquinas pue<strong>de</strong>aprovechar la capacidad <strong>de</strong> procesamiento, ahoramayor en el host, logrando que cada procesador <strong>de</strong>lhost pueda realizar el procesamiento <strong>de</strong> cada máquinasimulada. Esto producirá para el usuario una percepción<strong>de</strong> la misma velocidad que en el caso inicial,como el <strong>de</strong> una sola máquina simulada en un computador<strong>de</strong> un solo núcleo.<strong>La</strong> memoria compartida es uno <strong>de</strong> los medios queusa Simics para liberar la <strong>de</strong>manda <strong>de</strong> memoria enel sistema a simular. Lo que hace es verificar quelos contenidos <strong>de</strong>ntro <strong>de</strong> las memorias RAM, ROM,FLASH o <strong>de</strong>l disco simulado no sean redundantes <strong>de</strong>tal forma que no se duplique contenido y sólo se tengauna copia <strong>de</strong>l mismo en la memoria <strong>de</strong> la máquinaen don<strong>de</strong> se realiza la simulación.<strong>La</strong> simulación distribuida que ofrece esta nuevaversión <strong>de</strong> Simics permite el uso <strong>de</strong> múltiples hostspara aumentar la escalabilidad y aprovechar mejor eluso <strong>de</strong> clusters. Esto mejora directamente el rendimientoen la ejecución <strong>de</strong> múltiples sesiones <strong>de</strong> Simicsen paralelo, especificándose la cantidad <strong>de</strong> núcleosque serán usados para cada sesión <strong>de</strong> Simics, logrando<strong>de</strong> esta forma escalabilidad, particionando los recursos<strong>de</strong>l host para la simulación y evitando bloqueosentre las simulaciones.<strong>La</strong> sincronización es importante cuando se realizauna simulación distribuida. I<strong>de</strong>almente los procesospodrían realizarse simultáneamente en tiempo simuladoy en tiempo real pero eso no se pue<strong>de</strong> por la grancantidad <strong>de</strong> sobrecarga que sería necesaria para lasincronización <strong>de</strong>jando muy poco tiempo para el trabajoreal. Simics introduce un pequeño retardo quehace que la simulación distribuida no esté completamentesincronizada, a costa <strong>de</strong> no producir tanta sobrecargapermitiendo que los distintos componentespuedan comunicarse solamente a intervalos especificados,los cuales son <strong>de</strong>finidos <strong>de</strong>s<strong>de</strong> la configuración<strong>de</strong> la simulación.Simics permite la simulación <strong>de</strong> máquinas interconectadasmediante una red <strong>de</strong> área local lográndoseconectar varias máquinas mediante ethernet-links,con las que se mo<strong>de</strong>la una red Ethernet a nivel <strong>de</strong>trama. Esta conexión se pue<strong>de</strong> ver como un cableethernet que va conectado a un dispositivo ethernet<strong>JP2011</strong>-299


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>de</strong> la máquina virtual o como un switch/hub al quepue<strong>de</strong>n conectarse varios dispositivos. El tráfico quese envía sobre dicha conexión pue<strong>de</strong> ser TCP/IP ocualquier otro protocolo que funcione en Ethernet.A esta conexión también se le pue<strong>de</strong> añadir ciertosservicios IP simulados mediante una clase llamadaservice-no<strong>de</strong> que proporciona un nodo <strong>de</strong> red simuladoa modo <strong>de</strong> servidor y que pue<strong>de</strong> actuar como unrouter IP entre re<strong>de</strong>s.Simics permite mejoras en el mo<strong>de</strong>lado <strong>de</strong> sistemas,lo cual es <strong>de</strong> suma importancia para obtenermayores beneficios <strong>de</strong> la simulación, como se pue<strong>de</strong>ver en la Figura 3, don<strong>de</strong> se representan un cluster <strong>de</strong>procesadores, SoCS, memorias, placa y <strong>de</strong>más partes<strong>de</strong> un sistema interconectados para luego ser combinadosa través <strong>de</strong> una estructura jerárquica. Todoello usando las herramientas <strong>de</strong> diseño <strong>de</strong> dispositivoscon los que cuenta Simics Accelerator.Para po<strong>de</strong>r realizar simulaciones en paralelo se <strong>de</strong>becumplir con ciertos requisitos como que los mo<strong>de</strong>lossimulados no <strong>de</strong>ben compartir memoria y quelas arquitecturas a simular permitan simulación multihilo.Dentro <strong>de</strong> los mo<strong>de</strong>los ya diseñados, los quepermiten simulación multihilo son el x86-440bx yMPC8641.Una <strong>de</strong> las razones para comparar las versiones <strong>de</strong>Simics, es para po<strong>de</strong>r <strong>de</strong>terminar si es conveniente ono realizar la actualización a la versión 4 en los trabajosya <strong>de</strong>sarrollados con la versión 3, teniendo encuenta, por ejemplo, la compatibilidad con otras herramientasque extien<strong>de</strong>n Simics como es el caso <strong>de</strong>GEMS (General Execution-driven Multiprocessor Simulator)[7]. GEMS es un programa compuesto porun conjunto <strong>de</strong> módulos que hace posible la simulación<strong>de</strong> sistemas multiprocesadores <strong>de</strong> forma más<strong>de</strong>tallada.Básicamente, GEMS está formado por dos módulos:Ruby y Opal. Ruby permite simular la jerarquía<strong>de</strong> memorias cache, controladores <strong>de</strong> memoria, bancos<strong>de</strong> memoria principal y la red que interconectatodos estos elementos. Opal permite la simulacióncon ejecución fuera <strong>de</strong> or<strong>de</strong>n, para mo<strong>de</strong>lar diferentesarquitecturas, <strong>de</strong>s<strong>de</strong> monoprocesadores hasta multiprocesadorescomo SMPs, CC-NUMAs y CMPs,don<strong>de</strong> es posible la ejecución <strong>de</strong> varios hilos <strong>de</strong> formasimultánea.Si bien originalmente fue <strong>de</strong>sarrollado para el estudio<strong>de</strong> sistemas <strong>de</strong> memoria proporcionando mo<strong>de</strong>los<strong>de</strong> temporización <strong>de</strong>tallados, enfocados a la simulación<strong>de</strong> arquitecturas concretas, ahora tambiénpermite profundizar en otros tipo <strong>de</strong> investigacionescomo las <strong>de</strong> re<strong>de</strong>s <strong>de</strong> interconexión en el chip [8].El inconveniente que por ahora mantiene Simics4es no ser compatible con la actual versión <strong>de</strong> GEMS2.1.1. En la página <strong>de</strong> GEMS se cuenta con un parcheexterno que funciona con las versiones 3.0, 3.2, 4.0,4.2, y 4.4. Sin embargo, también se hace mención queéste no ofrece soporte para el módulo Opal y se retirael soporte para la versión Simics2.2, y en caso <strong>de</strong> quese <strong>de</strong>see trabajar con estos módulos se sugiere usarla versión <strong>de</strong> Simics3 [9]. También se indica que elparche no ha sido probado por el equipo <strong>de</strong> GEMSy no se brindará soporte para el mismo. Según lainformación que se tiene actualmente en los foros yla documentación hay bastantes problemas para laintegración <strong>de</strong> GEMS con Simics4. Recientemente,GEMS informó <strong>de</strong> su integración con el simuladorM5 [10], otro simulador <strong>de</strong> sistema completo, el cualahora se encuentra integrado en un nuevo simuladorllamado GEM5, por lo cual aparentemente GEMSestaría más abocado a dicha integración, <strong>de</strong>jando unpoco <strong>de</strong> lado su continuidad con Simics.III. Evaluación <strong>de</strong> RendimientoEn este trabajo se busca comparar el tiempo <strong>de</strong>simulación entre las versiones 3 y 4 <strong>de</strong> Simics, y cómoinfluye la complejidad <strong>de</strong>l mo<strong>de</strong>lado al aumentar lacantidad <strong>de</strong> procesadores en dicho cálculo.A. Arquitectura mo<strong>de</strong>ladaFig. 3. Ejemplo <strong>de</strong> componentes jerárquicos.B. Simics 4 y GEMSPara la realización <strong>de</strong> las pruebas se usó la arquitecturax86-440BX, la cual pue<strong>de</strong> mo<strong>de</strong>lar variossistemas con procesadores x86 y AMD64 basados enel chipset 440BX. “Tango” es la máquina simulada,que viene ya instalada con Fedora Core 5 con soportepara <strong>de</strong>sarrolladores.En la Tabla II se pue<strong>de</strong>n ver las principales características<strong>de</strong> la máquina simulada utilizada para laspruebas. Por el tipo <strong>de</strong> arquitectura se tiene el límite<strong>de</strong> un máximo <strong>de</strong> ocho procesadores en la placabase. En las pruebas se harán mediciones <strong>de</strong> tiempo<strong>de</strong> simulación en don<strong>de</strong> se variará la cantidad <strong>de</strong>procesadores.<strong>JP2011</strong>-300


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 4. Resultados <strong>de</strong> tiempo <strong>de</strong> simulación <strong>de</strong> aplicaciones PARSECTABLA IICaracterísticas <strong>de</strong> la máquina simulada.Mo<strong>de</strong>lo x86-440BXSlots para CPU 8 máximo.Dump <strong>de</strong> disco tango1-fedora5.craffKernel 2.6.15Procesador 2 GHz Pentium 4Disco duro 20GBMemoria RAM 2 GBB. Aplicaciones PARSECPara la evaluación <strong>de</strong> rendimiento se han realizadopruebas con el benchmark PARSEC, midiendoel tiempo <strong>de</strong> simulación al ejecutar las aplicacionesque forman esta suite. Para po<strong>de</strong>r realizar la mediciónse hace uso <strong>de</strong> las Instrucciones Mágicas (MagicInstructions), para lo cual se compiló el benchmarkPARSEC con la opción gcc-hooks y <strong>de</strong>terminar así elmomento en que entra a una fase la ejecución <strong>de</strong> laaplicación.Dependiendo <strong>de</strong> la arquitectura, se podrá pasar unvalor a través <strong>de</strong> las instrucciones mágicas, teniendocomo referencia el archivo magic-instruction.h don<strong>de</strong>se <strong>de</strong>talla las instrucciones para cada tipo <strong>de</strong> arquitecturay para el caso <strong>de</strong> la arquitectura X86en Simics3 solo se retorna el valor 0 por lo que setendrá que pasar el valor a través <strong>de</strong> los registros <strong>de</strong>lprocesador <strong>de</strong> la máquina simulada [11].De todos los programas <strong>de</strong> la suite PARSEC,aquí se mostrarán resultados <strong>de</strong> las aplicaciones freqmine(fm), fluidanimate (fa) y x264 (x2).C. Realización <strong>de</strong> pruebasPara las pruebas se crearon checkpoints base conuna cantidad <strong>de</strong>terminada <strong>de</strong> procesadores para cadaprueba. Se simularon máquinas con 2, 4 y 8 procesadores.Teniendo en cuenta las diferencias en cómose pasan las instrucciones mágicas en las dos versiones<strong>de</strong> Simics, para cada una <strong>de</strong> ellas se compiló elbenchmark con las instrucciones mágicas correspondientes.Una vez compilado el benchmark a través <strong>de</strong>l API<strong>de</strong> Simics y con un script en python se recogen lasestadísticas <strong>de</strong>l tiempo <strong>de</strong> simulación <strong>de</strong> los distintosprogramas usados. También hay que tener en cuenta,<strong>de</strong> igual forma que para la instrucciones mágicas, quealgunas funciones ya no son soportadas por el nuevoAPI, como es el caso <strong>de</strong> la función run(), que se usaba<strong>de</strong>s<strong>de</strong> la versión <strong>de</strong> Simics 2 y que aún era compatiblepara la versión <strong>de</strong> Simics 3. <strong>La</strong> versión 4 solo soportala función SIM run command().Para la creación <strong>de</strong> los checkpoints se ha <strong>de</strong> teneren cuenta que no son compatibles para las versionesanteriores, lo que quiere <strong>de</strong>cir que en caso <strong>de</strong> quecreemos un checkpoint con la versión <strong>de</strong> Simics 4 nopodrá ser leída con la <strong>de</strong> Simics 3. Otro punto a teneren cuenta es que la nueva versión <strong>de</strong> Simics asignaun código al momento <strong>de</strong> crear el checkpoint que seguarda en la variable build id en el archivo <strong>de</strong> configuración.Al migrar un checkpoint este código pue<strong>de</strong>dar problemas al no i<strong>de</strong>ntificar la misma versión porlo que en caso <strong>de</strong> que sea necesario tendrá que sermodificado.<strong>La</strong>s imágenes <strong>de</strong>l disco trabajadas entre distintasversiones pue<strong>de</strong>n ser reutilizadas entre versiones, <strong>de</strong>igual forma las que han sido agrupadas con las diferencias<strong>de</strong> disco con la herramienta craff <strong>de</strong> Simics.Lo único que se tiene que tener en cuenta es la compatibilidadcon las instrucciones mágicas <strong>de</strong> cada versión.D. ResultadosUna vez realizadas las ejecuciones <strong>de</strong> las aplicacionesse obtuvieron los tiempos <strong>de</strong> simulación por cadauna. En la Figura 4 se pue<strong>de</strong> ver el tiempo <strong>de</strong> simulaciónpara las dos versiones <strong>de</strong> Simics a estudiar,y para las aplicaciones utilizadas. En las gráficas sepue<strong>de</strong> apreciar que las simulaciones realizadas con lanueva versión <strong>de</strong> Simics se completan con un menortiempo <strong>de</strong> simulación que con la versión anterior. Engeneral, y como parece lógico, al aumentar la cantidad<strong>de</strong> procesadores el tiempo <strong>de</strong> simulación tambiénaumenta, lo que se pue<strong>de</strong> apreciar más claramentepara la versión <strong>de</strong> Simics 3.De las pruebas realizadas, se obtiene un mayor rango<strong>de</strong> diferencia en el tiempo <strong>de</strong> simulación para elcaso <strong>de</strong> la aplicación freqmine. Para este caso se obtieneuna reducción <strong>de</strong>l tiempo <strong>de</strong> simulación <strong>de</strong> 61 %para 2 procesadores, 70,1 % para 4 procesadores y<strong>JP2011</strong>-301


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 201185,4 % para 8 procesadores.Por contra, con la aplicación x264 es en don<strong>de</strong> ladiferencia es menor. En este caso se obtiene un 22,6 %para 2 procesadores, 53,9 % para 4 procesadores y69,6 % para 8 procesadores.En la Figura 5 se pue<strong>de</strong> observar el tiempo total<strong>de</strong> simulación para las pruebas realizadas, es <strong>de</strong>cir eltiempo que tomaría haber ejecutado las 3 aplicaciones<strong>de</strong> la suite simultáneamente. En este caso tenemosuna reducción <strong>de</strong>l tiempo <strong>de</strong> simulación <strong>de</strong> 45 %cuando son 2 procesadores, 58 % para 4 procesadoresy 75 % para 8 procesadores.Para las pruebas con 8 procesadores se obtiene cerca<strong>de</strong> un 10 % <strong>de</strong> mejor rendimiento por cada procesador.En promedio, se pue<strong>de</strong> alcanzar un 60 % <strong>de</strong>reducción en tiempo <strong>de</strong> simulación respecto a la versión3.Fig. 5. Tiempos totales <strong>de</strong> simulación.IV. Conclusiones<strong>La</strong>s mejoras en cuanto a aceleración <strong>de</strong> procesos ytiempo <strong>de</strong> simulación para la nueva versión <strong>de</strong> Simicseliminan cuellos <strong>de</strong> botella y mejoran el rendimientoen mo<strong>de</strong>los complejos, realizando varias simulacionesen paralelo y aprovechando el po<strong>de</strong>r <strong>de</strong> procesamiento<strong>de</strong> un host multinúcleo o incluso un cluster.<strong>La</strong>s mejoras en cuanto a sincronización <strong>de</strong> tiemposen la simulación y la administración <strong>de</strong> informaciónredundante al momento <strong>de</strong> ejecutar el benchmark llegana reducir en promedio un 60 % <strong>de</strong> tiempo <strong>de</strong>simulación para las pruebas realizadas con las aplicacionesfreqmine, fluidanimate y x264 <strong>de</strong>l PARSEC.Y para el caso <strong>de</strong> una simulación con una máquinacon 8 procesadores se llega a obtener hasta un 10 %<strong>de</strong> reducción en tiempo <strong>de</strong> simulación por cada procesador.En general, las mejoras obtenidas por la nueva versión<strong>de</strong> Simics4 son muy positivas permitiendo realizarsimulaciones con una mayor cantidad <strong>de</strong> procesadoressin tener una gran <strong>de</strong>manda en tiempo<strong>de</strong> simulación, permitiendo así analizar mo<strong>de</strong>los máscomplejos.El punto débil por el momento <strong>de</strong> la nueva versión<strong>de</strong> Simics es la no compatibilidad con otros programasque lo extien<strong>de</strong>n, como es el caso <strong>de</strong> GEMS, elcual es compatible con la versión 3 <strong>de</strong> Simics y actualmenteno ofrece soporte para la nueva versión.A<strong>de</strong>más, es posible que no lo tenga en cuenta por suactual trabajo en el nuevo simulador GEM5En el momento <strong>de</strong> redactar este documento, se estabaindicando un estudio para mejorar las simulacionescon paralelismo <strong>de</strong> núcleos y su análisis, loscuales <strong>de</strong>pendían <strong>de</strong>l uso <strong>de</strong> GEMS pero al tener problemaspara la compilación <strong>de</strong> sus módulos se podríatener en cuenta para un futuro trabajo el análisis <strong>de</strong>lnuevo simulador para las investigaciones con máquinasmultinúcleo.Agra<strong>de</strong>cimientosEste trabajo ha sido realizado gracias a la beca <strong>de</strong>ayudas <strong>Universidad</strong> <strong>de</strong> Castilla-<strong>La</strong> Mancha - BancoSantan<strong>de</strong>r para estancias <strong>de</strong> investigación <strong>de</strong> profesoresiberoamericanos en la <strong>Universidad</strong> <strong>de</strong> Castilla-<strong>La</strong>Mancha en 2011Referencias[1] Jakob Engblom, Daniel Aarno, and Bengt Werner Full-System Simulation from Embed<strong>de</strong>d to High-PerformanceSystemsl, Processor and System-on-Chip Simulation, pp.25-44 , 2010.[2] Jakob Engblom, Simics Accelerator, in Whitepaper Virtutech,March 2009.[3] Christian Bienia, Sanjeev Kumar, Jaswin<strong>de</strong>r PalSingh,and Kai Li, The PARSEC Benchmark Suite:Characterization and architectural implications, in Proceedingsof the 17th International Conference on ParallelArchitectures and Compilation Techniques, October 2008[4] Simics Mo<strong>de</strong>ls, http://www.virtutech.com/products /simicsmo<strong>de</strong>ls[5] Jakob Engblom, Transaction-Level Mo<strong>de</strong>ling in Simic, inWhitepaper Virtutech, August 2009.[6] Magnusson, P., Christensson, M., Eskilson, J., Forsgren,D., Hallberg, G., Hogberg, J.,<strong>La</strong>rsson, F., Moestedt, A.,Werner, B. Simics: A full system simulation platform,Computer, Innovative Technology for Computer Professionals,pp. 50-58, Febrary 2002.[7] Milo M. K. Martin, Daniel J. Sorin, Bradford M. Beckmann,Michael R. Marty, Min Xu, Alaa R. Alamel<strong>de</strong>en,Kevin E. Moore, Mark D. Hill, and David A. Wood, Multifacet’sgeneral execution-driven multiprocessor simulator(GEMS) toolset,, SIGARCH Comput. Archit.News, vol.33, no. 4, pp. 92-99, 2005.[8] Francisco Triviño, Francisco J. Andujar, Alberto Ros,José L. Sánchez, Francisco J. Alfaro Sistema Integrado<strong>de</strong> Simulación <strong>de</strong> NoCs, XX Jornadas <strong>de</strong> Paralelismo <strong>La</strong>Coruña(Spain). Septiembre 2009.[9] Multifacet GEMS: External patches for Simics,http://www.cs.wisc.edu/gems/common/release notes/gems2.1.1 patch1 releasenotes.txt[10] The GEM5 Simulator System, http://gem5.org/[11] Virtutech: Simics User Gui<strong>de</strong> forUnix, pp 143-145, Febrary 2008.https://www.simics.net/pub/simics/3.0 fyr609/simicsuser-gui<strong>de</strong>-unix.pdf<strong>JP2011</strong>-302


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Arquitecturas, algoritmos y aplicaciones sobreaceleradores hardware<strong>JP2011</strong>-303


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-304


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Parallelization of the Generalized HoughTransform on GPUJuan Gómez-Luna 1a , José María González-Linares b , José Ignacio Benavi<strong>de</strong>s a , Emilio L. Zapata b andNicolás Guil bAbstract–Programs <strong>de</strong>veloped un<strong>de</strong>r the ComputeUnified Device Architecture (CUDA) obtain the highestperformance rate, when the exploitation of hardwareresources on a Graphics Processing Unit (GPU) ismaximized. In or<strong>de</strong>r to achieve this purpose, loadbalancing among threads and a high value of processoroccupancy, i.e. the ratio of active threads, areindispensable. However, in certain applications, anoptimally balanced implementation may limit theoccupancy, due to a greater need of registers and sharedmemory. This is the case of the Fast Generalized HoughTransform (Fast GHT), an image processing technique forlocalizing an object within an image. In this work, wepresent two parallelization alternatives for the Fast GHT,one that optimizes the load balancing and another thatmaximizes the occupancy. We have compared them using alarge amount of real images to test their strong and weakpoints and we have drawn several conclusions about un<strong>de</strong>rwhich conditions it is better to use one or another. We havealso tackled several parallelization problems related tosparse data distribution, divergent execution paths andirregular memory access patterns in updating operationsby proposing a set of generic techniques as compacting,sorting and memory storage replication.Keywords–GPU, CUDA, occupancy, load balancing,Generalized Hough Transform.GI. INTRODUCTIONRAPHICS Processing Units (GPUs) haveemerged as general purpose coprocessors inthe last years. An extensive variety ofapplications is nowadays benefiting from theirimpressive potential, especially after the launch ofCUDA [9]. GPUs offer a huge amount of computingthreads, arranged in a Single-Program Multiple-Data(SPMD) mo<strong>de</strong>l. Such extensive resources make themattractive for general-purpose computations. Thisinterest has boosted the <strong>de</strong>velopment of GPUprogramming tools, such as CUDA and OpenCL [10].General programming recommendations are optimizingload balancing and increasing processor occupancy.However, <strong>de</strong>pending on the algorithm structure, bothrecommendations cannot be applied simultaneously.Then some kind of tra<strong>de</strong>off must be un<strong>de</strong>rtaken, since anoptimally balanced implementation may increase the useof registers and the need for sharing data among threads,what <strong>de</strong>creases occupancy. Moreover, parallelizationbecomes even more challenging, if the algorithmpresents workload-<strong>de</strong>pen<strong>de</strong>nt computations and nonlinearmemory references. The former provokes1 Corresponding author: el1goluj@uco.esa Computer Architecture and Electronics Department,University of Córdoba, Córdoba, Spainb Computer Architecture Department, University ofMálaga, Málaga, Spaindivergence among threads, if the layout is not carefullyplanned. The latter affects the locality of references,what entails serialized memory accesses.In this work, we will discuss how performanceproblems caused by previous consi<strong>de</strong>rations can bemitigated using suitable strategies. They will beillustrated by implementing an efficient parallelizationof the GHT. We conduct an exhaustive analysis of theprevious consi<strong>de</strong>rations that leads us to the followingresults:• We propose compacting and sorting, in or<strong>de</strong>r toreduce accesses to global memory and thenumber of executed instructions.• We present two efficient mechanisms fordistributing two sorted lists among blocks andthreads. One of them optimizes the loadbalancing, whilst the other maintains theoccupancy at the highest possible values.• We use replicated sub-histograms per blockwith successful results.The rest of the paper is organized as follows. Section 2<strong>de</strong>picts the characteristics of regular and irregularapplications. Section 3 presents the GHT. Section 4<strong>de</strong>scribes our proposals for an efficient implementationof irregular parts. In section 5, we propose the use ofreplicated sub-histograms per block, in or<strong>de</strong>r to improvea voting process. Section 6 presents the executionresults. Finally, section 7 conclu<strong>de</strong>s the paper.II. REGULAR AND IRREGULAR PROBLEMSParallelizing any application on any parallel platformrequires programmers to apply a certain level ofabstraction. The change from a sequential conception toa parallel conception is never trivial. However, somealgorithms are regular in the sense that they use linearaddressing and apply the same computation on everyinstance of the input data. This inherent parallelismmakes those algorithms to be easier to implement on aSPMD platform, as is a GPU. In this regard, manyimage and vi<strong>de</strong>o processing applications exhibit regularcomputation patterns and regular memory accesses. TheCUDA SDK inclu<strong>de</strong>s some samples of regular imageprocessing.Following the optimization recommendations when aregular problem is parallelized, ensures a goodperformance and impressive speedups on CUDAenabledGPUs. However, achieving an importantimprovement with the implementation of an irregularproblem is always har<strong>de</strong>r. The distribution of work anddata in such algorithms cannot be characterized a priori,because these quantities are input-<strong>de</strong>pen<strong>de</strong>nt and evolvewith the computation itself. Algorithms with theseproperties yield performance problems for parallelimplementations, where equal distribution of work over<strong>JP2011</strong>-305


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011processors and locality of reference are required withineach processor. In this way, programmers shouldcarefully analyze the memory access patterns, in or<strong>de</strong>r toavoid penalties due to uncoalescing or bank conflicts.Idle threads and warp divergence should be minimizedby properly planning of work distribution and loadbalancing across threads and blocks.III. PARALLELIZING A COMPLEX IMAGE AND VIDEOPROCESSING APPLICATIONThis work illustrates different strategies to cope withsparse data array access, divergent execution paths andirregular memory access patterns in GPU applicationsusing, as a case study, a version of the GeneralizedHough Transform, called Fast GHT. As it is explainednext, this technique presents regular as well as irregularcomponents.A. The Generalized Hough TransformTemplate matching is a difficult problem with highcomputational requirements. One of the most popularalgorithms for <strong>de</strong>tecting shapes in images is the HoughTransform [8]. Ballard [1] generalized the HoughTransform (GHT) to <strong>de</strong>tect arbitrary shapes, which arerepresented by a template. In the original formulation,called Classic GHT, a feature space (composed of thetemplate contour points and their vectors to a referencepoint) is transformed into a four-dimensional Houghspace (the rotation, scale and displacement of thetemplate in the image). The maximum value in thisHough space corresponds to the rotation, scale anddisplacement parameters of the template in the image.The size of the Hough space and the number of votingoperations can be enormous. Thus, the computation timeof the Classic GHT is very high, making it inappropriatefor real-time applications. A solution to reduce thememory and computational requirements were presentedby Guil et al [6]. In that work, the <strong>de</strong>tection process issplit into three stages by uncoupling the rotation, scaleand displacement calculation using invariantinformation. Three transforms are applied in thisversion, called Fast GHT, to obtain the rotation, scaleand displacement parameters.The invariant features selected in that work arepairings of contour points, p i and p j , whose gradientangles, θ i and θ j, are separated by a given differenceangle ξ . For every pairing a spatial angle, α ij, adistance value, d ij , and reference vectors, r i and r j, arecomputed as shown in Figure 1. The feature space(composed of the pairings with their gradient angles,spatial angles, distances and vectors) is transformed in atwo-dimensional Hough space (the gradient and spatialangles) with every pairing voting in the bin with thesame gradient and spatial angle. The Hough spaces ofthe template and the image can be compared using aspecial cross-correlation function whose maximumvalue is located in the rotation value, β , of the templatein the image.Next, the gradient angles of the pairings in thetemplate are rotated β <strong>de</strong>grees and a new transform in aone-dimensional Hough space (the scale parameter) isapplied. Every pairing in the template and the imagefeature space with the same gradient and spatial anglesare selected and the quotient of their distances is used tovote in the Hough space. The position of the maximumof the Hough space is the scale parameter. Finally, thereference vectors of the pairings in the template arerotated and scaled using the calculated parameters, and atransform in a two-dimensional Hough space (thedisplacement coordinates) is computed. Pairings withthe same gradient and spatial angles are selected and thevectors superimposed to vote in the Hough space whosemaximum corresponds to the position of the template inthe image.Fig. 1. Variables <strong>de</strong>fined in the GHTLet T be the template, I the image, (x i , y i ) thecoordinates of an edge point p i , ξ the difference angle,O , S and D the Hough spaces to computeorientation, scale and displacement respectively, andmaxi(Μ) a function that returns the in<strong>de</strong>x where themaximum value of Μ takes place, the algorithm steps inpseudo-co<strong>de</strong> are1. Compute contour points pi = { xi, yi, θi}in TT T2. For each pairing { pi, pj} with θ i − θ j = ξ ,<strong>de</strong>fT compute p = { α , d , r, r }ijTij ij i j3. For each p T ij increment O ( θi, αij)4. Repeat steps 1, 2, 3 for I to obtain p I ij ,IT<strong>de</strong>fp IijandOI T5. β = maxi( corr( O , O ))6. Rotate template contour points<strong>de</strong>fTpi = { xi, yi, θi+ β}7.T IFor each { pij, pkl} with θ i = θ k and α ij − α klincrement S ( dij, dkl)8. ς = maxi( S )9. Scale vectors in p Tij using ςT I10. For each { pij, pkl} with θ i = θ k and α ij − α kl,increment D (( xk, yk) + ri), D (( xk, yk) + rj),D (( x , y ) + r) and D (( x , y ) + r)11. ( )i i iδx, δ y = maxi( D )i i jB. Regular computation within the GHTEdge <strong>de</strong>tection and correlation, applied in steps 1 and5 respectively, exhibit a regular parallelism, since asimple workload distribution guarantees a good load<strong>JP2011</strong>-306


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 2. Our implementation of the GHT: Stages in blue compute the O , S and D Hough spaces; stages in green compact and/or sort theworkloads of the kernels.balance, coalesced memory accesses and, consequently,good performance values. Edge <strong>de</strong>tection is performedusing the wi<strong>de</strong>ly known Canny algorithm [2]. Theversion of the Canny edge <strong>de</strong>tector, used in this work,was <strong>de</strong>veloped by Gómez-Luna et al. [4].Correlation between O T and O I is implementedusing a separable convolution [12]. Correlation isapplied once per each possible rotation angle of thetemplate within the image. Finally, the functionmaxi(M), used in step 5 to obtain β , is performed by akernel which follows the optimizing strategies presentedin the CUDA parallel reduction [7].C. Irregular computation within the GHTComputation of O (steps 2-3), S (steps 6-7) and D(steps 9-10) Hough spaces is not regular. All thesestages have some common features as far as memoryaccesses and work distribution are concerned:• Computation of the three Hough spacesrequires some kind of features comparison,followed by some computation, among theelements of the corresponding input workload,as stated in steps 2, 7 and 10.• The features comparisons in steps 2, 7 and 10need a huge number of memory accesses,which seriously penalizes the performance. Bysorting the input workload, the number ofmemory accesses will be greatly reduced.• O , S and D Hough spaces are generatedduring a voting process. This entails the use ofatomic additions –in shared or global memory,<strong>de</strong>pending on the size of the voting space–,which serialize the execution. In Section V, wepropose the replication of the Hough spaces, inor<strong>de</strong>r to <strong>de</strong>crease the impact of serialization.Figure 2 shows a scheme of our implementation of theGHT, which is thoroughly <strong>de</strong>scribed in Sections IV andV. Stages in blue correspond to kernels that perform thecomputation of the O Hough spaces (Search forpairings), the S Hough space (Scale calculation) andthe D Hough space (Displacement calculation). Stagesin green represent the primitives applied for regularizingthe problem by compacting and/or sorting the workloadsof the kernels.IV. EFFICIENT MEMORY ACCESS AND WORKDISTRIBUTIONIn this section, we <strong>de</strong>tail how to re-organize theworkloads, in or<strong>de</strong>r to obtain an efficient computation ofthe Hough spaces on the GPU. Then, we propose twomechanisms for efficiently distributing the workloadsamong blocks and threads.A. Re-organizing the workload: compacting andsortingAn efficient implementation of the search for pairingsrequires the compaction of the whole set of contourpoints into a <strong>de</strong>nse list. Thus, for each contour point inthe template or the image, a tuple p i composed of itsgradient direction θ i and its coordinates (x i , y i ) is storedinto a List of Template Edges (LTE) or a List of ImageEdges (LIE). The compact primitive returns a List ofEdges composed by three output arrays: one for thegradient directions and two for the coordinates. Thegradient directions are used to <strong>de</strong>tect pairings and,together with the coordinates, are nee<strong>de</strong>d for computingthe angle α ij. The CUDPP library [3] inclu<strong>de</strong>s acompact primitive based on the prefix sum or scanoperation, that we have used.As it is shown in Figure 2, the List of Edges is theworkload of the kernel that performs the search forpairings. It outputs a List of Template or Image Pairings(LTP or LIP), whose elements are tuples p ij , and aT Itemplate or image O Hough space ( O or O ). LTPand LIP are <strong>de</strong>nse lists used as inputs for the scale andthe displacement calculations. Due to implementationconvenience, tuples p ij in a List of Pairings contain thein<strong>de</strong>x of the pairing in the corresponding O Houghspace ( αθ _ in<strong>de</strong>x = αij× 90+ θi), the in<strong>de</strong>x of eachcontour point ( pk _ in<strong>de</strong>x = yk × width + xk, where widthis the width of the image) and the distance betweenthese paired contour points (d ij ).At this point, we propose a previous sorting of the<strong>de</strong>nse lists, in or<strong>de</strong>r to minimize global memoryaccesses. In the search for pairings, the List of Edgescan be sorted by the quantized gradient direction. Then,given a certain value of the quantized gradient direction,this value plus the difference angle (ξ ) <strong>de</strong>termines thepart of the List of Edges where the pairing points lie. Inthe scale and the displacement calculations, the Lists ofPairings are sorted by the αθ _ in<strong>de</strong>x , that is, pairingsare grouped in sub-lists with the same α and θ values.B. Work distribution among blocks and threadsIn this sub-section we present two mechanisms forworking with the created sorted lists. Both can beapplied to the search for pairings and to the scale anddisplacement calculations.As it is seen in Figure 2, computing stages (in blue)which generate the Hough spaces use sorted <strong>de</strong>nse lists<strong>JP2011</strong>-307


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011as inputs. We assume that two lists (List1 and List2) arethe inputs to the computing stages. Specifically, LTPand LIP are List1 and List2 for scale and displacementcalculations and in the case of the search for pairings, aTemplate or Image List of Edges takes the role of bothList1 and List2.We consi<strong>de</strong>r a kernel, whose inputs are two <strong>de</strong>nse lists(List1 and List2), which have been sorted by an in<strong>de</strong>x I.List1 and List2 are divi<strong>de</strong>d into sub-lists, in which everytuple has the same in<strong>de</strong>x. Each list has its own constantarray associated (Pointers array), in which the k thelement contains the position of the list where the sublistwith in<strong>de</strong>x I equal to k starts. Pointers arrays areplaced in constant memory or texture memory,<strong>de</strong>pending on their size, since they are read-only data.Each block takes one chunk of List1, belonging to asub-list with a certain in<strong>de</strong>x I 1 , and loads it in sharedmemory. Each thread loads just one tuple of the chunk,thus the size of the chunk is at most the number ofthreads in a block. Then, the block performs an iterativeprocess with an outer and an inner loop. The outer loopaccesses those chunks of List2, which belong to the sublistwith an in<strong>de</strong>x I 2 that fulfills a certain condition withrespect to the in<strong>de</strong>x I 1 . The inner loop distributes thework among the threads, which perform somecomputation using one tuple from List1 and anotherfrom List2. The following co<strong>de</strong> summarizes this process:Load chunk of List1 sub-list with I1 in sharedmemory;I2 = function of I1;// Outer loop:For (each chunk of sub-list with I2 of List2)Load chunk in shared memory or registers;// Inner loop:For (<strong>de</strong>pending on mechanism)// Compare and compute:If (Features comparison)Computation(tuple List1,tuple List2);Work distribution within the inner loop can be done intwo ways that are explained next: the first one achievesan optimal load balancing, while the second one focuseson increasing occupancy of the multi-processors.1) Load-balancing (LB) mechanismA load-balancing work distribution must ensure thatevery thread will perform the same number of featurescomparisons or, in other words, the same number ofiterations of the inner loop. The red chunk in Figure 3contains n tuples and the blue chunk contains m. Valuesn and m are less or equal to the number of threads in theblock (block_size). Thus, the number of comparisons isn× m. Thread N performs the N th comparison, the N th +block_size, and so on. This mechanism requires thatevery tuple of the chunk of List2 is available for everythread. Thus, the chunk of List2 is loa<strong>de</strong>d in sharedmemory.2) Save-shared-memory (SSM) mechanismAlthough the former mechanism ensures an optimalload balancing, it requires loading two chunks in sharedmemory. Unfortunately, the occupancy is <strong>de</strong>termined bythe amount of shared memory and registers used by eachthread block, thus load balancing can affect negativelythe efficiency. We propose a new mechanism, SSM,which saves shared memory to increase occupancy.This mechanism, as it can be seen in Figure 4, assignsone tuple of the chunk of List2 to one thread, so thateach thread loads only its tuple in registers. Then, thethread performs the comparisons between its tuple andall the tuples of the chunk of List1. Since usually thenumber of tuples with the same in<strong>de</strong>x I is not a multipleof the block size, there will be idle threads in the innerloop. Nevertheless, we expect a good performance dueto the increase of occupancy.V. REPLICATION OF THE VOTING SPACEImplementations of the three stages have also incommon the fact that they perform a voting process,which is the generation of some kind of histogram.Since voting operations entail unpredictable memoryaccesses, efficient implementations use several copies orsub-histograms, in or<strong>de</strong>r to reduce conflicts amongthreads, while updating the histogram bins.The CUDA SDK implementations of 64- and 256-binshistograms [11] use, respectively, per-thread and perwarpsub-histograms, which are lied in shared memory.At the end of the process, all the sub-histograms aremerged into a single histogram in global memory.However, the use of per-thread sub-histograms is limitedto those cases in which the number of bins of thehistogram is very small. On the other hand, thedrawback of per-warp sub-histograms, with respect toper-thread, is the use of atomic additions in sharedmemory. Since every thread, belonging to a half-warp,tries to access the same sub-histogram at the same time,serialization is unavoidable.For both reasons, we propose the use of replicated subhistogramsper block in shared memory. Threads of eachblock access more than one sub-histogram. If M subhistogramsper block are <strong>de</strong>clared, thread number Naccesses sub-histogram N%M, where % stands for theoperation modulo. This represents an improvement withrespect to per-warp sub-histograms, since consecutivethreads, belonging to the same warp, access differentsub-histograms, reducing serialization due to atomicadditions. There will be an optimal value of M, whichrepresents a tra<strong>de</strong>-off between reducing serialization,when using atomic additions, and preserving a goodvalue of occupancy.Replication is also useful in global memory, in or<strong>de</strong>r toreduce serialization while using atomic functions. In thecase of the displacement calculation, since the DHough space does not fit in shared memory, the wholevoting space is replicated in global memory.VI. EXPERIMENTAL RESULTSIn this section, a thorough analysis of theimprovements achieved by the proposed techniques iscarried out. In addition, the impact of theseimprovements in the final performance of the GHT isevaluated. Thus, we have analyzed the impact of theirregular stages in the total execution times as they arethe most time-consuming ones in the GHT. In fact,computation of O , S and D Hough spaces requiremore than 90% of the execution time while Canny<strong>de</strong>tection, rotation calculation, compacting and sortinghave negligible execution times. Tests have been ma<strong>de</strong>on a GeForce GTX 280 GPU.<strong>JP2011</strong>-308


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 3. Load-balancing mechanism: Each thread performs approximately the same number of features comparisons, represented by blackarrows. For the sake of clarity, blocks of 8 threads are represented.Fig. 4. Save-shared-memory mechanism: Each thread performs the features comparisons of one tuple, as indicated by the black arrows.Although the GHT was originally <strong>de</strong>signed to <strong>de</strong>tectarbitrary shapes in two-dimensional images, it can beeasily applied to vi<strong>de</strong>o processing [13]. We haveselected this real application for the experiments becausevi<strong>de</strong>os provi<strong>de</strong> an assorted database of images to test ourimprovements, especially when the chosen vi<strong>de</strong>osbelong to different genres. In Table I the workloads ofthe four vi<strong>de</strong>os used in the experiments are shown.These vi<strong>de</strong>os have been selected from the MPEG-7Content Set.TABLE ITEST WORKLOADS CHARACTERISTICS. VIDEOS HAVE A RESOLUTIONOF 352× 288 PIXELS. NUMBER OF EDGE POINTS AND PAIRINGS AREAVERAGE VALUES. EACH VIDEO IS CONSISTING IN 4000 FRAMESVi<strong>de</strong>o Edge points Pairings (ξ = 90º)Cycling 2778 78770Movie 1436 13332Basket 5061 140030Drama 2684 54921tuples per sub-list, so that the number of chunks in asub-list changes between 1 and 6.In the case of SSM, the saving of shared memorypermits 5 blocks of 128 threads per multi-processor, onemore than LB. On the other hand, LB guarantees anoptimal load balancing, while SSM will have idlethreads in the last block assigned to a sub-list. Usingblocks of 128 threads, if each sub-list contains T tuples,this last block have only T%128 active threads.A. An exhaustive comparison between the loadbalancingand the save-shared-memory mechanismsWe are not able to assert which of the mechanisms isbetter, since both have their own strong points. For thisreason, we have compared both mechanisms changingthe size and data distribution of a sorted list. Withoutloss of generality, we have used a synthetic sorted list,equally divi<strong>de</strong>d among sub-lists with different in<strong>de</strong>xvalues. Each element of the synthetic sorted listemulates a tuple. Since each block works with chunksbelonging to a sub-list, we have changed the number ofFig. 5. Comparison between SSM and LB using a synthetic sorted list.The number of blocks assigned to a sub-list has been changedfrom 1 to 6, as the abscissas showsWe have carried out 55 tests of the SSM and LBmechanisms, changing the number of tuples of the sublists.Figure 5 presents the execution results for thesetests. Abscissas represent the number of 128-tupleschunks per sub-list, which is also the number of blocksworking with the same sub-list. The graph on the topshows the ratio between the execution times of LB andSSM. Values above 1 mean the SSM mechanism runs<strong>JP2011</strong>-309


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLE II.AVERAGE EXECUTION TIMES (MS) OF THE MAIN PARTS OF THE APPLICATION FOR FOUR VIDEOS. THE NUMBER BESIDE THE NAME OF THESTRATEGY REPRESENTS THE REPLICATION FACTOR.Vi<strong>de</strong>o CannySearch for pairingsScaleDisplacementOrientationLB(1) SSM(2) LB(8) SSM(16) LB(64) SSM(64)Cycling 0.45 1.78 1.66 5.68 86.53 53.10 265.02 210.09Movie 0.46 0.28 0.63 5.66 20.13 18.37 29.93 22.29Basket 0.46 1.13 1.36 5.68 102.38 83.83 198.09 152.28Drama 0.46 0.67 0.99 5.66 49.31 42.00 85.17 60.07faster. The graph on the bottom shows two columns foreach test. The left column (yellow), called “%<strong>La</strong>stblock”, represents the percentage of active threads in thelast block assigned to a sub-list, in SSM. The rightcolumn (green), called “%GPU”, stands for thepercentage of active threads in the whole GPU, in SSM.The higher these values the better is the distribution ofthe workload in SSM. Thus, both columns give a hint ofthe computational load balance of SSM.For a number of blocks per sub-list between 1 and 4,there exists a value of “%<strong>La</strong>st block” which <strong>de</strong>terminesthat the SSM mechanism outperforms the LB onebecause the impact of load unbalance is less importantthan the occupancy value. When the number of blocksper sub-list is 5 or more, the SSM mechanism alwaysperforms better due to the higher occupancy, whichpermits to execute more blocks simultaneously.B. Replication for the generation of Hough spacesIn the search for pairings, the case with 2 replicatedsub-histograms results in 13% improvement with respectto the per-warp approach.The size of the S Hough space is not critical foroccupancy. Such a small size permits to attempt evensub-histograms per thread. The best case is a per blockreplication of 16. It works 28% faster than the per-warpapproach and 109% faster than the per-thread approach.Displacement calculation replicates the D Houghspace in global memory. The best approach is withreplication of 64, obtaining a speedup of 3.2 with respectto the version without replication.C. Comparison among implementationsThe execution times of the different implementationsof the main parts of the application are shown in TableII. Results reflect that the search for pairings performsbetter using the LB mechanism in three of the fourvi<strong>de</strong>os. This makes sense with the conclusions presentedin sub-section VI.A because the size of the sub-lists issmall. If the number of tuples increases, the percentageof idle threads <strong>de</strong>creases for SSM. In this way, its loadbalancing improves and the occupancy becomes more<strong>de</strong>cisive. This explains that SSM outperforms LB forscale and displacement calculations, since the Lists ofPairings are much longer than the Lists of Edges.VII. CONCLUSIONSThis work has studied how load balancing andoccupancy impact the performance of an application ona GPU using the CUDA environment. This analysis hasbeen carried out through the parallelization of the FastGeneralized Hough Transform (Fast GHT).We have implemented and compared two generalparallelization strategies. One, called Load Balancing(LB), tries to obtain an optimum load balancing. Anotherone, called Saved Shared Memory (SSM), tries tomaximize processor occupancy by reducing data loa<strong>de</strong>din shared memory. Results show the SSM mechanismoutperforms the LB one when there is enough input datafor every simultaneous block in the GPU. We have alsominimized the impact of divergent execution paths bycompacting and sorting the input data.Memory accesses conflicts have been addressed in twoways <strong>de</strong>pending on if they were read or write accesses.Read accesses to global memory have been minimizedby sorting input data. Unpredictable write accesses canseriously reduce the performance due to memory bankconflicts and serialization, but by replicating the writearea these conflicts are minimized. We have proposed anew technique that replicates in shared memory data perblock and compared it with the common strategy ofreplicating per warp, obtaining a better performance.Voting spaces are also replicated in global memory withsuccessful results.REFERENCES[1] Ballard, D.H. (1981). Generalizing the Hough transform to <strong>de</strong>tectarbitrary shapes. Pattern Recognition 13 (2): 111-122.[2] Canny, J. (1986). A computational approach to edge <strong>de</strong>tection.IEEE Transactions on Pattern Analysis and Machine Intelligence8 (6): 679-698.[3] CUDPP (2010). CUDA Data Parallel Primitives Library homepage. http://co<strong>de</strong>.google.com/p/cudpp[4] Gómez-Luna, J., González-Linares, J.M., Benavi<strong>de</strong>s, J.I. and Guil,N. (2009). Parallelization of a vi<strong>de</strong>o segmentation algorithm onCUDA-enabled Graphics Processing Units. In proceedings of 15thInternational Euro-Par Conference (Euro-Par’09), pp. 924-935.[5] Green, S. (2007). CUDA particles.http://<strong>de</strong>veloper.nvidia.com/object/cuda_sdk_samples.html[6] Guil, N., González-Linares, J.M. and Zapata, E.L. (1999).Bidimensional shape <strong>de</strong>tection using an invariant approach.Pattern Recognition 32 (6): 1025-1038.[7] Harris, M. (2007). Optimizing parallel reduction in CUDA.http://<strong>de</strong>veloper.nvidia.com/object/cuda_sdk_samples.html[8] Hough, P.V.C. (1962). Method and means for recognizingcomplex patterns. U.S. Patent 3069654.[9] NVIDIA (2007). NVIDIA CUDA home page.http://www.nvidia.com/cuda[10] OpenCL (2009). OpenCL home page.http://www.khronos.org/opencl[11] Podlozhnyuk, V. (2007a). Histogram calculation in CUDA.http://<strong>de</strong>veloper.nvidia.com/object/cuda_sdk_samples.html[12] Podlozhnyuk, V. (2007b). Image convolution with CUDA.http://<strong>de</strong>veloper.nvidia.com/object/cuda_sdk_samples.html[13] Sáez, E., González-Linares, J.M., Palomares, J.M., Benavi<strong>de</strong>s, J.I.and Guil, N. (2003a). New edge-based feature extractionalgorithm for vi<strong>de</strong>o segmentation. In proceedings of Image andVi<strong>de</strong>o Communications and Processing (SPIE’03), pp. 861-872.<strong>JP2011</strong>-310


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011rCUDA: Uso Concurrente <strong>de</strong> DispositivosCompatibles con CUDA <strong>de</strong> Forma Remota.Adaptación a CUDA 4Carlos Reaño, Antonio J. Peña, Fe<strong>de</strong>rico Silla y José Duato 1Rafael Mayo y Enrique S. Quintana-Ortí 2Resumen—<strong>La</strong>s mejoras realizadas en las GPUs (GraphicsProcessor Units) en la última década han propiciado queéstas sean utilizadas para incrementar el rendimiento enlos sistemas <strong>de</strong> computación <strong>de</strong> altas prestaciones. A esterespecto, NVIDIA viene <strong>de</strong>sarrollando <strong>de</strong>s<strong>de</strong> 2007 unanueva tecnología <strong>de</strong>nominada CUDA (Compute UnifiedDevice Architecture) que permite <strong>de</strong>scargar en la GPU granparte <strong>de</strong> los cómputos <strong>de</strong> la aplicación. En general, elprincipal inconveniente <strong>de</strong> esta ten<strong>de</strong>ncia es el aumento <strong>de</strong>energía que introducen las GPUs. Si, a<strong>de</strong>más, tenemos encuenta que en este tipo <strong>de</strong> sistemas no se suelen utilizartodos los recursos <strong>de</strong> las mismas, compartirlas seríabeneficioso en ambos sentidos: menor consumo y mayorutilización. Con el objetivo <strong>de</strong> proporcionar una soluciónbajo estas premisas nace rCUDA, un marco <strong>de</strong> trabajo quepermite el uso concurrente <strong>de</strong> dispositivos CUDA <strong>de</strong> formaremota.Este artículo <strong>de</strong>scribe las experiencias y conclusionesextraídas durante la primera fase <strong>de</strong> adaptación <strong>de</strong> rCUDA<strong>de</strong>s<strong>de</strong> la versión 3 <strong>de</strong> CUDA a la nueva versión 4.Palabras clave—CUDA, computación <strong>de</strong> altasprestaciones, aceleración basada en GPUs, virtualización,clústeres, ahorro <strong>de</strong> energía.EI. INTRODUCCIÓNN la actualidad, <strong>de</strong>bido a la creciente <strong>de</strong>manda <strong>de</strong>requisitos que se les viene exigiendo a las GPUs, sehan realizado gran<strong>de</strong>s avances en el <strong>de</strong>sarrollo <strong>de</strong> lasmismas, dando lugar a dispositivos con mayor po<strong>de</strong>rcomputacional y mayor ancho <strong>de</strong> banda <strong>de</strong> memoria quelas CPUs actuales [1]. En las Figuras 1 y 2 po<strong>de</strong>mos vergráficamente una comparativa <strong>de</strong> dichas característicasentre GPUs NVIDIA y CPUs Intel.<strong>La</strong> Figura 1 nos muestra cómo mediante el uso <strong>de</strong> GPUses posible obtener, en algunos casos, una tasa teórica <strong>de</strong>operaciones en coma flotante por segundo hasta casi 8veces superior a la <strong>de</strong> las CPUs más potentes en el año2010. En la Figura 2, por su parte, vemos cómo el ancho<strong>de</strong> banda <strong>de</strong> memoria teórico <strong>de</strong> las GPUs sextuplicaba,en el mismo año, al <strong>de</strong> las CPUs, a pesar <strong>de</strong> lascrecientes mejoras que estas últimas introducenpaulatinamente para incrementar éste.Figura 2. Ancho <strong>de</strong> banda <strong>de</strong> la memoria en CPUs y GPUs.Esta gran potencia <strong>de</strong> cálculo, junto con la eficiencia enel acceso a memoria, ha motivado la utilización <strong>de</strong>GPUs en ámbitos distintos a aquellos para los queinicialmente fueron diseñadas: son las llamadas tareas <strong>de</strong>propósito general, <strong>de</strong>rivando todo ello en la <strong>de</strong>nominadacomputación GPU o GPGPU (General PurposeComputing on GPU). Cabe <strong>de</strong>stacar, en cualquier caso,que las GPUs no son un reemplazo <strong>de</strong> las CPUs, dadoque solo son útiles para <strong>de</strong>terminados tipos <strong>de</strong>problemas en los que la misma operación es aplicadasobre una gran cantidad <strong>de</strong> datos y con un patrón <strong>de</strong>acceso <strong>de</strong>terminado.Por otra parte, <strong>de</strong>bido principalmente al gran volumen<strong>de</strong> negocio generado por la industria <strong>de</strong>l vi<strong>de</strong>ojuego, lasGPUs se han convertido en dispositivos <strong>de</strong> relativamentebajo coste, proporcionando una potencia <strong>de</strong> cómputoextraordinaria para la inversión que suponen.Figura 1. Operaciones en coma flotante por segundo en CPUs y GPUs.1 DISCA, Universitat Politècnica <strong>de</strong> València (UPV), e-mails:{carregon, apenya}@gap.upv.es, {fsilla, jduato}@disca.upv.es.2 DICC, Universitat Jaume I (UJI), e-mails: {mayo, quintana}@icc.uji.es.Todo ello ha provocado que en la actualidad los gran<strong>de</strong>sclústeres <strong>de</strong> computadores <strong>de</strong> altas prestaciones seinclinen hacia la utilización <strong>de</strong> estos dispositivos comouna vía para acelerar <strong>de</strong>terminadas partes <strong>de</strong>l código <strong>de</strong>las aplicaciones a las que prestan servicio. <strong>La</strong> propuesta<strong>de</strong> NVIDIA en este sentido es CUDA: una arquitectura<strong>JP2011</strong>-311


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>de</strong> computación paralela que aprovecha la potencia <strong>de</strong> laGPU para aumentar consi<strong>de</strong>rablemente el rendimiento<strong>de</strong> los cálculos, quitándole carga <strong>de</strong> trabajo a la CPU, lacual pue<strong>de</strong>, <strong>de</strong> esta manera, <strong>de</strong>dicarse a otras tareas.Sin embargo, <strong>de</strong>ntro <strong>de</strong>l contexto <strong>de</strong> la computación <strong>de</strong>altas prestaciones, las GPUs presentan el inconveniente<strong>de</strong>l consumo <strong>de</strong> energía, el cual pue<strong>de</strong> incrementarsenotablemente con su uso. Si a ello le unimos el hecho <strong>de</strong>que las aplicaciones en general no suelen utilizar todoslos recursos <strong>de</strong> las GPUs al completo, compartir GPUsentre varios nodos <strong>de</strong>l clúster parece una solución muyapropiada. A modo <strong>de</strong> ejemplo, si una aplicación utilizaúnicamente la GPU el 25% <strong>de</strong>l tiempo, podría pensarseen compartir una GPU entre cuatro nodos <strong>de</strong>l clúster.Este principio motiva la aparición <strong>de</strong> rCUDA (remoteCUDA) [2]. rCUDA es un marco <strong>de</strong> trabajo para lautilización concurrente <strong>de</strong> GPUs compatibles conCUDA <strong>de</strong> forma remota. Dicho marco se basa en lacreación <strong>de</strong> dispositivos virtuales compatibles conCUDA en aquellos nodos que no poseen una GPU local.Estos dispositivos virtuales representan GPUsfísicamente localizadas en nodos remotos, los cualesofrecen servicios GPGPU. De esta forma, todos losnodos <strong>de</strong> un mismo clúster pue<strong>de</strong>n beneficiarse <strong>de</strong> lasGPUs, in<strong>de</strong>pendientemente <strong>de</strong> en qué nodos seencuentren éstas físicamente. Al mismo tiempo, sereduce la <strong>de</strong>sventaja, en cuanto a consumo energético serefiere, <strong>de</strong> introducir una GPU por nodo y se aumenta lautilización <strong>de</strong> las mismas, haciendo más rentable lainversión económica.<strong>La</strong> última versión estable <strong>de</strong> rCUDA da soporte a laversión 3 <strong>de</strong> CUDA. No obstante, en el mes <strong>de</strong> mayo <strong>de</strong>2011 ha sido publicada una nueva versión <strong>de</strong> CUDA, la4, lo cual ha hecho necesaria una adaptación <strong>de</strong> la actualimplementación <strong>de</strong> rCUDA. Una vez finalizada laprimera fase <strong>de</strong> dicha adaptación, exponemos en elpresente artículo las tareas realizadas, las conclusionesobtenidas y el trabajo pendiente para futuras fases.El resto <strong>de</strong>l artículo está organizado <strong>de</strong> la siguienteforma: en la sección II <strong>de</strong>scribiremos el marco <strong>de</strong> trabajorCUDA; en la sección III expondremos las diferenciasmás <strong>de</strong>stacables entre las versiones <strong>de</strong> CUDA 3 y 4; enla sección IV comentaremos las experiencias extraídasdurante la primera fase <strong>de</strong> adaptación <strong>de</strong> rCUDA a lanueva versión <strong>de</strong> CUDA 4; finalmente, en la sección Vcomentaremos las conclusiones obtenidas tras el trabajorealizado y en la sección VI posibles tareas a realizar enel futuro.II. RCUDA: REMOTE CUDATal y como hemos comentado, rCUDA permite el usoconcurrente <strong>de</strong> GPUs compatibles con CUDA <strong>de</strong> formaremota. Así, cada nodo en un clúster pue<strong>de</strong> utilizar losaceleradores compatibles con CUDA instalados encualquier nodo <strong>de</strong>l mismo.<strong>La</strong> arquitectura <strong>de</strong> rCUDA [2, 3] consiste en un sistemadistribuido cliente-servidor, tal y como po<strong>de</strong>mos ver enla Figura 3.Figura 3. Arquitectura <strong>de</strong> rCUDA.Des<strong>de</strong> el punto <strong>de</strong> vista <strong>de</strong> los nodos cliente, las GPUsremotas son dispositivos virtuales a los que es posibletener acceso <strong>de</strong> la misma forma que si éstas estuvieranconectadas directamente en su puerto PCIe (PeripheralComponent Interconnect Express). De hecho, lasaplicaciones no son conscientes <strong>de</strong> que la GPU a la queestán accediendo no es un dispositivo real sino virtual.Ello es posible gracias a una biblioteca que reemplaza labiblioteca original <strong>de</strong>l Runtime API <strong>de</strong> CUDA,manteniendo los prototipos <strong>de</strong> las funciones perore<strong>de</strong>finiendo su implementación para que, básicamente,las llamadas a la API <strong>de</strong> CUDA sean redirigidas al nodoen el que físicamente se encuentra la tarjeta gráfica oacelerador.El servidor, por su parte, es un <strong>de</strong>monio que se ejecutaen aquellos nodos que ofrecen servicios <strong>de</strong> aceleraciónGPGPU, es <strong>de</strong>cir, en los nodos con GPU física. Seencarga <strong>de</strong> recibir, interpretar y ejecutar las peticionesrealizadas por la aplicación a través <strong>de</strong>l cliente remoto.Para cada ejecución remota, un nuevo proceso servidores creado para aten<strong>de</strong>r todas las peticiones <strong>de</strong> un mismocliente y ejecutarlas en un contexto <strong>de</strong> GPUin<strong>de</strong>pendiente. Esto permite, en caso <strong>de</strong> error fatal(violación <strong>de</strong> acceso a memoria) en uno <strong>de</strong> los procesosservidor, la continuidad <strong>de</strong>l resto <strong>de</strong> procesos, adiferencia <strong>de</strong> lo que ocurriría en un entorno multi-hilo.<strong>La</strong> comunicación entre cliente y servidor es llevada acabo mediante la utilización <strong>de</strong> la API <strong>de</strong> sockets TCP,aunque para optimizar el intercambio <strong>de</strong> datos a través<strong>de</strong> la red se ha <strong>de</strong>sarrollado un protocolo <strong>de</strong>comunicación a nivel <strong>de</strong> aplicación altamenteoptimizado [4].En general, la virtualización <strong>de</strong> servicios en rCUDAconsiste en redirigir las llamadas <strong>de</strong> la API <strong>de</strong> CUDA alnodo con la GPU, como hemos comentado. Este procesoresulta, a gran<strong>de</strong>s rasgos, sencillo <strong>de</strong> implementar. Noobstante, este no es el caso <strong>de</strong> las transferenciasasíncronas, las cuales requieren introducir lógicaadicional <strong>de</strong> mayor complejidad. A continuación<strong>de</strong>scribimos este tipo <strong>de</strong> transferencias más<strong>de</strong>talladamente.<strong>La</strong> complejidad <strong>de</strong> las transferencias asíncronas radica,fundamentalmente, en dos aspectos:1. Requieren el uso <strong>de</strong> memoria no paginable.2. Pue<strong>de</strong>n estar asociadas a un stream (secuencia<strong>de</strong> operaciones que se ejecutan <strong>de</strong> formaor<strong>de</strong>nada, pero que pue<strong>de</strong>n ejecutarseconcurrentemente o <strong>de</strong> forma <strong>de</strong>sor<strong>de</strong>nadarespecto a otros streams).<strong>JP2011</strong>-312


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Para implementar este tipo <strong>de</strong> servicios se ha optado poruna planificación ―round-robin‖ para tratar el conjunto<strong>de</strong> streams, y por una estructura FIFO (First In, FirstOut) para tratar las operaciones <strong>de</strong>ntro <strong>de</strong> un mismostream. Po<strong>de</strong>mos verlo <strong>de</strong> forma esquemática en laFigura 4.• Código a ejecutar en la GPU, se compilaráempleando la herramienta ―nvcc‖proporcionada por NVIDIA [5].• Código a ejecutar en la máquina, se compilarácon un compilador C/C++ nativo (p. ej. GNUgcc).Po<strong>de</strong>mos encontrar información más <strong>de</strong>tallada respectoa este último punto en [2].Figura 4. Tratamiento <strong>de</strong> operaciones asíncronas.Cuando el cliente recibe una petición <strong>de</strong> transferenciaasíncrona, ésta se programa y se retorna el control <strong>de</strong> laejecución al peticionario. Esto pue<strong>de</strong> ocurrir antes <strong>de</strong>que la transferencia se haya completado o inclusoiniciado. En función <strong>de</strong> si el origen y el <strong>de</strong>stino son lamáquina local o la GPU <strong>de</strong> la máquina remota, po<strong>de</strong>mosclasificar las transferencias asíncronas en los siguientestipos (origen – <strong>de</strong>stino):• Máquina local – máquina local. No implica aldispositivo remoto, por lo que es implementadacomo una operación local.• Máquina local – GPU remota. Una vez todaslas transferencias <strong>de</strong>l dispositivo remoto alcliente <strong>de</strong>ntro <strong>de</strong>l stream han finalizado, serealiza una petición <strong>de</strong> transferencia al servidory se le envían los datos.• GPU remota – máquina local. Directamente serealiza una petición <strong>de</strong> transferencia aldispositivo remoto, el cual gestionará cuándo sepue<strong>de</strong> llevar a cabo la misma. Posteriormente,los datos serán enviados al cliente <strong>de</strong> formaasíncrona.• GPU remota – GPU remota. Similar al casoanterior con la diferencia <strong>de</strong> que no se envíandatos al cliente.Así pues, las únicas tareas pendientes tras la ejecución<strong>de</strong> una operación asíncrona son la recepción <strong>de</strong> los datosresultantes <strong>de</strong> las transferencias <strong>de</strong> la GPU remota a lamáquina local. Por esta razón, aquellas transferenciascuyo origen <strong>de</strong> memoria sea un puntero en la máquinalocal <strong>de</strong>ben esperar a las operaciones pendientes paracompletarse. Para gestionar estas operaciones <strong>de</strong> formaasíncrona, y permitir así la recepción <strong>de</strong> datos síncronosy asíncronos por el mismo socket, el cliente utiliza unhilo Posix <strong>de</strong>dicado y sincronizado con el hilo principal<strong>de</strong> la ejecución y con el hilo <strong>de</strong> recepción.De forma similar, existe un hilo <strong>de</strong> envío en el servidorpara multiplexar el socket y permitir así el envío <strong>de</strong>datos tanto síncrono como asíncrono.Por último, comentar que rCUDA sólo soporta la API <strong>de</strong>C plano y no es posible utilizar extensiones CUDA.A<strong>de</strong>más, el código <strong>de</strong> las aplicaciones se <strong>de</strong>be dividiren:III. CUDA 3 Y CUDA 4El <strong>de</strong>sarrollo <strong>de</strong> CUDA está divido en módulos queagrupan funcionalida<strong>de</strong>s relacionadas entre sí [6].Algunos módulos que ya existían en la versión 3 <strong>de</strong>CUDA y a los cuales haremos referencia en este artículoson:• Módulo ―Device Management‖: formado porlas funciones que permiten gestionar lasdistintas características <strong>de</strong> los dispositivosCUDA.• Módulo ―Thread Management‖: permite lagestión <strong>de</strong> hilos en aplicaciones que utilicenCUDA.• Módulo ―Memory Management‖: contiene lasfunciones necesarias para operar tanto con lamemoria <strong>de</strong>l sistema como con la memoria <strong>de</strong>las GPUs.También haremos referencia a la biblioteca CUBLAS[7], una implementación <strong>de</strong> BLAS (Basic LinearAlgebra Subprograms) sobre CUDA proporcionada porNVIDIA.En lo referente a las nuevas características que introducela nueva versión <strong>de</strong> CUDA con respecto a su anteriorversión 3, quizá la funcionalidad más <strong>de</strong>stacable sea lareferida a la comunicación entre GPUs (NVIDIAGPUDirect v2.0) y al direccionamiento virtual unificadoo Unified Virtual Addressing (UVA) [1, 6]. Acontinuación introduciremos cada uno <strong>de</strong> ellos, así comootras diferencias reseñables.A. NVIDIA GPUDirect v2.0<strong>La</strong> versión 2.0 <strong>de</strong> NVIDIA GPUDirect proporcionanuevas funcionalida<strong>de</strong>s (nuevo módulo ―Peer DeviceMemory Access‖) que permiten la comunicación directaentre dispositivos compatibles con CUDA: acceso amemoria, transferencias y sincronización entre losmismos. Por ejemplo, en la versión anterior <strong>de</strong> CUDA, ala hora <strong>de</strong> realizar transferencias <strong>de</strong> memoria entre dosGPUs instaladas en una misma máquina, era necesariorealizar una copia intermedia en la memoria <strong>de</strong> la CPU.Sin embargo, ahora es posible realizar transferenciasdirectas entre ambas. Po<strong>de</strong>mos visualizar gráficamenteesta nueva característica en las Figuras 5 y 6.Esta característica sólo es soportada por tarjetas gráficasNVIDIA <strong>de</strong> la serie Tesla 20 en aplicaciones <strong>de</strong> 64 bitsbajo sistemas operativos Linux y Windows. En el caso<strong>de</strong> Windows también es necesario tener instalado eldriver TCC (Tesla Computer Cluster) diseñado paranodos que disponen <strong>de</strong> más <strong>de</strong> un producto Teslainstalado.<strong>JP2011</strong>-313


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>de</strong>l cual una GPU acce<strong>de</strong> a su memoria es el mismo parael resto <strong>de</strong> GPUs conectadas a la misma máquina.Al igual que ocurría con NVIDIA GPUDirect 2.0, UVAsólo es soportada por tarjetas gráficas NVIDIA <strong>de</strong> laserie Tesla 20 en aplicaciones <strong>de</strong> 64 bits bajo sistemasoperativos Linux y Windows con el driver TCCinstalado.Figura 5. Transferencia <strong>de</strong> memoria entre GPUs en CUDA 3.Figura 6. Transferencia <strong>de</strong> memoria entre GPUs en CUDA 4.B. Unified Virtual Addressing (UVA)<strong>La</strong> nueva versión 4 <strong>de</strong> CUDA proporcionadireccionamiento virtual unificado (nuevo módulo―Unified Addressing‖), el cual permite un marco <strong>de</strong>trabajo con un único espacio <strong>de</strong> direcciones para todaslas memorias <strong>de</strong> las distintas CPUs y GPUs en unmismo computador. En las Figuras 7 y 8 mostramos <strong>de</strong>forma visual dicha característica.Figura 7. Espacio <strong>de</strong> memoria sin UVA.Figura 8. Espacio <strong>de</strong> memoria con UVA.Cabe <strong>de</strong>stacar que con la utilización <strong>de</strong> UVA, lastransferencias directas entre GPUs que permite NVIDIAGPUDirect v2.0 funcionan <strong>de</strong> forma transparente, sin sernecesario especificar las GPUs <strong>de</strong> origen y <strong>de</strong>stino. Ellose <strong>de</strong>be a que en estos casos el valor <strong>de</strong>l puntero a travésC. Otras diferenciasOtro <strong>de</strong> los aspectos que introduce la nueva versión esuna mayor facilidad a la hora <strong>de</strong> utilizar aceleraciónCUDA en las aplicaciones existentes, <strong>de</strong> tal forma que altratar con espacios <strong>de</strong> memoria no paginable <strong>de</strong>l sistema,ya no son necesarias reservas <strong>de</strong> memoria ni copiasadicionales en el entorno CUDA. Por ejemplo, antes eranecesario seguir los siguientes pasos:1. Reservar memoria en CPU (#1).2. Reservar memoria en CPU para que seaaccesible por la GPU (#2).3. Copiar memoria #1 a memoria #2.4. Aplicar aceleración CUDA.5. Copiar memoria #2 a memoria #1.6. Liberar memoria #2.Mientras que ahora es posible ―registrar‖ un espacio <strong>de</strong>memoria <strong>de</strong> la CPU para que sea utilizado por la GPU y―<strong>de</strong>sregistrarlo‖ al finalizar la aceleración CUDA:1. Reservar memoria en CPU (#1).2. Registrar memoria #1 para que sea accesiblepor la GPU.3. Aplicar aceleración CUDA.4. Desregistrar memoria #1.Algunas características que también cabe <strong>de</strong>stacar sonlas siguientes:• Posibilidad <strong>de</strong> compartir GPUs entre múltipleshilos y <strong>de</strong> acce<strong>de</strong>r a todas las GPUs <strong>de</strong>s<strong>de</strong> unmismo hilo.• En la versión anterior <strong>de</strong> CUDA existía laposibilidad <strong>de</strong> generar el código relativo a unaGPU en un repositorio externo, <strong>de</strong> forma quepara cada versión compilada con una<strong>de</strong>terminada arquitectura se generaba unmódulo diferente. En la nueva versión <strong>de</strong>CUDA existe la posibilidad <strong>de</strong> agrupar en unmismo módulo código para diferentesarquitecturas [5], son los llamados ―fatbin‖ (fatbinary).• Respecto a la biblioteca CUBLAS, seproporciona una nueva API que permiteoptimizar el paralelismo entre streams y lasllamadas concurrentes a CUBLAS <strong>de</strong>s<strong>de</strong>múltiples hilos.Los cambios referentes a los módulos <strong>de</strong>interoperabilidad entre gráficos no los comentaremospuesto que, por el momento, no son objeto <strong>de</strong>l marco <strong>de</strong>trabajo <strong>de</strong> rCUDA.IV. ADAPTACIÓN DE RCUDA A CUDA 4En esta sección presentaremos las tareas realizadas y losproblemas encontrados durante el proceso <strong>de</strong> adaptación<strong>JP2011</strong>-314


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>de</strong> rCUDA a CUDA 4.En primer lugar, se han realizado las modificacionesnecesarias para que el marco <strong>de</strong> trabajo <strong>de</strong> rCUDA fueraoperativo bajo la nueva versión <strong>de</strong> CUDA. Estasmodificaciones han consistido, básicamente, en laimplementación <strong>de</strong> la carga <strong>de</strong> módulos a partir <strong>de</strong>fatbins, puesto que la versión actual <strong>de</strong> rCUDA utilizalos repositorios externos con el código <strong>de</strong> losdispositivos comentados en la sección anterior. <strong>La</strong>utilización <strong>de</strong> fatbins tiene la ventaja <strong>de</strong> que es posibleincluir en un mismo módulo código <strong>de</strong> un mismodispositivo compilado y optimizado para diferentesarquitecturas, siendo CUDA quién seleccione la versiónmás apropiada.Seguidamente, se han implementado las nuevasfuncionalida<strong>de</strong>s <strong>de</strong> los distintos módulos que resultabantriviales o con poca complejidad:• Módulo ―Device Management‖: se hanimplementado las funciones que anteriormentese encontraban en el módulo ―ThreadManagement‖ y se han codificado las funcionespara las que no se daba soporte en la anteriorversión <strong>de</strong> rCUDA.• Módulo ―Memory Management‖: se hancodificado las funciones necesarias pararegistrar/<strong>de</strong>sregistrar memoria <strong>de</strong> la CPU en elsistema CUDA, así como algunas funcionesasíncronas <strong>de</strong> inicialización <strong>de</strong> regiones <strong>de</strong>memoria <strong>de</strong> GPU para las que no se dabasoporte en la anterior versión <strong>de</strong> rCUDA.• Biblioteca CUBLAS: las funciones soportadaspor la antigua versión <strong>de</strong> rCUDA han sidoadaptadas a la nueva API <strong>de</strong> dicha biblioteca,manteniendo compatibilidad con la versiónanterior.Cómo se ha comentado en la sección II, rCUDA sólosoporta la API <strong>de</strong> C plano y también es necesariocompilar el código a ejecutar en la GPU por separado.Así, rCUDA dispone <strong>de</strong> una SDK similar a la <strong>de</strong> CUDApero con dichas modificaciones. <strong>La</strong> siguiente tarea arealizar ha consistido en actualizar los ejemplos <strong>de</strong> laSDK <strong>de</strong> rCUDA según los cambios realizados en lapropia SDK <strong>de</strong> CUDA 4, con el fin <strong>de</strong> testear el correctofuncionamiento <strong>de</strong> rCUDA tras las modificacionesrealizadas.Llegados a este punto, restan por implementar lassiguientes características <strong>de</strong> CUDA 4:• Módulo ―Memory Management‖: nuevasfunciones que permiten la copia <strong>de</strong> memoriaentre GPUs, tanto <strong>de</strong> forma síncrona comoasíncrona.• Módulo ―Peer Device Memory Access‖: nuevomódulo para dar soporte a las mejorasintroducidas por la nueva versión 2.0 <strong>de</strong>NVIDIA GPUDirect, <strong>de</strong>scritas en apartadosanteriores.• Módulo ―Unified Addressing‖: nuevo módulointroducido como consecuencia <strong>de</strong>ldireccionamiento virtual unificado (UVA),también comentado en secciones previas.<strong>La</strong> adaptación <strong>de</strong> rCUDA para soportar lascaracterísticas comentadas anteriormente es bastantecompleja teniendo en cuenta la actual implementación<strong>de</strong>l propio rCUDA, por lo que requiere <strong>de</strong> un estudioprevio más profundo que <strong>de</strong>tallamos en la siguientesubsección.A. NVIDIA GPUDirect v2.0 y UVATal y como hemos comentado, rCUDA está pensado,principalmente, para clústeres <strong>de</strong> computadores <strong>de</strong> altasprestaciones don<strong>de</strong> sólo algunos nodos dispondrán <strong>de</strong>GPU. De esta forma, un nodo podrá acce<strong>de</strong>r a todas lasGPUs <strong>de</strong> un clúster <strong>de</strong> la misma manera que si éstasestuvieran físicamente en dicho nodo. Si a ello leañadimos el hecho <strong>de</strong> que, potencialmente, cada GPUestará en un nodo distinto, el po<strong>de</strong>r realizarcomunicaciones entre distintas GPUs y, a<strong>de</strong>más,disponer <strong>de</strong> un espacio <strong>de</strong> direccionamiento virtualunificado para todas las GPUs y la CPU <strong>de</strong>l nodocliente, se convierte en un reto mayor que en el casocontemplado en CUDA, tal y como explicaremos acontinuación. En la Figura 9 tratamos <strong>de</strong> ilustrar estaproblemática.Figura 9. Problemática en la adaptación <strong>de</strong> rCUDA a CUDA 4.Por un lado, el ofrecer <strong>de</strong> forma transparente a un nodocliente comunicación directa entre las GPUs a las quetiene acceso en diversos nodos, gracias a rCUDA, vamás allá <strong>de</strong> las características <strong>de</strong> CUDA, ya que estaúltima asume que los dispositivos siempre estaránconectados a un mismo nodo. <strong>La</strong> misma argumentaciónpue<strong>de</strong> ser utilizada en el caso <strong>de</strong> querer soportar unespacio <strong>de</strong> direccionamiento virtual unificado.Por otro lado, rCUDA tiene la limitación <strong>de</strong> que cadaproceso servidor gestiona únicamente un dispositivo, locual presenta una dificultad añadida.Actualmente, en el proyecto <strong>de</strong> rCUDA nosencontramos en una fase <strong>de</strong> análisis sobre cómo resolveresta situación.Entre las soluciones que se están barajando, pareceevi<strong>de</strong>nte que una solución final que dé soporte a estasfunciones <strong>de</strong>berá utilizar un protocolo <strong>de</strong> comunicaciónentre los procesos servidores, aunque la duda radica ensi disponer <strong>de</strong> un servidor maestro que realice unagestión global o no. A<strong>de</strong>más, todo indica que seránecesario implementar un mecanismo <strong>de</strong> señales juntocon regiones <strong>de</strong> memoria compartida para permitir lacomunicación <strong>de</strong> servidores <strong>de</strong>ntro <strong>de</strong> un mismo nodo.<strong>JP2011</strong>-315


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Esto último podría permitir también resolver unalimitación actual <strong>de</strong> rCUDA según la cual no es posibleel uso <strong>de</strong> memoria mapeada (característica llamadazero-copy).Otro punto <strong>de</strong> vista totalmente opuesto podría ser el nodar soporte a dichas características ya que, como se haindicado previamente, el hecho <strong>de</strong> que las GPUs esténen diferentes nodos conlleva que estas funcionalida<strong>de</strong>sno sean las propias <strong>de</strong> CUDA.Una tercera perspectiva podría ser una soluciónintermedia entre las dos explicadas anteriormente, es<strong>de</strong>cir, asumiendo que si las GPUs están en máquinasdiferentes no es posible aprovechar al completo lasventajas comentadas <strong>de</strong> la nueva versión <strong>de</strong> CUDA,tratar <strong>de</strong> implementar internamente las nuevasfuncionalida<strong>de</strong>s utilizando las herramientas queproporciona CUDA <strong>de</strong> forma transparente al usuario.Por ejemplo, como hemos señalado en seccionesprevias, en la nueva versión <strong>de</strong> CUDA es posiblerealizar copias directas <strong>de</strong> memoria entre GPUs.Internamente, rCUDA podría dividir dicha operación endos:1. Copia <strong>de</strong>s<strong>de</strong> la memoria <strong>de</strong> la GPU origen a lamemoria <strong>de</strong> la CPU.2. Copia <strong>de</strong>s<strong>de</strong> la memoria <strong>de</strong> la CPU a lamemoria <strong>de</strong> la GPU <strong>de</strong>stino.Esto es, realizar la copia <strong>de</strong>l mismo modo que se haríaen la versión anterior <strong>de</strong> CUDA, pero <strong>de</strong> formatransparente al usuario. Esta solución sería ventajosa envarios aspectos. Por un lado, la conversión <strong>de</strong>aplicaciones <strong>de</strong> CUDA a rCUDA no requeriría cambios<strong>de</strong> código en este sentido. Por otro lado, se estaríaalcanzando uno <strong>de</strong> los objetivos que pretendían lasnuevas funcionalida<strong>de</strong>s: reducir el código <strong>de</strong> lasaplicaciones con el consecuente aumento <strong>de</strong> laproductividad.No obstante, tal y como hemos comentadoanteriormente, éstas y otras cuestiones aún están siendo<strong>de</strong>batidas y analizadas <strong>de</strong>ntro <strong>de</strong>l proyecto, por lo queaún no se ha alcanzado una <strong>de</strong>cisión <strong>de</strong>finitiva alrespecto.V. CONCLUSIONESEn el presente artículo hemos expuesto los pasosllevados a cabo en la primera fase <strong>de</strong>l proceso <strong>de</strong>adaptación <strong>de</strong>l marco <strong>de</strong> trabajo <strong>de</strong> rCUDA a la nuevaversión 4 <strong>de</strong> CUDA.Tras finalizar esta primera fase, disponemos <strong>de</strong> unmarco <strong>de</strong> trabajo estable pero al que aún le restan porresolver dos aspectos fundamentales introducidos en lanueva versión <strong>de</strong> CUDA:1. Comunicación directa entre GPUs.2. Espacio <strong>de</strong> direccionamiento virtual unificadopara las memorias <strong>de</strong> las GPUs y <strong>de</strong> la CPU.Actualmente dichos aspectos se encuentran en fase <strong>de</strong>análisis y todavía no se ha alcanzado una solución<strong>de</strong>finitiva.VI. TRABAJO FUTUROEntre las posibles tareas a <strong>de</strong>sarrollar en el futuro,a<strong>de</strong>más <strong>de</strong> resolver la problemática comentada ensecciones anteriores, cabe <strong>de</strong>stacar las siguientes:• Portabilidad <strong>de</strong> rCUDA a sistemas operativosWindows (actualmente únicamente soportasistemas operativos Linux).• Desarrollo <strong>de</strong> una arquitectura <strong>de</strong>comunicaciones segmentada que permita elaumento <strong>de</strong> las prestaciones <strong>de</strong> rCUDA alaumentar el ancho <strong>de</strong> banda efectivo entrecliente y servidor.• Soporte nativo para la tecnología InfiniBand [8]que permita evitar el uso <strong>de</strong> sockets TCP/IP.Este soporte permitiría el uso <strong>de</strong> rCUDA enmultitud <strong>de</strong> clústeres que incluyen esta red <strong>de</strong>altas prestaciones en lugar <strong>de</strong> usar Ethernet.• Soporte nativo para la tecnología <strong>de</strong>comunicaciones en clústeres EXTOLL [9], queproporciona un interfaz <strong>de</strong> memoria compartiday un interfaz <strong>de</strong> paso <strong>de</strong> mensajes muy eficientepara fines tales como compatibilidad conaplicaciones MPI (Message Passing Interface),que podría utilizarse para el envío y recepción<strong>de</strong> los mensajes generados por rCUDA.AGRADECIMIENTOSEl personal <strong>de</strong> la UPV ha sido subvencionado bien porel programa PROMETEO <strong>de</strong> la Generalitat Valenciana(GVA) bajo el acuerdo PROMETEO/2008/060, o bienpor el Ministerio <strong>de</strong> Educación (MEC) y el Ministerio <strong>de</strong>Ciencia e Innovación (MICINN) <strong>de</strong> España bajo elacuerdo CONSOLIDER INGENIO CSD2006-00046. Elpersonal <strong>de</strong> la UJI, por su parte, ha sido financiado porel Ministerio <strong>de</strong> Ciencia español, el programa FEDER(número <strong>de</strong> contrato TIN2008- 06570-C04) y laFundación Caixa-Castelló Bancaixa (contrato númeroP1-1B2009-35).REFERENCIAS[1] NVIDIA, ―NVIDIA CUDA C Programming Gui<strong>de</strong> Version 4.0‖,NVIDIA, 2011.[2] J. Duato, F. D. Igual, R. Mayo, A. J. Peña, E. S. Quintana-Ortí, yF. Silla, ―An Efficient Implementation of GPU Virtualization inHigh Performance Clusters‖, Euro-Par 2009, Parallel Processing— Workshops, vol. 6043 Lecture Notes in Computer Science, p.385–394. Springer-Verlag, 2010.[3] J. Duato, A. J. Peña, F. Silla, R. Mayo y E.S. Quintana-Ortí,―rCUDA: Reducing the Number of GPU-based Accelerators inHigh Performance Clusters‖, High Performance Computing andSimulation, 2010.[4] J. Duato, A. J. Peña, F. Silla, R. Mayo y E.S. Quintana-Ortí,―Performance of CUDA Virtualized Remote GPUs in HighPerformance Clusters‖, International Conference on ParallelProcessing, 2011.[5] NVIDIA, ―The CUDA Compiler Driver NVCC‖, NVIDIA, 2011.[6] NVIDIA, ―CUDA Toolkit Reference Manual‖, NVIDIA, 2011.[7] NVIDIA, ―CUBLAS Library‖, NVIDIA, 2011[8] InfiniBand(SM) Tra<strong>de</strong> Association, ―InfiniBand(TM) ArchitectureSpecification‖, InfiniBand(SM) Tra<strong>de</strong> Association, 2007.[9] N. Nüssle, B. Geib, H. Fröning, and U. Brüning, "An FPGA-basedcustom high performance interconnection network", InternationalConference on Reconfigurable Computing and FPGAs, 2009.<strong>JP2011</strong>-316


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Un nuevo entorno para el uso <strong>de</strong> GPUs.Pedro Valero 1 , Fernando L. Pelayo 2Resumen— En este artículo se realiza un análisis sobrela viabilidad primero y las prestaciones <strong>de</strong>spués <strong>de</strong>un nuevo marco <strong>de</strong> trabajo en el que se usan GPUsen entornos con altos requerimientos <strong>de</strong> prestaciones,en este sentido se va más allá proponiéndose algunasmejoras en estas arquitecturas que incrementarían laefectividad <strong>de</strong> estos dispositivos ante estas <strong>de</strong>mandas.Para la parte <strong>de</strong>l análisis se ha llevado a cabo un conjunto<strong>de</strong> pruebas <strong>de</strong> ejecución que se consi<strong>de</strong>ran estandaren términos computacionales y como resultado<strong>de</strong> tal análisis, se <strong>de</strong>scriben la serie <strong>de</strong> mejoras que losautores entien<strong>de</strong>n mejorarían <strong>de</strong> manera significativalas prestaciones <strong>de</strong> las arquitecturas basadas en GPUen entornos con altos requerimientos <strong>de</strong> potencia computacional.Palabras clave— Graphics Processing Units (GPU),computación <strong>de</strong> altas prestaciones (HPC), CUDA(Compute Unified Device Architecture), evaluación<strong>de</strong> rendimiento.I. IntroducciónHoy en día, las actuales GPUs constituyenuna apropiada plataforma paralela para acelerarcualquier aplicación, <strong>de</strong>bido a sus características,número elevado <strong>de</strong> cores, alto ancho <strong>de</strong> banda y unalto ratio rendimiento/coste.<strong>La</strong>s GPUs pue<strong>de</strong>n ejecutar millones <strong>de</strong> hilos simultaneamente,sin embargo, sólo pue<strong>de</strong>n ejecutarun trabajo o aplicación al mismo tiempo. Si unaaplicación en particular necesitase 512 hilos para suejecución paralela, y teniendo en cuenta que algunasGPUs pue<strong>de</strong>n ejecutar hasta 6.7 × 10 7 hilos, estetrabajo solo utilizaría el 0.0001% <strong>de</strong> toda la capacidad<strong>de</strong> la GPU haciendo un uso muy ineficiente <strong>de</strong> lamisma. Por esa razón, hemos modificado el métodotradicional <strong>de</strong> utilizar las GPUs con el fin <strong>de</strong> ejecutarmás <strong>de</strong> un trabajo al mismo tiempo. Más aún hemosrealizado una comparación <strong>de</strong> rendimiento entre elmétodo tradicional y nuestra propuesta.Estos dispositivos estan siendo utilizados en lamayoría <strong>de</strong> los entornos HPC actuales, basta <strong>de</strong>cirque hay tres sistemas <strong>de</strong> supercomputación en lascuatro primeras posiciones <strong>de</strong> la lista top 500 [18]los cuales utilizan GPUs (en el primer, segundo ycuarto lugar). Así mismo, las GPUs estan siendo introducidasen entornos GRID [8] y CLOUD [7]. Enestos entornos las GPUs son utilizadas en muy diferentescampos como ciencia fundamental, medicina,astronomía, ingeniería, etc. [7]-[17].Este trabajo se estructura <strong>de</strong> la siguiente manera:<strong>La</strong> sección II <strong>de</strong>scribe las principales características<strong>de</strong> las actuales GPUs. <strong>La</strong> sección III presenta unanueva propuesta para un uso más eficientes <strong>de</strong> las actualesGPUs, más a<strong>de</strong>lante la sección IV muestra losresultados experimentales y análisis <strong>de</strong> rendimiento1 Inst. <strong>de</strong> Investigación en Informática, Univ. <strong>de</strong> Castilla-<strong>La</strong>Mancha, e-mail: Pedro.Valero<strong>La</strong>ra@uclm.es2 Dpto. <strong>de</strong> Sistemas Informáticos, Univ. <strong>de</strong> Castilla-<strong>La</strong> Mancha,e-mail: FernandoL.Pelayo@uclm.esllevado a cabo. A continuación, en la seción V losautores <strong>de</strong>scriben algunas alternativas con el fin <strong>de</strong>mejorar la eficiencia <strong>de</strong> estas plataformas para lapropuesta presentada con algunos pequeños cambiossobre la actual arquitectura. Finalmente, la seciónVI resume las conclusiones y esboza el trabajo futuro.II. GPU<strong>La</strong>s GPUs son tradicionalmente utilizadas paraaplicaciones interactivas, sin embargo, sus característicashan permitido la posibilidad <strong>de</strong> acelerarotro tipo <strong>de</strong> aplicaciones más generales. Esta ten<strong>de</strong>ncíarecibe el nombre <strong>de</strong> GPGPU (General PurposeComputing on GPU) [1]<strong>La</strong> principal características <strong>de</strong> estos dispositivosconsiste en su gran número <strong>de</strong> cores y por tanto lacapacidad <strong>de</strong> manejar un alto número <strong>de</strong> hilos, juntoa un gran ancho <strong>de</strong> banda interno y una rápida comunicacióncon el procesador a través <strong>de</strong> un puerto<strong>de</strong> alta velocidad (PCI Express). Debido a todo estolas GPUs pue<strong>de</strong>n alcanzar hasta 10 veces el ancho<strong>de</strong> banda y por atnto una gran superioridad en elcálculo en punto flotante respecto a las plataformastradicionales [2].<strong>La</strong> arquitectura <strong>de</strong> GPU esta formada por unnúmero <strong>de</strong> multiprocesadores (1-30), cada uno <strong>de</strong>ellos con un número <strong>de</strong> cores (8 ó 32). Todos losprocesadores comparten la misma memoria llamadamemoria global. A<strong>de</strong>más todos los cores <strong>de</strong> un multiprocesadorpue<strong>de</strong>n acce<strong>de</strong>r a la misma memoria(memoria compartida). Esta memoria sólo es útilcuando muchos hilos ejecutados en el mismso multiprocesadortienen que acce<strong>de</strong>r a las mismas posiciones<strong>de</strong> memoria; ya que para cargar un datoen memoria compartida es necesario cargarlo <strong>de</strong>s<strong>de</strong>memoria global. <strong>La</strong> figura 1 muestra un ejemplo <strong>de</strong>arquitectura <strong>de</strong> GPU.En los últimos años, ha habido diferentes iniciativaspara utilizar lenguages orientados a gráficos paraaccelerar partes especificas <strong>de</strong> códigos utilizandoGPUs [3], [4]. Más recientemente, los fabricantes<strong>de</strong> GPUs como NVIDIA o AMD/ATI, han <strong>de</strong>sarrolladonuevos lenguajes, por ejemplo, NVIDIA proponeCUDA [6], el cual conforma una plataformasoftware para computación paralela <strong>de</strong> altas prestaciones.En CUDA los hilos son distribuidos <strong>de</strong>ntro <strong>de</strong> unamalla <strong>de</strong> bloques <strong>de</strong> hilos, todos los bloques <strong>de</strong> hilostienen el mismo tamaño (número <strong>de</strong> hilos). Estoshilos ejecutan un código <strong>de</strong> GPU (kernel) que es lanzadopor la CPU y ejecutado en la GPU.Todos los códigos CUDA estan divididos en dospartes diferentes. El primero es el código <strong>de</strong> CPU,este código proporciona las instrucciones ejecutadas<strong>JP2011</strong>-317


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Algorithm 2 CUDA pseudoco<strong>de</strong> example 2.Function CPU⊲ Código CPU1: ReservaMemoriaCPU(C-CPU)2: ReservaMemoriaCPU(D-CPU)3: ReservaMemoriaGPU(C-GPU)4: ReservaMemoriaGPU(D-GPU)5: TransferenciaCPU-GPU(C-CPU,C-GPU)6: TransferenciaCPU-GPU(D-CPU,D-GPU)7: Kernel2(C-GPU,D-GPU)8: TransferenciaGPU-CPU(D-GPU,D-CPU)Function kernel2(C,D) ⊲ Código GPU9: i = i<strong>de</strong>ntificación <strong>de</strong> hilo10: D[i] = C[i] × D[i]Fig. 1.Arquitectura <strong>de</strong> GPU.Algorithm 1 CUDA pseudoco<strong>de</strong> example 1.Function CPU⊲ Código CPU1: ReservaMemoriaCPU(A-CPU)2: ReservaMemoriaCPU(B-CPU)3: ReservaMemoriaGPU(A-GPU)4: ReservaMemoriaGPU(B-GPU)5: TransferenciaCPU-GPU(A-CPU,A-GPU)6: Kernel1(A-GPU,B-GPU)7: TransferenciaGPU-CPU(B-GPU,B-CPU)Function kernel1(A,B) ⊲ Código GPU8: i = i<strong>de</strong>ntificación <strong>de</strong> hilo9: B[i] = A[i] + 100por la CPU, por ejemplo, reservar memoria en lamemoria principal (CPU) y en la memoria global(GPU), transferencia entre memorias y lanzamiento<strong>de</strong> kernels. Por otro lado, el código <strong>de</strong> GPU (kernel)provee las instruciones a ser ejecutadas en la GPU,por todos los hilos <strong>de</strong>l kernel.Este mo<strong>de</strong>lo <strong>de</strong> programación se estructura segúnlas etapas:1. Reserva <strong>de</strong> memoria principal (CPU)2. Reserva <strong>de</strong> memoria global (GPU)3. Transferencia <strong>de</strong> memoria principal a global4. <strong>La</strong>nzamiento <strong>de</strong> kernels5. Transferencia <strong>de</strong> memoria principal a globalIII. Nueva propuestaEsta nueva propuesta busca po<strong>de</strong>r ejecutar más <strong>de</strong>un trabajo al mismo tiempo en una única GPU. <strong>La</strong>scaracterísticas tanto <strong>de</strong> las actuales GPUs como <strong>de</strong> laherramienta software CUDA, permiten implementaresta propuesta, ya que cada multiprocesador tiene supropia unidad <strong>de</strong> control <strong>de</strong> instrucción.Ejecutar más <strong>de</strong> un kernel al mismo tiempo fuerzaa unir todos los co´digos <strong>de</strong> los kernels en uno, así puescada kernel será in<strong>de</strong>xado por uno o varios bloques<strong>de</strong> hilos. De esta forma, cada kernel es ejecutado <strong>de</strong>Algorithm 3 Ejemplo <strong>de</strong> propuesta.Function CPU⊲ Código CPU1: ReservaMemoriaCPU(A-CPU)2: ReservaMemoriaCPU(B-CPU)3: ReservaMemoriaCPU(C-CPU)4: ReservaMemoriaCPU(D-CPU)5: ReservaMemoriaGPU(A-GPU)6: ReservaMemoriaGPU(B-GPU)7: ReservaMemoriaGPU(C-GPU)8: ReservaMemoriaGPU(D-GPU)9: TransferenciaCPU-GPU(A-CPU,A-GPU)10: TransferenciaCPU-GPU(C-CPU,C-GPU)11: TransferenciaCPU-GPU(D-CPU,D-GPU)12: Kernel(A-GPU,B-GPU,C-GPU,D-GPU)13: TransferenciaGPU-CPU(B-GPU,B-CPU)14: TransferenciaGPU-CPU(D-GPU,D-CPU)Function kernel(A,B,C,D) ⊲ Código GPU15: i = i<strong>de</strong>ntificación <strong>de</strong> hilo16: j = i<strong>de</strong>ntificación <strong>de</strong> bloque17: if j = 0 then ⊲ kernel118: B[i] = A[i] + 10019: else if j = 1 then ⊲ kernel220: D[i] = C[i] × D[i]21: end ifforma in<strong>de</strong>pendiente y simultaneamente con otros.Se requiere un conjunto <strong>de</strong> condiciones para abordarla implementación:• Cada trabajo <strong>de</strong>be tener sus propias etapas (1-3)y 5 (sección II).• Un único kernel <strong>de</strong>be contener todos los kernelsin<strong>de</strong>xados por bloques.• Los kernels <strong>de</strong>ben <strong>de</strong> ser in<strong>de</strong>pendientes, es <strong>de</strong>cir<strong>de</strong>ben <strong>de</strong> tener sus propios parámetros y soluciones.Con el fin <strong>de</strong> indicar los cambios realizados paraimplementar nuestra propuesta, se muestran dosdiferentes ejemplos que <strong>de</strong>scriben la forma tradicional<strong>de</strong> utilizar una GPU (algoritmos 1 y 2). Elalgoritmo 3 está formado por la unión <strong>de</strong> estos dosalgoritmos, con el fin <strong>de</strong> ejecutar sus kernels simultaneamente.Estos tres algoritmos muestran las dospartes <strong>de</strong>l código, la parte ejecutada por la CPU yla parte ejecutada por la GPU (kernel).<strong>JP2011</strong>-318


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA ICaracterísticas <strong>de</strong> la GPU GTX 285.Característica GTX 285Número <strong>de</strong> multiprocesadores 30Número <strong>de</strong> cores 240Frecuencia <strong>de</strong> reloj 648 MhzFrecuencia <strong>de</strong> memoria 1242 MhzCapacidad <strong>de</strong> memoria 1 GBTamaño <strong>de</strong>l bus <strong>de</strong> memoria 512 bitsAncho <strong>de</strong> banda 159 GB/sGigaflops 1062.72TABLA IITiempo <strong>de</strong> ejecución para la multiplicación <strong>de</strong> unamatriz.Tamaño T. ejecución(ms) M.A.64 0.073 5,632128 0.115 22,528192 0.167 50,688256 0.232 90,112320 0.325 140,800384 0.433 202,752448 0.653 275,968512 1.253 360,448576 1.411 456,192704 2.672 681,472832 3.791 951,808960 5.686 1,267,2001088 8.324 1,627,6481216 12.979 2,033,1521408 19.249 2,725,8881600 27.100 3,520,0001792 39.969 4,415,4881984 51.398 5,412,3522240 72.078 6,899,2002496 98.981 8,566,2722816 148.161 10,903,5523136 194.940 13,522,4323520 274.715 17,036,8003904 374.485 20,956,672IV. Evaluación <strong>de</strong>l rendimientoPara llevar a cabo las pruebas <strong>de</strong> rendimientohemos utilizado una plataforma basada en GPU conla GPU GTX 285 cuyas características se muestranen la Tabla I. El propósito <strong>de</strong> estas pruebas es i<strong>de</strong>ntificarlos factores clave en relación a los resultadosalcanzados.Para realizar la evaluación <strong>de</strong> rendimiento hemoselegido la multiplicación <strong>de</strong> matrices, una <strong>de</strong> las pruebasestandar más aceptadas y costosas computacionalmente.<strong>La</strong>s matrices utilizadas son cuadradase inicializadas aleatoriamente.<strong>La</strong>s pruebas se han dividido en dos casos, elprimero <strong>de</strong> ellos consiste en ejecutar simultaneamentedos multiplicaciones <strong>de</strong> matrices, el segundocaso consiste en multiplicar cuatro. En ambos casos,se incrementa el tamaño <strong>de</strong> las matrices con el fin <strong>de</strong>analizar el peso <strong>de</strong> este parámetro. <strong>La</strong> Tabla II mues-TABLA IIITiempo <strong>de</strong> ejecución para la ejecución <strong>de</strong> 2multiplicaciones <strong>de</strong> matrices simultaneas.Tamaño F.A. S.A. S M.A.64 0.142 0.057 2.49 11,264128 0.23 0.087 2.64 45,056192 0.336 0.128 2.62 101,376256 0.469 0.191 2.45 180,224320 0.645 0.383 1.68 281,600384 0.929 0.523 1.77 405,504448 1.301 0.869 1.49 551,936512 2.475 1.186 2.08 720,896576 2.817 1.588 1.77 912,384704 5.386 2.863 1.88 1,362,944832 7.585 4.571 1.65 1,903,616960 11.360 7.981 1.42 2,534,4001088 18.647 11.449 1.62 3,255,2961216 926.109 14.944 1.74 4,066,3041408 38.759 22.866 1.69 5,451,7761600 55.144 31.930 1.72 7,040,0001792 81.564 44.561 1.83 8,830,9761984 101.733 59.925 1.69 10,824,7042240 144.600 85.764 1.68 13,798,4002496 198.677 118.128 1.68 17,132,5442816 299.409 169.929 1.76 21,807,1043136 392.051 233.500 1.67 27,044,8643520 549.755 329.229 1.66 34,073,6003904 750.115 448.490 1.67 41,913,344tra el tamaño <strong>de</strong> matriz y el tiempo <strong>de</strong> ejecución parala multiplicación <strong>de</strong> una matriz. <strong>La</strong>s Tablas III y IVmuestran el tiempo <strong>de</strong> ejecución para los dos casos<strong>de</strong> prueba, multiplicación <strong>de</strong> dos y cuatro matricesrespectivamente.Como se muestran en los resultados a mayortamaño <strong>de</strong> matriz, menor speedup. Uno <strong>de</strong> los principalesmotivos <strong>de</strong> este comportamiento son los conflictos<strong>de</strong> memoria, este hecho ocurre cuando más <strong>de</strong>un hilo tiene que acce<strong>de</strong>r al mismo banco <strong>de</strong> memoriasimultaneamente, esto fuerza a que los accesos serealicen <strong>de</strong> forma secuencial y se pierda eficiencia.Este comportamiento es más común cuando todoslos multiprocesadores comparten la misma memoria(memoria global). En el segundo caso (cuatro multiplicaciones<strong>de</strong> matrices), la caida <strong>de</strong>l speedup esmayor que en el primer caso, esto se <strong>de</strong>be a que conun mayor número <strong>de</strong> trabajos hay un mayor número<strong>de</strong> accesos a memoria y por tanto mayor número <strong>de</strong>conflictos.A través <strong>de</strong> los resultados obtenidos en las pruebas,hemos <strong>de</strong>mostrado la capacidad <strong>de</strong> nuestra propuesta<strong>de</strong> ejecutar más <strong>de</strong> un kernel <strong>de</strong> forma simultanea.El número <strong>de</strong> accesos a memoria es uno <strong>de</strong> los factoresque implican el buen o mal funcionamiento <strong>de</strong>esta plataforma. A<strong>de</strong>más, hemos encontrado algunas<strong>de</strong>ficiencias que podrían ser mejoradas, con el fin <strong>de</strong>obtener una mejor plataforma para la propuesta presentadaen este trabajo:• Todos los multiprocesadores comparten la<strong>JP2011</strong>-319


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA IVTiempo <strong>de</strong> ejecución para la ejecución <strong>de</strong> 2multiplicaciones <strong>de</strong> matrices simultaneas.Tamaño F.A. S.A. S M.A.64 0.284 0.070 4.05 22,528128 0.459 0.198 2.31 90,112192 0.671 0.306 2.19 202,752256 0.940 0.739 1.27 360,448320 1.286 1.174 1.09 563,200384 1.752 1.954 0.89 811,008448 2.621 2.932 0.89 1,103,872512 4.967 4.444 1.11 1,441,792576 5.634 6.121 0.92 1,824,768704 10.757 10.998 0.97 2,725,888832 15.131 18.133 0.83 3,807,232960 22.724 27.195 0.83 5,068,8001088 33.269 39.805 0.83 6,510,5921216 48.028 55.599 0.86 8,132,6081408 74.383 85.898 0.86 10,903,5521600 105.013 124.801 0.84 14,080,0001792 159.711 175.371 0.91 17,661,9521984 200.123 238.672 0.83 21,649,4082240 285.814 342.187 0.83 27,596,8002496 395.214 472.163 0.83 34,265,0882816 603.733 683.050 0.88 43,614,2083136 779.449 936.571 0.83 54,089,7283520 1,099.669 1,326.072 0.82 68,147,2003904 1,499.572 1,815.135 0.82 83,826,688misma memoria <strong>de</strong>bido a ello, cuando muchostrabajos ejecutados en la misma GPU tienenque acce<strong>de</strong>r a memoria se produce una caida <strong>de</strong>lspeedup.• Es necesario transferir datos entre ambas memorias,antes y <strong>de</strong>spués <strong>de</strong> cada ejecución.• Todos los kernels tienen que ser lanzados almismo tiempo, a<strong>de</strong>más estos tienen que finalizaral mismo tiempo también.En la siguiente sección, presentamos diferentes opcionespara incrementar el rendimiento, principalmenteatacando los puntos anteriormente <strong>de</strong>tallados.V. Nuevo mo<strong>de</strong>loA partir <strong>de</strong> aquí, los autores presentan una nuevaarquitectura basada en GPU. Esta sección está estrucutradapor las diferentes opciones seguidas con elfin <strong>de</strong> obtener un mejor rendimiento para el propósitopresentado en este artículo.A. Gestión <strong>de</strong> memoriaComo hemos indicado en la anterior sección, losaccesos a memoria pue<strong>de</strong>n ser el principal cuello <strong>de</strong>botella presente en esta arquitectura. Por esa razón,es necesario una gestión mejor <strong>de</strong> memoria. En nuestrahumil<strong>de</strong> opinión, estos dispositivos <strong>de</strong>berían tenertantos espacios <strong>de</strong> memoria “privada” como número<strong>de</strong> multiprocesadores. Gracias a esto, cada flujo <strong>de</strong>instrucciones <strong>de</strong> cada multiprocesador no interferirácon los <strong>de</strong>más evitando los conflictos <strong>de</strong> memoria.Speed upSpeed up32.521.510.5064 960 39044.543.532.521.510.5Tamaño064 960 3904TamañoFig. 2. Speedup para la multiplicación <strong>de</strong> 2 matrices(izquierda) y 3 matrices (<strong>de</strong>recha)Según po<strong>de</strong>mos ver en la figura 3, cada multiprocesadortiene sus propia memoria “privada” la cual sólopue<strong>de</strong> ser accedida por este, y su propio controlador<strong>de</strong> memoria. Por lo tanto, con esta alternativa cadakernel es in<strong>de</strong>pendiente <strong>de</strong> los <strong>de</strong>más y así los requisitos<strong>de</strong> memoria <strong>de</strong> un kenrel no interfiere con los<strong>de</strong>l resto.B. Comunicación entre CPU y GPU<strong>La</strong> GPU y CPU estan localizadas en diferentes espaciosy tienen sus propias memorias. <strong>La</strong> primeraimplicación <strong>de</strong> este aspecto es la necesidad <strong>de</strong> transferirlos parámetros <strong>de</strong>s<strong>de</strong> la memoria principal(CPU) a la memoria global (GPU), y las soluciones<strong>de</strong>s<strong>de</strong> la memoria global a la memoria principal.Con el fin <strong>de</strong> evitar este tráfico es necesario quetanto la CPU como la GPU puedan compartir lamisma memoria. Hoy en día, hay al menos, unejemplo en don<strong>de</strong> una CPU y un acelerador hardwarecomparten la misma memoria, este es el procesadorCELL (IBM) [19] don<strong>de</strong> el procesador principal(Power Processor Element, PPE) pue<strong>de</strong> manejarocho procesadores más pequeños (Synergistic ProcessingElements, SPE). <strong>La</strong> comunicación <strong>de</strong>ntro <strong>de</strong>lCELL pue<strong>de</strong> realizarse mediante memoria compartidao a través <strong>de</strong> un bus en anillo. Este procesadoralcanza 200 Gflops, un 20% <strong>de</strong> Gflops <strong>de</strong> laGTX 285. Actualmente, AMD/ATI está <strong>de</strong>sarrollandouna nueva arquitectura llamada Fusion [20]don<strong>de</strong> CPU y GPU comparten el mismo espacio.En esta sección presentamos una opción para evitarlas transferencias entre memorias. No es suficienteque la CPU y GPU compartan la mismamemoria, a<strong>de</strong>más la CPU <strong>de</strong>be <strong>de</strong> tener acceso a todoslos espacios <strong>de</strong> memoria <strong>de</strong> la GPU para escribiry leer.<strong>JP2011</strong>-320


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 3.Nueva estructura <strong>de</strong> memoriaFig. 4.Un nuevo mo<strong>de</strong>lo <strong>de</strong> comunicación entre CPU y GPUComo po<strong>de</strong>mos ver en la figura 4, la CPU y GPUcomparten el mismo espacio <strong>de</strong> memoria, la CPUcon su controlador <strong>de</strong> memoria (M.C.CPU) pue<strong>de</strong>acce<strong>de</strong>r a todos los espacios <strong>de</strong> memoria, y mantenerla opción mostrada arriba don<strong>de</strong> cada multiprocesadortenía su propia memoria privada.Debido a esto, no se requiere ninguna trasferencia<strong>de</strong> datos entre la CPU y GPU, a<strong>de</strong>más no esnecesario tener duplicados ni los parámetros ni lassoluciones en diferentes espacios <strong>de</strong> memoria, lo cualredundaría también en un ahorro energético.C. Gestión <strong>de</strong> kernelsActualmente, es necesario que la CPU lance todoslos kernels al mismo tiempo, a<strong>de</strong>más estos tienen queterminar también al mismo tiempo. Por lo tanto, noes posible utilizar una solución <strong>de</strong> un kernel particularhasta que todos los kernels terminen. Esto es una<strong>de</strong>sventaja ya que el trabajo más lento impone sustiempos sobre el resto, puesto que la CPU no pue<strong>de</strong>utilizar las soluciones hasta que este kernel finalice.A<strong>de</strong>más, <strong>de</strong>bido a la imposición <strong>de</strong>l kernel más lento,tenemos que parte <strong>de</strong> los recursos computacionales(multiprocesadores y memoria) estan inactivos.Para que podamos utilizar los resultados <strong>de</strong> loskernels tan pronto como estos esten disponibles, esnecesario un mecanismo que permita a la CPU conocerla finalización <strong>de</strong> los mismos. Este mecanismopodría ser implementado con una simple cola monitorizadapor la CPU, esta cola (finished jobs queue,FJQ), <strong>de</strong>bería indicar a la CPU el in<strong>de</strong>ntificador <strong>de</strong>los kernels ya acabados, y por tanto la CPU podríautilizar las soluciones <strong>de</strong> estos, y asignar otros kernelsa los recursos computacionales inactivos.Para ello sería necesario un mecanismo que permitieselanzar los kernels en cualquier momento, envez <strong>de</strong> tener que ser lanzados todos a la vez. Estopodría ser implementado gracias a un conjunto <strong>de</strong>colas (jobs queues, JQ), una por multiprocesador,que almacenase los trabajos a ser ejecutados en unmultiprocesador partcular.Gracias a esto, la CPU podría utilizar los resultados<strong>de</strong> los kernels tan pronto como estos esténdisponibles. A<strong>de</strong>más es posible lanzar kernels encualquier instante, sin tener que esperar a que el máslento <strong>de</strong> ellos finalice. Con todo lo anterior se obtendríaun uso sustancialmente más eficiente <strong>de</strong> losrecursos.Como po<strong>de</strong>mos ver en la figura 5, hay una cola(FJQ) don<strong>de</strong> todos los multiprocesadores envian la<strong>JP2011</strong>-321


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 5.Una neva alternativa para ejecutar más <strong>de</strong> un trabajo en una GPUseñal <strong>de</strong> finalización <strong>de</strong> kernel. Esta cola permite ala CPU conocer los kernel acabados y su or<strong>de</strong>n <strong>de</strong>terminación. Por otro lado, cada multiprocesadortiene en su cola JQ nuevos kernels listos para serejecutados.VI. Conclusiones y trabajo futuroEn este trabajo hemos realizado un estudio sobrelas prestaciones <strong>de</strong> arquitecturas GPUs bajo unascondiciones tales que nos permiten afirmar que esposible ejecutar más <strong>de</strong> un trabajo en una GPU ynos indican un posible camino a seguir para la optimización<strong>de</strong>l uso <strong>de</strong> este tipo <strong>de</strong> dispositivos en entornos<strong>de</strong> High Performance Computing.Este estudio ha estado basado en el coste computacional,temporal, <strong>de</strong>l producto <strong>de</strong> matrices cuadradasbajo los requerimientos estandar <strong>de</strong> este tipo <strong>de</strong>análisis.Para alcanzar los resultados mostrados, previamentese muestra la posibilidad <strong>de</strong> la ejecución <strong>de</strong>más <strong>de</strong> 1 trabajo simultaneamente en una GPU. Dehecho, en el mo<strong>de</strong>lo más reciente <strong>de</strong> GPU (FERMI,que no estaba disponible cuando iniciamos la realización<strong>de</strong> estos estudios) <strong>de</strong> la firma NVIDIA ya esposible está ejecución simultánea <strong>de</strong> más <strong>de</strong> 1 trabajoen una GPU, las diferencias con el mo<strong>de</strong>lo queplanteamos siguen siendo importantes, pero el interés<strong>de</strong>l camino seguido por los autores queda refrendadopor esta <strong>de</strong>cisión comercial.También ha sido necesario i<strong>de</strong>ntificar que el cuello<strong>de</strong> botella en la computación en estos dispositivos,radica en los accesos a memoria, lo cual nos ha guiadoen las propuestas <strong>de</strong> mejora aquí reflejadas. Talespropuestas <strong>de</strong> mejora está fundamentalemente enfocadasen pequeños cambios a nivel <strong>de</strong> arquitecturaque, para ser aprovechados necesitan consecuentemente<strong>de</strong> algunos cambios en su mo<strong>de</strong>lo <strong>de</strong> programación.En la actualidad estamos interesados en el análisis<strong>de</strong> viabilidad real y prestaciones <strong>de</strong> estas ligeramentemodificadas GPUs.Referencias[1] GPGPU. General-purpose computation using graphicshardware. http://www.gpgpu.org.[2] W.-C. Feng, D. Manocha. High-performance computingusing accelerators, Parallel Computing, Elsevier, 33(2007), 645-647.[3] R.J. Rost. OpenGL Shading <strong>La</strong>nguage, Addison-Wesley,2005.[4] W.R. Mark, S.R. Glanville, K. Akeley, M.J. Kilgard. Cg: asystem for programming graphics hardware in a C-like language.SIGGRAPH’03: ACM SIGGRAPH 2003 Papers,pages 896-907, New York, NY, USA, 2003. ACM Press.[5] Pedro Valero, Fernando L. Pelayo. Towards a moreefficient use of GPUs. U.C.L.M. Technical ReportDIAB-11-02-4. http://www.info-ab.uclm.es/trep.php?codtrep=DIAB-11-02-4[6] NVIDIA. NVIDIA CUDA Compute Unified DeviceArchitecture-Programming Gui<strong>de</strong>, Version 2.3 2009,http://www.nvidia.com/object/cuda_home.html.[7] Speeding up pricing complex instruments in the cloud withscifinance. SciComp Inc. http://www.scicomp.com/.[8] GPUGRID. http://www.gpugrid.net.[9] BOINC. http://boinc.berkeley.edu/gpu.php.[10] SETI. http://setiathome.berkeley.edu/cuda.php.[11] Milkyway. http://milkyway.cs.rpi.edu/milkyway_gpu/.[12] AQUA. http://aqua.dwavesys.com/.[13] The <strong>La</strong>ttice Project. http://boinc.umiacs.umd.edu/.[14] Einstein. http://einstein.phys.uwm.edu/.[15] Collatz. http://boinc.thesonntags.com/collatz/.[16] Primegrid. http://www.primegrid.com/.[17] DNETC. http://dnetc.net/.[18] TOP500. http://www.top500.org/.[19] H. Peter Hofstee. Introduction to the CellBroadband Engine. IBM Corporation. https://www-01.ibm.com/chips/techlib/techlib.nsf/techdocs/D21E662845B95D4F872570AB0055404D/$file/2053_IBM_CellIntro.pdf.[20] Nathan Brookwood. AMD Fusion Family of APUs: Enablinga Superior, Immersive PC Experience. AMD Corporation.http://sites.amd.com/us/Documents/48423B_fusion_whitepaper_WEB.pdf<strong>JP2011</strong>-322


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Pre-procesamiento <strong>de</strong> Flujo Óptico Robusto enHardware GráficoFermín Ayuso 1 , Guillermo Botella, Carlos García, Manuel Prieto y Francisco TiradoResumen—Este trabajo aborda la implementacióneficiente <strong>de</strong> filtros bioinspirados espaciales y temporalesconstitutivos <strong>de</strong> etapas previas en la estimación <strong>de</strong>movimiento mediante mo<strong>de</strong>los <strong>de</strong> gradiente. Este estudio selleva a cabo con el objetivo <strong>de</strong> obtener una primeraevaluación en términos <strong>de</strong> rendimiento que ofrece elhardware gráfico. Esta implementación se ha efectuadousando procesadores gráficos (GPU). Se <strong>de</strong>scriben losfiltros, su plausibilidad biológica y así mismo suimplementación óptima aprovechando la arquitecturaparalela que nos brindan las GPUs mo<strong>de</strong>rnas. Se presentaun estudio <strong>de</strong> viabilidad en comparación a un procesador<strong>de</strong> propósito general actual, por medio <strong>de</strong> experimentosque tratan <strong>de</strong> explorar el rendimiento frente a diferentesparámetros <strong>de</strong> diseño algorítmicos en el contexto <strong>de</strong>mo<strong>de</strong>los <strong>de</strong> estimación <strong>de</strong> movimiento que conforman eltamaño <strong>de</strong> filtros temporales y espaciales, or<strong>de</strong>nes <strong>de</strong>precisión y flujo <strong>de</strong> información.Palabras clave— Estimación <strong>de</strong> Movimiento, ProcesadoDigital <strong>de</strong> Señal, Hardware Gráfico, CUDA, SistemasBioinspirados, Sistemas en Tiempo-Real. 1LI. INTRODUCCIÓNA estimación <strong>de</strong> movimiento es un tema muyabordado a lo largo <strong>de</strong> los últimos años <strong>de</strong>bidoa sus múltiples aplicaciones relativas al procesamiento<strong>de</strong> señal, como tracking, vigilancia, disparidadbinocular, etc. Dentro <strong>de</strong> este paradigma encontramostres familias representativas <strong>de</strong> las diferentes técnicas <strong>de</strong>estimación los mo<strong>de</strong>los <strong>de</strong> emparejamiento [1], los <strong>de</strong>energía [2] y los <strong>de</strong> gradiente [3]. <strong>La</strong> primera familiaaplica plantillas dando una i<strong>de</strong>a <strong>de</strong>l ajuste entre una<strong>de</strong>terminada ventana <strong>de</strong> comparación y su ventanaobjetivo <strong>de</strong>ntro <strong>de</strong> un espacio <strong>de</strong> búsqueda dado. Losmo<strong>de</strong>los <strong>de</strong> energía hacen uso <strong>de</strong> probabilida<strong>de</strong>s yesquemas bayesianos, <strong>de</strong> forma que tenemos unadistribución final <strong>de</strong> soluciones válidas (poblaciones <strong>de</strong>filtros) no únicas. Podríamos resumir estos dosesquemas como una aplicación <strong>de</strong> plantillas, buscando<strong>de</strong> forma i<strong>de</strong>al un ajuste óptimo entre el movimiento y laplantilla, con problemas no triviales como el contraste<strong>de</strong>l estímulo, necesitando complejas etapas <strong>de</strong>normalización.<strong>La</strong> filosofía <strong>de</strong> los mo<strong>de</strong>los <strong>de</strong> gradiente sin embargo,viene dada por una solución a la ecuación <strong>de</strong>constricción <strong>de</strong>l flujo óptico:I x I 0x t t1 fermin@fdi.ucm.es,Dept. <strong>de</strong> Arquitectura <strong>de</strong> Computadores y Automática.<strong>Universidad</strong> Complutense <strong>de</strong> Madrid, España(1)Siendo I la intensidad <strong>de</strong> la imagen, don<strong>de</strong> lavelocidad se calcula directamente a través <strong>de</strong> sendoscocientes <strong>de</strong> <strong>de</strong>rivadas temporales y espaciales en cadapunto [3]. El contraste varía igualmente en el<strong>de</strong>nominador y el numerador, resultando un invariante alcontraste sin un coste <strong>de</strong> cálculo adicional.Por otra parte, la percepción <strong>de</strong>l movimiento <strong>de</strong>s<strong>de</strong> elpunto <strong>de</strong> vista sensorial es un tema fundamental parasobrevivir. Existen áreas en el córtex visual cuya únicafunción es <strong>de</strong>tectar movimiento [4]. Uno <strong>de</strong> los retosactuales todavía no resueltos es una explicaciónplausible <strong>de</strong> cómo el sistema visual pue<strong>de</strong> calcular lavelocidad <strong>de</strong>l movimiento a partir <strong>de</strong> los cambiosespaciales y temporales <strong>de</strong> la imagen proyectada en laretina [5].El mo<strong>de</strong>lo neuromórfico en el que se basa este trabajo[6] recoge conocimientos <strong>de</strong> la biología y la fisiologíacortical y está basado en una estructura <strong>de</strong> operadoresdiferenciales espaciales y temporales que luego se rotanen el espacio acelerados mediante arquitecturasespecíficas en hardware gráfico [7].Los procesadores <strong>de</strong> procesamiento gráfico (GPU), seencuentran disponibles en dispositivos <strong>de</strong> bajo costegracias a la evolución <strong>de</strong> la industria <strong>de</strong> los vi<strong>de</strong>ojuegos.Estos dispositivos están basados en sistemasmultinúcleo con una jerarquía <strong>de</strong> memoria compleja.Estas plataformas están diseñadas para aprovechar elalto grado <strong>de</strong> paralelismo <strong>de</strong> datos en el ren<strong>de</strong>rizado <strong>de</strong>escenas en 3D. Sin embargo, se pue<strong>de</strong>n utilizar hoy endía como coprocesadores paralelos mediante laejecución <strong>de</strong> un alto número <strong>de</strong> threadssimultáneamente. A modo <strong>de</strong> ejemplo empleandotecnología actual, un chip <strong>de</strong> NVIDIA Tesla C2070alcanza un rendimiento máximo <strong>de</strong> 1,28 Tera FLOPs,mientras que un procesador Intel i7-975 únicamentepue<strong>de</strong> completar 55 GigaFLOPs. Esta sorpren<strong>de</strong>ntepotencia <strong>de</strong> cómputo ha servido para llamar la atención<strong>de</strong> muchos programadores y científicos proce<strong>de</strong>ntes <strong>de</strong>múltiples áreas, que están utilizando las GPUs actualescomo sistemas paralelos que permiten acelerar suspropias aplicaciones.II. DESCRIPCIÓN DEL PROBLEMAPartiendo <strong>de</strong> la i<strong>de</strong>a <strong>de</strong> este trabajo como una evaluacióninicial <strong>de</strong> las posibilida<strong>de</strong>s que ofrecen las GPUs enaplicaciones <strong>de</strong> estimación <strong>de</strong> movimiento, se planteacomo objetivo inicial implementar tres etapas <strong>de</strong> preprocesamiento<strong>de</strong> movimiento, común a la familia <strong>de</strong>mo<strong>de</strong>los <strong>de</strong> gradiente. Esta máquina será diseñada <strong>de</strong>forma óptima y eficiente aprovechando la arquitecturaespecífica y el mo<strong>de</strong>lo <strong>de</strong> memoria <strong>de</strong> una GPU con el<strong>JP2011</strong>-323


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011fin <strong>de</strong> aprovechar las ventajas <strong>de</strong>l procesamientoconvolutivo y paralelo que está presente en este tipo <strong>de</strong>algoritmos.Estas etapas están fundamentadas en evi<strong>de</strong>ncias <strong>de</strong>existencia <strong>de</strong> estos operadores en el sistema visual <strong>de</strong>mamíferos.A. Filtros temporalesHess y Snow<strong>de</strong>n investigaron el procesamiento visualhumano con una serie <strong>de</strong> experimentos [8] encontrandoevi<strong>de</strong>ncias <strong>de</strong> 3 canales temporales: un canal paso baja,un canal paso banda con frecuencia central aproximadaa 10 Hz y otro paso banda con frecuencia central a 18Hz. Esos 3 canales se pue<strong>de</strong>n mo<strong>de</strong>lar por diferenciación<strong>de</strong> una gaussiana en el dominio <strong>de</strong>l logaritmo <strong>de</strong>l tiempo(Fig. 1).Fig. 1. Representación <strong>de</strong> los tres canales temporales encontrados en elhumano [9] <strong>de</strong>s<strong>de</strong> el punto <strong>de</strong> vista <strong>de</strong> su respuesta impulsiva(arriba) y su comportamiento en frecuencia (abajo).El núcleo será una función que proporcione operadores<strong>de</strong>rivativos a medida que se <strong>de</strong>rive. Como tal, se usaráuna gaussiana en el espacio temporal logarítmico(log(tiempo)), con α=10, τ=0.2, <strong>de</strong>scrito en la ecuaciónsiguiente:enucleo B. Filtros espaciales(log(t / ) / )e 2( )4(2)En el dominio espacial, la forma <strong>de</strong> los camposreceptivos <strong>de</strong> las células en el córtex visual primitivopue<strong>de</strong> ser mo<strong>de</strong>lada con <strong>de</strong>rivadas gaussianas [9]. Amedida que el or<strong>de</strong>n <strong>de</strong> diferenciación aumenta, lasgaussianas se ajustan a frecuencias espaciales máselevadas, obteniendo un rango <strong>de</strong> canales espacialesin<strong>de</strong>pendientes entre sí, que han sido verificadosexperimentalmente como se ilustra en la Fig. 2 y semo<strong>de</strong>la según la expresión siguiente:2Fig. 2. Representación <strong>de</strong> gaussiana bidimensional, y susdiferentes <strong>de</strong>rivadas, haciendo uso <strong>de</strong> la ecuación (1). Filasuperior, <strong>de</strong>rivadas <strong>de</strong> or<strong>de</strong>n 0,1 y 2. Fila inferior, <strong>de</strong>rivadas<strong>de</strong> or<strong>de</strong>n 3,4 y 5.2 2( x y nn2d d 2se ( G ) n 0 ndx dx s 2 p (3) 2 2( x y2n2 2s x y 1e Hn Hn 2s 2s2s s 2 p Don<strong>de</strong> σ representa la anchura <strong>de</strong> la Gaussiana, H n es elpolinomio <strong>de</strong> Hermite <strong>de</strong> or<strong>de</strong>n n. <strong>La</strong> convolución serealiza <strong>de</strong> forma separable, usando <strong>de</strong>rivadas tomadas enfilas y columnas respectivamente, <strong>de</strong>bido a laseparabilidad <strong>de</strong> la gaussiana bidimensional.C. Orientación <strong>de</strong> los Filtros en el espacio(Steering)Esta etapa representa la proyección <strong>de</strong> los filtroscalculados previamente en diferentes orientaciones en elespacio. Representamos en la expresión siguiente laexpresión general <strong>de</strong> las diferentes rotaciones <strong>de</strong> lagaussiana y sus <strong>de</strong>rivadas. Se <strong>de</strong>nomina n y m el or<strong>de</strong>n<strong>de</strong> diferenciación en las direcciones x e y, el ánguloproyectado, D el operador <strong>de</strong>rivativo y G O la expresión<strong>de</strong> la Gaussiana. Esta expresión se resume en expresarcada filtro orientado como una combinación lineal <strong>de</strong> losfiltros <strong>de</strong> su mismo or<strong>de</strong>n <strong>de</strong> diferenciación, como se<strong>de</strong>mostró en trabajo previo [10].n nGnm ,( x, y) Dxcos Dysin k0kmm imi Dxsin DycosG0i0 i k nkIII. MODELO FLUJO OPTICO EN GPUEn este trabajo hemos empleado un sistema basado entecnología Tesla <strong>de</strong> NVIDIA. El sistema cuenta convarias GPUs que se pue<strong>de</strong>n programar empleando elparadigma <strong>de</strong> programación <strong>de</strong> CUDA (ComputeUnified Device Architecture). CUDA es un conjunto <strong>de</strong> (4)<strong>JP2011</strong>-324


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011herramientas <strong>de</strong> NVIDIA [7] que incluye un compiladorespecífico para el hardware gráfico.A. Arquitectura <strong>de</strong> una GPUEl mo<strong>de</strong>lo <strong>de</strong> programación CUDA representa la GPUcomo un coprocesador que pue<strong>de</strong> ejecutar kernels enparalelo y ofrece extensiones para el lenguaje C para (1)mapear los datos <strong>de</strong> la GPU, (2) la transferencia <strong>de</strong> datosentre la GPU y la CPU y (3) lanzar dichos kernels.Un kernel CUDA ejecuta unas líneas <strong>de</strong> código sobre ungran número <strong>de</strong> hilos en paralelo. Este tipo <strong>de</strong> sistemasexplotan el concepto SIMT (Single Instruction MutipleThreads), una misma instrucción es ejecutada pormuchos threads con datos <strong>de</strong> entrada distintos. <strong>La</strong>stareas son organizadas mediante bloques CUDA, don<strong>de</strong>se pue<strong>de</strong>n llegar a lanzar hasta 1024 hilos que pue<strong>de</strong>ncooperar entre sí por (1) compartición <strong>de</strong> datos a través<strong>de</strong> una memoria local <strong>de</strong> baja latencia y (2) lasincronización mediante barreras. Diferentes bloquesCUDA sólo se pue<strong>de</strong>n coordinar a través <strong>de</strong> los accesosa una memoria global <strong>de</strong> alta latencia<strong>La</strong> figura 3 muestra un esquema <strong>de</strong>l hardware en unaGPU. Los núcleos <strong>de</strong> la GPU (procesadores) seorganizan en varios multiprocesadores. Cada uno <strong>de</strong>estos núcleos integra sus propias unida<strong>de</strong>s funcionales yun registro <strong>de</strong> gran tamaño que tiene capacidad para laejecución <strong>de</strong> cientos <strong>de</strong> hilos concurrentes. Cadamultiprocesador posee una Instruction Unit que controlael lanzamiento <strong>de</strong> los hilos y <strong>de</strong> una memoria localcompartida. <strong>La</strong> jerarquía <strong>de</strong> memoria también incluyememoria caché <strong>de</strong> sólo lectura para acelerar el acceso alas texturas y las constantes. <strong>La</strong> abstracción <strong>de</strong>l bloqueCUDA está estrechamente relacionado con estaorganización: cada bloque <strong>de</strong> CUDA es ejecutado por unmultiprocesador, que <strong>de</strong>pendiendo <strong>de</strong> la disponibilidad<strong>de</strong> recursos pue<strong>de</strong>n mapear varios bloques al mismo.en el hardware. <strong>La</strong> unidad <strong>de</strong> programación no es el hiloindividual, sino un grupo <strong>de</strong> hilos llamados warp. Encada ciclo el planificador elige el siguiente warp aejecutar <strong>de</strong> forma semejante a la planificación <strong>de</strong> unprocesador Multihreading <strong>de</strong> grado fino.Uno <strong>de</strong> lo factores más significativos que afectan alrendimiento final es el uso eficiente <strong>de</strong> la jerarquía <strong>de</strong>memoria. A pesar <strong>de</strong> que este tipo <strong>de</strong> hardware permitela ocultación <strong>de</strong> accesos a memoria <strong>de</strong> alta latencia aligual que un procesador Multithreading <strong>de</strong> grano fino, elacceso simultáneamente <strong>de</strong> un número alto <strong>de</strong> threads ala DRAM plantea un enorme <strong>de</strong>safío. Debido a esteproblema, el uso eficiente <strong>de</strong> la memoria localcompartida y las texturas <strong>de</strong> sólo lectura sonfundamentales para lograr buenos rendimientos enmuchos algoritmos. A<strong>de</strong>más, el acceso <strong>de</strong> los threads <strong>de</strong>un warp <strong>de</strong>be <strong>de</strong> ser alineado, porque se traduce en unúnico acceso a memoria reduciendo significativamentela contención con memoria [11].B. Programación <strong>de</strong>l pre-procesamiento <strong>de</strong> flujoóptico en GPUEn esta subsección se abordará la <strong>de</strong>scripción <strong>de</strong>l mapeo<strong>de</strong>l algoritmo bajo estudio en una GPU. Vamos asuponer que una parte <strong>de</strong> la película <strong>de</strong> entrada seadquiere en tiempo real, y que se pue<strong>de</strong> alimentar anuestro sistema con un número <strong>de</strong> frames consi<strong>de</strong>rable.Cada una <strong>de</strong> las etapas correspon<strong>de</strong> a un kernel <strong>de</strong>ejecución en la GPU. A continuación se <strong>de</strong>scribebrévemente su programación:Etapa <strong>de</strong> filtros temporalesRespecto a los filtros temporales, hay que hacer unadiscretización <strong>de</strong> los valores <strong>de</strong>l caso continuo y unposterior ecualizado <strong>de</strong> forma que la integral <strong>de</strong> lasdiferentes funciones se ajuste a cero.Fig 4: Paso <strong>de</strong> una realización <strong>de</strong> filtro temporal, (siendo t=0,n,L elprimer fotograma, el último y la longitud <strong>de</strong>l filtro) que nos da unarespuesta para el fotograma alfa.Fig. 3. Mo<strong>de</strong>lo <strong>de</strong> programación CUDA. GPU como un coprocesadorque integra varios multiprocesadores y una jerarquía <strong>de</strong> memoriacompleja.Como se mencionó anteriormente, la creación <strong>de</strong>subprocesos y la programación se realiza por completoPara realizar su implementación en una GPU hemosconsi<strong>de</strong>rado varias versiones con el ánimo <strong>de</strong> escoger lamás a<strong>de</strong>cuada. Una primera versión en la cual el filtro seencuentre almacenado en diferentes lugares <strong>de</strong> lajerarquía <strong>de</strong> memoria: global, textura o constantes. Yuna segunda versión que almacene la información <strong>de</strong> losnL fotogramas en memoria global o en memoriacompartida. Por último se estudiará el rendimientoalcanzado <strong>de</strong> una versión en la que se evalúe la<strong>JP2011</strong>-325


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011conveniencia <strong>de</strong> reusar información en la memoriacompartida. Los nL fotogramas involucrados en estaetapa se divi<strong>de</strong>n en bloques <strong>de</strong> 16x16 que se mapean enun multiprocesador. El procesado <strong>de</strong> los nL fotogramasen bloques <strong>de</strong> 16x16 pixeles lo realizan 16x16 threads<strong>de</strong> forma que cada hilo realice los cálculos equivalentesal procesado <strong>de</strong> un píxel <strong>de</strong> salida. Como salida seobtiene un suavizado temporal, y las <strong>de</strong>rivadas <strong>de</strong> primery segundo or<strong>de</strong>n respectivamente <strong>de</strong> la secuenciaoriginal mostrado en la figura 4.Etapa <strong>de</strong> filtros espacialesPreviamente a esta etapa, se aplica un filtro paso baja,con objeto <strong>de</strong> suavizar las imágenes y mejorar losresultados <strong>de</strong> las etapas posteriores. A cada una <strong>de</strong> lassalidas temporales le aplicamos una "pirámi<strong>de</strong>" espacial<strong>de</strong> varios filtros (por ejemplo se muestran 10 en la figura5), comprendiendo todas las <strong>de</strong>rivadas <strong>de</strong> una gaussianabidimensional hasta su tercer or<strong>de</strong>n según se ilustra encada una <strong>de</strong> las diagonales <strong>de</strong> la pirámi<strong>de</strong> mostrada en lafigura siguiente.Fig. 5. Pirámi<strong>de</strong> <strong>de</strong> filtros diferenciales espaciales <strong>de</strong> or<strong>de</strong>n 0 hasta 3.<strong>La</strong> implementación en GPU se basa en la creación <strong>de</strong>dos kernels para procesar el filtrado separable vertical yhorizontal. Tomaremos como punto <strong>de</strong> partida el códigoSDK <strong>de</strong> NVIDIA [12] <strong>de</strong> convolución para imágenes.<strong>La</strong> principal diferencia radica en que nuestro algoritmoutiliza una convolución centrada. Con el fin <strong>de</strong>incrementar el grado <strong>de</strong> paralelismo se elige unadimensión mayor, blockid.x o blockid.y en lanomenclatura <strong>de</strong> CUDA, en el eje en que realice elfiltrado. Los filtros correspondientes se almacenan en lamemoria <strong>de</strong> texturas y se aborda el cálculo <strong>de</strong> forma quela información <strong>de</strong> salida que<strong>de</strong> almacenadaconsecutivamente en relación con el or<strong>de</strong>n que seprocesa.Etapa <strong>de</strong> OrientaciónEsta etapa se basa en una síntesis <strong>de</strong>l filtro F orientado grados. Gracias a la linealidad y conmutatividad <strong>de</strong> laconvolución, siendo posible sintetizar el filtro orientadoF a partir <strong>de</strong> los filtros <strong>de</strong> su base (mismo or<strong>de</strong>n <strong>de</strong>diferenciación), será posible obtener su respuestaorientada R a partir <strong>de</strong> su conjunto <strong>de</strong> respuestasR 1 …R n ., tal y como muestra la expresión siguiente: R F I ( K1F1K2F2 .... KnFn)IKF1 1IKF 2 2I...KnFnI KRKR ...K R1 1 2 2 n n(4)Don<strong>de</strong> K 1 ,…,K n representan los pesos, I es la imagen <strong>de</strong>entrada, es la orientación.El cómputo en la GPU se aborda <strong>de</strong> forma similar a laetapa <strong>de</strong> filtrado temporal con la diferencia que el vector<strong>de</strong> pesos se almacena en memoria compartida.IV.RESULTADOSA. Entorno <strong>de</strong> simulaciónEl sistema empleado en nuestras simulaciones es unequipo basado con la tecnología Tesla, posee dosprocesadores Intel Xeon E5530 equipados con cuatrocores a 2.40 GHz con 8MB <strong>de</strong> cache y tecnologíaHyperthreading, conectados a 4 tarjetas gráficas tipoTesla C1060. En este trabajo únicamente se hanempleado un core <strong>de</strong> una CPU y una GPU. El sistemaoperativo es Debian con el kernel 2.6.38, el compiladores el g++ <strong>de</strong> GNU versión 4.5.2 usado con las opciones<strong>de</strong> compilación -O3 -m64 y para hacer uso <strong>de</strong>l hardwaregráfico se emplea la versión 2.3 <strong>de</strong> CUDA.<strong>La</strong> tarjeta gráfica empleada tiene el índice <strong>de</strong> capacidad(CUDA capabilities) 1.3 que indica que posee 240núcleos <strong>de</strong> procesamiento con 1024 threads pormultiprocesador. Posee una jerarquía <strong>de</strong> memoria <strong>de</strong>4GB para memoria global, 16KB <strong>de</strong> memoriacompartida y 64KB para la <strong>de</strong> constantes.B. Resultados <strong>de</strong> rendimientoComo el objetivo <strong>de</strong> este trabajo es evaluar losbeneficios potenciales <strong>de</strong>l hardware gráfico en elcontexto <strong>de</strong> aplicaciones <strong>de</strong> estimación <strong>de</strong> movimiento,hemos enfocado esta sección como un estudiopreliminar <strong>de</strong> las aceleraciones que se pue<strong>de</strong>n alcanzarabordando la implementación <strong>de</strong> algunas <strong>de</strong> las etapasmás relevantes <strong>de</strong>l algoritmo.El primero <strong>de</strong> los análisis que vamos a realizar consisteen observar los beneficios <strong>de</strong> la arquitectura GPU en laetapa <strong>de</strong> filtrado temporal. Se han barajado variasimplementaciones que <strong>de</strong>scribiremos a continuación:- Base: punto <strong>de</strong> partida don<strong>de</strong> la información <strong>de</strong>la película y los filtros se almacenan en lamemoria global. El particionado <strong>de</strong> datos ycómputo empleado está <strong>de</strong>scrito en la secciónIII.B.- Global: la información <strong>de</strong> la película sealmacena en memoria global y el filtro enmemoria <strong>de</strong> constantes.- Shared: los nL fotogramas para ser filtrados sealmacenan en memoria compartida y el filtrosigue en constantes.- Shared-optimizada: el filtro espacial continúaen memoria <strong>de</strong> constantes y los nL fotogramasen memoria compartida creando una estructura<strong>de</strong> buffer circular. El funcionamiento <strong>de</strong> dicho<strong>JP2011</strong>-326


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011buffer es el siguiente: a) en t=0 se inicializa conlos fotogramas <strong>de</strong>s<strong>de</strong> el 1 al nL+1 y b) en t=1 ysucesivos se reemplaza el contenido <strong>de</strong>lfotograma 1 por el <strong>de</strong>l fotograma nL+2. De estaforma se reducen el número <strong>de</strong> copias en lamemoria compartida y se explota el reuso <strong>de</strong>información.<strong>La</strong> figura 6 muestra las aceleraciones obtenidas para loscasos anteriormente <strong>de</strong>scritos respecto a la versión enCPU para un conjunto <strong>de</strong> entradas <strong>de</strong> diferente tamaño<strong>de</strong> fotograma y nL=7,9 y 15.7, 9, 15 y 31. Según se ha observado empíricamente elnúmero <strong>de</strong> ór<strong>de</strong>nes espaciales no afectasignificativamente al rendimiento observándoseresultados análogos para otros valores consi<strong>de</strong>rados. Endicha figura se perciben mejores rendimientos con filtrosmayores porque es posible explotar mayor cantidad <strong>de</strong>paralelismo en el cómputo <strong>de</strong> la convolución llegando alograr aceleraciones cercanas o incluso superiores ax25.908070speedups en filtado temporal30speedup en filtrado espacialSPAC_FILT=4605040302010baseglobalsharedshared-opt25201510532x3264x64128x128256x256032² 64² 128²256² 32² 64² 128²256² 32² 64² 128²256²0CONV=15 CONV=31CONV=7 CONV=23nL=7 nL=9 nL=15Fig. 7. Aceleraciones obtenidas en la etapa <strong>de</strong> filtrado espacialvariando el tamaño <strong>de</strong>l fotograma y el tamaño <strong>de</strong>l filtro espacial.Fig. 6. Aceleraciones obtenidas en la etapa <strong>de</strong> filtrado temporalvariando el tamaño <strong>de</strong>l fotograma y el número <strong>de</strong> fotograma a filtrar(nL).20Speedup en etapa steeringComo se aprecia en la figura las ganancias en tiempo <strong>de</strong>ejecución son importantes sea cual sea la versiónutilizada para GPU. Sin embargo los mejores resultadosse observan cuando los filtros temporales se encuentranalmacenados en memoria <strong>de</strong> constantes y los fotogramasen global (versión global) alcanzando unasaceleraciones <strong>de</strong> hasta 85x.Aunque la versión shared y shared-opt <strong>de</strong>berían lograr apriori mejores resultados porque los tiempos <strong>de</strong> latenciacon memoria compartida son menores que con memoriaglobal, el hecho <strong>de</strong> realizar un cómputo sencillo conpocas operaciones, permite alojar los datos directamenteen los registros <strong>de</strong>l multiprocesador (posee hasta 16Kregistros <strong>de</strong> 32 bits). A modo <strong>de</strong> ejemplo con nL=15, elkernel opera con 3840 elementos por bloque que comose observa es mucho menor a los 16K <strong>de</strong> la arquitectura.En dicha figura también se observan aceleracionesimportantes y crecientes con el tamaño <strong>de</strong>l fotograma,tal y como parece esperable ya que el número <strong>de</strong>bloques-CUDA es mayor lo que se traduce en unamayor utilización <strong>de</strong> los recursos <strong>de</strong> la GPU.A continuación vamos a evaluar los beneficios <strong>de</strong> laarquitectura GPU en la etapa <strong>de</strong>l filtrado espacial. Paraello, con el fin <strong>de</strong> realizar comparaciones con losmismos datos <strong>de</strong> entrada se ha fijado el tamaño <strong>de</strong>l filtrotemporal nL a 15. Tomando los tamaños <strong>de</strong> fotogramaidénticos al análisis anterior, se ha estudiado el impacto<strong>de</strong>l tamaño <strong>de</strong>l filtro espacial y como afecta el número<strong>de</strong> or<strong>de</strong>nes en el rendimiento global.<strong>La</strong> figura 7 muestra las aceleraciones con filtrosespaciales <strong>de</strong> or<strong>de</strong>n 4, variando el tamaño <strong>de</strong>l mismo a15105064x64 128x128 256x2566 ángulos12 ángulos24 ángulosFig. 8. Aceleraciones obtenidas en la etapa <strong>de</strong> steering variando eltamaño <strong>de</strong>l fotograma y en número <strong>de</strong> ángulos.El siguiente análisis correspon<strong>de</strong> con la etapa <strong>de</strong> las<strong>de</strong>rivadas orientadas, o steering. Al ser el cómputo <strong>de</strong>esta etapa bastante sencillo, puesto que únicamenteconlleva la rotación <strong>de</strong> las <strong>de</strong>rivadas anteriores yaplicarles una función <strong>de</strong> pesos según su importanciarelativa, su implementación se fundamenta en almacenarla información <strong>de</strong> entrada en memoria global. <strong>La</strong> i<strong>de</strong>aque subyace es idéntica a conclusión <strong>de</strong> la etapa <strong>de</strong><strong>de</strong>rivadas temporales, el conjunto <strong>de</strong> datos <strong>de</strong> entrada sepue<strong>de</strong> mapear directamente sobre los registros <strong>de</strong> laarquitectura porque su volumen es escaso haciendo uso<strong>de</strong> la memoria compartida para almacenar el contenido<strong>de</strong> los pesos.<strong>La</strong> figura 8 muestra los resultados obtenidos variando eltamaño <strong>de</strong>l fotograma y el número <strong>de</strong> ángulos cada 60º,30º y 15º (6, 12 y 24 ángulos en la figura). En dichafigura se aprecia que, salvo para el caso <strong>de</strong> fotogramas<strong>JP2011</strong>-327


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011pequeños (<strong>de</strong> 64 2 pixeles), el número <strong>de</strong> ángulos y laaceleración obtenida son parecidos, resultando ser lamejor configuración la <strong>de</strong> 24 ángulos y el mayor tamaño<strong>de</strong> fotograma. <strong>La</strong> razón es obvia, para este caso elvolumen <strong>de</strong> datos consi<strong>de</strong>rado es el más alto, por lo queexiste mayor grado <strong>de</strong> paralelismo y por en<strong>de</strong> el grado<strong>de</strong> utilización <strong>de</strong> la GPU es máximo.Tabla 1: Rendimiento en una GPU en comparación con una CPU.64²128²256²Inic. GPU F. temporal F. espacial Steering Total(s/pixel) (kpixel/s) (kpixel/s) (kpixel/s) (kpixel/s)CPU 12848 1441 2090 800GPU 9,08E-6 495984 2552 7882 1214CPU 13965 923 1203 503GPU 7,21E-6 1166121 8792 18271 3454CPU 21503 1047 1304 565GPU 2,25E-6 1724632 27557 24183 6530Y por último en la tabla 1 se recogen los rendimientos<strong>de</strong> cada una <strong>de</strong> las etapas así como el <strong>de</strong>l procesocompleto para los tamaños <strong>de</strong> fotograma consi<strong>de</strong>rados.<strong>La</strong> primera columna correspon<strong>de</strong> al coste <strong>de</strong>inicialización <strong>de</strong>l problema en la GPU, básicamenteinicialización <strong>de</strong>l hardware, reserva <strong>de</strong> memoria y envío<strong>de</strong> información medidos en segundos/píxel. Aunque seobserva que los tiempos por píxel son pequeños estesobrecoste tiene una relevancia importante en el procesofinal que supone un 35-49% <strong>de</strong>l tiempo total, si bien escierto que su impacto se irá disminuyendo a medida quemás etapas <strong>de</strong>l algoritmo se computen en la GPU. <strong>La</strong>scolumnas F. Temporal, F. Espacial y Steeringcorrespon<strong>de</strong>n a cada etapa analizada medidas enkpixel/s. Es importante reseñar que la etapa steering esla que mayor peso computacional tiene (30% <strong>de</strong> mediaincluyendo la fase <strong>de</strong> inicialización <strong>de</strong> la GPU), por loque la aceleración global vendrá <strong>de</strong>terminada por dichaetapa. Y por último la columna Total muestra elrendimiento global observado en una GPU frente a unCPU en igualdad <strong>de</strong> condiciones. En dicha columna sehan tenido presentes los sobrecostes <strong>de</strong> inicializaciónpor lo que se observa una disminución <strong>de</strong>l rendimientorespecto a cada una <strong>de</strong> las etapas por separado.CONCLUSIONES Y LINEAS FUTURASTeniendo en cuenta los análisis realizados conanterioridad, po<strong>de</strong>mos concluir que el uso <strong>de</strong>l hardwaregráfico como acelerador para aplicaciones <strong>de</strong> flujoóptico es interesante y abordable pudiendo llegar aalcanzar aceleraciones globales <strong>de</strong> x12. Sin embargo hayque tener presente sobrecostes <strong>de</strong>rivados <strong>de</strong> gestión <strong>de</strong>memoria y envío <strong>de</strong> información a la GPU que reducesignificativamente los rendimientos.Para alcanzar resultados satisfactorios es crucial haceruna distribución <strong>de</strong> trabajo a<strong>de</strong>cuada y sobre todoexplotar eficientemente la jerarquía <strong>de</strong> memoria <strong>de</strong> laGPU que no es tarea intuitiva.Por otro lado, en este trabajo solamente se ha tenido encuenta el rendimiento, sin embargo al estar trabajandocon un algoritmo expansivo, a medida que crecen lasetapas el consumo <strong>de</strong> memoria pue<strong>de</strong> llegar a actuarcomo limitador. Con la configuración más <strong>de</strong>mandantese consumen 3.5GB <strong>de</strong> memoria global acercándonos allímite <strong>de</strong> su capacidad. Parece indicado explorarmecanismos que reduzcan el número <strong>de</strong> datos o i<strong>de</strong>arestrategias que exploten el paralelismo existente entreetapas siguiendo la analogía <strong>de</strong> un procesadorsegmentado.Y por último, como línea futura se prevé la implantación<strong>de</strong>l mo<strong>de</strong>lo completo <strong>de</strong> procesado <strong>de</strong> movimiento <strong>de</strong>gradiente, multicanal y multiescala, consi<strong>de</strong>rando surepresentación en colores, no exisitiendo actualmenteninguna implementación <strong>de</strong>l mismo que haga uso <strong>de</strong>hardware gráfico.AGRADECIMIENTOSEl presente trabajo ha sido financiado mediante elproyecto CICYT-TIN 2008/508 e Ingenio Consoli<strong>de</strong>rESP00C-07-20811.REFERENCIAS[1] H. Oh, H. Lee, “Block Matching algorithm based on aadaptative reduction of the search area for motionestimation”. Real Time Imaging, vol. 6, pp. 407-414,2000.[2] C. Huang, Y. Chen, “Motion Estimation Method Using a3D Steerable Filter”. Image and Vision Computing, vol13, pp. 21-32, 1995.[3] S. Baker, I. Matthews, "Lucas-Kana<strong>de</strong> 20 Years On: AUnifying Framework," International Journal of ComputerVision, Vol. 56, No. 3pp. 221 – 255, 2004.[4] V. Bruce, P.R. Green, M.A. Georgeson, “VisualPerception: Physiology, Psychology & Ecology”, thir<strong>de</strong>d., <strong>La</strong>urence Erlbaum Associates, Hove, 1996.[5] Claeys, K., Lindsey, D., De Schutter, E., & Orban, G. Ahigher or<strong>de</strong>r motion region in human inferior parietallobule: Evi<strong>de</strong>nce from fMRI.Neuron, 40, 631-642.(2003).[6] A. Johnston, P.W. McOwan, C.P. Benton, “Biologicalcomputation of image motion from flows overboundaries”. J Physiol. Paris, vol. 97, pp. 325-334, 2003.[7] [on-line] http://<strong>de</strong>veloper.nvidia.com/cuda-downloads[8] R. F. Hess, R. J Snow<strong>de</strong>n, “Temporal frequency filters inthe human peripheral visual field”, Vision Research, vol.32, pp. 61-72, 1992.[9] J.J. Koen<strong>de</strong>rink, A.J. Van Doorn, “Representation of localgeometry in the Visual System”, Biol. Cybernetics, 55,pp. 367-375, 1987.[10] G. Botella, “Robust Optical Flow Implementation inReconfigurable Hardware”, PhD Thesis. Dept. ComputerArchitecture, University of Granada (Spain), ISBN 978-84-338-4381-4, 2007.[11] CUDA: Compute Unified Device Architecture., NVIDIACorporation.http://<strong>de</strong>veloper.nvidia.com/object/cuda.html, 2007.[12] CUDA C/C++ SDK CODE Samples, NVIDIADepeloper Zone. http://<strong>de</strong>veloper.nvidia.com/cuda-ccsdk-co<strong>de</strong>-samples<strong>JP2011</strong>-328


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Experiencias con Python y CUDA enComputación <strong>de</strong> Altas PrestacionesSergio Armas, Lionel Mena, Alejandro Samarín,Vicente Blanco 1 , Alberto Morales y Francisco AlmeidaResumen--- <strong>La</strong> computación paralela no ha cesado <strong>de</strong>explorar nuevos horizontes con el objetivo <strong>de</strong> obtenermejoras tangibles <strong>de</strong> rendimiento en la ejecución <strong>de</strong>algoritmos <strong>de</strong> toda clase. Si bien durante muchos añosse ha seguido el camino <strong>de</strong> innovar en la arquitectura<strong>de</strong> las CPU y crear software que se aproveche <strong>de</strong> esosbeneficios, la consolidación <strong>de</strong> la que vienen disfrutandoen la última década los dispositivos gráficos comohardware <strong>de</strong> cómputo general es difícil <strong>de</strong> ignorar.Este cambio <strong>de</strong> paradigma trae consigo nuevas formas<strong>de</strong> programar, nuevas herramientas y por supuesto,nuevos <strong>de</strong>safíos. El hecho <strong>de</strong> que el lenguaje C y sus<strong>de</strong>rivados sean la lingua franca <strong>de</strong> este tipo <strong>de</strong> programaciónno <strong>de</strong>bería sorpren<strong>de</strong>r a propios ni a extraños,pero otros lenguajes se van haciendo huecopoco a poco. Es el caso <strong>de</strong> Python, que gracias alwrapper PyCUDA [1] es capaz <strong>de</strong> ofrecer al programadoracceso a la computación <strong>de</strong> altas prestacionessobre dispositivos gráficos sin renunciar a la comodidady dinamismo <strong>de</strong> este lenguaje. El propósito <strong>de</strong>este artículo es comprobar las facilida<strong>de</strong>s que prometePyCUDA así como su rendimiento frente a problemasreales.Palabras clave--- Python, CUDA, PyCUDA, Py-CUBLASI. Introducción<strong>La</strong> capacidad <strong>de</strong> cómputo <strong>de</strong> las unida<strong>de</strong>s <strong>de</strong> procesamientográfico (GPU) ha alcanzado en los últimosaños un <strong>de</strong>sarrollo notable, que ha crecido <strong>de</strong> maneraparalela a un fuerte incremento en la produccióny <strong>de</strong>manda <strong>de</strong> dispositivos que las integran, talescomo smartphones, tablets, etc., a<strong>de</strong>más <strong>de</strong> seguirpresentes en tarjetas gráficas o placas base con cadavez más relevancia. Precisamente, dicho aumento <strong>de</strong>potencia ha comenzado a hacer atractivo su empleopara la manipulación <strong>de</strong> cantida<strong>de</strong>s masivas <strong>de</strong> datosen ámbitos ajenos al <strong>de</strong>l vi<strong>de</strong>o tales como criptología,biología computacional, cálculo científico etc., que,por su naturaleza paralela, son susceptibles <strong>de</strong> ejecutarsecon más eficiencia, incluso, que en una CPUtradicional. Esta técnica <strong>de</strong> usar la GPU en aplicacionesque tradicionalmente se habían ejecutado enCPU recibe el nombre <strong>de</strong> GPGPU (General-purposecomputing on graphics processing units).A pesar <strong>de</strong> que existen diversos fabricantes especializadosen dispositivos gráficos que ofrecen algúntipo <strong>de</strong> framework para <strong>de</strong>sarrollo <strong>de</strong> aplicacionesparalelas sobre GPGPU, e incluso alternativasmás generales como OpenCL [2], NVIDIA esprobablemente el que más ha apostado por este enfoque.Prácticamente <strong>de</strong>s<strong>de</strong> los albores <strong>de</strong> esta computación,ha ido <strong>de</strong>sarrollando un mo<strong>de</strong>lo <strong>de</strong> programación<strong>de</strong>nominado CUDA (Compute Unified DeviceArchitecture) [3], que permite al programador1 Dpto. Estadística, I.O. y Computación, Univ. <strong>La</strong> <strong>La</strong>guna,e-mail: vblanco@ull.esejecutar algoritmos casi arbitrarios en sus GPU. Ellenguaje <strong>de</strong> programación diseñado para ello es unavariación <strong>de</strong> C que contiene extensiones para trabajarcon la GPU, amén <strong>de</strong> ciertas restricciones (nopermite recursividad ni punteros a funciones, solopermite números en precisión simple en la mayoría<strong>de</strong> tarjetas lanzadas al mercado hasta ahora, etc.).El término anglosajón wrapper se emplea en computaciónpara <strong>de</strong>signar, a gran<strong>de</strong>s rasgos, un tipo <strong>de</strong>software que aña<strong>de</strong> una capa <strong>de</strong> código para traducir<strong>de</strong> una interfaz existente a otra, generalmente con lafinalidad <strong>de</strong> ganar portabilidad, sencillez o compatibilidad.PyCUDA, que ha sido <strong>de</strong>sarrollado por AndreasKlöckner 2 , es un ejemplo <strong>de</strong> esto: ejerce la función<strong>de</strong> interfaz en Python para las funciones nativasescritas en C que proporciona la SDK <strong>de</strong> NVIDIA.<strong>La</strong> principal ventaja que representa la utilización <strong>de</strong>PyCUDA en el <strong>de</strong>sarrollo, en contraposición al uso<strong>de</strong> las funciones propias <strong>de</strong> NVIDIA bajo C/C++, essin duda la comodidad. PyCUDA permite abstraer,por ejemplo, <strong>de</strong> todo lo relacionado con la reservay liberación <strong>de</strong> memoria en el dispositivo, lo cualhubiera representado una carga adicional <strong>de</strong> trabajo<strong>de</strong>stacable en la versión C/C++. En este artículo seanalizará si las ventajas <strong>de</strong> utilizar un lenguaje interpretado<strong>de</strong> muy alto nivel para ejecutar algoritmosen una GPU compensa la menor velocidad inherentea los lenguajes interpretados.II. Acerca <strong>de</strong>l mo<strong>de</strong>lo <strong>de</strong> programaciónCUDAEl diseño <strong>de</strong> CUDA tiene como el objetivo el <strong>de</strong>sarrollo<strong>de</strong> software que, <strong>de</strong> manera transparente, escaleel paralelismo <strong>de</strong> manera que se pueda aprovecharel incremento <strong>de</strong>l número <strong>de</strong> procesadores al tiempoque mantiene una baja curva <strong>de</strong> aprendizaje paralos programadores familiarizados con lenguajes estándarescomo el C. Para lograr esto fundamentalmenteposee tres puntos clave:Jerarquía <strong>de</strong> hilosJerarquía <strong>de</strong> memoriaSincronizaciones por barreraA. Jerarquía <strong>de</strong> HilosSe <strong>de</strong>fine en base a 3 elementos: hilo, bloque y grid.Así pues, cada grid contiene bloques y estos a su vezcontienen hilos.Por conveniencia, cada hilo se i<strong>de</strong>ntifica por unvector <strong>de</strong> tres componentes (x, y, z) <strong>de</strong>nomina-2 Courant Institute of Mathematical Sciences - New YorkUniversity - http://mathema.tician.<strong>de</strong>/aboutme<strong>JP2011</strong>-329


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011C. Sincronizaciones por BarreraComo los distintos hilos colaboran entre ellos ypue<strong>de</strong>n compartir datos, se requieren directivas <strong>de</strong>sincronización. En CUDA se pue<strong>de</strong> especificar unasincronización <strong>de</strong>l tipo barrera, en la que todos loshilos esperan a que los <strong>de</strong>más lleguen al mismo punto.Fig. 1. Jerarquía <strong>de</strong> hilos y patrones <strong>de</strong> accesodo threadIdx, así los hilos pue<strong>de</strong>n i<strong>de</strong>ntificados porun índice threadIdx unidimensional, bidimensionalo tridimensional, formando a su vez un bloque unidimensional,bidimensional o tridimensional. Estoprovee <strong>de</strong> una manera natural <strong>de</strong> realizar cálculossobre elementos tales como un vector o una matriz.B. Jerarquía <strong>de</strong> MemoriaLos hilos en CUDA pue<strong>de</strong>n acce<strong>de</strong>r a distintasmemorias, unas compartidas y otras privadas. Enprimer lugar tenemos la memoria local privada <strong>de</strong>cada hilo. Cada bloque <strong>de</strong> hilos posee memoria compartidavisible solo por los hilos <strong>de</strong>l bloque y con elmismo tiempo <strong>de</strong> vida <strong>de</strong>l bloque. Finalmente cadahilo en cada bloque <strong>de</strong> cada grid pue<strong>de</strong> acce<strong>de</strong>r a lamemoria global.Adicionalmente existen dos espacios <strong>de</strong> memoria<strong>de</strong> sólo lectura accesible por todos los hilos: la memoria<strong>de</strong> texturas y la memoria <strong>de</strong> constante, optimizadaspara usos específicos. <strong>La</strong>s memorias global,<strong>de</strong> textura y constante persisten mientras el kernelpermanezca en acción.Asi como se pue<strong>de</strong> i<strong>de</strong>ntificar los hilos <strong>de</strong>ntro <strong>de</strong>un bloque, se pue<strong>de</strong>n i<strong>de</strong>ntificar los bloques <strong>de</strong>ntro <strong>de</strong>un grid, mediante una variable blockIdx que tambiénpue<strong>de</strong> ser un índice unidimensional, bidimensional otridimensional.D. KernelCUDA extien<strong>de</strong> el lenguaje permitiendo <strong>de</strong>finirfunciones llamadas kernels, que cuando son invocadas,son ejecutadas N veces en paralelo por N diferentehilos <strong>de</strong> CUDA. Estas abstracciones permitenun granulado fino en el paralelismo <strong>de</strong> los datos ylos hilos, conduciendo al programador a dividir elproblema en subproblemas que pue<strong>de</strong>n ser tratadosin<strong>de</strong>pendientemente y en paralelo por bloques <strong>de</strong> hilos,y su vez dividir estos subproblemas en elementosindividuales que pue<strong>de</strong>n ser resueltos en paralelo y <strong>de</strong>manera cooperativa por todos los hilos <strong>de</strong> un mismobloque.Esta estructura preserva la expresividad <strong>de</strong>llenguaje permitiendo que los hilos cooperen en laresolución <strong>de</strong> cada subproblema, y al mismo tiempopermite la escalabilidad. En efecto, cada bloque<strong>de</strong> hilos pue<strong>de</strong> ser programado en cualquier núcleo<strong>de</strong> procesamiento que este disponible, en cualquieror<strong>de</strong>n, concurrente o secuencialmente. Por lo quecualquier programa CUDA ya compilado pue<strong>de</strong> ejecutarseen sistemas con distinto número <strong>de</strong> núcleos <strong>de</strong>procesamiento, y solo el sistema <strong>de</strong> tiempo <strong>de</strong> ejecución<strong>de</strong>be conocer el dicho número <strong>de</strong> núcleos físicos.Todo esto <strong>de</strong>s<strong>de</strong> el punto <strong>de</strong> vista <strong>de</strong>l programadorconsiste en la extensión <strong>de</strong>l lenguaje con un conjuntoreducido <strong>de</strong> instrucciones, lo que supone un curva <strong>de</strong>aprendizaje suave; cabe notar, sin embargo, que a pesar<strong>de</strong> que CUDA permite la programación <strong>de</strong> kernelscon pocas restricciones sobre el lenguaje, es necesarioadoptar ciertas pautas a la hora <strong>de</strong> generar los kernels<strong>de</strong> las aplicaciones <strong>de</strong> interés, ya que <strong>de</strong> no seguirestas directrices el rendimiento se verá afectado severamente.Existen varias <strong>de</strong> ellas, pero las más importantesson dos: garantizar la coalescencia en el accesoa memoria (tanto en operaciones <strong>de</strong> lectura como <strong>de</strong>escritura) y usar la memoria compartida común a loshilos <strong>de</strong> un mismo bloque, para aprovechar su mayorvelocidad <strong>de</strong> acceso en comparación con la memoriaglobal <strong>de</strong>l dispositivo [4]. Si se tienen en cuenta ambascaracterísticas, es muy probable que el kernel encuestión tenga un rendimiento excelente.III. Computación con PyCUDAA. Requerimientos previosAntes <strong>de</strong> nada, es conveniente mencionar quepara po<strong>de</strong>r utilizar PyCUDA en una <strong>de</strong>terminadamáquina <strong>de</strong> pruebas, es necesario proveer primero <strong>de</strong>todo un framework asociado que necesita dicho software.En líneas generales, PyCUDA necesita obviamente<strong>de</strong> Python instalado en el sistema, así como<strong>de</strong> NumPy/SciPy y <strong>de</strong> las librerías boost. Estos a suvez tienen algunas <strong>de</strong>pen<strong>de</strong>ncias <strong>de</strong> software con la<strong>JP2011</strong>-330


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011b = np . random . randn (16)Aunque las más recientes GPUs soportan númerosen coma flotante <strong>de</strong> doble precisión, la mayoría <strong>de</strong>los dispositivos disponibles actualmente sólo soportanprecisión simple, por lo que se impone la siguienteconversión <strong>de</strong> tipos:a . astype ( np . float32 )b . astype ( np . float32 )Fig. 2. Software necesario para ejecutar PyCUDAque se <strong>de</strong>be tener cuidado, ya que <strong>de</strong> la correcta configuración<strong>de</strong> ATLAS y LAPACK, por ejemplo, vaa <strong>de</strong>pen<strong>de</strong>r en buena medida el rendimiento posterior<strong>de</strong> PyCUDA. Asimismo, para el ejemplo práctico<strong>de</strong>l <strong>de</strong>sarrollo <strong>de</strong> un algoritmo <strong>de</strong> <strong>de</strong>tección <strong>de</strong>movimiento, se impone la necesidad <strong>de</strong> disponer <strong>de</strong>algunas librerías externas que faciliten sobremanerael manejo <strong>de</strong> imágenes y vi<strong>de</strong>os <strong>de</strong> manera suficientementetransparente para el usuario, como es el caso<strong>de</strong> PIL y OpenCV; y todo esto en su conjunto <strong>de</strong>behacer uso <strong>de</strong> las librerias que proporciona la SDK <strong>de</strong>NVIDIA. En la figura 2 se representan <strong>de</strong> maneraclara estas <strong>de</strong>pen<strong>de</strong>ncias <strong>de</strong> software.B. Ejecución <strong>de</strong> un kernel con PyCUDANo existe una única manera <strong>de</strong> ejecutar un algoritmoen un dispositivo con PyCUDA y, por supuesto,no todas resultan igual <strong>de</strong> eficientes. A continuación,se mostrará una sencilla secuencia <strong>de</strong> instruccionesque ilustran <strong>de</strong> manera bastante exacta el nivel<strong>de</strong> abstracción que pue<strong>de</strong> llegar a alcanzarse sinmenoscabo <strong>de</strong> la eficiencia.En primer lugar, se importan los mínimos paquetesnecesarios para el funcionamiento <strong>de</strong> PyCUDA:import pycuda . autoinitimport pycuda . driver as cudafrom pycuda . compilerimport SourceModuleConviene hacer notar que aunquepycuda.autoinit se encarga <strong>de</strong> inicializar eldispositivo (seleccionando el <strong>de</strong> mayor capacidad <strong>de</strong>cómputo si hay más <strong>de</strong> uno), así como <strong>de</strong> crear uncontexto automáticamente, ambos aspectos pue<strong>de</strong>nser configurados manualmente.El siguiente paso consiste en cargar en memorialos datos que se <strong>de</strong>sean procesar. En este punto, resultamuy aconsejable el uso <strong>de</strong>l paquete NumPy <strong>de</strong>la librería SciPy, pues está provisto <strong>de</strong>l potente tipo<strong>de</strong> dato numpy.array, que facilita la preparación ymanipulación <strong>de</strong> los datos. En este ejemplo, consi<strong>de</strong>raremosdos arrays aleatorios a y b, cuyas componentesse suman dos a dos sobreescribiendo b con elresultado.import numpy as npa = np . random . randn (16)Una vez cargados los datos en memoria, los siguientespasos son transferirlos al dispositivo y ejecutarel kernel. Con PyCUDA, ambos pasos pue<strong>de</strong>nconcentrar en uno solo, porque en la propia llamadaal kernel pue<strong>de</strong> estar implícita la transferencia<strong>de</strong> los datos a la memoria <strong>de</strong>l dispositivo si sehace uso <strong>de</strong> la clase ArgumentHandler disponible enpycuda.driver, la cual está preparada para trabajarcon arrays numpy como argumentos <strong>de</strong> entrada/salida.kernel = SourceModule ( " " "__global__ void name( f l o a t *a ,f l o a t *b ) {i n t idx = threadIdx . x ;b [ idx ] = b [ idx ] + a [ idx ] ;}" " " )f = kernel . get_function ( " name " )f ( cuda . In ( a ) , cuda . InOut ( b ) ,block =(16 ,16 ,1))C. Overhead inducidoObviamente, el hecho <strong>de</strong> trabajar con un lenguajeinterpretado como lo es Python, y con un wrappercomo lo es PyCUDA, implica una carga <strong>de</strong> trabajoextra para el procesador (no directamente relacionadocon el cómputo en GPU) que <strong>de</strong>be ser analizaday comparada con la misma ejecución nominal en Cpara <strong>de</strong>terminar si este overhead supone un gravamenaceptable o no. En la figura 3 se pue<strong>de</strong> observaruna comparación al ejecutar un filtro <strong>de</strong> convoluciónseparable [5] tanto en C como en Python + PyCU-DA, separando en cada caso (para distintos tamaños<strong>de</strong> matrices cuadradas) el tiempo empleado en ejecutarúnicamente el kernel en GPU y el programacompleto (que engloba reserva <strong>de</strong> memoria, creacion<strong>de</strong> los arrays aleatorios, instanciacion <strong>de</strong>l kernel, liberacion<strong>de</strong> memoria... así como el tiempo <strong>de</strong> ejecución<strong>de</strong>l propio kernel en la GPU). Como se pue<strong>de</strong>observar, y como era <strong>de</strong> esperar, los kernels se ejecutansiempre ligeramente más rápidos en C (un 50 %más rápido como mínimo, aunque hay que recordarque en estos niveles se habla <strong>de</strong> milisegundos paraprocesar matrices cuadradas <strong>de</strong>l or<strong>de</strong>n <strong>de</strong> 2048x2048elementos). Sin embargo, en el tiempo total <strong>de</strong> ejecuciónse pue<strong>de</strong> observar como lo que a priori <strong>de</strong>beríaser una ventaja para C, a partir <strong>de</strong> 2048x2048 elementosel programa en C tarda <strong>de</strong> hecho más que elmismo programa en Python. Esto pue<strong>de</strong> <strong>de</strong>berse a<strong>JP2011</strong>-331


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 3. Kernel para un filtro <strong>de</strong> convolución: C y PyCUDAFig. 4. Producto <strong>de</strong> matrices en CUDA: C y PyCUBLASdiversas razones: en C, los arrays a procesar se rellenancon números aleatorios obtenidos mediante lafunción rand(), mientras que en Python es NumPyel encargado <strong>de</strong> generar las matrices aleatorias. Esconocida la gran eficiencia <strong>de</strong> NumPy a la hora <strong>de</strong>manejar matrices <strong>de</strong> gran tamaño, por lo que este <strong>de</strong>tallepue<strong>de</strong> jugar a su favor. Otro posible punto <strong>de</strong>divergencia (ya que aunque los programas sean funcionalmenteiguales, evi<strong>de</strong>ntemente hay ciertos elementos<strong>de</strong>l lenguaje que están programados <strong>de</strong> formadistinta) sea la utilización <strong>de</strong> los timers propios<strong>de</strong> NVIDIA para realizar las medidas en C (a través<strong>de</strong> la librería proporcionada por la SDK shrUtils);sería interesante comprobar hasta que punto están ono interfiriendo estos timers particulares en las medicionestotales.En cualquier caso, pue<strong>de</strong> comprobarse como eloverhead que introduce la utilización <strong>de</strong> Python +PyCUDA no es, en ningún caso, alarmante. Sí quees necesario hacer notar, sin embargo, que en el caso<strong>de</strong> las primeras ejecuciones <strong>de</strong> algún programa queuse PyCUDA, la fase <strong>de</strong> carga <strong>de</strong> los import inicialessí que es importante, llegando a tardar los mismosejemplos <strong>de</strong> la figura 3 cerca <strong>de</strong> 2 segundos, y don<strong>de</strong>la mayoría <strong>de</strong> los cuales se emplea en la precarga <strong>de</strong>estas directivas <strong>de</strong>l wrapper: comunicación inicial conel/los dispositivos existentes, selección <strong>de</strong> dispositivo,carga <strong>de</strong> la interfaz con el compilador <strong>de</strong> NVIDIAnvcc, etc.IV. Producto matricial<strong>La</strong> manera tradicional <strong>de</strong> abordar la multiplicación<strong>de</strong> matrices pasa por ejecutar un algoritmo secuencial<strong>de</strong> complejidad casi cúbica en las mejores implementaciones.Su versión paralela, en cambio, permiteel cálculo simultáneo <strong>de</strong> las filas <strong>de</strong> la primera matrizmultiplicando con la correspondiente columna <strong>de</strong> lasegunda para formar el resultado.BLAS (Basic Linear Algebra Subprograms) es, <strong>de</strong>facto, una interfaz estándar <strong>de</strong> programación <strong>de</strong> libreríasque realizan operaciones básicas <strong>de</strong> álgebralineal con vectores y/o matrices.Des<strong>de</strong> su primera publicación, en 1979, numerososfabricantes <strong>de</strong> hardware han <strong>de</strong>sarrollado versionesaltamente optimizadas <strong>de</strong> BLAS. También NVIDIAlo ha incluido en el SDK <strong>de</strong> CUDA para proporcionaruna versión <strong>de</strong> altas prestaciones para estas operaciones.Dicha implementación ha sido <strong>de</strong>nominadaCUBLAS.Por su parte, PyCUBLAS es un wrapper [6] <strong>de</strong>Python para CUBLAS creado por Derek An<strong>de</strong>rsonque ha centrado su diseño en la multiplicación <strong>de</strong>gran<strong>de</strong>s matrices. Dispone, a<strong>de</strong>más, <strong>de</strong> las ventajasya comentadas <strong>de</strong> Python en cuanto a abstracción,lo que posibilita la ejecución <strong>de</strong> una operación conmuy pocas líneas <strong>de</strong> código.import numpy as npfrom pycublas import CUBLASMatrixa = np . random . randn ( width , length ) .astype ( np . float32 )b = np . random . randn ( width , length ) .astype ( np . float32 )a = CUBLASMatrix ( np . mat ( a ) )b = CUBLASMatrix ( np . mat ( b ) )c = a * bEsta sencillez sintáctica podría ser atractiva paraexten<strong>de</strong>r el uso <strong>de</strong> CUDA entre investigadores <strong>de</strong>otras ciencias cuyos estudios precisen <strong>de</strong> la manipulación<strong>de</strong> cantida<strong>de</strong>s masivas <strong>de</strong> datos.En esta sección se confrontan el tiempo <strong>de</strong> ejecuciónen el dispositivo <strong>de</strong> una multiplicación <strong>de</strong> matricescuadradas <strong>de</strong> diferentes dimensiones, tanto através <strong>de</strong> PyCUBLAS como <strong>de</strong> su correspondienteversión nativa en C. No se ha contemplado en la gráfica<strong>de</strong> la figura 4 los tiempos <strong>de</strong> ejecución en la CPU,puesto que estos llegan a ser hasta 35 millones <strong>de</strong> vecesmayor en el caso <strong>de</strong> una matrix <strong>de</strong> 2048x2048.V. Detección <strong>de</strong> movimientoTeniendo en cuenta las posibilida<strong>de</strong>s <strong>de</strong>l mo<strong>de</strong>loCUDA exploradas hasta ahora, parece lógico buscaralgún algoritmo que conlleve un esfuerzo computacionalnotable para ir un paso más allá en la exploración<strong>de</strong>l uso <strong>de</strong> Python como vehículo conductor<strong>de</strong> los programas <strong>de</strong> cómputo. Una primera consi<strong>de</strong>racióninteresante es el RANSAC [7], un algoritmoutilizado frecuentemente en campos muy diversos,pero no resulta fácilmente acomodable al cómputo<strong>JP2011</strong>-332


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 5. Jerarquía <strong>de</strong> clases <strong>de</strong>l <strong>de</strong>tector <strong>de</strong> movimientoparalelo bajo esta arquitectura <strong>de</strong>bido a que requiere<strong>de</strong> estructuras <strong>de</strong> datos complejas que a<strong>de</strong>más contemplanmúltiples <strong>de</strong>pen<strong>de</strong>ncias entre ellas.Finalmente, se ha escogido como objetivo <strong>de</strong> <strong>de</strong>sarrolloel diseño e implementación <strong>de</strong> un paquete quepermita aplicar diferentes filtros a una imagen, a unconjunto <strong>de</strong> imágenes o a un vi<strong>de</strong>o, en cuyo caso será<strong>de</strong>scompuesto en sus correspondientes frames. Estepaquete pue<strong>de</strong> utilizarse para acelerar el cálculo <strong>de</strong>aplicaciones complejas que requieran <strong>de</strong> la aplicación<strong>de</strong> filtros [8]. En concreto, una <strong>de</strong> las más interesantesconsiste en un programa <strong>de</strong> <strong>de</strong>tección <strong>de</strong> movimiento:a gran<strong>de</strong>s rasgos, toma 2 frames <strong>de</strong> un vi<strong>de</strong>o ydiscierne (marcando en color rojo sobre uno <strong>de</strong> losframes original) las partes en movimiento entre losmismos. Esto mismo se ejecuta <strong>de</strong> manera iterativael número <strong>de</strong> veces necesario para realizar la <strong>de</strong>tección<strong>de</strong> movimiento sobre un vi<strong>de</strong>o compuesto <strong>de</strong> unamultitud <strong>de</strong> frames.El paquete Filters <strong>de</strong>sarrollado para este fin seestructura, esencialmente, en torno a dos clases:CUDAHandler, concebido para abstraer <strong>de</strong> muchos<strong>de</strong>talles <strong>de</strong> la comunicación con la GPU (informalmente,podría consi<strong>de</strong>rarse un wrapper <strong>de</strong>l propio Py-CUDA); y Filter, clase abstracta <strong>de</strong> la que heredancada uno <strong>de</strong> los filtros implementados. En la figura5, pue<strong>de</strong>n observarse tres clases hijas <strong>de</strong> Filterque contienen las instrucciones para gestionar tresfiltros necesarios para la <strong>de</strong>tección <strong>de</strong> movimiento(Difference, Threshold y Erosion), como se explica enla posterior subsección. También se contempla unaclase MotionDetector, encargada <strong>de</strong> dirigir la <strong>de</strong>tecciónen sí aplicando los filtros frame tras frame y quehace uso <strong>de</strong>l paquete Filters, a<strong>de</strong>más por último <strong>de</strong>la clase Vi<strong>de</strong>oHandler que la abstrae <strong>de</strong> la manipulación<strong>de</strong> las operaciones <strong>de</strong> gestión <strong>de</strong> ví<strong>de</strong>o.A. Implementación <strong>de</strong>l algoritmoEl algoritmo <strong>de</strong> <strong>de</strong>tección <strong>de</strong> movimiento más simplese basa en la aplicación <strong>de</strong> una secuencia <strong>de</strong> filtrossobre los frames (imágenes) <strong>de</strong>l vi<strong>de</strong>o [9]. Paraenten<strong>de</strong>r el proceso basta con escoger 2 frames consecutivos<strong>de</strong>l vi<strong>de</strong>o y aplicar los siguientes pasos:1. Conversión a escala <strong>de</strong> grises <strong>de</strong> las 2 imágenes2. Aplicación <strong>de</strong>l filtro <strong>de</strong> diferencia a las 2 imágenes3. Aplicación <strong>de</strong>l filtro Threshold4. Aplicación <strong>de</strong>l filtro <strong>de</strong> Erosión5. Mezcla en el canal R <strong>de</strong> la imagen original conla imagen resultado <strong>de</strong> los filtrosUna vez obtenidos las 2 imágenes en escala <strong>de</strong> grises,se proce<strong>de</strong> a aplicar el primer filtro:Filtro <strong>de</strong> Diferencia: Este filtro consiste en elvalor absoluto <strong>de</strong> la resta <strong>de</strong> cada píxel (restandocanal a canal en caso <strong>de</strong> imágenes <strong>de</strong> varios canales)<strong>de</strong> las dos imágenes. Con esto obtenemos las zonasdon<strong>de</strong> se ha producido movimiento, como se pue<strong>de</strong>observar en la primera imagen <strong>de</strong> la figura 6.Filtro Threshold: <strong>La</strong> finalidad <strong>de</strong> este filtro esobtener una imagen binaria don<strong>de</strong> solo aparecen píxelesblancos o negros. Este filtro compara cada píxelcon un umbral, y si el valor <strong>de</strong>l píxel está por <strong>de</strong>bajose asigna el valor 0 (negro), en caso contrario (porencima <strong>de</strong>l umbral) se asigna el valor 255 (blanco).Así pues, la imagen resultante quedaría como la segundaimagen <strong>de</strong> la figura 6, don<strong>de</strong> a<strong>de</strong>más se apreciala aparición <strong>de</strong> ruido a simple vista.Filtro <strong>de</strong> Erosión: Contenido <strong>de</strong>ntro los llamadosFiltros Morfológicos, este filtro <strong>de</strong>termina si unpíxel se mantiene (se <strong>de</strong>fine como blanco) o se elimina(se <strong>de</strong>fine como negro). Para sopesar esta <strong>de</strong>cisiónse hace uso <strong>de</strong> una máscara (<strong>de</strong>finida a conveniencia)que <strong>de</strong>termina los píxeles vecinos a examinar; <strong>de</strong>s<strong>de</strong>que al menos uno <strong>de</strong> estos vecinos esté en negro, seelimina el píxel analizado (operación and lógica. Porel contrario, si todos los píxeles vecinos existen el píxelanalizado permanecerá en blanco. El objetivo <strong>de</strong>aplicar este filtro es eliminar el ruido expuesto por elfiltro anterior, como se pue<strong>de</strong> apreciar en la tercera<strong>JP2011</strong>-333


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011la misma como por rendimiento, a cambio <strong>de</strong> un pequeñoe inevitable overhead inherente a la naturalezainterpretada <strong>de</strong> Python y al uso <strong>de</strong> wrappers. Decualquier forma, ese incremento en tiempo es lo suficientemente<strong>de</strong>spreciable para que se pueda ignorarsin temor, máxime si se tiene en cuenta el hecho <strong>de</strong>que a mayor tamaño <strong>de</strong>l problema, más imperceptiblese torna dicha carga <strong>de</strong> trabajo adicional. Por último,pero no por ello menos importante, los autores<strong>de</strong>sean recalcar que la curva <strong>de</strong> aprendizaje necesariapara po<strong>de</strong>r manejarse en este entorno con ciertasolvencia es consi<strong>de</strong>rablemente más suave que laque conlleva el entorno tradicional <strong>de</strong> programación<strong>de</strong> CUDA bajo C/C++, lo cual consi<strong>de</strong>ran un argumento<strong>de</strong> suma importancia para atraer usuariospotenciales, ya sean académicos <strong>de</strong> nueva hornadao investigadores asentados que tienen necesidad <strong>de</strong>cálculo masivo paralelo y que utilizan para ello aplicaciones<strong>de</strong>sarrolladas hace años en lenguajes comoFORTRAN cuyo mantenimiento se hace cada vezmás inviable. En <strong>de</strong>finitiva, si se tiene intención <strong>de</strong>migrar estas aplicaciones, Python y PyCUDA conformanuna alternativa perfectamente capaz.Fig. 6. Fases <strong>de</strong>l algoritmo <strong>de</strong> <strong>de</strong>tección <strong>de</strong> movimientoimagen <strong>de</strong> la figura 6.Por último, queda realizar el fundido en el canalR <strong>de</strong> la imagen original con la imagen resultante <strong>de</strong>aplicar el filtro <strong>de</strong> erosión. Este fundido no es más queuna suma <strong>de</strong> píxel a píxel, obteniendo así el resultadofinal <strong>de</strong> la figura 6.VI. ConclusionesComo se ha podido observar, implementar la resolución<strong>de</strong> problemas relativamente complejos noes especialmente costoso en tiempo con lenguajesdinámicos como Python. Si a eso se le aña<strong>de</strong> la posibilidad<strong>de</strong> utilizar todo el potencial <strong>de</strong> cómputo paraleloque ofrece CUDA a través <strong>de</strong> wrappers comoPyCUDA, el resultado es una herramienta muy potenteque pue<strong>de</strong> satisfacer las necesida<strong>de</strong>s <strong>de</strong> investigadoresy científicos en general tanto por madurez <strong>de</strong>Referencias[1] Andreas Klöckner, Nicolas Pinto, Yunsup Lee, Bryan C.Catanzaro, Paul Ivanov, and Ahmed Fasih, ``Pycuda:Gpu run-time co<strong>de</strong> generation for high-performance computing,''CoRR, vol. abs/0911.3456, 2009.[2] Khronos Group, ``OpenCL - The open standard for parallelprogramming of heterogeneous systems,'' 2011.[3] NVIDIA Corp., ``What is CUDA - NVIDIA DeveloperZone,'' 2011.[4] NVIDIA Corp., ``NVIDIA CUDA C Best PracticesGui<strong>de</strong>,'' 2010.[5] Victor Podlozhnyuk (NVIDIA Corp.), ``Image Convolutionwith CUDA,'' 2007.[6] Derek An<strong>de</strong>rson, ``PyCUBLAS - EasyPython/NumPy/CUDA/CUBLAS Integration,'' 2009.[7] Liu Jiayin, Wang Chuang, and Jae Ho Kim, ``Camera motion<strong>de</strong>tection for conversation scenes in movies,'' in Proceedingsof the 2010 International Conference on Computationaland Information Sciences, Washington, DC, USA,2010, ICCIS '10, pp. 725--728, IEEE Computer Society.[8] Zhiyi Yang, Yating Zhu, and Yong Pu, ``Parallel imageprocessing based on cuda,'' in CSSE (3). 2008, pp. 198--201, IEEE Computer Society.[9] Andrew Kirillov, ``Motion <strong>de</strong>tection algorithms,'' 2007.<strong>JP2011</strong>-334


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011A Scalable Visualization System for CrowdSimulationsGuillermo Vigueras, Juan M. Orduña, Miguel Lozano y Víctor Fernán<strong>de</strong>z-Bauset 1Abstract— The visualization system of large-scalecrowd simulations should scale up with both the numberof visuals (views of the virtual world) and thenumber of agents displayed in each visual. Otherwise,we could have large scale crowd simulationswhere only a small percentage of the population isdisplayed. Several approaches have been proposed inor<strong>de</strong>r to efficiently ren<strong>de</strong>r crowds of animated characters.However, these approaches either ren<strong>de</strong>r crowdsanimated with simple behaviors or they can only supporta few hundreds of user-driven entities. In thispaper, we propose a distributed visualization systemfor large crowds of autonomous agents that allows thevisualization of the crowd without adding significantoverhead to the simulation servers. The proposed implementationcan be hosted on <strong>de</strong>dicated computersdifferent from the servers, and it takes advantage ofthe Graphics Processor Unit (GPU) capabilities. Asa result, the performance evaluation shows that thousandsof agents can be ren<strong>de</strong>red without affecting theperformance of the simulation servers. These resultssuggest that the <strong>de</strong>sign of the visual client allows toadd multiple visuals for displaying large crowds.Keywords— Distributed simulation, parallel ren<strong>de</strong>ringI. IntroductionLA rge scale crowd simulations are becoming essentialtools for many virtual environment applicationsin education, training, and entertainment [1],[2]. In or<strong>de</strong>r to <strong>de</strong>al with the computational complexityof large scale simulations, different proposals havebeen ma<strong>de</strong> for achieving both very populated scenes[3] and scalable autonomous behaviors [4], [5]. However,the scalability of autonomous complex agents(crowd simulations) is still an open issue in spite ofthese efforts.In previous works, we proposed a distributed systemarchitecture that can simulate large crowds ofautonomous agents at interactive rates [6], [7], [8],and it can take advantage of the inherent scalabilityof manycore computer architectures [9]. However, inor<strong>de</strong>r to make a truly scalable system for crowd simulations,the visualization system (the module responsibleof ren<strong>de</strong>ring the images of the virtual world)should also be addressed. The visualization systemshould scale up with both the number of visuals(cameras focusing on the virtual world) and the numberof agents displayed in each camera. Otherwise,we could have large scale crowd simulations whereonly a small percentage of the population could beren<strong>de</strong>red (displayed).In this paper, we propose a distributed visualizationsystem that allows the visualization of the virtualworld without adding significant overhead to thesimulation servers, regardless of both the number of1 Dpto. <strong>de</strong> Informática, Univ. <strong>de</strong> Valencia e-mail:{Guillermo.Vigueras,Juan.Orduna}@uv.esvisuals and the number of agents ren<strong>de</strong>red by eachvisual. In or<strong>de</strong>r to achieve this goal, the visualizationsystem consists of a visual client process (VCP)for each camera, and each VCP is hosted on a computerdifferent from the ones hosting the simulationservers. In this way, the connection of the visualclient does not significantly affects the performanceof the simulation system. The proposed implementationmigrates different ren<strong>de</strong>ring tasks of the VCPfrom the CPU to the Graphics Processor Unit (GPU)of the hosting computer, reducing the CPU workloadof the visual client and increasing throughput. Also,we use skinned instancing for reducing the ren<strong>de</strong>ringworkload. As a result, the performance evaluationshows that thousands of agents can be ren<strong>de</strong>redwithout affecting the performance of the simulationservers. These results suggest that the <strong>de</strong>sign of thevisual client allows to add multiple visuals for displayinglarge crowds.The rest of the paper is organized as follows: sectionII shows some related work about visual clientsfor crowd simulations. Section III briefly <strong>de</strong>scribesthe distributed architecture for crowd simulationthat was previously proposed, and it shows the scalabilityproblems arising when connecting a VCP tothis kind of systems. Next, section IV <strong>de</strong>scribes theproposed implementation for the distributed visualclient, and section V shows the performance evaluationof the proposed implementation. Finally, sectionVI shows some conclusions.II. Related WorkFrom the graphics community, several approacheshave been proposed in or<strong>de</strong>r to efficiently ren<strong>de</strong>rcrowds of animated characters. Image-based [10] andPoint-based [11] techniques obtain interactive framerates when ren<strong>de</strong>ring crow<strong>de</strong>d animated scenes byreducing the geometrical complexity of the 3D charactersmeshes. Other approaches use efficient parallelgraphic techniques to provi<strong>de</strong> interactive graphicsperformance for crow<strong>de</strong>d scenes [12]. Although thesegraphic-based approaches obtain good frame rates,they are not focused on providing scalable architectures.Other proposals [13] combine parallel architectureswith efficient graphic techniques to simulateand to display thousands of individuals. In this case,authors use the Cell processor architecture withoutconsi<strong>de</strong>ring scalability issues.From the distributed simulation arena, there havebeen several approaches oriented to handle multiplayergames [14], [15]. Other works use the HLAarchitecture [16] combining classical scene graphswith simulated fe<strong>de</strong>rations to provi<strong>de</strong> interactive<strong>JP2011</strong>-335


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011graphic applications for military and entertainmentpurposes.Although these approaches can provi<strong>de</strong> interactivelatencies and frame rates, required by multiplayergames, they usually can only support a few hundredsof user-driven entities within a simulation.III. A Distributed System for <strong>La</strong>rge-ScaleCrowd SimulationIn previous works, we proposed an architecturethat can simulate large crowds of autonomous agentsat interactive rates [6], [7]. In that architecture, thecrowd system is composed of many Client Computers,that host agents implemented as threads of aClient Process, and one Action Server (AS), executedin one computer, that is responsible for checking theactions (eg. collision <strong>de</strong>tection) sent by agents [6].In or<strong>de</strong>r to avoid server bottleneck, the simulationworld was partitioned into subregions and each oneassigned to one parallel AS [7]. A scheme of thisarchitecture is shown in figure 1. This figure showshow the 2D virtual world occupied by agents (blackdots) is partitioned into three subregions, and eachone managed by one parallel AS (labeled in the figureas AS x ). Each AS is hosted by a different computer.Agents are execution threads of a Client Process (labeledin the figure as CP x ) that is hosted on oneClient Computer. The computers hosting client andserver processes are interconnected. Each AS processhosts a copy of the Semantic Database. However,each AS exclusively manages the part of thedatabase representing its region. In or<strong>de</strong>r to guaranteethe consistency of the actions near the bor<strong>de</strong>rof the different regions (see agent k in figure 1), theASs can collect information about the surroundingregions by querying the servers managing the adjacentregions. Additionally, the associated Clients arenotified about the changes produced by the agents locatednear the adjacent regions by the ASs managingthose regions.The architecture shown in Figure 1 allows to simulatelarge crowds of autonomous agents providing agood scalability. However, it also needs a scalable visualizationmethod in or<strong>de</strong>r to ren<strong>de</strong>r the simulatedcrowd. The visualization system will be in chargeof ren<strong>de</strong>ring the simulated world, starting from theinformation generated by the distributed servers. Inor<strong>de</strong>r to provi<strong>de</strong> scalability, the visualization systemshould be <strong>de</strong>signed in a distributed fashion.A feasible way of implementing a distributed visualizationsystem could be the integration of a ren<strong>de</strong>ringmodule within each Action Server. In thisway, each AS could visualize its own region of thevirtual world. However, the computational workloadresulting from adding a ren<strong>de</strong>ring module to eachAS could result in a performance <strong>de</strong>gradation of thewhole simulation system [17]. Additionally, with thisapproach the number of cameras would be limitedby the number of servers in the system. Instead, wehave followed a different approach, where the visualizationof the simulation is distributed among dif-Fig. 1. General scheme of the distributed simulation systemwith a Visual Client Process.ferent processes, each one <strong>de</strong>noted as Visual ClientProcess (VCP). Each VCP manages one camera, andit is hosted in a <strong>de</strong>dicated computer different fromthe ones hosting either CPs or ASs. A VCP can beconnected to several different ASs, <strong>de</strong>pending on thearea of the virtual world covered by the camera ofthe VCP. For example, in Figure 1 the VCP is connectedto both AS 1 and AS 2 , since the projection ofthe camera plane (<strong>de</strong>noted as MBR Frustum) intersectsthe regions managed by these ASs.In or<strong>de</strong>r to efficiently <strong>de</strong>signing the ren<strong>de</strong>ring moduleof the VCP, the first step consists of measuringthe workload that the information received from theASs represents for a single VCP. The amount of informationsent by the ASs <strong>de</strong>pends on two factors: thenumber of simulated agents and the acting period ofthose agents (the period of time between two successiveactions requested by an agent). Table I showsthe percentage of CPU utilization in the computerhosting the VCP when increasing both the numberof agents in the MBR Frustum and the acting period.The results were obtained using up to four servers,each one managing 3000 agents (12000 agents in totalfor four servers). In these tests, the VCP wereconnected to the servers and all the agent requestsreceived by the servers were sent to the VCP, i.e. theVCP received updates from 12000 agents when usingfour servers. Table I shows that the VCP workloa<strong>de</strong>xceeds the computational bandwidth of the hostingcomputer when 6000 agents (2 servers) are connectedto the VCP, since the percentage of CPU utilizationreaches 100%. Also, this table shows that the workloadgenerated by the VCP is inversely related to theacting period, as it could be expected.In or<strong>de</strong>r to find how the saturation of the CPU affectsthe performance of the VCP, we have measured<strong>JP2011</strong>-336


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLE ICPU utilization (%) of the computer hosting the VCP.Agents Acting Period (ms.)100 400 700 10003000 69 67 65 556000 100 100 100 1009000 100 100 100 10012000 100 100 100 100the difference between the number of operations sentby the ASs and the number of operations actuallyprocessed by the VCP. Table II shows these data,and it shows that for 3000 agents there are no lostoperations (the CPU hosting the VCP is not saturated,reaching a maximum CPU utilization of 69%for the lowest acting period (100 ms). However, from6000 agents up, the VCP does not process all the requests,<strong>de</strong>pending on the agent period. It is worthmention that for the case of 6000 agents the VCP iscapable of process all the operations received whenusing an acting period of 700 and 1000 ms. However,when simulating 12000 agents the VCP cannot processall the operations, regardless of the agent periodconsi<strong>de</strong>red. These results show that the implementationof the VCP should reduce the CPU utilizationassociated to the graphic tasks as much as possible,in or<strong>de</strong>r to increase the VCP throughput.or received from other ASs and CPs are exchangedasynchronously. This means that the AE threadsonly may have to wait when accessing the semanticdatabase.The changes required in the Action Server forconnecting the VCP exclusively affects the InterfaceModule. Figure 2 shows the general scheme of an ActionServer modified for accepting VCP connections.Two I/O threads are created for each VCP connectedto an AS. One of the I/O threads receives, through asocket, the MBR frustum updates sent by the VCP.It must be noticed that the updates received fromthe VCP are not passed to the Crowd AS ControlModule. In this way, the workload ad<strong>de</strong>d by eachVCP connected to the AS is reduced. The other I/Othread is in charge of forwarding to the VCP theAS replies to agents requests. This thread uses theMBR frustum updates received from the VCP to filterforwar<strong>de</strong>d replies. It simply checks whether anagent falls within the MBR frustum or not (see Figure1). In this way, a VCP can visualize less agentsthan those that form the crowd simulated by the distributedsystem.TABLE IIVisualization requests not processed by the VCP.AgentsActing Period (ms.)100 400 700 10003000 0 0 0 06000 76207 44729 0 09000 205545 238244 61972 012000 433716 391644 157606 19137IV. Distributed Ren<strong>de</strong>ring of CrowdSimulationsIn this section we <strong>de</strong>scribe the proposed implementationof the Visual Client Process. The proposedapproach for ren<strong>de</strong>ring crowd simulation is based onhaving each VCP connected with one or more ActionServers. Therefore, the first step is to modifythe AS scheme proposed in [7] in such a way thatthe information about the agent actions is also sentto the VCPs. Then, an implementation of the VCPaccording to that scheme should be <strong>de</strong>veloped.A. Modifications to the Action ServerEach AS process [7] contains three basic elements:the Interface module, the Crowd AS Control (CASC)module and the Semantic Data Base (SDB). The Interfacemodule is in charge of communicating theAS with other ASs and CPs. The main module isthe Crowd AS Control module, which is responsiblefor executing the crowd actions. This module containsa configurable number of threads for executingactions (action execution threads). For an actionexecution thread (AE thread), all messages sent toFig. 2.Scheme of an Action Server with VCP connections.B. Implementation of the Visual Client ProcessThe VCP is mainly composed by two modules: theInterface Module and the Graphic Application Module.Figure 3 shows an schematic view of this process.The Interface Module is in charge of sending updatesof the MBR frustum to the ASs. Also , this moduleshould receive agents updates and pass them to theGraphic Application Module. The Graphic ApplicationModule is in charge of performing the graphictasks. Some of these tasks are executed on the CPUand other ones are executed on the GPU.As shown in section III, it is crucial to reduce asmuch as possible the percentage of CPU utilization inthe computer hosting the VCP in or<strong>de</strong>r to minimizethe number of visualization updates not processedby the VCP. In or<strong>de</strong>r to achieve this goal, the frustumculling and the <strong>de</strong>termination of the Level Of<strong>JP2011</strong>-337


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Detail (LOD) are performed by the GPU, like otherapproaches do [18].Additionally, we use Instancing to efficiently ren<strong>de</strong>rcrow<strong>de</strong>d scenes [19]. When ren<strong>de</strong>ring a 3D mesh,typical graphic APIs issue a Draw call to the graphicpipeline. Each API call has associated a fixed-costoverhead for processing a primitive, regardless of thesize. Due to this API call overhead, the performanceof a graphic application (in terms of Frames PerSecond or FPS) is CPU-boun<strong>de</strong>d instead of GPUboun<strong>de</strong>d.Instancing consists in grouping charactersthat share a 3D mesh into a batch, generating onlyone Draw call. However, when using Instancing charactershave to share both the mesh and the poseat a given time. Since a crowd is composed of autonomousagents, each one has a different pose at agiven time. As a result, the use of Instancing provi<strong>de</strong>snon-realistic movements. In or<strong>de</strong>r to solve thisproblem, we have implemented the VCP using theSkinned Instancing technique [20]. This techniquetakes advantage of the new DirectX graphic API,that allows to perform Instancing but generating ani<strong>de</strong>ntifier for each instance of the 3D mesh. In thisway, each instance can keep its own properties (i.e.translation, rotation and scale) and the GPU skinningmethod [12] can be in<strong>de</strong>pen<strong>de</strong>ntly applied toanimate the character meshes.Figure 3 shows a scheme of the VCP and the differenttasks of each part of the Graphic Module. TheCPU part of this Module acts as an interface withthe user, updating the camera position according tothe MBR frustum. All the MBR frustum updatesare passed to the Interface Module in or<strong>de</strong>r to sendthem to the ASs. Additionally, the CPU processesthe agents updates received by the Interface Moduleand formates this data in or<strong>de</strong>r to properly performthe skinned instancing on the GPU. Once theGPU part of the Graphic Module receives agents updatesthrough a vertex buffer, it firstly perform theview frustum culling and the LOD <strong>de</strong>termination.As a result, agents that have passed the culling testare grouped by LOD and one GPU buffer is usedto store agents sharing the same LOD. Since we areusing three LODs, three buffers are the input of theSkinned Instanced step. Once the instanced meshesare properly animated, they are ren<strong>de</strong>red.V. Performance EvaluationFig. 3.Scheme of the <strong>de</strong>sign of the Visual Client Process.In this section, we show the performance evaluationof the proposed distributed visual client. Likeother distributed systems, the most important performancemeasurements in these systems are latencyand throughput. However, since we are focusing onthe visual client performance and how the integrationof a VCP affects to the overall system (crowdsimulation) performance, we have performed simulationswith different servers and we have measuredboth the response time of the servers and frames rateobtained in the VCP. In or<strong>de</strong>r to <strong>de</strong>fine an acceptablebehavior for the system, we have consi<strong>de</strong>red 250 ms.as the maximum acceptable value for the responsetime, since it is consi<strong>de</strong>red as the limit for providingrealistic effects to users in DVEs [21]. For the VCP,we have consi<strong>de</strong>red about 30 frames per second as anacceptable frame rate.As a simulation platform, we have used a clusterof computers based on AMD Opteron (2 processors@ 1.56 GHz) with 3.84GB of RAM, executing Linux2.6.9-1 operating system. The interconnection networkin the cluster was a Gigabit Ethernet network.The machine used for the visual client was based onIntel Core 2 Duo @ 2.4 GHz with 4GB of RAM,executing Windows Vista operating system. Thegraphic card within the VCP was a NVIDIA GForce9600M GT. We have performed the distributed simulationsusing up to four computers of the clusterfor hosting an AS each. For that case, we used eightcluster no<strong>de</strong>s (four of them for hosting the serversand four of them for hosting four clients). Usingthis platform, we have simulated up to twelve thousandagents. The VCP was connected to the serversthrough the cluster network and the number of agentupdates received by the VCP was increased in or<strong>de</strong>rto study the VCP performance.For comparison purposes, we have implementedthree different VCPs. The first one (<strong>de</strong>noted as SDC,for ”separate draw calls”) does not use Instancingto ren<strong>de</strong>r the crowd and performs the LOD computationon the CPU. The second version (<strong>de</strong>notedas iCPU) uses Skinned Instancing and it computesthe LODs on the CPU. Finally, and the third kindof VCP (<strong>de</strong>noted as iGPU) uses Skinned Instancingand performs the LOD calculations on the GPU. Figure4 shows the CPU load of the different versions ofthe visual client when the number of ren<strong>de</strong>red agentsis increased. In this figure, the X-axis shows the<strong>JP2011</strong>-338


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011number of ren<strong>de</strong>red characters and the Y-axis showsthe percentage of CPU utilization when executingthe VCP. This figure shows very much higher CPUutilization load for the SDC version than the one requiredfor the iCPU and iGPU versions. This versionof the VCP leads the CPU close to saturation levelsfor 5000 agents due to the absence of Instancing,while the other two versions only require less than a50% of CPU utilization. This figure also shows thatthe iGPU version 3 reduces the percentage of CPUutilization around a 10% respect to the iCPU version.Therefore, the version that provi<strong>de</strong>s the bestresults in terms of visual throughput (the maximumnumber of characters that can be ren<strong>de</strong>red) is theiGPU implementation of the VCP.Figure 5 shows the performance of the differentversions of the VCP in terms of FPS. In this figure,the X-axis shows the number of ren<strong>de</strong>red agentsand the Y-axis shows the frame rate achieved by theVCP. It can be seen that both the iCPU and theiGPU versions clearly outperform the SDC version.The reason for that behavior is that the SDC versionsaturates the CPU. However, there is no a significantdifference between the frame rates obtained by theiCPU and the iGPU versions of the VCP becauseboth of them use Instancing. Therefore, they generatethe same number of draw calls. Since the iGPUprovi<strong>de</strong>s the best throughput and a similar framerate than the iCPU version, we have used this versionas the VCP implementation for the rest of theevaluation.Fig. 4. CPU utilization for different implementations of theVCP.Once the version of the VCP that provi<strong>de</strong>s thebest performance has been selected, the next stephas been to study the performance of that VCP whenit is connected to the crowd simulation system. TableIII shows the performance measurements for theVCP when the number of agents updates receivedfrom the ASs is increased. It can be seen that whenren<strong>de</strong>ring 2000 agents at a good frame rate the CPUutilization is around 87% and no agents updates arelost (all the requests are processed by the VCP). Asthe number of agent ren<strong>de</strong>ring requests increases, sodoes the CPU utilization, causing a frame rate <strong>de</strong>creaseon the VCP but still above acceptable valuesFig. 5. Frame rates for different implementations of the VCP.(higher than 30 FPS). However, from 5000 agents upto 6000 agents the CPU reaches saturation, resultingin agents updates that are not processed and causingthe frame rate to fall below 30 FPS.TABLE IIIPerformance measurements for the VCP whenincreasing the number of agents updates received.Characters ren<strong>de</strong>red2000 3000 4000 5000 6000% CPU 86,7 89,3 94 95,7 98,8FPS 55,4 41,6 34,8 28,4 25,4Lost ops. 0 0 0 34134 57348Finally, we have studied the performance of thesimulation servers when the VCP is connected, inor<strong>de</strong>r to show that the latter one does not have a significanteffect on the servers performance. Figures 6and 7 show the performance of the simulation systemwhen the VCP is connected to a simulation systemconsisting of four servers and the number of agentsupdates sent to the VCP is increased. In these figures,the X-axis shows the number of agents updatesthat the VCP receives. The Y-axis in figure 6 showsthe CPU utilization in the system servers, while theY-axis in figure 7 shows the response time (in ms.)provi<strong>de</strong>d to agents (that are executed as threads ofthe client processes).Figure 6 shows that the CPU utilization in the systemservers remains almost constant as the numberof agents ren<strong>de</strong>red by the VCP increases. It startsfrom a CPU utilization of 80% for 2000 agents andfor 6000 agents it does not reach 90%. Since the VCPdoes not lead the system servers to saturation, figure7 shows that they provi<strong>de</strong> an acceptable responsetime (shorter than 250 ms.) up to 6000 agents. Theseresults show that the VCP does no have significanteffects on the performance of the system servers.VI. ConclusionsIn this paper, we have proposed a distributed visualizationsystem that allows the visualization of thevirtual world without adding significant overhead tothe simulation servers. The proposed implementationcan be hosted on <strong>de</strong>dicated computers different<strong>JP2011</strong>-339


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 6. CPU utilization of simulation servers with a connectedVCP.Fig. 7. Response time provi<strong>de</strong>d by simulation servers with aconnected VCP.from the servers, and it migrates different ren<strong>de</strong>ringtasks of the VCP from the CPU to the GPU of thehosting computer. Also, we use skinned instancingfor reducing the ren<strong>de</strong>ring workload. As a result,the performance evaluation shows that thousands ofagents can be ren<strong>de</strong>red without affecting the performanceof the simulation servers. These results suggestthat the <strong>de</strong>sign of the visual client allows to addmultiple visuals for displaying large crowds.AcknowledgementsThis work has been jointly supported by the SpanishMICINN, the European Commission FEDERfunds, and the University of Valencia un<strong>de</strong>r grantsConsoli<strong>de</strong>r-Ingenio CSD2006-00046 and TIN2009-14475-C04-04.references[1] Ameya Shendarkar, Karthik Vasu<strong>de</strong>van, Seungho Lee,and Young-Jun Son, “Crowd simulation for emergencyresponse using bdi agent based on virtual reality,” inWSC ’06: Proceedings of the 38th conference on Wintersimulation, 2006, pp. 545–553.[2] Dan Chen, Georgios K. Theodoropoulos, Stephen J.Turner, Wentong Cai, Robert Minson, and Yi Zhang,“<strong>La</strong>rge scale agent-based simulation on the grid,” FutureGeneration Computer Systems, vol. 24, no. 7, pp. 658 –671, 2008.[3] Adrien Treuille, Seth Cooper, and Zoran Popovic, “Continuumcrowds,” in SIGGRAPH ’06: ACM SIGGRAPH2006 Papers. 2006, pp. 1160–1168, ACM.[4] A. Iglesias and F. Luengo, “New goal selection schemefor behavioral animation of intelligent virtual agents,”IEICE Transactions on Information and Systems, vol.E88-D, no. 5, pp. 865–871, 2005.[5] Huaglory Tianfield, Jiang Tian, and Xin Yao, “On thearchitectures of complex multi-agent systems,” in Proc.of the IEEE/WIC International Conference on Web Intelligence/ Intelligent Agent Technology,. 2003, pp. 195–206, IEEE Press.[6] M. Lozano, P. Morillo, J. M. Orduña, V. Cavero, andG. Vigueras, “A new system architecture for crowd simulation,”J. Netw. Comput. Appl., vol. 32, no. 2, pp.474–482, 2009.[7] G. Vigueras, M. Lozano, C. Pérez, and J.M. Orduña, “Ascalable architecture for crowd simulation: Implementinga parallel action server,” in Proceedings of InternationalConference on Parallel Processing (ICPP), Los alamitos,CA, USA, 2008, pp. 430–437, IEEE Computer Society.[8] G. Vigueras, M. C. Lozano, J.M. Orduña, andF. Grimaldo, “A comparative study of partitioning methodsfor crowd simulations,” Appl. Soft Comput., vol. 10,no. 1, pp. 225–235, 2010.[9] G. Vigueras, J. M. Orduña, and M Lozano, Advancesin Practical Applications of Agents and Multiagent Systems,chapter A GPU-Based Multi-agent System forReal-Time Simulations, pp. 15–24, Springer Berlin / Hei<strong>de</strong>lberg,2010.[10] Simon Dobbyn, John Hamill, Keith O’Conor, and CarolO’Sullivan, “Geopostors: a real-time geometry/impostorcrowd ren<strong>de</strong>ring system,” ACM Trans. Graph., vol. 24,no. 3, pp. 933–933, 2005.[11] Michael Wand and Wolfgang Straßer, “Multi-resolutionren<strong>de</strong>ring of complex animated scenes,” Comput. Graph.Forum, vol. 21, no. 3, 2002.[12] Golam Ashraf and Junyu Zhou, “Hardware acceleratedskin <strong>de</strong>formation for animated crowds,” in 13th InternationalMultimedia Mo<strong>de</strong>ling Conference, MMM. 2007,pp. 226–237, Springer.[13] Craig Reynolds, “Big fast crowds on ps3,” in Proceedingsof the 2006 ACM SIGGRAPH symposium onVi<strong>de</strong>ogames, New York, NY, USA, 2006, pp. 113–121.[14] Ashwin Bharambe, Jeffrey Pang, and Srinivasan Seshan,“Colyseus: a distributed architecture for online multiplayergames,” in NSDI’06: Proceedings of the 3rd conferenceon Networked Systems Design & Implementation,Berkeley, CA, USA, 2006, pp. 12–12.[15] Alma V. Martinez, Héctor Rafael Orozco, Félix F. RamosCorchado, and Mario Siller, “A peer-to-peer architecturefor real-time distributed visualization of 3d collaborativevirtual environments,” in 13th IEEE/ACM InternationalSymposium on Distributed Simulation and RealTime Applications, 2009, pp. 251–254.[16] Hua Xiong, Zonghui Wang, Xiaohong Jiang, and JiaoyingShi, “Building high performance DVR via HLA, scenegraph and parallel ren<strong>de</strong>ring,” in Proc. of the 2007 ACMsymposium on Virtual reality software and technology,New York, NY, USA, 2007, pp. 141–144.[17] P. Morillo, J. M. Orduña, M. Fernán<strong>de</strong>z, and J. Duato,“Improving the performance of distributed virtual environmentsystems,” IEEE Transactions on Parallel andDistributed Systems, vol. 16, no. 7, pp. 637–649, 2005.[18] Hunki Park and Junghyun Han, “Fast ren<strong>de</strong>ring of largecrowds using GPU,” in ICEC ’08: Proceedings of the 7thInternational Conference on Entertainment Computing,Berlin, Hei<strong>de</strong>lberg, 2009, pp. 197–202, Springer-Verlag.[19] Tomas Akenine-Möller, Eric Haines, and Natty Hoffman,Real-Time Ren<strong>de</strong>ring 3rd Edition, A. K. Peters, Ltd.,Natick, MA, USA, 2008.[20] B. Dudash, “Skinned instancing,” Tech. Rep., NVIDIACorp., February 2007.[21] T. Hen<strong>de</strong>rson and S. Bhatti, “Networked games: a qossensitiveapplication for qos-insensitive users?,” in Proceedingsof the ACM SIGCOMM 2003. 2003, pp. 141–147, ACM Press / ACM SIGCOMM.<strong>JP2011</strong>-340


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011A New Approach to rCUDAJosé Duato, Antonio J. Peña, and Fe<strong>de</strong>rico Silla 1Juan C. Fernán<strong>de</strong>z, Rafael Mayo, and Enrique S. Quintana-Ortí 2Abstract— In this paper we propose a first step towardsa general and open source approach for usingGPGPU (General-Purpose Computation on GPUs)features within virtual machines (VMs). In particular,we <strong>de</strong>scribe the use of rCUDA, a GPGPU virtualizationframework, to permit the execution ofGPU-accelerated applications within VMs, thus enablingGPGPU capabilities on any virtualized environment.Our experiments with rCUDA in the contextof KVM and VirtualBox on a system equippedwith two NVIDIA GeForce 9800 GX2 cards illustratethe overhead introduced by the rCUDA middlewareand prove the feasibility and scalability of this generalvirtualizing solution.Keywords— CUDA, GPUs, GPGPU, high performancecomputing, virtual machines, virtualization.I. IntroductionMANY-CORE specialized processors and, inparticular, graphics processors (GPUs), are experiencingincreased adoption as an appealing wayof reducing the time-to-solution in areas as diverseas finance [1], image analysis [2], and many others.These hardware accelerators offer a large amount ofprocessing elements and high processor-to-memorybandwidth, so that applications featuring a high rateof computations per data item can attain high performance.In addition, these <strong>de</strong>vices present a relativelyhigh performance/cost ratio, resulting in aninteresting option for HPC (high performance computing).On the other hand, virtualization technologies arecurrently wi<strong>de</strong>ly <strong>de</strong>ployed, as their use yields importantbenefits such as resource sharing, process isolation,and reduced management costs. Thus, it isstraight-forward that the usage of virtual machines(VMs) in HPC is an active area of research [3]. VMsprovi<strong>de</strong> an improved approach to increase resourceutilization in HPC clusters, as several different customersmay share a single computing no<strong>de</strong> with theillusion that they own it in an exclusive way.Processes running in a VM may also require theservices of a GPU in or<strong>de</strong>r to accelerate part oftheir computations. To do so, the GPGPU capabilitiesshould be exposed to VMs so that they canmake use of the real GPU. However, although thereis currently some work on the virtualization of thegraphics application programming interfaces (APIs)of GPUs (e.g., [4]), those efforts are not directlyuseful to expose GPGPU features to virtualized environments.The main cause is that both uses ofGPUs are completely different and, therefore, advancesin one of them do not translate in progress in1 DISCA, Universitat Politècnica <strong>de</strong> València (UPV), e-mail:{jduato,fsilla@disca.upv.es}, apenya@gap.upv.es.2 DICC, Universitat Jaume I (UJI), e-mail:{jfernand,mayo,quintana}@icc.uji.es.the other. The reason for this is that current GPUslack a standard low-level interface —unlike other<strong>de</strong>vices such as storage and network controllers—and, therefore, their use for graphics purposes isapproached by using high-level standard interfacessuch as Direct3D [4] or OpenGL [5], while usingthem for GPGPU requires APIs like OpenCL [6] orNVIDIA CUDA [7], which significantly differ fromtheir graphics-processing oriented counterparts. Onthe other hand, the few efforts done up to now toexpose CUDA capabilities to VMs [8], [9], [10] (1)are incomplete prototypes, (2) make use of obsoleteversions of the GPGPU API, (3) are not general solutions,as they target a particular virtual machinemonitor (VMM), or (4) employ inefficient communicationprotocols between their middleware si<strong>de</strong>s.In this paper we move a step forward in the virtualizationof GPUs for their use as GPGPU acceleratorsby VMs. We propose using an open source, VMMin<strong>de</strong>pen<strong>de</strong>nt,and communication-efficient way of exposingGPGPU capabilities to VMs featuring a recentGPGPU API version. Our work addressesthe virtualization of the CUDA Runtime API, awi<strong>de</strong>ly used GPGPU API supporting the latestNVIDIA GPUs. The framework we employ, namedrCUDA [11], [12], was initially <strong>de</strong>signed to use TCPsockets to communicate a GPU-accelerated processrunning in a computer not having a GPU with aremote host providing GPGPU services, thus providingthe accelerated process with the illusion ofdirectly using a GPU. Note however that althoughthe primary goal of rCUDA was providing a way toreduce the number of GPU-based accelerators in acluster, in this paper we extend its applicability toalso expose CUDA capabilities to VMs running in aCUDA-enabled computer. More specifically, we explorethe benefits of using rCUDA in VMs, rangingfrom a single VM instance to multiple VMs concurrentlyrunning in the same server, equipped with asmall number of accelerators. To do this, we analyzethe execution of a set of CUDA SDK examples ona platform composed of 8 general-purpose cores andtwo NVIDIA cards providing a total of 4 GPUs. Theresults obtained with the Kernel-based Virtual Machine(KVM) and Oracle’s VirtualBox Open SourceEdition (VB-OSE) VMMs using rCUDA are additionallycompared with those of the native environment.Although our solution is also valid for theVMware Server environment, we cannot disclose theresults due to licensing policies.II. Background on CUDA VirtualizationIn addition to rCUDA, which will be <strong>de</strong>scribed inthe following section, there are other approaches that<strong>JP2011</strong>-341


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011pursue the virtualization of the CUDA Runtime APIfor VMs. All solutions feature a distributed middlewarecomprised of two parts: the front-end and theback-end. The former is installed on the VM, whilethe back-end counterpart, with direct access to theacceleration hardware, is run by the host operatingsystem (OS) — the one executing the VMM.vCUDA [10] implements an unspecified subset ofthe CUDA Runtime version 1.1. It employs XML-RPC for the application level communications, whichmakes the solution portable across different VMMsbut, as the experiments in [10] show, the time spentin the encoding/<strong>de</strong>coding steps of the communicationprotocol causes a consi<strong>de</strong>rable negative impacton the overall performance of the solution.On the other hand, GViM [9] uses Xen-specificmechanisms for the communication between bothmiddleware actors, including shared memory buffers,which enhance the communications between user andadministrative domains, at the expense of losingVMM in<strong>de</strong>pen<strong>de</strong>nce. This solution, based in CUDA1.1, does not seem to implement the whole API.Finally, gVirtuS [8] (version 01-beta1) is a toolwith a purpose similar to rCUDA. This version seemsto only cover a subset of the Runtime API v2.3 (e.g.:it lacks 20 out of the 37 functions of the memorymanagement module of this API).In this paper we propose using rCUDA, aproduction-ready framework to run CUDA applicationsfrom VMs, based in a recent CUDA API version(currently 3.1). This middleware makes use of acustomized communications protocol and is VMMin<strong>de</strong>pen<strong>de</strong>nt,thus addressing the main drawbacks ofprevious works.III. The rCUDA FrameworkrCUDA is inten<strong>de</strong>d to provi<strong>de</strong> access to GPUs installedin remote no<strong>de</strong>s. Hence, this framework offersHPC clusters a way of reducing the total number ofGPUs in the system or, alternatively, to significantlyaccelerate the computations of a traditional clusterby adding a reduced number of accelerators. Inother words, in the former case, by slightly increasingthe execution time of the applications that makeuse of GPUs to accelerate parts of their co<strong>de</strong>, consi<strong>de</strong>rablesavings can be achieved in energy, maintenance,space, and cooling. On the other hand, whenadding a few accelerators to a cluster, rCUDA bringsthe possibility of significantly reducing the executiontime of suitable applications with a small impact onthe system energy consumption.As in the case of the software presented in theprevious section, the rCUDA framework is split intotwo major software modules:• The client middleware consists of a collectionof wrappers which replace the NVIDIA CUDARuntime (provi<strong>de</strong>d as a shared library) in theclient computer (not having a GPU). Thesewrappers are in charge of forwarding the APIcalls from the applications requesting accelerationservices to the server middleware, and retrievingthe results back, providing applicationswith the illusion of direct access to a real GPU.• The server middleware runs as a service onthe computer owning the GPU. It receives, interprets,and executes the API calls from theclients, employing a different process to serveeach remote application over an in<strong>de</strong>pen<strong>de</strong>ntGPU context, thus attaining GPU multiplexing.Communication between rCUDA components isperformed employing a highly-tuned, TCP-basedapplication-level protocol.The current release of rCUDA (2.0) targets theLinux OS. It implements the CUDA Runtime APIversion 3.1, excluding OpenGL and Direct3D interoperability,as graphics-oriented capabilities are notof interest in this environment. One drawback ofrCUDA is that it lacks support for the C for CUDAextensions, as the CUDA Runtime library comprisessome hid<strong>de</strong>n and undocumented support functions,as reported by the vCUDA <strong>de</strong>velopers in [10] 1 .Although there are other GPGPU APIs such asthe CUDA Driver API or OpenCL, rCUDA focuseson the most wi<strong>de</strong>ly used: the CUDA Runtime, asat the moment applications using CUDA seem toachieve higher performance than when employingOpenCL [13]. These alternatives might be exploredin the future employing tools similar to rCUDA forthese APIs, such as VCL [14] for OpenCL.Note that the NVIDIA CUDA Runtime Libraryalso allows CUDA executions on computers with noCUDA-compatible <strong>de</strong>vices by means of the DeviceEmulation Mo<strong>de</strong>, as GPU kernels are executed bythe CPU emulating the many-core architecture ofthe GPU. However, the resulting overhead is oftenunbearable for complete executions (in<strong>de</strong>ed, this featureis inten<strong>de</strong>d for <strong>de</strong>bugging purposes instead of areplacement of a physical accelerator).Rea<strong>de</strong>rs can find additional <strong>de</strong>tails about therCUDA architecture in [11], and a more <strong>de</strong>tailed<strong>de</strong>scription of the implementation with a discussionon energy consumption implications in [12]. Further<strong>de</strong>tails are available on the Web (www.gap.upv.es/rCUDA, www.hpca.uji.es/rCUDA).IV. rCUDA on Virtual MachinesrCUDA was initially <strong>de</strong>signed to provi<strong>de</strong> access toGPGPU features to computers not owning a GPUby accessing remote computers equipped with thathardware, as explained in the previous section. However,we propose to additionally use this frameworkto access GPUs from VMs. In this case, the VMs areconsi<strong>de</strong>red no<strong>de</strong>s without a physical GPU, and thehost OS is that acting as a GPGPU server. Hence,the client middleware of rCUDA is installed on theguest OS (that executed by a VM), as a replacementof the NVIDIA Runtime library, while the rCUDAserver is executed on the host OS.1 gVirtuS software is supposed to support the undocumentedfunctions. However, when looking at the corresponding sourceco<strong>de</strong>, the following advise is found: “Routines not found in thecuda’s hea<strong>de</strong>r files. KEEP THEM WITH CARE”.<strong>JP2011</strong>-342


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 1.rCUDA architecture on a VMM environment.When used with VMs, the communication protocolin rCUDA will make use of the virtual network<strong>de</strong>vice to communicate the front-end and back-endmiddleware. Therefore, the network has to be configuredin a way that both the VM and the host OScan address IP packets to each other. Fig. 1 showsan rCUDA architecture diagram modified to reflectits usage in VM environments. We were able to successfullytest the current implementation of rCUDAin KVM, VB-OSE, and VMware Server virtualizationsolutions. However, we were unable to run itin a recent release of the Xen Hypervisor (3.4.3), aswe could not gain access to a recent NVIDIA GPUdriver that worked properly un<strong>de</strong>r the modified kernelfor the administrative domain, with the ultimatereason being that this driver is not <strong>de</strong>signed to supportthe Xen environment.With rCUDA, multiple VMs running in the samephysical computer can make concurrent use of allCUDA-compatible <strong>de</strong>vices installed on the computer(as long as there is enough memory on the <strong>de</strong>vices tobe allocated by the different applications). Furthermore,although not addressed in this paper, rCUDAalso allows the usage of a GPU located in a differentphysical computer.In the following section we provi<strong>de</strong> an in-<strong>de</strong>pthanalysis of the use of rCUDA to enable GPGPUcapabilities within VMs. We believe our proposalis the first work <strong>de</strong>scribing a VMM-in<strong>de</strong>pen<strong>de</strong>ntproduction-ready CUDA solution for VMs.V. Experimental EvaluationIn this section we conduct a collection of experimentsin or<strong>de</strong>r to evaluate the performance of therCUDA framework on a VMM environment. Thetarget system consists of two Quad-core Intel XeonE5410 processors running at 2.33 GHz with 8 GB ofmain memory. An OpenSuse Linux distribution withkernel version 2.6.31 is run at both host and guestsi<strong>de</strong>s. The GPGPU capabilities are provi<strong>de</strong>d by twoNVIDIA GeForce 9800 GX2 cards featuring a totalof 4 NVIDIA G92 GPUs; the driver version is 190.53.We selected two Open Source VMMs for theperformance analysis: KVM (userspace qemu-kvmv0.12.3) and VB-OSE 3.1.6, with their VMs configuredto make use of para-virtualized network <strong>de</strong>vices.In addition, for load isolation purposes, each VM wasconfigured to make use of only one processor core.All benchmarks employed in our evaluation arepart of the CUDA SDK. From the 67 benchmarksin the suite, we selected 10 representativeSDK benchmarks of varying computationFig. 2.Native vs. KVM and VB-OSE.loads and data sizes, which use different CU-DA features: alignedTypes (AT), asyncAPI (AA),bicubicTexture (BT), BlackScholes (BS), box-Filter (BF), clock (CLK), convolutionSeparable(CS), fastWalshTransform (FWT), image-Denoising (ID), and matrixMul (MM). A <strong>de</strong>scriptionof each benchmark can be found in the documentationof the SDK package [15]. The benchmarkswere executed with the <strong>de</strong>fault options, otherthan setting the target <strong>de</strong>vice. In addition, benchmarksrequiring OpenGL capabilities for their <strong>de</strong>faultexecutions (BT, BF, and ID) were executedwith the -qatest argument, in or<strong>de</strong>r to perform a“quick auto test”, which does not make use of thegraphics-oriented API. To make the original benchmarkco<strong>de</strong> compatible with rCUDA, which does notsupport the C for CUDA extensions, the pieces ofco<strong>de</strong> using these extensions were rewritten using theplain C API (only a 7% of the total effective sourcelines of co<strong>de</strong> required being modified).The execution times reported in the next experimentsare the minimum from 5 executions, in or<strong>de</strong>rto avoid eventual network and CPU noise. They reflectthe elapsed time experienced by the users, fromthe start of the execution of the application till theend of it. The experiments are presented in this sectionin two groups. First, those concerning one VMare presented. <strong>La</strong>ter, we introduce experiments involvingseveral VMs being concurrently executed.A. Single Virtual MachineWe first analyze the performance of the CUDASDK benchmarks running in a VM using rCUDA,and compare their execution times with those of anative environment —i.e., using the regular CUDARuntime library in a non-virtualized environment.The results of this experiment are reported in Fig. 2.It would also be interesting including data for a versionof the benchmarks that makes only use of theCPU. However, as it is difficult to find optimized algorithmsfor CPUs performing the same operationsas all of our benchmarks, and those inclu<strong>de</strong>d in theSDK package are often naive versions, we cannotpresent such a comparison. Nevertheless, it is notstrictly required for un<strong>de</strong>rstanding the experimentspresented and, additionally, the convenience of usingvirtualized remote GPUs instead of the local CPUwas previously discussed [11].<strong>JP2011</strong>-343


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Results show that, for the evaluated benchmarks,the combination of KVM + rCUDA performs muchbetter than VB-OSE + rCUDA. The reason for thesedifferences will probably lay on the way each VMMmanages the virtual I/O. However, as the focus ofthe paper is analyzing the feasibility of using GPUsin VMs and not the discussion of a performance comparisonbetween VMMs, we will not pursue furtherthe causes of this difference. Hereafter, for simplicityand brevity, the results for VB-OSE are not furtherdiscussed, as compared with those of KVM they reportsimilar behavior but at a higher scale.Figure 2 shows that the performance of KVM +rCUDA is close to that of the native executions.Therefore, even though the combination KVM +rCUDA pays the penalty for a non-optimized hostguestcommunication, using this general approachis feasible. Unfortunately, we cannot compare theoverhead of the rCUDA-based solution with that ofsolutions based in prior middleware such as GViMor vCUDA because (1) GViM and vCUDA softwareare not publicly available, (2) in their associated papers,CUDA 1.1 was used instead of the more recentversion rCUDA uses, and (3) both used the Xenvirtual platform 2 . On the other hand, we alreadymentioned that we could not get the public versionof gVirtuS working in our test-bed. For referencepurposes, executions up to 5.28 times slower usingvCUDA with respect to those on a native environmentcan be extracted from [10], up to 1.25 in thecase of GViM [9], and up to 7.12 and 2.98 for gVirtuS[8] when using TCP-based and VMM-<strong>de</strong>pen<strong>de</strong>ntcommunications, respectively. Nevertheless, as previouslystated, rCUDA aims at attaining a performancesomewhere between those prior prototypeswith the advantage of featuring VMM in<strong>de</strong>pen<strong>de</strong>nce.Fig. 3 specifies the time required by network transfers,thus illustrating that the overhead of KVM +rCUDA mostly originates in the network. Networktransfer times have been measured as the addition ofthe times spent in data sending in both middlewaresi<strong>de</strong>s of rCUDA. A conclusion from this experimentis that a shared-memory scheme for communicationsmay improve the performance at the expense of losingVMM in<strong>de</strong>pen<strong>de</strong>nce. However, losing VMM in<strong>de</strong>pen<strong>de</strong>ncewould lead to a significant reduction inthe flexibility provi<strong>de</strong>d by rCUDA, which is the mainbenefit of this package. Therefore, in the rest of thissection we will analyze the exact causes for the overheadintroduced by virtual network transfers in or<strong>de</strong>rto know if they can be improved.Fig. 4 relates the dataset size of each benchmarkwith the network transfer time. Note, however, thatas the AA benchmark performs asynchronous memorytransfers, which might be overlapped with CPUand GPU computations, the time spent in networkcommunications might not be proportional to theglobal overhead introduced by those; therefore, the2 NVIDIA GPU drivers supporting up to version 1.1 ofCUDA worked on the Xen dom0, but this is no longer thecase for more recent versions like those used by us.Execution time (s)Time (s)121086420Fig. 3.3.532.521.51NativerCUDA communicationsKVM + rCUDA computationAT AA BT BS BF CLK CS FWT ID MMSDK benchmarkBreakdown of KVM + rCUDA.BS48.3 MB/s107.7 MB/s0.5 FWTBenchmarkCSRegression all0CLK, MM, ID, BT, BF Regression CLK-BF0 50 100 150 200 250 300 350 400Data size (MB)Fig. 4. Dataset size and total network transfer time on KVM.data corresponding to this benchmark is not inclu<strong>de</strong>din the figure and skipped during the rest of this section.As shown in the figure, the time spent in networkcommunications seems to be proportional tothe data size of the problem, as other transfers relatedwith the application-level communication protocolbecome negligible for “large” datasets. Nevertheless,as the points for CLK, MM, ID, BT, and BFin Fig. 4 are so close to the axis origins that they cannotbe clearly distinguished, Fig. 5 provi<strong>de</strong>s a zoomof the plot area for those points. As can be seen, thepoints in that figure evi<strong>de</strong>nce a significantly lowernetwork throughput than AT, CS, FWT, or BS. Inor<strong>de</strong>r to analyze the reason for this lower throughput,we <strong>de</strong>termined the <strong>de</strong>gree of utilization of the bandwidthof the virtual network examining the averagetransfer rates of the memory transfer operations foreach of the benchmarks. Additionally, a simple pingpongtest revealed a peak transfer rate between KVMVMs and the host OS of 126 MB/s. The results ofthis analysis are shown in Table I, illustrating thatin some cases the experienced average transfer rate(TR) was much lower than this value.The bandwidth for the smallest data sizes shownin Table I may be far from the theoretical peak ofthe network due to the intrinsics of the TCP protocol.That is, the cause for these low transfer ratesmay be related with the size of the memory transferoperations and the configuration of the TCP transmissionwindow. Inspecting the source co<strong>de</strong> we <strong>de</strong>terminedthat data transfers are performed in chunksof sizes between 2 KB and 32 MB. Numbers in TableI reveal that the benchmarks that transfer datain chunks smaller than 1 MB yield specially low averagetransfer rates (below 50% of the peak). Toconfirm the relationship between the low bandwidthAT<strong>JP2011</strong>-344


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLE IAverage transfer rate (TR) obtained for each benchmarkAT BT BS BF CLK CS FWT ID MMData (MB) 413.26 4.25 76.29 5.00 2 · 10 −3 36.00 64.00 2.49 0.08Time (s) 3.53 0.08 0.88 0.12 4 · 10 −4 0.47 0.75 0.06 0.01TR (MB/s) 117.19 52.44 86.61 42.93 6.17 76.55 84.82 44.21 6.91Transfers 13 4 5 5 1 2 2 5 3Chunk 32 MB 1 MB 15 MB 1 MB 2 KB 18 MB 32 MB 512 KB 15-40 KBTime (s)0.120.10.080.060.04107.7 MB/sID48.3 MB/s0.02MMBenchmarkRegression allCLKRegression CLK-BF00 1 2 3 4 5Data size (MB)BTBFTime (ms)2015105MMPing-pong testMaximum TRObtained TTIDCLK00 0.2 0.4 0.6 0.8 1Data size (MB)BFBTFig. 5. Area closest to the coordinate origin in Fig. 4.and the intrinsics of TCP, we next compare the resultsof the ping-pong test for data payload sizes upto 1 MB with the average transfer rates obtainedin our executions. Fig. 6 shows that the transferrates obtained by the ping-pong test vary from 16to a maximum of 119 MB/s. However, the averagethroughputs for the benchmarks are still below thoseobtained with this simple test. Therefore, the reasonmay be that the TCP layer protocol is basedon a transmission window size which is progressively—but not immediately— adapted to the amount oftransferred data. To assess the impact of this phenomenonin our experiments, we performed a carefulanalysis of the time employed by each memory transferoperation. In Fig. 7 we show the transfer times for4 consecutive and i<strong>de</strong>ntical memory transfers of oneof the benchmarks. As expected, the figure revealsthat the transfer of the first large packet takes significantlylonger time than the following transfers of thesame size, which require times close to those of theping-pong test, as the TCP transfer window is progressivelybeing increased to reach the appropriatesize for that data payload. Therefore, the low averagetransfer rates shown in Table I are explained bythe transport layer protocol particularities regardinghow the window in the transmitter si<strong>de</strong> is managedby TCP. This window management also explains thenetwork overhead in Fig. 3.The network analysis presented above reveals that,in or<strong>de</strong>r to obtain faster network transmissions, onthe one hand memory transfer operations should involveas much data as possible and, on the otherhand, the initial TCP window size should be increased.One proposal for future work in rCUDAis to try to artificially open the transmission windowupon the TCP connection establishment. However,as the maximum effective transfer rate of the virtualnetwork is 126 MB/s, when compared to nativeFig. 6. Ping-pong test, peak transfer rate (TR) of the virtualnetwork, and minimum obtained transfer times (TT).Fig. 7.Time (µs)140001200010000800060004000200001 2 3 4Transfer numberID benchmarkPing-pongFour consecutive transfers in ID vs. ping-pong test.solutions, where memory transfers directly use thePCI Express (PCIe) bus (with an effective transferrate around 5.5 GB/s in our tests over a PCIe v2.0x16), the overhead when performing GPGPU over aVM using a virtual network will never be reducedbelow a minimum value. In this regard, the experimentsshow that <strong>de</strong>spite the increase of the throughputwith large data transfers from VMs, the overheadof transferring large amounts of data is higher thanthe benefits obtained with the higher throughput,and proportional to the dataset size. In general, thisoverhead could be reduced with improved support forthe virtual network <strong>de</strong>vice from VMM <strong>de</strong>velopers.B. Multiple Virtual MachinesTo measure the usability of a highly loa<strong>de</strong>d systemusing rCUDA, we performed some scalability testsrunning up to 8 VMs on the target platform, makinguse of the 4 GPUs of the computer via rCUDA. Theresults were compared with those corresponding toconcurrent executions in a native environment.Fig. 8 shows the results employing from one toeight KVM VMs. The GPUs used by each VM aredistributed in a round-robin fashion as the required<strong>JP2011</strong>-345


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 8.Fig. 9.Time (s)1816141210864201 2 3 4 5 6 7 8Number of VMsATAABTBSBFCLKCSFWTIDMMConcurrency tests on multiple KVM VMs and GPUs.Time (s)1412108642ATAABTBSBFCLKCSFWTIDMM01 2 3 4 5 6 7 8Number of concurrent instances of the benchmarkConcurrency tests on the native environment.number increases. Thus, as soon as 5 or more concurrentVMs are run, the GPUs become a sharedresource. The results show a smooth <strong>de</strong>gradation inperformance up to 4 VMs, as the different instancesare only competing for the network channel and thePCIe bus; from five to eight VMs, the overhead introducedis more evi<strong>de</strong>nt, as the GPUs also becomea shared resource. For instance, for the AT sample,the most time-consuming benchmark in the set, theoverhead when executed in four VMs is 14.7%, butit raises to 71.4% when the eight VMs are used.On the other hand, the native concurrent testsshown in Fig. 9 —where the different GPUs of thesystem are used following the same policy as in theprior case— present scalability results close to thoseobtained in the VM environment. For reference, theAT sample overhead when running 4 concurrent instancesis 8.9%, reaching 105.9% for 8 instances as,similarly to the VM environment, there is a competitionfor the PCIe bus up to 4 instances, while thereis an additional competition for the GPU resourcesstarting from 5 concurrent instances.Interestingly, in our case studies we noticed betterscalability in rCUDA than in the native environment.As CPU and GPU computation time, inaddition to that of the data transfers across the PCIebus, present no major differences in native and KVMtests (see Fig. 3), the difference in time between bothenvironments is mostly caused by network transfers.VI. ConclusionsrCUDA enables remote CUDA Runtime API calls,thus enabling an application making use of a CUDAcompatibleaccelerator to be run on a host withouta GPU. Thus, this framework can offer GPGPU accelerationto applications running either in a remotehost, or similarly in a VM, where no direct access tothe hardware of the computer is provi<strong>de</strong>d.In this paper we have reported a variety of experimentalperformance results based on a set of CUDASDK benchmarks, showing that the rCUDA frameworkcan <strong>de</strong>liver CUDA-based acceleration supportto multiple VMs running in the same physical serverequipped with several GPUs. The experiments reportedan acceptable overhead —if compared withnative executions— for most applications ready tobe run in a virtualized environment. Our tests revealeda good level of scalability, thus <strong>de</strong>monstratingthat this solution can be run in a productive systemwith concurrent VMs in execution. In summary, ourresults state that it is possible to provi<strong>de</strong> GPGPUcapabilities with reasonable overheads to processesrunning in a VM, while keeping VMM in<strong>de</strong>pen<strong>de</strong>nce.AcknowledgementsThe researchers at UPV were supported byPROMETEO from GVA (Generalitat Valenciana)un<strong>de</strong>r Grant PROMETEO/2008/060, while thoseat UJI were supported by the Spanish Ministryof Science and FEDER (contract no. TIN2008-06570-C04), and by the Fundación Caixa-Castelló/Bancaixa (contract no. P1-1B2009-35).References[1] A. Gaikwad and I. M. Toke, “GPU based sparse gridtechnique for solving multidimensional options pricingPDEs,” in Proceedings of the 2nd Workshop on HighPerformance Computational Finance, 2009.[2] Y. C. Luo and R. Duraiswami, “Canny edge <strong>de</strong>tection onNVIDIA CUDA,” in Computer Vision on GPU, 2008.[3] W. Huang, J. Liu, B. Abali, D. K. Panda, and Y. Muraoka,“A case for high performance computing withvirtual machines,” in ICS, 2006.[4] M. Dowty and J. Sugerman, “GPU virtualization onVMware’s hosted I/O architecture,” in First Workshopon I/O Virtualization, December 2008.[5] H. A. <strong>La</strong>gar-Cavilla, N. Tolia, M. Satyanarayanan, andE. <strong>de</strong> <strong>La</strong>ra, “VMM-in<strong>de</strong>pen<strong>de</strong>nt graphics acceleration,”in VEE, 2007, pp. 33–43.[6] OpenCL 1.0 Specification, Khronos OpenCL WG, 2009.[7] NVIDIA CUDA Programming Gui<strong>de</strong> Version 3.1, 2010.[8] G. Giunta, R. Montella, G. Agrillo, and G. Coviello, “AGPGPU transparent virtualization component for highperformance computing clouds,” in Euro-Par. 2010.[9] V. Gupta, A. Gavrilovska, K. Schwan, H. Kharche, N. Tolia,V. Talwar, and P. Ranganathan, “GViM: GPUacceleratedvirtual machines,” in 3rd Workshop onSystem-level Virtualization for High Performance Computing,NY, USA, 2009, pp. 17–24.[10] L. Shi, H. Chen, and J. Sun, “vCUDA: GPU acceleratedhigh performance computing in virtual machines,” inIPDPS, 2009.[11] J. Duato, F. D. Igual, R. Mayo, A. J. Peña, E. S.Quintana-Ortí, and F. Silla, “An efficient implementationof GPU virtualization in high performance clusters,” inEuro-Par 2009, Parallel Processing — Workshops, 2010.[12] J. Duato, A. J. Peña, F. Silla, R. Mayo, and E. S.Quintana-Ortí, “rCUDA: Reducing the number of GPUbasedaccelerators in high performance clusters,” inHPCS, June 2010, pp. 224–231.[13] K. Karimi, N. G. Dickson, and F. Hamze, “A PerformanceComparison of CUDA and OpenCL,” ArXive-prints, 2010, Online: http://arxiv.org/pdf/1005.2581v2.[14] A. Barak, T. Ben-Nun, E. Levy, and A. Shiloh, “A packagefor OpenCL based heterogeneous computing on clusterswith many GPU <strong>de</strong>vices,” in PPAAC, 2010.[15] NVIDIA, “NVIDIA CUDA SDK co<strong>de</strong> samples,”http://<strong>de</strong>veloper.download.nvidia.com/compute/cuda/3_1/sdk/gpucomputingsdk_3.1_linux.run, 2010.<strong>JP2011</strong>-346


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Métodos no lineales basados en el gradienteconjugado para GPUsH. Migallón, 1 V. Migallón 2 y J. Penadés 2Resumen— En este artículo se presentan algoritmos paralelospara resolver sistemas no lineales, diseñados para GPUs (GraphicsProccesing Unit), para lo cual se hecho uso <strong>de</strong> CUDA (ComputeUnified Device Architecture). Los algoritmos propuestos estánbasados tanto en la versión <strong>de</strong> Fletcher-Reeves <strong>de</strong>l método <strong>de</strong>l gradienteconjugado, como en precondicionadores polinomiales construidosmediante el método por bloques en dos etapas. Se analizandiversas estrategias para la paralelización <strong>de</strong> dichos algoritmos,así como diferentes formatos <strong>de</strong> almacenamiento/compresión <strong>de</strong> lasmatrices dispersas consi<strong>de</strong>radas en este trabajo. Expondremos resultadosnuméricos comparando la ejecución en plataformas paralelas<strong>de</strong> grano fino (GPU) con la ejecución en plataformas paralelasbasadas en hilos (multiprocesadores <strong>de</strong> memoria compartida o multicores).Palabras clave—GPGPU, librerías GPU, gradiente conjugado nolineal, precondicionadores paralelos, factorizaciones ILU, métodospor bloques en dos etapas.I. INTRODUCCIÓNSE consi<strong>de</strong>ra la resolución <strong>de</strong>l sistema no linealAx = Φ(x), (1)don<strong>de</strong> A ∈ R n×n es una matriz simétrica y <strong>de</strong>finida positiva,y Φ : R n → R n es una función no lineal con ciertaspropieda<strong>de</strong>s. Sea Ψ : R n → R una aplicación no lineal, ysea 〈x, y〉 = x T y el producto interno en R n . El problema<strong>de</strong> minimización consistente en encontrar x ∈ R n tal queJ(x) = min J(y), (2)y∈Rn don<strong>de</strong> J(x) = 1 2〈Ax, x〉 − Ψ(x), es equivalente a encontrarx ∈ R n tal que F (x) = Ax − Φ(x) = 0, don<strong>de</strong>Φ(x) = Ψ ′ (x).Un método efectivo para resolver el sistema (1), teniendoen cuenta la conexión con el problema <strong>de</strong> minimización(2), es la versión <strong>de</strong> Fletcher-Reeves [1] <strong>de</strong>l método <strong>de</strong>lgradiente conjugado no lineal (NLCG), que se <strong>de</strong>talla acontinuación:Algoritmo 1: (GC no lineal (Fletcher-Reeves))Dado un vector inicial x (0)r (0) = Φ(x (0) ) − Ax (0)p (0) = r (0)Para i = 0, 1, . . . , hasta convergenciaα i =→ (ver a continuación)x (i+1) = x (i) + α i p (i)r (i+1) = r (i) − Φ(x (i) ) + Φ(x (i+1) ) − α i Ap (i)Test <strong>de</strong> convergenciaβ i+1 = − 〈r(i+1) ,r (i+1) 〉〈r (i) ,r (i) 〉p (i+1) = r (i+1) − β i+1 p (i)1 Dpto. <strong>de</strong> Física y Arquitectura <strong>de</strong> Computadores, <strong>Universidad</strong>Miguel Hernán<strong>de</strong>z, e-mail: hmigallon@umh.es.2 Dpto. <strong>de</strong> Ciencia <strong>de</strong> la Computación e InteligenciaArtificial, <strong>Universidad</strong> <strong>de</strong> Alicante, e-mail:violeta,jpena<strong>de</strong>s@dccia.ua.es.En el Algoritmo 1 la elección <strong>de</strong> α i <strong>de</strong>be minimizar lafunción asociada J en la dirección p (i) . Esto es equivalentea resolver el problema unidimensional <strong>de</strong> punto cerodJ(x (i) +α ip (i) )dα i12= 0. De la <strong>de</strong>finición <strong>de</strong> J, se <strong>de</strong>duce queJ(x (i) + αp (i) ) =〈A(x (i) + α ip (i) ), x (i) + α ip (i)〉 − Ψ(x (i) + α ip (i) ).Por tanto, diferenciando respecto a α i se obtienedJ(x (i) + α ip (i) )dα i=α i〈Ap (i) , p (i)〉 〈− r (i) , p (i)〉 〈+ Φ(x (i) ) − Φ(x (i) + α ip (i) ), p (i)〉 ,don<strong>de</strong> r (i) = Φ(x (i) ) − Ax (i) es el residuo no lineal.Por otra parte, pue<strong>de</strong> verse que la segunda <strong>de</strong>rivada respectoa α i esd 2 J(x (i) + α ip (i) )dα 2 =i〈Ap (i) , p (i)〉 〈− Φ ′ (x (i) + α ip (i) )p (i) , p (i)〉 .Por lo tanto, si se usa el método <strong>de</strong> Newton para resolverel problema <strong>de</strong> punto cero para α i , se obtiene α (k+1)α (k)i− δ (k) , don<strong>de</strong> (siendo γ = (x (i) + α (k)i p (i) ))δ (k) =dJ(x(i) + α (k)i p (i) )/dα id 2 J(x (i) + α (k)i p (i) )/dα 2 i=i =〈α (k)i Ap (i) , p (i)〉 〈− r (i) , p (i)〉 +〈Φ(x (i) ) − Φ(γ), p (i)〉〈Ap (i) , p (i)〉 − 〈 Φ ′ (γ)p (i) , p (i)〉 .Hay que remarcar que para obtener δ (k) , los productosinternos 〈Ap (i) , p (i) 〉 y 〈r (i) , p (i) 〉 pue<strong>de</strong>n computarseúnicamente en la iteración inicial <strong>de</strong>l método <strong>de</strong> Newton.A<strong>de</strong>más Ap (i) ha sido calculado en la iteración correspondiente<strong>de</strong>l método <strong>de</strong>l gradiente conjugado.El objetivo <strong>de</strong>l precondicionamiento es mejorar elnúmero <strong>de</strong> condición (cond) <strong>de</strong> la matriz <strong>de</strong>l sistema aresolver. Supongamos que M es una matriz simétricay <strong>de</strong>finida positiva que aproxima a A, y fácilmente invertible.Entonces, po<strong>de</strong>mos resolver indirectamente elsistema Ax = Φ(x) resolviendo el sistema M −1 Ax =M −1 Φ(x). Si cond(M −1 A)


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011α i =→ ver algoritmo 1x (i+1) = x (i) + α i p (i)r (i+1) = r (i) − Φ(x (i) ) + Φ(x (i+1) ) − α i Ap (i)Resolver Ms (i+1) = r (i+1)Test <strong>de</strong> convergenciaβ i+1 = − 〈s(i+1) ,r (i+1) 〉〈s (i) ,r (i) 〉p (i+1) = r (i+1) − β i+1 p (i)Dado que el sistema auxiliar Ms = r ha <strong>de</strong> resolverseen cada iteración <strong>de</strong>l algoritmo, está solución ha<strong>de</strong> po<strong>de</strong>rse obtener rápidamente. A<strong>de</strong>más, para que elprecondicionador sea efectivo es necesario que M seauna buena aproximación <strong>de</strong> A. El precondicionamientomediante series truncadas [2] es una técnica común <strong>de</strong>precondicionamiento para resolver sistemas lineales, queconsiste en consi<strong>de</strong>rar una partición <strong>de</strong> la matriz A talque,A = P − Q (3)y realizar m iteraciones <strong>de</strong>l proceso iterativo <strong>de</strong>finidopor esta partición, buscando la solución <strong>de</strong> As = r, ytomando s (0) = 0. Es bien conocido que la solución <strong>de</strong>lsistema auxiliar Ms = r es s = (I + R + R 2 + . . . +R m−1 )P −1 r, don<strong>de</strong> R = P −1 Q y la matriz <strong>de</strong> precondicionamientoes M m = P (I + R + R 2 + . . . + R m−1 ) −1(ver [2]).Si a<strong>de</strong>más suponemos que A está dividida en p × pp∑bloques, con bloques diagonales <strong>de</strong> or<strong>de</strong>n n j , n j =j=1n, tal que el sistema (1) pue<strong>de</strong> escribirse como:⎡⎤ ⎡ ⎤ ⎡ ⎤A 11 A 12 · · · A 1p x 1 Φ 1 (x)A 21 A 22 · · · A 2px 2Φ ⎢⎥ ⎢⎥⎣. .. ⎦ ⎣. ⎦ = 2 (x)⎢⎥⎣. ⎦ , (4)A p1 A p2 · · · A pp x p Φ p(x)don<strong>de</strong> x y Φ(x) están particionados en función <strong>de</strong>ltamaño <strong>de</strong> los bloques <strong>de</strong> A. Si consi<strong>de</strong>ramos la partición(3) estando P compuesta por los bloques diagonales <strong>de</strong> Aen la ecuación (4), es <strong>de</strong>cirP = diag(A 11 , . . . , A pp ), (5)realizar m iteraciones <strong>de</strong>l proceso iterativo <strong>de</strong>finido por lapartición (3) para obtener una aproximación <strong>de</strong> As = r,correspon<strong>de</strong> a realizar m iteraciones <strong>de</strong>l método <strong>de</strong> Jacobipor bloques. Por lo tanto, en cada iteración l, l =1, 2, . . . , <strong>de</strong>l método <strong>de</strong> Jacobi por bloques, ha <strong>de</strong> resolversep sistemas lineales in<strong>de</strong>pendientes <strong>de</strong>l tipo,A jj s (l)j = (Qs (l−1) + r) j , 1 ≤ j ≤ p. (6)Por tanto, los sistemas lineales (6) pue<strong>de</strong>n ser resueltospor procesos distintos. Sin embargo, cuando el tamaño<strong>de</strong> los bloques diagonales A jj , 1 ≤ j ≤ p, es gran<strong>de</strong>, esaconsejable utilizar un proceso iterativo para obtener unaaproximación <strong>de</strong> las soluciones, utilizando por tanto elmétodo en dos etapas; ver por ejemplo [3]. Formalmente,consi<strong>de</strong>ramos las particionesA jj = B j − C j , 1 ≤ j ≤ p, (7)y en la l-ésima iteración se realizan, para cada j, 1 ≤j ≤ p, q(j) iteraciones <strong>de</strong>l proceso iterativo <strong>de</strong>finido porlas particiones (7) para obtener una aproximación <strong>de</strong> lasolución <strong>de</strong> (6). Por tanto, para resolver el sistema auxiliarMs = r <strong>de</strong>l algoritmo 2, se realizan m pasos <strong>de</strong>la iteración s (l) = T s (l−1) + W −1 r, l = 1, 2, . . . , m,tomando s (0) = 0, don<strong>de</strong>T = H + (I − H)P −1 Q, W = P (I − H) −1 , (8)estando P <strong>de</strong>finido en (5) y H =diag((B1 −1 C 1) q(1) , . . . , (Bp−1 C p ) q(p) ); ver por ejemplo[4]. El siguiente algoritmo muestra el método utilizadopara aproximar el sistema lineal As = r (ver [3]).Algoritmo 3: (Método paralelo por bloques en dosetapas)Dado ( un vector inicial ) s (0) =T(s (0)1 )T , (s (0)2 )T , . . . , (s (0)p ) T , y una secuencia<strong>de</strong> número <strong>de</strong> iteraciones internas q(j), 1 ≤ j ≤ pPara l = 1, 2, . . ., hasta convergenciaEn el proceso j, j = 1, 2, . . . , py (0)j = s (l)jPara k = 1 hasta q(j)B j y (k)j = C j y (k−1)j + (Qs (l−1) + r) j() Ts (l) = (y (q(1))1 ) T , (y (q(2))2 ) T , . . . , (y p(q(p)) ) THay que remarcar, que el vector obtenido tras m iteraciones<strong>de</strong>l algoritmo 3, siendo s (0) = 0, viene dado pors (m) = (I + T + T 2 + . . . + T m−1 )W −1 r don<strong>de</strong> T yW están <strong>de</strong>finidos en (8). Por tanto, el precondicionadorobtenido mediante el método por bloques en dos etapases M m = W (I +T +T 2 +. . .+T m−1 ) −1 . Para obtenerlas particiones internas, en el método NLPCG, se ha hechouso <strong>de</strong> factorizaciones incompletas LU, en [5] pue<strong>de</strong>verse una <strong>de</strong>scripción <strong>de</strong>tallada <strong>de</strong>l algoritmo NLPCG.II. PROGRAMACIÓN PARALELA CON CUDA<strong>La</strong> arquitectura <strong>de</strong> una GPU (Graphics ProcessingUnit), está formada por un conjunto <strong>de</strong> multiprocesadores<strong>de</strong>nominados “streaming multiprocessors (SM)”, cadauno <strong>de</strong> los cuales está compuesto por un conjunto <strong>de</strong>procesadores <strong>de</strong>nominados “streaming processors (SP)”.CUDA es el mo<strong>de</strong>lo <strong>de</strong> programación utilizado para explotarel paralelismo <strong>de</strong> las GPUs, el cual es un mo<strong>de</strong>loheterogéneo que hace uso tanto <strong>de</strong> la CPU como<strong>de</strong> la GPU. En el mo<strong>de</strong>lo <strong>de</strong> programación <strong>de</strong> CUDA(ver por ejemplo [6] y [7]), una aplicación consiste enun programa secuencial principal (o “host”) ejecutadoen la CPU, el cual pue<strong>de</strong> lanzar programas, conocidoscomo “kernels”, en el dispositivo paralelo, es <strong>de</strong>cir enla GPU. Pese a que la CPU sobre la que se ejecuta elprograma host pue<strong>de</strong> ser un multiprocesador <strong>de</strong> memoriacompartida, con capacidad para ejecutar programas paralelos,<strong>de</strong>sarrollados por ejemplo con OpenMP, sólo unprocesador (o “core”) pue<strong>de</strong> lanzar un kernel, es <strong>de</strong>cir lasllamadas a los kernels <strong>de</strong>ben serializarse. <strong>La</strong> ejecución<strong>de</strong> los kernels son <strong>de</strong> tipo SPMD (Single Program MultipleData), que, a<strong>de</strong>más, pue<strong>de</strong> utilizar un gran número<strong>de</strong> “threads” o hilos. Cada hilo <strong>de</strong> un kernel ejecuta elmismo programa secuencial, siendo el programador elque <strong>de</strong>be organizar los hilos <strong>de</strong> un kernel en bloques,formando estos bloques lo que se conoce como “grid”.Los hilos <strong>de</strong> un bloque pue<strong>de</strong>n cooperar entre ellos, sin-<strong>JP2011</strong>-348


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011cronizando su ejecución mediante barreras. <strong>La</strong>s memoriasdisponibles en una GPU son: la memoria global quees la <strong>de</strong> mayor latencia, la memoria <strong>de</strong> sólo lectura (“constant”),la memoria <strong>de</strong> “textura”, la memoria compartiday los registros. <strong>La</strong> memoria compartida lo es para unbloque, y los registros son propios <strong>de</strong> cada hilo. Aunque,tanto la memoria “constant” como la memoria “texture”disponen <strong>de</strong> caché, no han sido utilizadas por la naturaleza<strong>de</strong> nuestro problema.El hardware se ocupa <strong>de</strong> la organización, creación ymanejo <strong>de</strong> los hilos. Por ejemplo, la GPU GTX 280dispone <strong>de</strong> 30 multiprocesadores, pudiendo trabajar hastacon 30K hilos. Para manejar eficientemente esta cantidad<strong>de</strong> hilos, la GPU utiliza una arquitectura SIMT (SingleInstruction Multiple Thread), ver por ejemplo [6] y [8],en la cual los hilos <strong>de</strong> un bloque se ejecutan en grupos<strong>de</strong> 32 hilos, llamados “warps”. Un warp en un momentodado ejecuta una única instrucción en todos sus hilos. Noobstante, los hilos <strong>de</strong> un warp pue<strong>de</strong>n seguir su propiaejecución, es <strong>de</strong>cir, la ejecución en cada hilo pue<strong>de</strong> serdiferente, siendo mucho más eficiente que todos los hilosrealicen la misma ejecución.III. FORMATOS DE ALMACENAMIENTO DE MATRICESDISPERSASEl producto <strong>de</strong> una matriz dispersa por un vector(SpMV) es una <strong>de</strong> las operaciones básicas en los algoritmosvistos en la sección I. Para optimizar esta operaciónhemos consi<strong>de</strong>rado varios formatos <strong>de</strong> almacenamiento<strong>de</strong> matrices dispersas. En concreto, se ha usado el formatoCRS (Compressed Row Storage), el formato ELL-PACK [9] (o ITPACK), y el formato propuesto en [10]<strong>de</strong>nominado ELLPACK-R. Existen multitud <strong>de</strong> posiblesrepresentaciones <strong>de</strong> matrices dispersas, cada una con diferentesrequisitos <strong>de</strong> almacenamiento, diferentes características<strong>de</strong> computación y distintas formas <strong>de</strong> acce<strong>de</strong>ry manipular los elementos <strong>de</strong> la matriz. Hemos consi<strong>de</strong>radoúnicamente formatos <strong>de</strong> almacenamiento <strong>de</strong> matricesdispersas <strong>de</strong> uso común y que a<strong>de</strong>más presentan unbuen comportamiento al computar la operación SpMV enuna GPU.El formato CRS (o CSR), muy común y <strong>de</strong> propósitogeneral, no presupone nada respecto al patrón <strong>de</strong> dispersión<strong>de</strong> la matriz, y no almacena ningún elemento nonecesario. El formato CRS almacena en posiciones contiguas<strong>de</strong> memoria los elementos no nulos <strong>de</strong> la matriz.Este formato utiliza tres vectores, uno <strong>de</strong> “floats” y dos<strong>de</strong> enteros. El primero almacena los elementos no nulos<strong>de</strong> la matriz A agrupados por filas. En el primer vector <strong>de</strong>enteros se almacena la columna <strong>de</strong> los elementos no nulos.El otro vector <strong>de</strong> enteros almacena la posición en laque empieza cada fila en los otros dos vectores, por tantoel último elemento <strong>de</strong> este vector correspon<strong>de</strong> al número<strong>de</strong> elementos no nulos (NNZ) o a NNZ+1 si el primerelemento es 1 en lugar <strong>de</strong> 0.El formato ELLPACK [9] fue diseñado para resolversistemas lineales <strong>de</strong> gran tamaño en arquitecturas vectoriales.Hay que hacer notar que existen ciertas similitu<strong>de</strong>sentre una arquitectura vectorial y la arquitectura <strong>de</strong>una GPU. El formato ELLPACK, también <strong>de</strong>nominadoITPACK, usa dos vectores, el primero, <strong>de</strong> floats, almacenalos elementos no nulos <strong>de</strong> la matriz; y el segundo,<strong>de</strong> enteros, almacena el número <strong>de</strong> columna <strong>de</strong> cadauno <strong>de</strong> los elementos no nulos almacenados en el primervector. <strong>La</strong> dimensión <strong>de</strong> ambos vectores es, al menos,N ∗ MaxEntriesbyRows, don<strong>de</strong> N es el número <strong>de</strong>filas y MaxEntriesbyRows es el número máximo <strong>de</strong>elementos no nulos por fila en la matriz. Por tanto, eneste formato todas las filas se almacenan ocupando elmismo tamaño, aquellas filas con un número <strong>de</strong> elementosno nulos inferior a MaxEntriesbyRows, son rellenadascon ceros. Teniendo en cuenta esta estructura, elformato ELLPACK almacena en una estructura regular,similar a una matriz <strong>de</strong>nsa, una matriz dispersa. Esta estructuraregular, como se ha dicho anteriormente, es apropiadapara realizar operaciones con matrices dispersas enarquitecturas vectoriales. Sin embargo, si el porcentaje<strong>de</strong> elementos nulos es alto y el patrón <strong>de</strong> dispersión <strong>de</strong>la matriz es irregular, respecto al número <strong>de</strong> elementosno nulos por fila, el rendimiento <strong>de</strong>l formato ELLPACKdisminuye, a<strong>de</strong>más <strong>de</strong> aumentar el tamaño <strong>de</strong> memorianecesario para almacenar la matriz respecto a otros formatos.<strong>La</strong> variante <strong>de</strong>l formato ELLPACK, <strong>de</strong>nominadaELLPACK-R [10], fue diseñada con el objetivo <strong>de</strong> optimizarel producto <strong>de</strong> una matriz dispersa por un vectoren GPUs. El formato ELLPACK-R está formado porlos mismos dos vectores <strong>de</strong>l formato ELLPACK, más untercer vector <strong>de</strong> enteros <strong>de</strong> tamaño N, que almacena elnúmero <strong>de</strong> elementos no nulos <strong>de</strong> cada fila, <strong>de</strong>scartando,por tanto, los elementos nulos con los que se han rellenadolas filas con un número <strong>de</strong> elementos no nulos inferiora MaxEntriesbyRows. En este caso es necesarioque los elementos <strong>de</strong> cada fila se almacenen por or<strong>de</strong>ncreciente <strong>de</strong> columna. <strong>La</strong> ventajas que presenta el formatoELLPACK (ver [10]) para su uso en GPUs son: proporcionaun acceso coalescente a la memoria global, paraello es necesario que las filas estén or<strong>de</strong>nadas en or<strong>de</strong>ncreciente <strong>de</strong> número <strong>de</strong> columna; al igual que los otrosdos formatos vistos, permite una ejecución sin procesos<strong>de</strong> sincronización entre hilos; reduce los tiempos <strong>de</strong> esperaentre los hilos <strong>de</strong> un warp; a<strong>de</strong>más, la computaciónrealizada por los hilos <strong>de</strong> un warp es homogénea.IV. OPERACIONES BÁSICASSegún la <strong>de</strong>scripción <strong>de</strong>l algoritmo 1 y <strong>de</strong>l algoritmo 2,las operaciones básicas para implementar dichos métodosson:• El producto <strong>de</strong> una matriz dispersa por un vector(SpMV).• Operaciones vectoriales básicas (incluidas en el nivel1 <strong>de</strong> la librería BLAS [11]).• El producto interno.• <strong>La</strong> resolución <strong>de</strong> un sistema LU (método incluidoen SPARSKIT [12]), utilizado únicamente en elmétodo NLPCG.Esta sección está <strong>de</strong>dicada a <strong>de</strong>scribir las diferentes opcionespara realizar las operaciones básicas reseñadas yanalizarlas en el contexto <strong>de</strong> nuestro trabajo.<strong>JP2011</strong>-349


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011A. Producto matriz dispersa por vectorEl objetivo <strong>de</strong> utilizar diferentes formatos <strong>de</strong> almacenamiento<strong>de</strong> matrices dispersas, <strong>de</strong>scritos en lasección III, es optimizar el producto <strong>de</strong> una matriz dispersapor un vector. El código <strong>de</strong>l kernel que implementala operación SpMV usando el formato CRS no ha sidooptimizado. Para optimizar este código existen dos vías,la primera es utilizar un formato <strong>de</strong> almacenamiento queoptimice dicho cálculo, opción que sí será consi<strong>de</strong>rada; yla segunda vía consiste en modificar la estructura <strong>de</strong> hiloscon el objetivo <strong>de</strong> optimizar el acceso a la memoriaglobal <strong>de</strong> la GPU. Sin embargo, en este segundo caso,las optimizaciones que podrían aplicarse se centran enmatrices con un patrón <strong>de</strong> dispersión mayor al <strong>de</strong>l ejemploutilizado en nuestro trabajo (ver la sección V). Enel ejemplo utilizado en nuestro trabajo el número típico<strong>de</strong> elementos no nulos por fila es <strong>de</strong> 7, y, por ejemplo,las optimizaciones propuestas en [13] necesitan más <strong>de</strong>32 elementos no nulos por fila para ser aplicadas. Portanto, la vía utilizada para optimizar la operación SpMVserá la utilización <strong>de</strong> los formatos <strong>de</strong> almacenamiento <strong>de</strong>matrices dispersas ELLPACK y ELLPACK-R, las cualesmejoran el patrón <strong>de</strong> acceso a memoria respecto al formatoCRS.Por otra parte, se ha utilizado la librería CUSPARSE[14] para calcular la operación SpMV. <strong>La</strong> librería CUS-PARSE es una reciente librería para la ejecución en GPUs<strong>de</strong> operaciones entre elementos (matrices o vectores) dispersos,y entre elementos dispersos y elementos <strong>de</strong>nsos.Actualmente, sólo soporta el formato CRS en el producto<strong>de</strong> una matriz dispersa por un vector.B. Operaciones vectorialesLos operaciones vectoriales, que no implican un proceso<strong>de</strong> reducción, incluidas en los algoritmos 1 y 2, sonla copia <strong>de</strong> vectores, el producto <strong>de</strong> un escalar por unvector, la operación axpy (o similar) y el cálculo <strong>de</strong> lafunción no lineal propia <strong>de</strong>l sistema. <strong>La</strong> computación <strong>de</strong>estas operaciones en una GPU ya está optimizada por lapropia arquitectura <strong>de</strong> la GPU, no obstante intentamosoptimizarlas agrupando varias <strong>de</strong> ellas en un único kernel.Por otra parte, se ha utilizado CUBLAS [15], versión<strong>de</strong> la librería BLAS para su uso con CUDA. El uso <strong>de</strong>CUBLAS impi<strong>de</strong> la agrupación <strong>de</strong> varias operaciones enúnico kernel, que era la primera vía <strong>de</strong> optimización propuesta.C. Producto internoEl proceso <strong>de</strong> reducción que implica el producto internohace que éste sea una operación especial en CUDA.En la computación en GPUs es necesario mantenerocupados a todos los SM (streaming multiprocessors),a<strong>de</strong>más para trabajar con vectores <strong>de</strong> gran tamaño esnecesario usar muchos bloques <strong>de</strong> hilos. Para conseguirestos dos propósitos cada bloque realiza el proceso <strong>de</strong> reducción<strong>de</strong> una porción <strong>de</strong>l vector. Dado que CUDA noproporciona mecanismos globales <strong>de</strong> sincronización quepermitan comunicar resultados parciales entre bloques, secalculan VectorN vectores <strong>de</strong> ElementN elementos, tal ycomo se propone en la NVIDIA CUDA C SDK. El número<strong>de</strong> elementos (ElementN) <strong>de</strong> cada porción <strong>de</strong> vector <strong>de</strong>beser múltiplo <strong>de</strong>l tamaño <strong>de</strong> un warp, para mantener lasrestricciones <strong>de</strong> alineamiento <strong>de</strong> la memoria y el accesocoalescente. Un bloque calcula la reducción <strong>de</strong> una omás porciones <strong>de</strong>l vector. A<strong>de</strong>más, para evitar procesos<strong>de</strong> sincronización se trabaja con la memoria compartida,la cual actúa como un acumulador. El tamaño<strong>de</strong> esta memoria compartida (ACCUM N) <strong>de</strong>ber ser potencia<strong>de</strong> dos y si es posible múltiplo <strong>de</strong>l tamaño <strong>de</strong> unwarp. Por tanto, cada hilo calcula un elemento <strong>de</strong>l acumuladortrabajando con elementos <strong>de</strong>l vector separadosen ACCUM N elementos. El kernel finaliza realizando unproceso <strong>de</strong> reducción tipo árbol <strong>de</strong> los elementos almacenadosen el acumulador y don<strong>de</strong> sí es necesario realizarprocesos <strong>de</strong> sincronización entre hilos. Hay que remarcarque la CPU <strong>de</strong>be finalizar la operación trabajando con losresultados parciales obtenidos, lógicamente el número <strong>de</strong>resultados parciales obtenidos es igual al número <strong>de</strong> porciones<strong>de</strong> vector (VectorN) con las que se ha trabajado.En nuestros algoritmos hemos agrupado varios productosinternos en único kernel.Por otra parte, la librería CUBLAS proporcionatambién la función que permite el cálculo <strong>de</strong>l productointerno, y teniendo en cuenta que hemos trabajado conla versión optimizada <strong>de</strong> CUBLAS incluida en el CUDAToolkit 3.2 RC, no se han consi<strong>de</strong>rado otras optimizaciones.D. Solucionador LUEn el proceso para resolver un sistema LU cada elementocomputado <strong>de</strong> la solución es utilizado para elcálculo <strong>de</strong>l siguiente elemento. Por tanto este proceso nodispone <strong>de</strong> paralelismo inherente <strong>de</strong> grano fino. Hemos<strong>de</strong>sarrollado diferentes algoritmos con diversas estrategiaspara resolver el sistema LU en la GPU, pero ninguna<strong>de</strong> ellas ha obtenido buenos resultados. Por lo tanto, lamejor opción ha sido resolver el sistema LU haciendouso <strong>de</strong> la arquitectura multicore <strong>de</strong> la CPU, lo cual no hasido <strong>de</strong>l todo efectivo al verse penalizado el algoritmo porel aumento <strong>de</strong> comunicaciones entre la CPU y la GPU.En la sección V presentaremos resultados haciendo uso<strong>de</strong> CUDA y <strong>de</strong> OpenMP conjuntamente. En este ámbitohay que remarcar que en el método NLCG, las comunicacionesentre GPU y CPU se reducen a algunos escalaresy los vectores necesarios para completar los procesos <strong>de</strong>reducción.V. RESULTADOS NUMÉRICOSPara analizar el comportamiento <strong>de</strong> los métodos propuestos,NLCG y NLPCG, se ha utilizado el multicoreIntel Core 2 Quad Q6600, 2.4 GHz, con 4 GB <strong>de</strong> RAMy 8 MB memoria caché L2, <strong>de</strong>nominado SULLI, con sistemaoperativo Ubuntu 9.04 (Jaunty Jackalope) para sistemas<strong>de</strong> 64 bits. <strong>La</strong> GPU disponible en SULLI es unaNVIDIA GeForce GTX 280. Los códigos <strong>de</strong> CUDA hansido compilados con el compilador <strong>de</strong> NVIDIA (nvcc)proporcionado por el CUDA Toolkit 3.2 RC.El ejemplo utilizado en nuestros experimentos es unaecuación en <strong>de</strong>rivadas parciales, no lineal y elíptica,conocida como el problema <strong>de</strong> Bratu. Este problematridimensional viene dado por∇ 2 u − λe u = 0, (9)<strong>JP2011</strong>-350


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 1. Speed-up <strong>de</strong>l método NLCG.Fig. 2. Método NLCG vs formato <strong>de</strong> almacenamiento.don<strong>de</strong> u es la temperatura y λ es una constante conocidacomo el parámetro <strong>de</strong> Frank-Kamenetskii; ver por ejemplo[16]. Hay dos posibles soluciones para este problemadado un valor <strong>de</strong> λ. Una <strong>de</strong> las soluciones, sencilla <strong>de</strong>obtener, es cercana a u = 0. Para converger a la otrasolución es necesario partir <strong>de</strong> un vector inicial cercanoa dicha solución. En nuestro mo<strong>de</strong>lo se consi<strong>de</strong>ra un dominiocúbico 3D <strong>de</strong> longitud unidad y λ = 6. Para resolverla ecuación (9) usando el método <strong>de</strong> diferenciasfinitas, consi<strong>de</strong>ramos un mallado <strong>de</strong>l dominio formadopor d 3 nodos. <strong>La</strong> discretización da lugar a un sistema nolineal <strong>de</strong> la forma Ax = Φ(x), don<strong>de</strong> Φ : R n → R n esuna aplicación diagonal y no lineal, en la cual la componentei-ésima Φ i <strong>de</strong> Φ <strong>de</strong>pen<strong>de</strong> únicamente <strong>de</strong> la componentei-ésima <strong>de</strong> x. <strong>La</strong> matriz A es una matriz dispersa<strong>de</strong> or<strong>de</strong>n n = d 3 , siendo el número típico <strong>de</strong> elementosno nulos por fila <strong>de</strong> siete, con menos elementos no nulosen aquellos puntos que correspon<strong>de</strong>n a la frontera <strong>de</strong>ldominio físico.El análisis que presentamos se basa en la comparación<strong>de</strong> los tiempos <strong>de</strong> ejecución utilizando como plataforma<strong>de</strong> computación la GPU GeForce GTX 280, con los tiempos<strong>de</strong> ejecución en el multicore SULLI. En primer lugarpresentamos resultados para resolver sistemas <strong>de</strong> variostamaños usando el método NLCG. En la figura 1 semuestra el speed-up utilizando, por un lado OpenMP condiferente número <strong>de</strong> cores, y por otro la GPU GeForceGTX 280. Lógicamente la GPU es controlada por uno <strong>de</strong>los cores <strong>de</strong> SULLI. En esta figura po<strong>de</strong>mos observar quese obtiene un buen speed-up usando los cores disponibles<strong>de</strong> SULLI, pero que dicho speed-up no es comparable alobtenido con la GPU, en la cual el valor es superior a 25.Este resultado confirma la expectativa <strong>de</strong> una muy buenainteracción entre el algoritmo NLCG y la GPU.En la figura 2 se pue<strong>de</strong> ver el comportamiento <strong>de</strong> los diferentesformatos <strong>de</strong> almacenamiento <strong>de</strong> matrices dispersas<strong>de</strong>scritos en la sección III. Hay que tener en cuenta,que el formato utilizado modifica el kernel que calcula laoperación SpMV. Los mejores resultados se obtienen utilizandoel formato ELLPACK-R, ya que este algoritmono incluye instrucciones <strong>de</strong> control <strong>de</strong> flujo que provoquenla serialización <strong>de</strong> la ejecución <strong>de</strong> los diferentes hilos<strong>de</strong> un warp y, a<strong>de</strong>más, permite el acceso coalescentea los elementos <strong>de</strong> la matriz. No obstante, hay que remarcarque el formato ELLPACK-R es el que más memoriarequiere <strong>de</strong> los formatos vistos, <strong>de</strong>bido al uso <strong>de</strong>l tercerFig. 3. Uso <strong>de</strong> CUBLAS y/o CUSPARSE en el método NLCG.vector para almacenar el número <strong>de</strong> elementos no nulos<strong>de</strong> cada fila, a<strong>de</strong>más <strong>de</strong>l rellenado <strong>de</strong> algunas filascon ceros. Hemos analizado el comportamiento <strong>de</strong>l algoritmoNLCG en función tanto <strong>de</strong>l número <strong>de</strong> hilos porbloque, como <strong>de</strong>l tamaño <strong>de</strong>l acumulador implementadoen la memoria compartida para calcular el producto interno.<strong>La</strong> figura 2 presenta resultados utilizando los valoresóptimos para estos dos parámetros, es <strong>de</strong>cir 256 hilospor bloque y un tamaño <strong>de</strong> ACCUM N igual a 128.Por último, respecto al método NLCG, en la figura 3se muestran resultados haciendo uso <strong>de</strong> las libreríasCUBLAS y CUSPARSE, librerías incluidas en el CUDAToolkit 3.2 RC. En dicha figura se analiza el uso <strong>de</strong>CUBLAS y <strong>de</strong> CUSPARSE por separado y también eluso <strong>de</strong> ambas librerías conjuntamente. En primer lugar,po<strong>de</strong>mos observar que el uso <strong>de</strong> CUBLAS presentapeores resultados que si se utiliza únicamente el API <strong>de</strong>CUDA. Esto es <strong>de</strong>bido a las optimizaciones realizadasagrupando varias operaciones en un único kernel, procesoque no pue<strong>de</strong> llevarse a cabo si se usa CUBLAS. Al contrario,el uso <strong>de</strong> CUSPARSE obtiene una pequeña mejora.Hay que remarcar que el uso conjunto <strong>de</strong> CUBLAS yCUSPARSE obtiene resultados aceptables con la ventajaque escon<strong>de</strong> al usuario la elección <strong>de</strong> parámetros talescomo el número <strong>de</strong> hilos por bloque y el tamaño <strong>de</strong>l acumuladorpara el cálculo <strong>de</strong> operaciones <strong>de</strong> reducción.En [5] se <strong>de</strong>talla el comportamiento <strong>de</strong>l algoritmoNLPCG en una plataforma multicore, todos los experimentosrealizados haciendo uso <strong>de</strong> la GPU muestran queese comportamiento no difiere al cambiar la plataforma<strong>de</strong> computación a una GPU. En resumen, el valor óptimo<strong>de</strong>l número <strong>de</strong> iteraciones internas y el valor óptimo <strong>de</strong>lnúmero <strong>de</strong> iteraciones externas es un valor pequeño. Respectoal nivel <strong>de</strong> llenado <strong>de</strong> la factorización ILU, se con-<strong>JP2011</strong>-351


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 4. Método NLPCG, m = 1, q = 1 y n = 884736.nuestros algoritmos, con el objetivo <strong>de</strong> optimizarlas y <strong>de</strong>experimentar algunas librerías disponibles. Hemos podidoconcluir que librerías como CUBLAS y CUSPARSEpue<strong>de</strong>n ofrecer un buen rendimiento. Respecto al formato<strong>de</strong> almacenamiento <strong>de</strong> matrices dispersas se concluye que<strong>de</strong>be ser seleccionado en función <strong>de</strong> las características <strong>de</strong>la plataforma paralela, siendo ELLPACK-R el formatomás eficiente para la ejecución en una GPU. Por último,se han mostrado las diferencias <strong>de</strong> adaptación <strong>de</strong> ambosmétodos a las dos arquitecturas paralelas utilizadas, obteniendoen ambos casos mejores resultados trabajando conla GPU que trabajando con el multicore, y a<strong>de</strong>más en estecaso el método NLCG explota mejor el paralelismo, obteniendomejores resultados que el método NLPCG.AGRADECIMIENTOSEl presente trabajo ha sido financiado por el Ministerio<strong>de</strong> Ciencia e Innovación mediante el proyecto TIN2008-06570-C04-04.Fig. 5. Comparación <strong>de</strong> los métodos NLCG y NLPCG en CPU y GPU,or<strong>de</strong>n <strong>de</strong>l sistema n = 373248.cluye que el valor óptimo es 0 o 1. Trabajando con dichosvalores óptimos, en la figura 4 presentamos resultados <strong>de</strong>lmétodo NLPCG haciendo uso <strong>de</strong> ambas plataformas <strong>de</strong>computación conjuntamente. En dicha figura po<strong>de</strong>mosobservar que el algoritmo NLPCG no se adapta bien alparalelismo ofrecido por la GPU, y que el uso <strong>de</strong> ambasplataformas tampoco obtiene buenos resultados al versepenalizado, como se ha comentado anteriormente, porel incremento <strong>de</strong> las comunicaciones entre GPU y CPU.Respecto al resto <strong>de</strong> parámetros vistos en el algoritmoNLCG, po<strong>de</strong>mos exten<strong>de</strong>r las conclusiones obtenidas endicho método al método NLPCG.Por último, si analizamos la figura 5 <strong>de</strong>ducimos queel speed-up obtenido usando la GPU siempre es mayorque usando los cuatro cores disponibles en SULLI. Deeste modo po<strong>de</strong>mos concluir que utilizando una GPU elmétodo NLCG ofrece mejores prestaciones, pero no asíusando un multicore, en cuya caso las mejores prestacioneslas ofrece el método NLPCG.VI. CONCLUSIONESHaciendo uso <strong>de</strong>l mo<strong>de</strong>lo <strong>de</strong> computación GPGPU(General-purpose computing on graphics processingunits) hemos <strong>de</strong>sarrollado la versión <strong>de</strong> Fletcher-Reeves<strong>de</strong>l método <strong>de</strong>l gradiente conjugado no lineal, y hemosaplicado, a dicho método, un precondicionador <strong>de</strong> tipopolinomial basado en los métodos en dos etapas. Sehan comparado los métodos <strong>de</strong>sarrollados con los mismosmétodos <strong>de</strong>sarrollados para OpenMP, y en el caso<strong>de</strong>l método precondicionado se ha utilizado un mo<strong>de</strong>lo<strong>de</strong> programación mixto para explotar el paralelismo ofrecidopor la GPU y el paralelismo ofrecido por el multicore.Hemos i<strong>de</strong>ntificado las operaciones básicas <strong>de</strong>REFERENCIAS[1] R. Fletcher y C. Reeves, “Function minimization by conjugategradients,” The Computer Journal, vol. 7, pp. 149–154, 1964.[2] L. Adams, “M-step preconditioned conjugate gradient methods,”SIAM Journal on Scientific and Statistical Computing, vol. 6, pp.452–462, 1985.[3] R. Bru, V. Migallón, J. Penadés, y D.B. Szyld, “Parallel, synchronousand asynchronous two-stage multisplitting methods,”Electronic Transactions on Numerical Analysis, vol. 3, pp. 24–38,1995.[4] V. Migallón y J. Penadés, “Convergence of two-stage iterativemethods for hermitian positive <strong>de</strong>finite matrices,” Applied MathematicsLetters, vol. 10, no. 3, pp. 79–83, 1997.[5] H. Migallón, V. Migallón, y J. Penadés, “Parallel nonlinear conjugategradient algorithms on multicore architectures,” in Proceedingsof the International Conference on Computational andMathematical Methods in Science and Engineering, pp. 689–700.2009.[6] J. Nickolls, I. Buck, M. Garland, y K. Skadron, “Scalable parallelprogramming with CUDA,” Queue, vol. 6, no. 2, pp. 40–53, 2008.[7] NVIDIA Corporation, “NVIDIA CUDA C programming gui<strong>de</strong>,”Version 3.2, http://<strong>de</strong>veloper.download.nvidia.com/compute/cuda/3_2/toolkit/docs/CUDA_C_Programming_Gui<strong>de</strong>.pdf, 2010.[8] E. Lindholm, J. Nickolls, S. Oberman, y J. Montrym, “NVIDIATesla: A unified graphics and computing architecture,” IEEE Micro,vol. 28, no. 2, pp. 39–55, 2008.[9] D.R. Kincaid y D.M. Young, “A brief review of the ITPACKproject,” Journal of Computational and Applied Mathematics,vol. 24, no. 1–2, pp. 121–127, 1988.[10] F. Vázquez, J.J. Fernán<strong>de</strong>z, y E.M. Garzón, “A new approachfor sparse matrix vector product on NVIDIA GPUs,” Concurrencyand Computation: Practice and experience, 2010, DOI:10.1002/cpe.1658.[11] C.L. <strong>La</strong>wson, R.J. Hanson, D. Kincaid, y F.T. Krogh, “Basic linearalgebra subprograms for FORTRAN usage,” ACM Transactionson Mathematical Software, vol. 5, pp. 308–323, 1979.[12] Y. Saad, “SPARSKIT: A basic tool kit for sparse matrix computation,”http://www-users.cs.umn.edu/ ∼ saad/software/SPARSKIT/sparskit.html.[13] M. Manikandan y R. Bordawekar, “Optimizing sparse matrixvectormultiplication on GPUs,” Tech. Rep. RC24704, IBM,2008.[14] NVIDIA Corporation, “CUDA CUSPARSE Library,” Tech.Rep. PG-05329-032 V01, 2010, http://<strong>de</strong>veloper.download.nvidia.com/compute/cuda/3_2/toolkit/docs/CUSPARSE_Library.pdf.[15] NVIDIA Corporation, “CUDA CUBLAS Library,” Tech.Rep. PG-05326-032 V01, 2010, http://<strong>de</strong>veloper.download.nvidia.com/compute/cuda/3_2/toolkit/docs/CUBLAS_Library.pdf.[16] B.M. Averick, R.G. Carter, J.J. More, y G. Xue, “The MINPACK-2 test problem collection,” Tech. Rep. MCS-P153-0692, Mathematicsand Computer Science Division, Argonne.<strong>JP2011</strong>-352


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Búsquedas por Similitud en Espacios Métricossobre Plataformas Basadas en GPUsRoberto Uribe-Pare<strong>de</strong>s 1 , Pedro Valero-<strong>La</strong>ra 2 ,Enrique Árias3 , José L. Sánchez 4 , Diego Cazorla 5Resumen— <strong>La</strong> búsqueda por similitud en espaciosmétricos resulta un problema <strong>de</strong> gran interés en laactualidad. <strong>La</strong> estructura <strong>de</strong> datos métrica Spaghettispermite in<strong>de</strong>xar y realizar búsquedas eficientes sobreun espacio métrico. Sin embargo, para aplicacionesreales don<strong>de</strong> se requiere procesamiento masivo<strong>de</strong> datos, los tiempos <strong>de</strong> resolución <strong>de</strong> una consultaresultan ser elevados. En estos casos, es necesarioaplicar mecanismos que permitan reducir consi<strong>de</strong>rablementelos tiempos <strong>de</strong> búsqueda. En este sentido,la paralelización <strong>de</strong> estructuras métricas es un campointeresante <strong>de</strong> investigación. <strong>La</strong> reciente aparición <strong>de</strong>plataformas computacionales que incluyen GPU s <strong>de</strong>proposito general (unida<strong>de</strong>s <strong>de</strong> procesamiento gráfico)ofrecen gran<strong>de</strong>s capacida<strong>de</strong>s <strong>de</strong> procesamiento paraleloa un bajo costo. En este artículo se presenta unaversión <strong>de</strong> la estructura métrica Spaghettis basada enGPU. En una primera etapa, se adapta la estructuraa una plataforma basada en GPU. Posteriormente seanaliza el rendimiento compararando la versión secuencialcontra la implementación basada en GPU,mostrando mejoras significativas en términos <strong>de</strong> reducción<strong>de</strong>l tiempo <strong>de</strong> respuesta, obteniendo valores<strong>de</strong> speed-up cercanos a 10. Por otra parte, también semuestra la ganancia obtenida en función <strong>de</strong>l consumo<strong>de</strong> energía, reduciendo este valor en un 80, 14%.Palabras clave— Bases <strong>de</strong> Datos, búsqueda por similitud,espacios métricos, estructuras <strong>de</strong> datos, procesamientoparalelo, GPU, CUDA.I. IntroducciónLA búsqueda <strong>de</strong> objetos similares sobre un granconjunto <strong>de</strong> datos se ha convertido en un problema<strong>de</strong> gran interés. Por ejemplo, una consultatípica para estas aplicaciones es la búsqueda porrango la cual consiste en obtener todos los objetosque están a una <strong>de</strong>terminada distancia <strong>de</strong>l objetoconsultado. A partir <strong>de</strong> esta operación se pue<strong>de</strong>construir otra, como los vecinos más cercanos. <strong>La</strong>aplicación <strong>de</strong> estas técnicas pue<strong>de</strong>n ser encontradas,en reconocimiento <strong>de</strong> voz e imagen, en problemas<strong>de</strong> minería <strong>de</strong> datos, <strong>de</strong>tección <strong>de</strong> plagios y muchasotras.1 Departamento <strong>de</strong> Ingeniería En Computación, <strong>Universidad</strong><strong>de</strong> Magallanes, UMAG, Punta Arenas, Chile. e-mail:roberto.uribepare<strong>de</strong>s@gmail.com.2 Centro <strong>de</strong> Investigaciones Energéticas, Medioambientalesy Tecnológicas, Madrid, España. e-mail:pedro.valero@ciemat.es.3 Departamento <strong>de</strong> Sistemas Informáticos, <strong>Universidad</strong><strong>de</strong> Castilla <strong>La</strong> Mancha, Albacete, España. e-mail:enrique.arias@uclm.es4 Departamento <strong>de</strong> Sistemas Informáticos, <strong>Universidad</strong><strong>de</strong> Castilla <strong>La</strong> Mancha, Albacete, España. e-mail:jose.sgarcia@uclm.es5 Departamento <strong>de</strong> Sistemas Informáticos, <strong>Universidad</strong><strong>de</strong> Castilla <strong>La</strong> Mancha, Albacete, España. e-mail:diego.cazorla@uclm.esA. Búsqueda por Similitud en Espacios Métricos<strong>La</strong> similitud se mo<strong>de</strong>liza en muchos casos interesantesa través <strong>de</strong> un espacio métrico, y la búsqueda<strong>de</strong> objetos más similares a través <strong>de</strong> una búsquedapor rango o <strong>de</strong> vecinos más cercanos. Un espaciométrico es un conjunto X con una función <strong>de</strong> distanciad : X 2 → R, tal que ∀x, y, z ∈ X, se <strong>de</strong>becumplir las propieda<strong>de</strong>s <strong>de</strong>: positividad (d(x, y) ≥0 and d(x, y) = 0 ssi x = y), simetría (d(x, y) =d(y, x)) y <strong>de</strong>sigualdad triangular (d(x, y) + d(y, z) ≥(d(x, z)).Sobre un espacio métrico (X,d), un conjunto <strong>de</strong>datos finito Y ⊆ X, se pue<strong>de</strong>n realizar una serie<strong>de</strong> consultas. <strong>La</strong> consulta básica es la consulta porrango. Sea una consulta x ∈ X, y un rango r ∈ R.<strong>La</strong> consulta <strong>de</strong> rango alre<strong>de</strong>dor <strong>de</strong> x con rango r esel conjunto <strong>de</strong> puntos y ∈ Y, tal que d(x, y) ≤ r.Un segundo tipo <strong>de</strong> consulta, que pue<strong>de</strong> construirseusando la consulta por rango es, los k vecinos máscercanos. Sea una consulta x ∈ X y un entero k.Los k vecinos más cercanos a x son un subconjuntoA <strong>de</strong> objetos <strong>de</strong> Y, don<strong>de</strong> la |A| = k y no existe unobjeto y ∈ A tal que d(y,x) sea menor a la distancia<strong>de</strong> algún objeto <strong>de</strong> A a x.El objetivo <strong>de</strong> los algoritmos <strong>de</strong> búsqueda es minimizarla cantidad <strong>de</strong> evaluaciones <strong>de</strong> distancia realizadaspara resolver la consulta. Los métodos parabuscar en espacios métricos se basan principalmenteen dividir el espacio empleando la distancia a unoo más objetos seleccionados. El no trabajar con lascaracterísticas particulares <strong>de</strong> cada aplicación tienela ventaja <strong>de</strong> ser más general, pues los algoritmosfuncionan con cualquier tipo <strong>de</strong> objeto [1].Existen distintas estructuras para buscar en espaciosmétricos, las cuales pue<strong>de</strong>n ocupar funcionesdiscretas o continuas <strong>de</strong> distancia.Algunos son GNAT, MTree, SAT, Slim-Tree, EG-NAT y muchos otros [1].Algunas <strong>de</strong> las estructuras basan la búsqueda enpivotes y otras en clustering. En el primer caso seseleccionan pivotes <strong>de</strong>l conjunto <strong>de</strong> datos y se precalculanlas distancias entre los elementos y los pivotes.Cuando se realiza una consulta, se calcula la distancia<strong>de</strong> la consulta a los pivotes y se usa la <strong>de</strong>sigualdadtriangular para <strong>de</strong>scartar candidatos.Los algoritmos basados en clustering divi<strong>de</strong>n el espacioen áreas, don<strong>de</strong> cada área tiene un centro. Sealmacena alguna información sobre el área que permita<strong>de</strong>scartar toda el área mediante sólo compararla consulta con su centro. Los algoritmos <strong>de</strong> clusteringson los mejores para espacios <strong>de</strong> alta dimensión,que es el problema más difícil en la práctica.<strong>JP2011</strong>-353


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Existen dos criterios para <strong>de</strong>limitar las áreas enlas estructuras basadas en clustering, hiperplanos yradio cobertor (covering radius). El primero divi<strong>de</strong>el espacio en particiones <strong>de</strong> Voronoi y <strong>de</strong>termina elhiperplano al cual pertenece la consulta según a quécentro correspon<strong>de</strong>. El criterio <strong>de</strong> radio cobertor divi<strong>de</strong>el espacio en esferas que pue<strong>de</strong>n intersectarse yuna consulta pue<strong>de</strong> pertenecer a más <strong>de</strong> una esfera.Un diagrama <strong>de</strong> Voronoi está <strong>de</strong>finido como lasubdivisión <strong>de</strong>l plano en n áreas, una por cada centroc i <strong>de</strong>l conjunto {c 1 , c 2 , . . . , c n } (centros), tal queq ∈ al área c i sí y sólo sí la distancia euclidianad(q, c i ) < d(q, c j ) para cada c j , con j ≠ i.En los métodos basados en pivotes, se seleccionaun conjunto <strong>de</strong> pivotes y se precalculan las distanciasentre los pivotes y todos los elementos <strong>de</strong> la base<strong>de</strong> datos. Los pivotes sirven para filtrar objetos enuna consulta utilizando la <strong>de</strong>sigualdad triangular, sinmedir realmente la distancia entre el objeto consultay los objetos <strong>de</strong>scartados.• Sea {p 1 , p 2 , ..., p k } ∈ X un conjunto <strong>de</strong> pivotes.Para cada elemento x <strong>de</strong> la base <strong>de</strong> datosY, se almacena su distancia a los k pivotes(d(x, p 1 ), ..., d(x, p k )). Dada una consulta q y unrango r, se calcula su distancia a los k pivotes(d(q, p 1 ), ..., d(q, p k )).• Si para algún pivote p i se cumple que|d(q, p i ) − d(x, p i )| > r, entonces por <strong>de</strong>sigualdadtriangular se tiene que d(q, x) > r, y porlo tanto no es necesario evaluar explícitamented(x, q). Todos los objetos que no se puedan<strong>de</strong>scartar por esta regla <strong>de</strong>ben ser comparadosdirectamente con la consulta q.<strong>La</strong>s estructuras <strong>de</strong> tipo árbol utilizan esta técnicaen forma indirecta. El árbol se va construyendotomando el nodo raíz como pivote. Posteriormente elespacio se divi<strong>de</strong> <strong>de</strong> acuerdo a la distancia <strong>de</strong> los objetosal pivote. Cada subárbol se construye recursivamentetomando un nuevo pivote <strong>de</strong> los elementos <strong>de</strong>lsubespacio. <strong>La</strong>s diferencias radican principalmenteen la forma y tamaño <strong>de</strong> los espacios. <strong>La</strong> búsquedarealiza un backtrack sobre el árbol y utiliza la <strong>de</strong>sigualdadtriangular para minimizar los subárboles.Algunas estructuras que utilizan esta técnica son elBKT y sus variantes [1].Otros algoritmos, <strong>de</strong> tipo arreglo, hacen una implementacióndirecta <strong>de</strong> este concepto, y se diferencianbásicamente en su estructura extra para reducir elcosto <strong>de</strong> CPU para encontrar los puntos candidatos,pero no en la cantidad <strong>de</strong> evaluaciones <strong>de</strong> distancia.Ejemplos <strong>de</strong> éstos son: LAESA [2], Spaghettis y susvariantes [3], [4].El aumento <strong>de</strong> tamaño <strong>de</strong> las bases <strong>de</strong> datos y laaparición <strong>de</strong> nuevos tipos <strong>de</strong> datos sobre los cuales nointeresa realizar búsquedas exactas, crean la necesidad<strong>de</strong> plantear nuevas estructuras para búsquedapor similtud o búsqueda aproximada. Así también,las aplicaciones reales requieren que dichas estructuraspermitan ser almacenadas en memoria secundariaeficientemente, como también que poseanmétodos optimizados para reducir los costos <strong>de</strong> accesosa disco.Finalmente, la necesidad <strong>de</strong> procesar gran<strong>de</strong>svolúmenes <strong>de</strong> datos requiere <strong>de</strong> incrementar la capacidad<strong>de</strong> procesamiento y reducir los tiempos <strong>de</strong>búsqueda promedio. En este contexto, es relevanteel estudio en términos <strong>de</strong> la paralelización <strong>de</strong> los algoritmosy distribución <strong>de</strong> la base <strong>de</strong> datos.B. Paralelización <strong>de</strong> Estructuras MétricasEn la actualidad, existen muchas plataformas ymo<strong>de</strong>los utilizados para la paralelización <strong>de</strong> estructurasmétricas. En este contexto, la investigación enesta área ha estado enfocada en tecnologías para aplicaciones<strong>de</strong> memoria distribuida, usando para ellolibrerías <strong>de</strong> alto nivel como MPI [5] or PVM [6], ymemoria compartida usando directivas <strong>de</strong> OpenMP[7].Algunos trabajos, [8], [9], se han enfocado a la paralelización<strong>de</strong> diferentes estructuras métricas sobreplataformas <strong>de</strong> memoria distribuida usando MPI oBSP, así como también al análisis <strong>de</strong> la distribución<strong>de</strong> los datos y el balance <strong>de</strong> la estructura sobre laplataforma.En términos <strong>de</strong> memoria compartida, [10] proponeuna estrategia para organizar el procesamiento <strong>de</strong>consultas sobre espacios métricos en nodos multicores,para ello propone combinar procesamiento <strong>de</strong>consultas multihilo totalmente asíncronas con masivamentesíncronas. El cambio entre los modos seajusta a una regla que <strong>de</strong>termina el nivel <strong>de</strong>l tráfico<strong>de</strong> consultas.<strong>La</strong> mayoría <strong>de</strong>l trabajo previo y actual <strong>de</strong>sarrolladoen esta área se lleva a cabo sobre plataformasclásicas <strong>de</strong> memoria distribuida y compartida. Sinembargo, nuevas plataformas computacionales hanido ganando significancia en la comunidad científica.Plataformas híbridas basadas en GPU son un ejemplo.En la actualidad existen muy pocos trabajos sobreestructuras métricas en plataformas <strong>de</strong> este tipo, lamayoría <strong>de</strong> las soluciones implementadas sobre GPUssólo abordan el problemas <strong>de</strong> consultas kNN sin utilizarestructuras <strong>de</strong> datos. En general, las GPUsbásicamente se utilizan para paralelizar búsquedasexhautivas (fuerza bruta) por lo que no se utilizanestructuras métricas [11], [12] y [13].En [11] se propone dividir la base <strong>de</strong> datos <strong>de</strong> elementos(A) y la <strong>de</strong> consultas (B) en submatrices<strong>de</strong> tamaño fijo. <strong>La</strong> matriz resultante es una matrizdon<strong>de</strong> cada elemento representa la distancia entreun elemento <strong>de</strong> A y uno <strong>de</strong> B. Cada submatriz <strong>de</strong> Ces resuelta por un bloque, para lo cual cada bloquecarga a memoria compartida cada submatriz <strong>de</strong> Ay B para po<strong>de</strong>r escribir las distancias resultantes enla submatriz correspondiente. Cada bloque hará lecturasa <strong>de</strong>vice memory <strong>de</strong> acuerdo a las cantida<strong>de</strong>s<strong>de</strong> filas y columnas <strong>de</strong> las matrices. Teniendo la matriz<strong>de</strong> distancias resultante, ésta se or<strong>de</strong>na usandoel CUDA-based Radix Sort [14] para posteriormenteseleccionar los k primeros elementos como resultado<strong>JP2011</strong>-354


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011final.En [12] se implementa el algoritmo <strong>de</strong> fuerza brutay se propone que cada thread resuelva la distancia <strong>de</strong>un elemento <strong>de</strong> la base <strong>de</strong> datos contra la consulta,para luego or<strong>de</strong>nar el arreglo resultante con una variante<strong>de</strong>l insertion sort.En general, en los trabajos anteriores la paralelizaciónes aplicada en dos etapas. <strong>La</strong> primeraconsiste en construir la matriz <strong>de</strong> distancias, y la segundaen el proceso <strong>de</strong> or<strong>de</strong>namiento para obtenerlos resultados.En [15] se presenta una variante <strong>de</strong> lo anterior.Este trabajo compara 2 estrategias, la primera, alestilo <strong>de</strong> los trabajos anteriores. Sin embargo, lasegunda estrategia, llamada Heap Based Reductionpropone resolver una consulta por cada bloque. Después<strong>de</strong> haber calculado todas las distancias parauna consulta (exhaustivamente), envia en cada lanzamiento<strong>de</strong> kernel un solo bloque, manteniendo unheap por cada thread <strong>de</strong>l bloque. Cada heap <strong>de</strong>tamaño k se utiliza para almacenar los k vecinos máscercanos a partir <strong>de</strong> las distancias entre los elementos<strong>de</strong> la base <strong>de</strong> datos y la consulta.En este artículo se presenta una versión <strong>de</strong> la estructuramétrica basada en pivotes Spaghettis [3] implementadasobre una plataforma basada en GPU.II. SpaghettisSpaghettis [3] es una estructura <strong>de</strong> datos métricabasada en pivotes y es una variante <strong>de</strong> LAESA [2].Propone reducir el tiempo <strong>de</strong> CPU extra necesarioal realizar una consulta utilizando una estructura <strong>de</strong>datos en don<strong>de</strong> las distancias a los pivotes están or<strong>de</strong>nadaspor separado, construyendo un arreglo porcada pivote, lo que permite realizar una búsquedabinaria en el rango relevante.Si para cada pivote se encuentra el conjunto S i ={x : |d(x, p i ) − d(q, p i )| ≤ r}, i = 1, ..., k entonces lalista <strong>de</strong> candidatos está dada por la intersección <strong>de</strong>todos estos conjuntos.A. ConstrucciónDurante la construcción <strong>de</strong> la estructura, se seleccionanun conjunto aleatorio <strong>de</strong> pivotes p 1 , ..., p k , loscuales pue<strong>de</strong>n o no pertenecer a la base <strong>de</strong> datos ain<strong>de</strong>xar. Cada posición en la tabla S i representa aun objeto <strong>de</strong> la base <strong>de</strong> datos que tiene un enlace asu posición en la siguiente tabla, la última tabla enlazael objeto a su posición en la base <strong>de</strong> datos. <strong>La</strong>Figura 1 muestra un ejemplo con 17 elementos.B. BúsquedaDurante el proceso <strong>de</strong> búsqueda, dada un consultaq, un rango r la búsqueda por rango sobre un spaghettistiene básicamente los siguientes paso:1. Se calcula la distancia entre q y todos los pivotesp1, . . . , p k , para luego obtener k intervalos <strong>de</strong> laforma [a 1 , b 1 ], ..., [a k , b k ], don<strong>de</strong> a i = d(p i , q) - ry b i = d(p i , q) + r.012250 70000 1111 0000 11110000 111111110000 1111 500001111 20000 1111 0000 11115 105 5 4 5 6 4000 111 000 1116 6 5 0 000 000 111000 1116 13000 111000011110000 1111600001111 11 6 9000011110000 1111600001111 110000 1111 0000 11110000 1111 0000 11117 12 7 11 6 60000 1111 0000 11110000 1111 0000 11118 80000 1111 00000000 1111 0000 11110000 1111 70000 1111 1 7 00000 11110000 11110000 1111 0000 1111 000 1118 9 7 6 7 9000 1110000 1111 0000 1111 000011118 14 0000 1111700001111 7 7 12000 111 000000 111 000 1110000 1111 0000 11118 10 8 10 7 39 15 9 14 8 5101115<strong>JP2011</strong>-355Pivote 1 Pivote 2 Pivote 3 Pivote 4 Base <strong>de</strong> Datos10247133160122299142313158412166 16149 810 1513 160 45 1111000111000000 111 6 000 111 21110006 766677779121736811000 000 111000 111111 7 000 111 151110008 10110000 11 8 00 11 1311009 1410 1614 5Objecto 1000000000000000000000000111111111111111111111111Objecto 20000000011111111Objecto 3Objecto 4Objecto 5Objecto 6Objecto 7Objecto 8Objecto 9Objecto 10Objecto 11Objecto 1200000000001111111111Objecto 13Objecto 14000000000000000000000000111111111111111111111111Objecto 150000000011111111Objecto 16Objecto 17Fig. 1. Spaghettis: Construcción y búsqueda. Ejemplopara una consulta q con rangos a los pivotes <strong>de</strong>{(6, 10), (5, 9), (2, 6), (4, 8)}.2. Los objetos que se encuentren en la intersecciónentre todos los intervalos, se convierten en candidatosa ser respuesta para la consulta q.3. Para cada objeto candidato y, se calcula la distanciad(q, y) y si ≤ r, entonces el objeto y essolución a la consulta.Algoritmo 1 Spaghettis: Algoritmo <strong>de</strong> Búsqueda.rangesearch(query q, range r)1: {Sea Y ⊆ X, la base <strong>de</strong> datos}2: {Sea P un conjunto <strong>de</strong> pivotes p 1 , . . . , p 2 ∈ X}3: {Sea D la tabla <strong>de</strong> distancias asociadas a q}4: {Sea S el Spaghettis}5: for all p j ∈ P do6: D j ← dist(q, p j )7: end for8: for all y i ∈ Y do9: <strong>de</strong>scartado ← false10: for all p j ∈ P do11: if D j − r > S ij || D j + r < S ij then12: <strong>de</strong>scartado ← true13: break;14: end if15: end for16: if !<strong>de</strong>scartado then17: if dist(y i , q) ≤ r then18: agrega y i al resultado19: end if20: end if21: end forDetalles <strong>de</strong> la implementación se muestra en el algoritmo1.En la Figura 1 se representa la estructura spaghettisen su forma original. Ésta está construida usando4 pivotes para in<strong>de</strong>xar una base <strong>de</strong> datos <strong>de</strong> 17 objetos.Sobre esta estructura se realiza la búsquedacomo sigue. Suponga una consulta q con distancia alos pivotes {8, 7, 4, 6} y rango <strong>de</strong> búsqueda r = 2 .


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011En la Figura 1 se muestran más oscurecidos los intervalos{(6, 10), (5, 9), (2, 6), (4, 8)} sobre los cuales serealizará la búsqueda. En la misma figura se apreciancon distintos achurados todos los objetos quepertenecen a la intersección <strong>de</strong> todos los intervalos.Dichos objetos son posibles candidatos a ser solución.Finalmente, para saber si un candidato es respuesta,se <strong>de</strong>be realizar un cálculo <strong>de</strong> distancia y <strong>de</strong>terminarsi es menor que el rango <strong>de</strong> búsqueda.III. Implementación Basada en GPUEl objetivo principal <strong>de</strong>l presente trabajo es <strong>de</strong>sarrollaruna versión basada en GPU para los algoritmos<strong>de</strong> búsqueda por rango.Este tipo <strong>de</strong> proceso es altamente paralelizable anivel <strong>de</strong> datos con un alto requerimiento computacional.Por esta razón, la computación en GPU esmuy usada en or<strong>de</strong>n a acelerar estos procesos <strong>de</strong>bidoel hecho <strong>de</strong> que las GPUs explotan muy eficientementeel paralelismo a nivel <strong>de</strong> datos.A. Búsqueda Exhaustiva Basada en GPUDada una base <strong>de</strong> datos y una consulta, labúsqueda exhaustiva secuencial es un proceso iterativodon<strong>de</strong> en cada iteración se calcula la distanciaentre la consulta y un elemento <strong>de</strong> la base <strong>de</strong> datospara <strong>de</strong>terminar si es o no una solución válida. <strong>La</strong>implementación paralela <strong>de</strong> este proceso es trivial, ydada las características <strong>de</strong> las GPUs, consiste en lanzartantos hilos como elementos haya en la base <strong>de</strong>datos.Por otro lado, <strong>de</strong>bido a las limitaciones <strong>de</strong> las actualesGPUs (número <strong>de</strong> hilos y capacidad <strong>de</strong> memoria),no es posible calcular simultaneamente todaslas distancias para todas las consultas usando sóloun kernel. Para esta implementación, se consi<strong>de</strong>rantantos kernel como consultas, don<strong>de</strong> cada kernel resuelvecompletamente una consulta.B. Spaghettis Basado en GPUEn or<strong>de</strong>n a obtener mayor rendimiento sobre laGPU, se hicieron modificaciones sobre la estructuraSpaghettis original. <strong>La</strong> versión presentada en estetrabajo or<strong>de</strong>na la estructura sólo por el primer pivote,esto permite almacenar contiguamente las distancias<strong>de</strong> los objetos a todos los pivotes. Inicialmentela estructura completa entra en el espacio <strong>de</strong>memoria global <strong>de</strong> la GPU.<strong>La</strong> paralelización <strong>de</strong>l algoritmo <strong>de</strong> búsqueda estádividido en tres partes, cada uno <strong>de</strong> estas partes correspon<strong>de</strong>a los procesos indicados en la subsecciónII-B.<strong>La</strong> primera parte resuelve el cálculo <strong>de</strong> las distanciasentre la query q y cada uno <strong>de</strong> los pivotes. Paraoptimizar el uso <strong>de</strong> la GPU, se resuelve en un sololanzamiento <strong>de</strong> kernel todo el conjunto <strong>de</strong> consultasQ. El proceso consistió en lanzar un kernel compuestopor una cantidad <strong>de</strong> hilos igual al número <strong>de</strong>queries (|Q|), <strong>de</strong> esta manera, cada hilo resuelve enforma in<strong>de</strong>pendiente las distancias <strong>de</strong> cada query alos pivotes. Como resultado, el kernel genera unamatriz <strong>de</strong> tamaño |Q| × |P | con las distancias correspondientes.<strong>La</strong> segunda parte <strong>de</strong> la paralelización se encarga<strong>de</strong> <strong>de</strong>terminar si un elemento es o no candidato auna query. Para ello se lanza el kernel <strong>de</strong>nominadoKCandidates (ver algoritmo 2) que ejecuta un hilopor cada dato (y i ) en la base <strong>de</strong> datos y <strong>de</strong>terminasi dicho dato es candidato o no, es <strong>de</strong>cir, este kernelentrega la lista <strong>de</strong> candidatos para una query. Enel algoritmo 2, S i es la posición i que representa alobjeto y i , el cual es resuelto por el hilo i, cuandoéste es candidato se agrega al conjunto C. En estealgoritmo, cada kernel resuelve completamente unaconsulta.Algoritmo 2 Algoritmo <strong>de</strong> Búsqueda en CUDA.global KCandidates(range r, Spaghettis S, distancesD, pivots P , candidates C)1: {Sea P el conjunto <strong>de</strong> pivotes p 1 , . . . , p 2 ∈ X}2: {Sea D la tabla <strong>de</strong> distancias asociadas a q}3: {Sea C la lista <strong>de</strong> candidatos para q}4: {Sea i el Id <strong>de</strong>l hilo}5: <strong>de</strong>scartado ← false6: for all p j ∈ P do7: if D j − r > S ij || D j + r < S ij then8: <strong>de</strong>scartado ← true9: break;10: end if11: end for12: if !<strong>de</strong>scartado then13: agrega el elemento y i a C (candidates)14: end ifFinalmente, el último kernel se encarga <strong>de</strong> <strong>de</strong>terminarcual <strong>de</strong> los candidados obtenidos en la segundaparte son realmente solución a la consulta q. En estekernel, el numero <strong>de</strong> hilos correspon<strong>de</strong> al número <strong>de</strong>candidatos por cada consulta. Al término <strong>de</strong>l terceerkernel, se obtiene una lista con las soluciones para laconsulta.IV. Evaluación ExperimentalEsta sección presenta los resultados para los algoritmosindicados en la sección anterior. El caso <strong>de</strong>estudio presentado en este artículo consi<strong>de</strong>ra que laestructura <strong>de</strong> datos Spaghettis generada entra completamenteen la memoria global <strong>de</strong> la GPU.A. Ambiente ExperimentalPara los experimentos mostrados en esta sección,se seleccionó una base <strong>de</strong> datos que correspon<strong>de</strong> aun diccionario español <strong>de</strong> 86.061 palabras. <strong>La</strong> distanciautilizada fue la distancia <strong>de</strong> edición, que correspon<strong>de</strong>al mínimo número <strong>de</strong> inserciones, eliminacioneso sustituciones necesarias para que una palabrasea igual a otra. <strong>La</strong> base <strong>de</strong> datos se divi<strong>de</strong>en dos conjuntos aleatorios, el primero <strong>de</strong> un 90%<strong>de</strong> los datos se utiliza para construir la estructuraSpaghettis, el 10% restante se utiliza como consultas.<strong>La</strong> plataforma <strong>de</strong> hardware usado fue la siguiente:<strong>JP2011</strong>-356


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011• CPU: Intel Core 2 Quad <strong>de</strong> 2.66GHz y 4GB <strong>de</strong>memoria RAM.• GPU: GTX 285 with 240 cores y una memoriaglobal <strong>de</strong> 1 GB.B. Resultados ExperimentalesLos resultados mostrados en la presente seccióntienen las siguientes características:• <strong>La</strong> seleccion <strong>de</strong> pivotes fue aleatoria.• Se construyeron estructuras con 4, 8, 16 y 32pivotes.• Se realizaron 8.606 consultas sobre una estructuracon 77.455 objetos, por cada experimento.• Para cada consulta se recuperaron los objetos arangos <strong>de</strong> búsqueda <strong>de</strong> 1, 2, 3 y 4,• Los tiempos <strong>de</strong> ejecución mostrados para ambasversiones, secuencial y paralelo, correspon<strong>de</strong> altiempo total <strong>de</strong> todo el proceso. Para el caso <strong>de</strong>la versión paralela, los tiempos <strong>de</strong> ejecución incluyenlos tiempos <strong>de</strong> transferencia entre memoriaprincipal (CPU) y el disppositivo <strong>de</strong> memoriaglobal (GPU).<strong>La</strong> Figura 2(a) muestra información resumida yel contexto secuencial-paralelo. Se observa que losresultados <strong>de</strong> la versión basada en CUDA reduce notoriamenteel tiempo, incrementando el rendimiento.Para tener una visión más clara, la Figura 2(b) muestra<strong>de</strong>talles <strong>de</strong> los resultados obtenidos sólo para laversión paralela. Como referencia, en ambos gráficosse incluyen los tiempos <strong>de</strong> las respectivas versiones<strong>de</strong> búsqueda exhaustiva (Fuerza Bruta Sec. y GPU).En la versión secuencial, se pue<strong>de</strong> observar queal aumentar el número <strong>de</strong> pivotes se logra mejorarel <strong>de</strong>sempeño <strong>de</strong> la estructura. También era <strong>de</strong>esperar que a mayor rango <strong>de</strong> búsqueda menor elel rendimiento. Lo mismo suce<strong>de</strong>, en términos <strong>de</strong>tiempo, en la versión paralela.Los graficos <strong>de</strong> speed-up se muestran en la Figura3. En este caso, se pue<strong>de</strong> observar que las mejorasalcanzan valores cercanos al 9, 5 para los rangosmás altos. Lo anterior indica que para los rangosmayores, don<strong>de</strong> es menor la cantidad <strong>de</strong> elementosa <strong>de</strong>scartar, y el comportamiento <strong>de</strong> la estructurase asemeja a búsqueda exhaustiva, la GPU obtienesu mejor <strong>de</strong>sempeño. En el mismo gráfico se muestrauna prueba para rango 8, a fin <strong>de</strong> <strong>de</strong>mostrar queel speed-up se vuelve asintótico alre<strong>de</strong>dor <strong>de</strong>l valormencionado anteriormente.Se pue<strong>de</strong> notar también, que hay diferencia notoria<strong>de</strong>l speed-up para rangos bajos y cantidad <strong>de</strong> pivotespequeñas versus la estructura con mayor cantidad <strong>de</strong>pivotes. Esto es provocado <strong>de</strong>bido a que la versiónsecuencial para, por ejemplo, 4 pivotes es <strong>de</strong> muybajo rendimiento versus la versión secuencial <strong>de</strong> 32pivotes, por lo tanto el speed-up para la estructura32 pivotes secuencial/paralela no es tan buena comola versión <strong>de</strong> 4 pivotes.Tiempo (seg.)Tiempo (seg.)4500400035003000250020001500100050045040035030025020015010050Costos Totales <strong>de</strong> Búsqueda, Secuencial vs GPU (n=77.455)Fuerza Bruta Sec.Seq. 04Seq. 08Seq. 16Seq. 32Fuerza Bruta (gpu)P 04 (gpu)P 08 (gpu)P 16 (gpu)P 32 (gpu)01 2 3 4 1 2 3 4Rango <strong>de</strong> Búsqueda(a) Resultados Secuencial versus GPUCosto Total <strong>de</strong> Búsqueda sobre GPU (n=77.455; dic. Español)Fuerza Bruta (gpu)P 04 (gpu)P 08 (gpu)P 16 (gpu)P 32 (gpu)01 2 3 4Rango <strong>de</strong> Búsqueda(b) GPU <strong>de</strong>tallesFig. 2. Resultados comparativos <strong>de</strong> los costos <strong>de</strong> búsquedapara el espacio <strong>de</strong> palabras para la estructura métricaSpaghettis (Spanish Dictionary). Número <strong>de</strong> pivotes 4,8, 16 y 32, y rango <strong>de</strong> búsqueda <strong>de</strong> 1 a 4.C. Consumo <strong>de</strong> EnergíaEl uso <strong>de</strong> GPUs pue<strong>de</strong> reducir consi<strong>de</strong>rablementelos tiempos <strong>de</strong> ejecución <strong>de</strong> distintas aplicaciones,sin embargo, estos mo<strong>de</strong>rnos dispositivos están compuestospor muchos núcleos <strong>de</strong> computación (cores),lo que implica un mayor consumo <strong>de</strong> energía. Deesta manera, el consumo <strong>de</strong> energía se convierte enun parámetro interesante <strong>de</strong> consi<strong>de</strong>rar al momento<strong>de</strong> <strong>de</strong>sarrollar código para GPUs.<strong>La</strong> figura 4 muestra en <strong>de</strong>talle el consumo <strong>de</strong> energíapara la versión secuencial ejecutandose en laCPU versus la versión paralela corriendo en la GPU.En este caso, la información mostrada en el gráficocorrespon<strong>de</strong> específicamente a la búsqueda sobre unaestructura con 16 pivotes y rango <strong>de</strong> búsqueda r =2. Los otros experimentos tuvieron similar comportamiento.<strong>La</strong> información <strong>de</strong> la forma y <strong>de</strong>l dispositivoutilizado para la medición <strong>de</strong> la energía estáexpuesta en <strong>de</strong>talle en [16].A primera vista, es posible ver que el consumo <strong>de</strong>energía <strong>de</strong> la GPU es más alto que el <strong>de</strong> la CPU.Sin embargo, <strong>de</strong>bido al hecho <strong>de</strong> que el tiempo <strong>de</strong>ejecución <strong>de</strong> la GPU es inferior a la CPU, el consumoglobal <strong>de</strong> energía es menor.El promedio <strong>de</strong> la energía eléctrica utilizada porla versión secuencial fue <strong>de</strong> 130, 38 watts durante589, 60 segundos, proporcionando un consumo <strong>de</strong><strong>JP2011</strong>-357


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Speed Up108642Speed−Up para la Búsqueda (n=77,455 palabras; dic. Español)Fuerza Bruta (gpu)Pivots : 04Pivots : 08Pivots : 16Pivots : 3201 2 3 4 8Rango <strong>de</strong> BúsquedaFig. 3. Gráficos <strong>de</strong> Speed-up para el espacio <strong>de</strong> palabras parala estructura métrica Spaghettis (Diccionario Español).Watts250200150100Consumo energía, Algoritmos Secuenciales vs basados en GPU50promedio GPUpromedio Secuencial00 71.76 589.60Tiempo (seg.)Fig. 4. Consumo <strong>de</strong> energía promedio para las versiones secuencialy paralelo <strong>de</strong> la estructura métrica Spaghettis,para el diccionario español.76.872, 048 Joules. <strong>La</strong> implementación paralela tuvoun promedio <strong>de</strong> energía eléctrica <strong>de</strong> 212, 68 watts durante71, 76 segundos, lo que resulta en un consumo<strong>de</strong> 15.261, 9168 Joules. Con lo anterior, se pue<strong>de</strong> <strong>de</strong>cirque el ahorro <strong>de</strong> energía <strong>de</strong> la versión paralelasobre la secuencial es <strong>de</strong> 80.14%.V. Conclusiones y Trabajo FuturoEn este artículo se ha presentado una implementaciónpara búsqueda por similitud sobre espaciosmétricos para la estructura Spaghettis sobre unaplataforma paralela basada en GPU.<strong>La</strong>s implementaciones realizadas han reducidolos tiempos <strong>de</strong> ejecución consi<strong>de</strong>rablemente, alcanzandovalores para el speed-up que bor<strong>de</strong>an los9.5. En el análisis experimental se consi<strong>de</strong>raronparámetros como, el número <strong>de</strong> pivotes y los rangos<strong>de</strong> búsquedas.Importante también es consi<strong>de</strong>rar el consumo <strong>de</strong>energía, en la cual se obtuvo una reducci”on <strong>de</strong>l80.14% utilizando la plataforma basada en GPU.En la actualidad los autores están realizando experimentossobre otras bases <strong>de</strong> datos e implementandoversiones multiples plataformas. Comotrabajo futuro se realizarán implementaciones <strong>de</strong>otras estructuras métricas que puedas servir <strong>de</strong> comparación,realizar implementaciones sobre plataformashíbridas (multicore + GPUs) y realizar análisis<strong>de</strong>l comportamiento <strong>de</strong> las estructuras métricas conotras funciones <strong>de</strong> distancia, entre otros.Agra<strong>de</strong>cimientosEste trabajo ha sido parcialmente financiado porel proyecto SATSIM (Ref: CGL2010-20787-C02-02).Referencias[1] Edgar Chávez, Gonzalo Navarro, Ricardo Baeza-Yates,and José L. Marroquín, “Searching in metric spaces,”in ACM Computing Surveys, September 2001, pp.33(3):273–321.[2] L. Micó, J. Oncina, and E. Vidal, “A new version of thenearest-neighbor approximating and eliminating search(AESA) with linear preprocessing-time and memory requirements,”Pattern Recognition Letters, vol. 15, pp.9–17, 1994.[3] E. Chávez, J. Marroquín, and R. Baeza-Yates, “Spaghettis:An array based algorithm for similarity queriesin metric spaces,” in 6th International Symposiumon String Processing and Information Retrieval(SPIRE’99). IEEE CS Press, 1999, pp. 38–46.[4] S. Nene and S. Nayar, “A simple algorithm for nearestneighbor search in high dimensions,” IEEE Transactionson Pattern Analysis and Machine Intelligence, vol. 19,no. 9, pp. 989–1003, 1997.[5] W. Gropp, E. Lusk, and A. Skelljum, UsingMPI:Portable Parallel Programming with the MessagePassing Interface, Scientific and Engineering computationSeries. MIT Press, Cambridge, MA, 1994.[6] A. Geist, A. Beguelin, J. Dongarra, W. Jiang,B. Manchek, and V. Sun<strong>de</strong>ram, PVM: Parallel VirtualMachine – A User’s Gui<strong>de</strong> and Tutorial for NetworkParallel Computing, MIT Press, 1994.[7] L. Dagum and R. Menon, “OpenMP: An industrystandardAPI for shared-memory programming,” IEEEComputational Science and Engineering, vol. 5, no. 1,pp. 46–55, 1998.[8] P. Zezula, P. Savino, F. Rabitti, G. Amato, and P. Ciaccia,“Processing m-trees with parallel resources,” inRIDE ’98: Proceedings of the Workshop on Research Issuesin Database Engineering, Washington, DC, USA,1998, p. 147, IEEE Computer Society.[9] Adil Alpkocak, Taner Danisman, and Ulker Tuba, “Aparallel similarity search in high dimensional metric spaceusing m-tree,” in Advanced Environments, Tools, andApplications for Cluster Computing, vol. 2326 of LectureNotes in Computer Science, pp. 247–252. Springer Berlin/ Hei<strong>de</strong>lberg, 2002.[10] Veronica Gil-Costa, Ricardo Barrientos, Mauricio Marin,and Carolina Bonacic, “Scheduling metric-space queriesprocessing on multi-core processors,” Parallel, Distributed,and Network-Based Processing, EuromicroConference on, vol. 0, pp. 187–194, 2010.[11] Quansheng Kuang and Lei Zhao, “A practical GPUbased kNN algorithm,” International Symposium onComputer Science and Computational Technology (ISC-SCT), pp. 151–155, 2009.[12] Vincent Garcia, Eric Debreuve, and Michel Barlaud,“Fast k nearest neighbor search using GPU,” ComputerVision and Pattern Recognition Workshop, vol. 0, pp.1–6, 2008.[13] Benjamin Bustos, Oliver Deussen, Stefan Hiller, andDaniel Keim, “A graphics hardware accelerated algorithmfor nearest neighbor search,” in ComputationalScience (ICCS). 2006, vol. 3994, pp. 196–199, Springer.[14] Nadathur Satish, Mark Harris, and Michael Garland,“Designing efficient sorting algorithms for manycoreGPUs,” Parallel and Distributed Processing Symposium,International, vol. 0, pp. 1–10, 2009.[15] R. J. Barrientos, J. I. Gómez, C. Tenllado, and M. Prieto,“Heap based k-nearest neighbor search on GPUs,”in Congreso Español <strong>de</strong> Informática (CEDI)), Valencia,Septiembre 2010.[16] Roberto Uribe-Pare<strong>de</strong>s, Pedro Valero-<strong>La</strong>ra, EnriqueÁrias, José L. Sánchez, and Diego Cazorla, “A GPUbasedimplementation for range queries on spaghettisdata structures,” Tech. Rep., Computing Systems Dept,University of Castilla-<strong>La</strong> Mancha, Spain, 2010.<strong>JP2011</strong>-358


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Query Processing in Metric Spaces using GPUsRicardo J. Barrientos 1 , José I. Gómez 1 , Christian Tenllado 1 , Manuel Prieto Matias 1Abstract— Similarity search has been a problemwi<strong>de</strong>ly studied in the last years as it can be appliedto several fields such as searching by content in multimediaobjects, text retrieval or computational biology.These applications usually work on very largedatabases that are usually in<strong>de</strong>xed off-line to enableacceleration of on-line searches. Even with in<strong>de</strong>xeddatabases, it is essential to parallelize the on-linequery solving process. In the past, many strategieshave been proposed to parallelize this problemin distributed and shared memory multicore systems.<strong>La</strong>tely, GPUs have also been used to implement bruteforceapproaches instead of using in<strong>de</strong>xing structures.In this work we propose a GPU based metric-spacein<strong>de</strong>x data structure for similarity search that outperformsprevious OpenMP and GPU brute-force basedimplementations. We also validate our implementationin the context of real-time systems, when it isnot affordable to wait for thousands of queries to fillthe system before processing them all in parallel.Keywords— Range Queries, Metric Spaces, MetricDatabases, Similarity Search, GPU.I. IntroductionSIMILARITY search has been wi<strong>de</strong>ly studied inrecent years and it is becoming more and morerelevant due to its applicability in many importantareas. Efficient similarity search is useful in multimediainformation retrieval, data mining or patternrecognition problems. Range search also enablesother relevant operations such as nearest neighborssearch. In general, when similarity search is un<strong>de</strong>rtakenby using metric-space database techniques,this problem is often featured by a large databasewhose objects are represented as high-dimensionalvectors. There exists a distance function that operateson those vectors to <strong>de</strong>termine how similar areobjects to a given query object. The distance betweenany given pair of objects is known to be anexpensive operation to compute and thereby the useof parallel computation techniques can be an effectiveway to reduce running times to practical valuesin large databases.In this paper we propose and evaluate efficientmetric-space techniques to solve range search queriesusing GPUs. We have found that obtaining efficientperformance from this hardware, in this applicationdomain, can be particularly difficult since many ofthe metric-space solutions <strong>de</strong>veloped for traditionalshared memory multiprocessors and distributed systemscannot be implemented efficiently on GPUs.Our focus is on search systems <strong>de</strong>vised to solvelarge streams of queries. Previous related work hasshown that conventional parallel implementations forclusters and multicore systems that exploit coarsegrainedinter-query parallelism are able to improvequery throughput by employing in<strong>de</strong>x data struc-1 ArTeCS Group, Complutense University, e-mail:ribarrie@fdi.ucm.estures constructed off-line upon the database objects.In contrast, on GPUs it is necessary to exploit bothcoarse and fine grained parallelism where the cost ofdata transfers such as pieces of in<strong>de</strong>x can hi<strong>de</strong> thebenefits of keeping smartly in<strong>de</strong>xed the database.We studied a number of alternative sequentialmetric-space in<strong>de</strong>x data structures and realized thattwo candidates, namely LC and SSS-In<strong>de</strong>x (<strong>de</strong>tailsbelow), were best suited for GPUs as their data organizationand operations resemble computations ontwo-dimensional matrices.Interestingly enough, the LC and SSS in<strong>de</strong>xes havebeen shown to achieve efficient performance in sharedmemory multi-core and distributed memory clusterprocessors by previous work. This allowed us to exposea comparative study of our proposal against optimizedimplementations of the same in<strong>de</strong>xes bothsequentially and in parallel for shared memory usingOpenMP [1].II. Related WorkA metric space (X, d) is composed of an universe ofvalid objects X and a distance function d : X x X →R + <strong>de</strong>fined among them. The distance function <strong>de</strong>terminesthe similarity between two given objectsand holds several properties such as strict positiveness,symmetry, and the triangle inequality The finitesubset U ⊂ X with size n = |U|, is called thedatabase and represents the collection of objects ofthe search space.There are two main queries of interest: RangeSearch [2] and The k nearest neighbors (kNN) [3],[4]. In the former, the goal is to retrieve all the objectsu ∈ U within a radius r of the query q (i.e.(q, r) d= {u ∈ U/d(q, u) ≤ r}), whereas in the latter,the goal is to retrieve the set kNN(q) ⊆ Usuch that |kNN(q)| = k and ∀u ∈ kNN(q), v ∈U−kNN(q), d(q, u) ≤ d(q, v).For solving both kind of queries and to avoid asmany distance computations as possible, many in<strong>de</strong>xingapproaches have been proposed. We havefocused on the List of Clusters (LC ) [5] and SSS-In<strong>de</strong>x [6] strategies since (i) they are two of the mostpopular non-tree structures that are able to prunethe search space efficiently and (ii) they hold theirin<strong>de</strong>xes on <strong>de</strong>nse matrices which are very convenientfor mapping algorithms onto GPUs [7].In the following subsections we explain the constructionof both in<strong>de</strong>xes and <strong>de</strong>scribe how rangequeries are solved using them in a sequential way(range searches are simpler than kNN, but manykNN searches are built on them).A. List of Clusters (LC)This in<strong>de</strong>x [5] is built by choosing a set of centersc ∈ U with radius r c where each center maintains<strong>JP2011</strong>-359


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011a bucket that keeps tracks of the objects containedwithin the ball (c, r c ). Each bucket holds the closestk-elements to c. Thus the radius r c is the maximumdistance between the center c and its k-nearestneighbor.The buckets are filled up sequentially as the centersare created and thereby a given element i locatedin the intersection of two or more center balls remainsassigned to the first bucket that hold it. The firstcenter is randomly chosen from the set of objects.The next ones are selected so that they maximizethe sum of the distances to all previous centers.A range query q with radius r is solved by scanningthe centers in or<strong>de</strong>r of creation. For each centerd(q, c) is computed and only if d(q, c) ≤ r c + r, it isnecessary to compare the query against the objectsof the associated bucket. This process ends up eitherat the first center that holds d(q, c) < r c − r, meaningthat the query ball (q, r) is totally contained inthe center ball (c, r c ), or when all centers have beenconsi<strong>de</strong>red.B. Sparse Spatial Selection (SSS-In<strong>de</strong>x)During construction, this pivot-based in<strong>de</strong>x [6] selectssome objects as pivots from the collection andthen computes the distance between these pivots andthe rest of the database. The result is a table of distanceswhere columns are the pivots and rows theobjects. Each cell in the table contains the distancebetween the object and the respective pivot. Thesedistances are used to solve queries as follows. For arange query (q, r) the distances between the queryand all pivots are computed. An object x from thecollection can be discar<strong>de</strong>d if there exists a pivot p ifor which the condition |d(p i , x) − d(p i , q)| > r doeshold. The objects that pass this test are consi<strong>de</strong>redas potential members of the final set of objects thatform part of the solution for the query and thereforethey are directly compared against the query byapplying the condition d(x, q) ≤ r. The gain in performancecomes from the fact that it is much cheaperto effect the calculations for discarding objects usingthe table than computing the distance between thecandidate objects and the query.A key issue in this in<strong>de</strong>x is the method that calculatesthe pivots, which must be good enough todrastically reduce total number of distance computationsbetween the objects and the query. An effectivemethod is as follows. Let (X, ) be a metricspace, U ⊂ X an object collection, and M the maximumdistance between any pair of objects, M =max{d(x, y)/x, y ∈ U}. The set of pivots containsinitially only the first object of the collection. Then,for each element x i ∈ U, x i is chosen as a new pivotif its distance to every pivot in the current set of pivotsis equal or greater than αM, being α a constantparameter. Therefore, an object in the collection becomesa new pivot if it is located at more than afraction of the maximum distance with respect to allthe current pivots.III. Graphic Processing Units (GPU)GPUs have emerged as a powerful cost-efficientmany-core architecture. They integrate a large numberof functional units following a SIMT mo<strong>de</strong>l.We <strong>de</strong>velop all our implementations using NVIDIAgraphic cards and its CUDA programming mo<strong>de</strong>l([7]). A CUDA kernel executes a sequential co<strong>de</strong>on a large number of threads in parallel. Thosethreads are grouped into fixed size sets called warps 1 .Threads within a warp proceed in a lock step execution.Every cycle, the hardware scheduler ofeach GPU multiprocessor chooses the next warp toexecute (i.e. no individual threads but warps areswapped in and out). If the threads in a warp executedifferent co<strong>de</strong> paths, only those that follow the samepath can be executed simultaneously and a penaltyis incurred.Warps are further organized into a grid of CUDABlocks: threads within a block can cooperate witheach other by (1) efficiently sharing data through ashared low latency local memory and (2) synchronizingtheir execution via barriers. In contrast, threadsfrom different blocks can only coordinate their executionvia accesses to a high latency global memory.Within certain restrictions, the programmer specifieshow many blocks and how many threads per blockare assigned to the execution of a given kernel. Whena kernel is launched, threads are created by hardwareand dispatched to the GPU cores.According to NVIDIA the most significant factoraffecting performance is the bandwidth usage. Althoughthe GPU takes advantage of multithreadingto hi<strong>de</strong> memory access latencies, having hundredsof threads simultaneously accessing the global memoryintroduces a high pressure on the memory busbandwidth. The memory hierarchy inclu<strong>de</strong>s a largeregister file (statically partitioned per thread) and asoftware controlled low latency shared memory (permultiprocessor). Therefore, reducing global memoryaccesses by using local shared memory to exploit interthread locality and data reuse largely improveskernel execution time. In addition, improving memoryaccess patterns is important to allow coalescingof warp loads and to avoid bank conflicts on sharedmemory accesses.IV. Range QueriesIn this section we <strong>de</strong>scribe the mapping of threerange search algorithms onto CUDA-enabled GPUs:a brute-force approach and two in<strong>de</strong>x-based searchmethods.All of them exploit two different levels of parallelism.As in some previous papers [8][9] we assumea high frequency of incoming queries and exploitcoarse-grained inter-query parallelism, i.e. we alwayssolve nq queries in parallel. However, we also exploitthe fine-grained parallelism available when solvinga single query. Overall, each query is processed bya different CUDA Block that contains hundreds of1 Currently, there are 32 threads per warp<strong>JP2011</strong>-360


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011threads (from 128 to 512, <strong>de</strong>pending of the specificimplementation) that efficiently cooperate to solve it.Communication and synchronization costs betweenthreads within the same CUDA Block are rather low,so this choice looks optimal to fully exploit the enormousparallelism present in range search algorithms.We introduced a brute force algorithm which isused as point of comparison with the in<strong>de</strong>xed methods.A. Brute Force AlgorithmThe overall i<strong>de</strong>a is that each CUDA Block processesa different query and within a CUDA Block,each thread computes the distance between the queryand a subset of the elements of the database. Thedatabase is a D × E matrix, where D is the dimensionof its elements and E is the size of the database,which has been uploa<strong>de</strong>d previously to <strong>de</strong>vice memory.Queries are also uploa<strong>de</strong>d into <strong>de</strong>vice memorybut the threads of each CUDA Block cooperate totransfer their associated query to the shared memoryto accelerate its access, which is the first step.Afterwards, threads compute the distance betweenthe query and the elements of the database followinga Round-Robin distribution. Most work is performedwithin the <strong>de</strong>vice function that performs the distancebetween elements and the query. Database elementsare stored column-wise to increase the chances of coalescememory accesses when computing these distancessince that way consecutive threads have toaccess adjacent memory locations.B. List of Clusters ( LC)The data structure that holds the LC in<strong>de</strong>x consistsof 3 matrices <strong>de</strong>noted as CENTER, RC andCLUSTERS. CENTER is a D × N cen matrix (D isthe dimension of the elements 2 and N cen is the numberof centers), where each column represents thecenter of a cluster, RC is an array that stores thecovering radius of each cluster, and CLUSTERS isa D × N clu matrix (N clu is the number of elementsin all the clusters) that holds the elements of eachcluster. In<strong>de</strong>x information is stored column-wise tofavor coalesce memory accesses as in the Brute ForceTechnique.Each CUDA Block processes a different query,which is transferred from <strong>de</strong>vice memory to sharedmemory since it is accessed by all its threads whenperforming distance evaluations. Once the query hasbeen saved into the shared memory, a for loop iteratesover the different clusters. Each thread computesthe distance between q and a subset of elementsof CENTER following a Round-Robin distribution.Most work is performed again within the<strong>de</strong>vice function that performs the distance betweenelements and the query. If distances are lower thanrange, the respective centers cluster are appen<strong>de</strong>d tothe list of results. Clusters are marked for exhaustivesearch only if their respective center balls have someintersection with the query ball. A property of this2 For the Spanish database, D is the maximum size of a word.in<strong>de</strong>x (given by its construction) is that the exhaustivesearch over a cluster can be pruned if the queryball is totally contained in a given center ball. If thisis the case, then we do not consi<strong>de</strong>r the subsequentclusters <strong>de</strong>limiting the number of clusters.Finally, a for loop processes all the elements of theselected clusters as in the Brute Force technique.C. SSS-In<strong>de</strong>xThe SSS-In<strong>de</strong>x consists of 3 matrices <strong>de</strong>notedas PIVOTS, DISTANCES and DB. PIVOTS is aD × N piv matrix (D is the dimension of the elementsand N piv is the number of pivots) where each columnrepresents a pivot, DISTANCES is a N piv ×N DB matrix(N DB = number of elements of the database)where each element is the distance between a pivotand a element of the database, and DB is a D×N DBmatrix where each column represents an element ofthe database. As in the LC, the in<strong>de</strong>x informationis stored column-wise to favor coalesce memory accesses.As in the LC, each CUDA Block transfers its associatedquery to shared memory due to its frequentaccess. Once the synchronization ensures the queryhas been copied before access it, each thread performsthe distance evaluations between the queryand a subset of pivots following a Round-Robin distribution.And finally, the rows of DISTANCES aredistributed across threads, that test if their respectiveelements of the database can be discar<strong>de</strong>d. Forevery non discar<strong>de</strong>d element, a distance evaluationis performed.In [6], authors have found empirically that aroundα = 0.4 yields the minimal number of distance evaluations.Our own experiments on GPUs confirm thisbehavior: the more pivots are used (up to a certainthreshold), the less distance evaluations are performed.However, the best performance is obtainedwith just one pivot for vector databases. In<strong>de</strong>ed themore pivots used, the worst the execution time becomes.Irregularity explains this apparent contradiction:when using more pivots, threads within a warpare more likely to diverge. Moreover, memory accesspattern becomes more irregular and hardware cannotcoalesced them, and this increases the numberof Read/Write operations. Summarizing, less distanceevaluations do not pay off due to the overheadscaused by warp divergences and irregular access patterns.Overall, just one pivot provi<strong>de</strong>s the optimalperformance for many of our reference databases.V. Experimental ResultsAll our GPU experiments were carried out on aNVIDIA GeForce GTX 280 which is shipped with30 multiprocessors, 8 cores per multiprocessor, 16KBof shared memory and 4GB of <strong>de</strong>vice memory. Thehost CPU is an Intel’s Clovertown processor, composedby 2xIntel Quad-Xeon (2.66 GHz), and in eachcore 32KB of L1 Cache for instructions and 32KB fordatas, each two cores shares the L2 Cache of 4MB,and the RAM is of 16 GB.<strong>JP2011</strong>-361


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011We have used two different reference databases:Spanish : A Spanish dictionary with 51,589 wordsand we used the edit distance [10] to measure similarity.On this metric-space we processed 40,000 queriesselected from a sample of the Chilean Web which wastaken from the TODOCL search engine. This can beconsi<strong>de</strong>red a low dimensional metric space.Images : We took a collection of images from aNASA database containing 40,700 images vectors,and we used them as an empirical probability distributionfrom which we generated a large collectionof random image objects containing 120,000 objects.We built each in<strong>de</strong>x with the 80% of the objects andthe remaining 20% objects were used as queries. Inthis collection we used the eucli<strong>de</strong>an distance to measurethe similarity between two objects. Intrinsic dimensionalityof this space higher than in the previousdatabase, but it is still consi<strong>de</strong>red low.In the vector database (Images) the radius usedwere those that retrieve on average the 0.01%, 0.1%and 1% of the elements of the database per query.In the Spanish database the radius were 1, 2 and3. Similar values have been also used in previouspapers [9][8]. In all the proposed methods, the set ofqueries are previously copied to <strong>de</strong>vice memory.Regarding the GPU implementation, we performeda wi<strong>de</strong> exploration to obtain the best parametersfor each in<strong>de</strong>xed structure. Regarding LC wefound that 64 elements per cluster is the best optionfor the vector database, while 32 performs thebest in the Spanish database. We already discussedSSS-In<strong>de</strong>x tuning in Section IV-C. The conclusionsthere drawn hold for the Images database, so a singlepivot (α = 0.66) is used. However, for the Spanishdatabase it is better to use 64 pivots (α = 0.5).Figure 1 illustrates the performance characteristicsof our GPU implementations. Brute Force stands forthe exhaustive-search algorithm. LC and SSS-In<strong>de</strong>xshow the results for the two implemented in<strong>de</strong>xingmechanisms with the parameters indicated above.All figures are normalized to the largest value of eachversion.We first place our attention on the total numberof distance evaluations (Figure 1(a)). Both databasebehaves as expected: in<strong>de</strong>xing mechanisms do significantly<strong>de</strong>crease the number of distance evaluationswhen compared to the brute force search method.SSS-In<strong>de</strong>x typically outperforms LC when checkingdistance evaluations. And it does it if we consi<strong>de</strong>rthe Spanish database. However, since we just usedone pivot for the Images, LC becomes the winner inthis category. One would expect that running timesmimic the trend exhibited by the distance evaluationsbut results in Figure 1(b) partially contradictsthis intuition: the brute force search algorithm behavesbetter than expected in the Images database.It equals or even improves SSS-In<strong>de</strong>x performance.For the Spanish database changes are not so drastic,but LC becomes the best implementation even if itperforms more distance evaluations.Figure 1(c) has the clue: the brute force techniqueNormalized Average of D.E.Normalized Running TimeNormalized Quantity of Read−Write OperationsD.B. ImagesD.B. Spanish0.80.70.60.50.40.30.20.100.9 1 0.01 0.1 1 1 2 3Percentage of Database RetrievedBrute ForceSSS−In<strong>de</strong>xL.C.Radii(a) Number of Distance EvaluationsD.B. ImagesD.B. Spanish0.80.70.60.50.40.30.20.100.9 1 0.01 0.1 1 1 2 3Percentage of Database RetrievedD.B Images(b) Running timeBrute ForceSSS−In<strong>de</strong>xL.C.RadiiD.B Spanish0.80.70.60.50.40.30.20.100.9 1 0.01 0.1 1 1 2 3Percentage of Database RetrievedBrute ForceSSS−In<strong>de</strong>xL.C.Radii(c) Number of read/write operationsFig. 1. Normalized a) Distance evaluations per query (average)b) Running time and c) Read-write Operations (of32, 64 o 128 bytes) to <strong>de</strong>vice memory.has a slightly better memory access pattern overSSS-In<strong>de</strong>x when <strong>de</strong>aling with the Images database.The alignment of memory access heavily influencesperformance on current GPUs. As stated in SectionIII, when a warp launches misaligned or nonconsecutivememory accesses, hardware is not able tocoalesce it and a single reference may become up to32 separate accesses. The LC shows the best resultson this aspect on both databases, which explains itssuperior performance previously reported.A. Performance of parallel implementationsFigure 2 shows the performance speed-ups of ourGPU in<strong>de</strong>xed implementations over optimized sequentialimplementations. Results are very impressivefor SSS-In<strong>de</strong>x (up to 248x for 1% elements re-<strong>JP2011</strong>-362


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Speed-Up260240220200180160140120100806040200LCSSS-In<strong>de</strong>x0.01 0.1 1Percentage of Database RetrievedFig. 2. Speed-Up of GPU versions of LC and SSS-In<strong>de</strong>x oversequential counterparts with DB Images.trieved) due to the poor CPU performance of thisin<strong>de</strong>xing mechanisms. But even for the lighter 3 in<strong>de</strong>x(List of Clusters) our implementation achievesa 29x speedup, which seems hard to attain with amedium-size multicore server.To prove that last point, we run the same experimentson the multicore system using the OpenMPimplementation presented in [9]. The OpenMP parallelversion scales worse than expected with thenumber of cores: our experimental framework consistsof 8 cores but the parallel implementation isjust 4 times faster than the sequential counterpart,as shown in figures 2 and 3.Given the synchonization-free parallelism exploited,we expected almost linear scaling with thenumber of cores. In<strong>de</strong>ed, with no aggressive compilationflags, the parallel version scales linearly. TableI shows this behavior for the List of Clusters implementationwhen retrieving 1% of the database foreach query: to increase the optimization level leadsto faster implementations but worsens the speedupmetric when compared with the sequential implementation.All the others experiments followed thesame trend.After aggressive compiler optimizations, the memorysystem becomes even more critical since <strong>de</strong>nsityof accesses increases. Even if no inter-thread communicationis present in our implementation, certainlevels of the memory system are shared. The effectof L2 sharing can be estimated when launching 4threads instead of 8. Default thread-to-core assignmentyields a x2.03 speedup factor over the sequentialimplementation. Making the assignment moreL2-cache friendly increases the speedup factor upto x2.5. The common memory controller is anotherbottleneck, since accesses from the 8 cores are issuedconcurrently. Conflicting accesses are then serialized,thus <strong>de</strong>creasing potential performance gains. Thisresource sharing explains the sub-linear speedup factorobtained.Figure 3 shows the speedups obtained by the GPUimplementation over the 8-core OpenMP version. Asexpected from the above discussion, it mimics the3 The required space to store the LC is equal to the 6% ofthe space required by the SSS-In<strong>de</strong>x.LC No optimization flags With optimization flagsSequential Time 89.46s 21.94s8 cores 11.2 s 4.95sspeedup 7.98 4.43TABLE IExecution times of sequential and parallel versionSpeed-Up(OpenMP based, 8 cores) for List of Clusters.80706050403020100LCSSS-In<strong>de</strong>x0.01 0.1 1Percentage of Database RetrievedFig. 3. Speedup of GPU versions of LC and SSS-In<strong>de</strong>xover corresponding OpenMP implementations with DBImages.trends of figure 2. SSS-In<strong>de</strong>x benefits much morefrom the two level of parallelism exploited (bothinter- and intra- query parallelism). We achieved amaximum speedup of x76.104 when searching witha radius r = 0.73 (this radius implies to retrieve a1% of the elements of the reference database). LCperformance gains are more mo<strong>de</strong>st, but still relevant:from 5.96x to 7.92x <strong>de</strong>pending on the selectedradius. This speedup factor may not lookimpressive taken into account that our GPU has30 multiprocessors on-board, compared with the 8-core Xeon based server used for OpenMP experiments.However, it is important to remind that eachof this NVIDIA multiprocessor is extremely simplerthan the Core/Nehalem michroarchitecture based IntelCPUs; instruction level parallelism is almost notexploited while it represents the main source of performancefor complex out-of-or<strong>de</strong>r processors.B. Solving queries on-lineAll results reported so far assume that we knowall the queries to be solved in advanced. For the Imagedatabase, that means that we assume a total of23831 queries in the system before we start solvingthem all in parallel. While this assumption could beadmissible for certain use cases, it could be unaffordablein on-line real-time systems like web searchingfor multimedia contents [11].We performed a productivity test in function ofthe number of queries issued in parallel. Figure 4(a)shows the results for the List of Cluster implementation.The x-axis indicates how many queries arelaunched in parallel (starting in five queries at atime). The y-axis shows the productivity of the systemmeasured in the number of queries processed bysecond. Not surprisingly, the productivity rapidly<strong>JP2011</strong>-363


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011increases up to the point where we launch 30 queriesin parallel (remind that the GPU used in the experimentsinclu<strong>de</strong>s 30 multiprocessors). Below thatpoint the GPU is un<strong>de</strong>rused and the constant penaltyof launching a kernel weights too much. There is aknee at 30 but productivity still slowly increases dueto the GPU multithreading capabilities which allowsto hi<strong>de</strong> long memory latencies effectively. <strong>La</strong>unchingqueries in batch of 200 is almost at the maximumproductivity achievable with our implementation(anyhow, it is always advisable to launch asmany queries in parallel as possible since it reducesthe number of kernel invocations).Figure 4(b) reviews the speed-up figures for the LCimplementation. The bar labeled Unlimited Batchcorresponds to the LC speed-up bar in figure 3. Itis the upper bound for GPU performance, since allqueries are solved with a single kernel invocation.Bars labeled Batch=30 and Batch=100 correspondswith a scenario where, as soon as we have 30 (resp.100) queries in the system, we launch a kernel tosolve them. Even if the productivity is not at itshighest point, the GPU implementation always outperformsthe OpenMP version. Please note thatOpenMP based implementations are still assumingtheir best-case, i.e. all queries are known from thebeginning, so no dispatching overhead is present. Aspeedup higher than 5x (in average) is achieved whenlaunching just 30 queries in parallel, which representsa very low frequency traffic scenario. Thus, we canconclu<strong>de</strong> that GPUs can be used for on-line queryprocessing in metric spaces as a low-cost high performancealternative to traditional multi CPU implementations.VI. ConclusionsIn this paper we have presented efficient implementationsof suitable in<strong>de</strong>xing mechanisms whichare mapped on CUDA based GPUs. We comparedthem against optimized OpenMP and sequential implementations,overcoming both of them.We found that the optimal parameters in the contextof the GPU, for both List of Clusters and SSS-In<strong>de</strong>x, are extremely different than those found onthe sequential and OpenMP implementations. Inparticular, the best GPU implementation found forSSS-In<strong>de</strong>x uses a single pivot to prune the searchspace, which shows that the SSS algorithm is inefficientsince this pivot is selected at random amongthe database objects.The List of Cluster is the in<strong>de</strong>x with best performanceon GPU, achieving a speed-up of 29x over thesequential counterpart, and 7.9x over an optimized8-thread OpenMP implementation.In the context of the processing of stream ofqueries, based on the productivity of our algorithms,we found that solving batches of queries whose sizeequals the number of GPU multi-processors is astrategy able to achieve good speed-up.References[1] Barbara Chapman, Gabriele Jost, and Ruud Van DerPas, Using OpenMP: portable shared memory parallelNumber of Queries/Time1000090008000700060005000400030002000100000 20 40 60 80 100 120 140 160 180 200Number of Queries(a) Productivity solving different number of queriesSpeed-Up876543210Batch=30Batch=100Unlimited Batch0.01 0.1 1Pecentage of Database Retrieved(b) Speed-Up over corresponding OpenMP implementationusing different size of batchFig. 4. a) Productivity (number of queries divi<strong>de</strong>d by itscorresponding running time) solving different number ofqueries of the LC over Images database. b) Speed-Upof LC solving a batch of queries (of 30 and 100) at atime over corresponding OpenMP implementation withDB Images.programming, The MIT Press, 2008.[2] Edgar Chávez, Gonzalo Navarro, Ricardo Baeza-Yates,and José L. Marroquín, “Searching in metric spaces,”in ACM Computing Surveys, September 2001, pp.33(3):273–321.[3] D. W. Aha and D. Kibler, “Instance-based learning algorithms,”in Machine Learning, 1991, pp. 37–66.[4] T. Cover and P. Hart, “Nearest neighbor pattern classification,”Information Theory, IEEE Transactions on,vol. 13, no. 1, pp. 21–27, 1967.[5] Edgar Chávez and Gonzalo Navarro, “A compact space<strong>de</strong>composition for effective metric in<strong>de</strong>xing,” PatternRecognition Letters, vol. 26, no. 9, pp. 1363–1376, 2005.[6] Nieves R. Brisaboa, Antonio Fariña, Oscar Pedreira, andNora Reyes, “Similarity search using sparse pivots forefficient multimedia information retrieval,” in ISM, 2006,pp. 881–888.[7] “CUDA: Compute Unified Device Architecture. c○2007NVIDIA Corporation.,” .[8] R. Uribe and G. Navarro, “Egnat: A fully dynamic metricaccess method for secondary memory,” in Proc. 2ndInternational Workshop on Similarity Search and Applications(SISAP). 2009, pp. 57–64, IEEE CS Press.[9] Veronica Gil Costa, Ricardo J. Barrientos, MauricioMarín, and Carolina Bonacic, “Scheduling metric-spacequeries processing on multi-core processors,” in PDP,Marco Danelutto, Julien Bourgeois, and Tom Gross, Eds.2010, pp. 187–194, IEEE Computer Society.[10] V.I. Levenshtein, “Binary co<strong>de</strong>s capable of correcting<strong>de</strong>letions, insertions, and reversals,” in Soviet PhysicsDoklady, 1966, vol. 10, pp. 707–710.[11] Mauricio Marin, Veronica Gil-Costa, CarolinaBonacic, Ricardo Baeza-Yates, and Isaac D. Scherson,“Sync/async parallel search for the efficient <strong>de</strong>signand construction of web search engines,” ParallelComputing, vol. 36, no. 4, pp. 153 – 168, 2010.<strong>JP2011</strong>-364


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Re<strong>de</strong>s y comunicaciones<strong>JP2011</strong>-365


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-366


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Desarrollo <strong>de</strong> un Prototipo para la NotificaciónAutomática <strong>de</strong> Acci<strong>de</strong>ntes <strong>de</strong> Tráfico usandoRe<strong>de</strong>s VehicularesManuel Fogue 1 , Piedad Garrido 1 , Francisco J. Martinez 1 , Carlos T. Calafate 2 , Juan C.Cano 2 y Pietro Manzoni 2Resumen— <strong>La</strong>s nuevas tecnologías <strong>de</strong> la comunicaciónincorporadas al sector automovilístico ofrecenuna oportunidad para conseguir mejorar la asistenciaa los heridos en acci<strong>de</strong>ntes <strong>de</strong> tráfico, reduciendo eltiempo <strong>de</strong> respuesta <strong>de</strong> los servicios <strong>de</strong> emergenciay aumentando la información que éstos disponen sobreel siniestro, con lo que sería posible <strong>de</strong>terminarcon mayor precisión el operativo humano y materiala<strong>de</strong>cuado a la situación. El sistema e-NOTIFY propuestopresenta una arquitectura para dar soporte aestas necesida<strong>de</strong>s, en la cual cada vehículo incorporauna Unidad <strong>de</strong> a Bordo encargada <strong>de</strong> <strong>de</strong>tectar y notificarsituaciones <strong>de</strong> acci<strong>de</strong>nte a una Unidad <strong>de</strong> Controlexterna que se ocupa <strong>de</strong> estimar su gravedad y<strong>de</strong>stinar los recursos para su asistencia. El <strong>de</strong>sarrollo<strong>de</strong> un prototipo basado en dispositivos <strong>de</strong> propósitogeneral con un coste reducido y un nivel <strong>de</strong> eficienciaa<strong>de</strong>cuado <strong>de</strong>muestra que este sistema podría reducirnotablemente el tiempo necesario para <strong>de</strong>splegarlos servicios <strong>de</strong> emergencia una vez producido elacci<strong>de</strong>nte.Palabras clave— VANET, Sistemas Inteligentes <strong>de</strong>Transporte, comunicaciones V2V y V2I, acci<strong>de</strong>ntes <strong>de</strong>tráfico.I. IntroducciónDURANTE las últimas décadas, el parque automovilísticoexistente alre<strong>de</strong>dor <strong>de</strong>l mundo hasufrido un crecimiento muy notable, aumentando la<strong>de</strong>nsidad <strong>de</strong>l tráfico y provocando que los acci<strong>de</strong>ntes<strong>de</strong> tráfico representen un problema muy grave en lamayoría <strong>de</strong> los países. Por poner un ejemplo, 2.714personas murieron en las carreteras españolas en elaño 2009, lo que significa una muerte por cada 16.949habitantes [1]. Gran parte <strong>de</strong> los fallecimientos seproducen en el tiempo comprendido entre el sucesoy la llegada <strong>de</strong> las asistencias médicas. En un acci<strong>de</strong>nte<strong>de</strong> tráfico, completar la asistencia <strong>de</strong> los heridosgraves durante la hora inmediatamente posterioral inci<strong>de</strong>nte (la llamada Hora <strong>de</strong> Oro) es crucial paraminimizar los posibles riesgos en la salud <strong>de</strong> los ocupantes.Por ello, una rápida y eficiente operación<strong>de</strong> rescate tras un acci<strong>de</strong>nte <strong>de</strong> tráfico incrementaríanotablemente la probabilidad <strong>de</strong> supervivencia <strong>de</strong> losheridos y reduciría la gravedad <strong>de</strong> las lesiones. Otro<strong>de</strong> los principales problemas actuales en la asistenciaa los acci<strong>de</strong>ntes <strong>de</strong> tráfico son las gran<strong>de</strong>s pérdidas,tanto económicas como <strong>de</strong> tiempo, que se dan al nodisponer <strong>de</strong> cierta información que permita prever1 Depto. <strong>de</strong> Informática e Ingeniería <strong>de</strong> Sistemas,<strong>Universidad</strong> <strong>de</strong> Zaragoza, e-mail: {m.fogue, piedad,f.martinez}@unizar.es.2 Depto. <strong>de</strong> Informática <strong>de</strong> Sistemas y Computadores, UniversitatPolitècnica <strong>de</strong> València, e-mail: {calafate, jucano,pmanzoni}@disca.upv.es.el tipo y cantidad <strong>de</strong> equipamiento médico y técnicoque es necesario enviar a la zona <strong>de</strong>l siniestro.Para una reducción notable <strong>de</strong>l tiempo <strong>de</strong> asistencia,dos pasos principales <strong>de</strong>ben abordarse: (i) la notificaciónrápida y precisa <strong>de</strong>l acci<strong>de</strong>nte al Punto <strong>de</strong>Respuesta (Public Safety Answering Point, PSAP)a<strong>de</strong>cuado, y (ii) la evacuación rápida y eficaz <strong>de</strong> losocupantes que se encuentran atrapados en el interiorun vehículo. El primero <strong>de</strong> estos objetivos pue<strong>de</strong>llevarse a cabo empleando las tecnologías y los sistemas<strong>de</strong> telecomunicaciones que, recientemente, seha ido incorporando al mundo <strong>de</strong> la automoción,don<strong>de</strong> la comunicación móvil y los sistemas GPSson los máximos representantes. Durante los últimosaños, se han realizado numerosos avances en el <strong>de</strong>sarrollo<strong>de</strong> tecnologías <strong>de</strong> comunicación entre vehículos(V2V), también conocidas como (VANETs o VehicularAd hoc NETworks [2]). Estas tecnologíasestán basadas en sistemas <strong>de</strong> comunicación <strong>de</strong> cortoalcance, o Dedicated Short-Range Communication(DSRC) [3], y ofrecen soporte a aplicaciones <strong>de</strong> seguridadcooperativa entre vehículos. De hecho, seespera que el grupo <strong>de</strong> trabajo 802.11p apruebeen breve el estándar IEEE 802.11p [4], ofreciendouna solución factible para aplicaciones <strong>de</strong> seguridadinter-vehicular. Por otra parte, numerosos esfuerzose investigaciones <strong>de</strong>s<strong>de</strong> el entorno académicoy <strong>de</strong> la industria han permitido avanzar en el <strong>de</strong>sarrollo<strong>de</strong> tecnologías <strong>de</strong> soporte a la interacciónvehículo-infraestructura (V2I), <strong>de</strong> especial relevanciapara aplicaciones <strong>de</strong> seguridad vial, movilidad ymonitorización.Respecto al segundo <strong>de</strong> los objetivos, la eficacia<strong>de</strong> la asistencia <strong>de</strong> los pasajeros involucrados en unacci<strong>de</strong>nte <strong>de</strong> tráfico, ésta podría aumentarse notablementesi los servicios <strong>de</strong> emergencia dispusieran <strong>de</strong>información relevante sobre las condiciones en quesucedió el siniestro antes <strong>de</strong> <strong>de</strong>splazarse a la zona<strong>de</strong>l acci<strong>de</strong>nte. Esta información extra se emplearíapara estimar la gravedad <strong>de</strong> las heridas <strong>de</strong> los ocupantes,basándose en la información proporcionadapor los sensores <strong>de</strong>l vehículo. Asimismo, disponer <strong>de</strong>más información permitiría <strong>de</strong>terminar el conjuntoóptimo <strong>de</strong> recursos humanos y materiales a enviara una situación <strong>de</strong> acci<strong>de</strong>nte, con la consecuente reducción<strong>de</strong> costes e incremento <strong>de</strong> la calidad <strong>de</strong> asistencia<strong>de</strong> los heridos.En este trabajo se presenta el sistema e-NOTIFY,diseñado para la <strong>de</strong>tección, notificación y asistenciaautomática <strong>de</strong> los acci<strong>de</strong>ntes viales utilizando las ca-<strong>JP2011</strong>-367


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 1.Arquitectura e-NOTIFY basada en combinación <strong>de</strong> comunicaciones V2V y V2I.pacida<strong>de</strong>s que brindan las nuevas tecnologías <strong>de</strong> comunicaciónvehicular. Esta propuesta no se centraen reducir el número <strong>de</strong> acci<strong>de</strong>ntes, sino en mejorar laasistencia post-colisión mediante una gestión rápiday eficiente <strong>de</strong> los recursos <strong>de</strong> emergencia disponibles,lo cual incrementa las posibilida<strong>de</strong>s <strong>de</strong> recuperacióny supervivencia para los heridos en acci<strong>de</strong>nte <strong>de</strong>tráfico.El resto <strong>de</strong> este artículo se estructura como sigue.<strong>La</strong> Sección II incluye la arquitectura <strong>de</strong>l sistema propuesto.<strong>La</strong> Sección III muestra los pasos para diseñarun prototipo con dispositivos <strong>de</strong> propósito generalque aporten la funcionalidad requerida por el sistema.<strong>La</strong> Sección IV presenta el entorno en el que sellevó a cabo la validación <strong>de</strong>l sistema y los resultados<strong>de</strong> su evaluación. Por último, la Sección V presentalas conclusiones obtenidas <strong>de</strong> la realización <strong>de</strong> estetrabajo.II. Arquitectura <strong>de</strong>l sistema e-NOTIFY<strong>La</strong> Figura 1 presenta la estructura básica empleadapara <strong>de</strong>sarrollar el sistema e-NOTIFY. El objetivo<strong>de</strong>l sistema consiste en proporcionar una arquitecturaque permita: (i) comunicación directa entre losvehículos involucrados en el acci<strong>de</strong>nte, (ii) el envíoautomático <strong>de</strong> un conjunto <strong>de</strong> datos al Centro <strong>de</strong>Coordinación <strong>de</strong> Emergencias, y (iii) una evaluaciónpreliminar automática <strong>de</strong> los daños, tanto enel vehículo, como en los ocupantes basándose en lainformación recibida y los datos sobre acci<strong>de</strong>ntes previamenteacaecidos, lo cual permitiría adaptar losrecursos <strong>de</strong> rescate necesarios para su correcta asistencia.El sistema e-NOTIFY combina comunicacionestanto V2V como V2I para conseguir notificar <strong>de</strong>forma eficiente una situación <strong>de</strong> acci<strong>de</strong>nte al Centro<strong>de</strong> Control. Los diferentes vehículos <strong>de</strong>ben incorporaruna Unidad <strong>de</strong> a Bordo (On Board Unit, OBU)que se encarga <strong>de</strong> <strong>de</strong>tectar cuándo se ha producidoun impacto peligroso para los ocupantes, <strong>de</strong> recogerla información disponible <strong>de</strong> los sensores instaladosen el automóvil y <strong>de</strong> comunicar la situación a unaUnidad <strong>de</strong> Control (Control Unit, CU) que se ocupará<strong>de</strong>l tratamiento <strong>de</strong>l mensaje <strong>de</strong> aviso y su posteriorenvío. Entre otros aspectos, la CU <strong>de</strong>be integrarmecanismos <strong>de</strong> estimación <strong>de</strong> la gravedad <strong>de</strong>l acci<strong>de</strong>ntey <strong>de</strong> las heridas <strong>de</strong> los pasajeros, por lo que<strong>de</strong>be tener acceso a una base <strong>de</strong> datos lo más completaposible con información sobre otros siniestros.Esta estimación pue<strong>de</strong> llevarse a cabo con mo<strong>de</strong>los <strong>de</strong>clasificación <strong>de</strong> minería <strong>de</strong> datos usando los registros<strong>de</strong> bases <strong>de</strong> datos existentes [5].<strong>La</strong> <strong>de</strong>finición <strong>de</strong> las OBUs es <strong>de</strong> gran importanciapara el sistema propuesto. Este dispositivo <strong>de</strong>be sertécnicamente y económicamente factible, ya que suimplantación en vehículos <strong>de</strong> diversa gama podría llegara ser masiva cuando se comiencen a exten<strong>de</strong>r lossistemas <strong>de</strong> comunicación entre vehículos. A<strong>de</strong>más,este sistema <strong>de</strong>be estar abierto a futuras actualizaciones<strong>de</strong> software. Aunque en el diseño <strong>de</strong>l hardwarea incluir en los vehículos consistía inicialmenteen sistemas <strong>de</strong> propósito específico, esta ten<strong>de</strong>nciaestá dirigiéndose hacia sistemas <strong>de</strong> propósito másgeneral dada la inclusión constante <strong>de</strong> nuevos servicios.Por tanto, la OBU tiene que incluir suficientesinterfaces que le permitan conectarse al sistema <strong>de</strong>comunicación.El intercambio <strong>de</strong> información entre las OBUs y laCU se produce a través <strong>de</strong> Internet, bien mediantevehículos que tengan instalado un acceso a Internet(mediante UMTS, por ejemplo), o bien alcanzandounida<strong>de</strong>s <strong>de</strong> infraestructura (Road-Si<strong>de</strong> Units, RSU)que proporcionen este servicio. En el caso <strong>de</strong> queel vehículo no consiga acceso directo hasta la CUpor sus propios medios, pue<strong>de</strong> generar mensajes <strong>de</strong>difusión que serán retransmitidos por los vehículoscercanos hasta que se alcance una <strong>de</strong> las dos posibilida<strong>de</strong>s.Estos mensajes que se van difundiendo entrelos vehículos en el área cercana al acci<strong>de</strong>nte tambiéntienen la función <strong>de</strong> alertar a los conductores que se<strong>JP2011</strong>-368


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20111050-5Aceleracion (G)-10-15-20-25-30No acc. (15 km/h)Acc. leve (40 km/h)Acc. grave (64 km/h)-350 0.05 0.1 0.15 0.2 0.25Tiempo (s)Fig. 2.Estructura <strong>de</strong>l prototipo <strong>de</strong> Unidad <strong>de</strong> a Bordo.Fig. 3. Pulsos <strong>de</strong> aceleración para diferentes clasificaciones<strong>de</strong> acci<strong>de</strong>nte frontal. Datos propocionados por Applus+IDIADA [10].dirijan a la zona afectada por el siniestro sobre lascondiciones en que se encuentra el vehículo acci<strong>de</strong>ntadoy su posible interferencia en el flujo <strong>de</strong> tráficohabitual.III. Diseño <strong>de</strong>l prototipo e-NOTIFYUsando esta arquitectura como marco <strong>de</strong> referencia,se ha <strong>de</strong>sarrollado un prototipo empleando dispositivos<strong>de</strong> propósito general que pueda servir parallevar a cabo pruebas preliminares hasta que la tecnología(como el estándar IEEE 802.11p) y la infraestructura(RSUs) necesaria esté disponible parasu <strong>de</strong>spliegue en un entorno real. <strong>La</strong> configuración <strong>de</strong>cada uno <strong>de</strong> los componentes <strong>de</strong>l sistema se <strong>de</strong>tallaa continuación.A. Diseño <strong>de</strong> la Unidad <strong>de</strong> a Bordo (OBU)El principal objetivo <strong>de</strong> una OBU resi<strong>de</strong> en obtenerla información disponible a partir <strong>de</strong> los sensores instaladosen el vehículo para <strong>de</strong>terminar cuándo se haproducido una situación <strong>de</strong> peligro que <strong>de</strong>ba ser notificadaal punto <strong>de</strong> respuesta más cercano, así comoal resto <strong>de</strong> vehículos cercanos que puedan enfrentarsea esta situación. <strong>La</strong> estructura <strong>de</strong>l prototipo <strong>de</strong>sarrolladoaparece en la Figura 2, en el cual la unida<strong>de</strong>mpleada es un netbook Asus Eee PC [6] dotado condisco <strong>de</strong> estado sólido (SSD) para minimizar la posibilidad<strong>de</strong> <strong>de</strong>terioro <strong>de</strong>bido al impacto. <strong>La</strong> posicióny velocidad <strong>de</strong>l vehículo se obtiene mediante un dispositivoGPS Qstarz BT-Q818XT [7] accesible porBluetooth.Cuando se <strong>de</strong>sarrolla un prototipo <strong>de</strong> Unidad <strong>de</strong>a Bordo, la conexión con la sensórica <strong>de</strong>l vehículopue<strong>de</strong> llegar a ser complicada ya que cada fabricantepresenta diferencias en la forma <strong>de</strong> representar losdatos. A<strong>de</strong>más, gran parte <strong>de</strong> estos sensores sonanalógicos, <strong>de</strong> forma que para po<strong>de</strong>r tratar correctamentelos datos proporcionados es necesario realizaruna transformación previa a un formato digital. Estosproblemas se han resuelto empleando un microcontroladorARM mbed NXP LPC1768 [8] que permitegenerar prototipos rápidamente ya que, entreotras funcionalida<strong>de</strong>s, incorpora un compilador parael lenguaje C++, permite leer directamente una entradaanalógica y pue<strong>de</strong> comunicarse con un PC mediantediversas interfaces, entre las que se incluyeUSB y un puerto Ethernet. Otros trabajos ya hanempleado este sistema con éxito en tareas <strong>de</strong> controlautomático [9].El microcontrolador está programado para recogerperiódicamente los datos <strong>de</strong> los sensores que permitirán<strong>de</strong>terminar cuándo un vehículo ha sufridoun acci<strong>de</strong>nte que sería necesario informar a las autorida<strong>de</strong>spertinentes. Básicamente, se trata <strong>de</strong>acelerómetros y giroscopios que indican la severidad<strong>de</strong> los golpes recibidos por el automóvil o si ha sufridoun vuelco que haga peligrar la integridad <strong>de</strong> los ocupantes.<strong>La</strong> comunicación <strong>de</strong>l microcontrolador conla Unidad <strong>de</strong> a Bordo se realiza enviando paquetesUDP con frecuencia variable (en las pruebas <strong>de</strong> funcionamiento,se empleó una frecuencia <strong>de</strong> 50 paquetespor segundo) a través <strong>de</strong> la interfaz Ethernet incorporada.<strong>La</strong> OBU se encarga <strong>de</strong> recoger los datos enviadospor el microcontrolador y generar una serie temporalcon los valores medidos. <strong>La</strong> evolución tantoen las medidas <strong>de</strong> aceleración como en las <strong>de</strong> inclinaciónrespecto a la horizontal permitirán <strong>de</strong>terminarcuándo el vehículo ha sufrido daños <strong>de</strong> consi<strong>de</strong>ración.El tratamiento <strong>de</strong> la inclinación es bastantesencillo, puesto que mediciones que se <strong>de</strong>svíen más<strong>de</strong> 90 o <strong>de</strong> la horizontal indicarán que el vehículo havolcado y precisa <strong>de</strong> medios <strong>de</strong> rescate. Interpretarlos valores <strong>de</strong> aceleración es más complicado <strong>de</strong>bidoa que los pulsos que se reciben tienen una duraciónmuy limitada y <strong>de</strong>be consi<strong>de</strong>rarse en su clasificacióntanto su amplitud como su duración. Este efectose aprecia en la Figura 3, en la que aparecen representadosdiferentes pulsos correspondientes a unacci<strong>de</strong>nte frontal <strong>de</strong> diversa consi<strong>de</strong>ración (<strong>de</strong>s<strong>de</strong> noconsi<strong>de</strong>rarlo un acci<strong>de</strong>nte, hasta acci<strong>de</strong>ntes severosdon<strong>de</strong> los ocupantes pue<strong>de</strong>n haber sufrido heridasgraves). Pue<strong>de</strong> apreciarse que el pico <strong>de</strong> aceleraciónregistrado en el acci<strong>de</strong>nte leve supera al máximo en lacolisión grave, aunque la duración <strong>de</strong> su pulso es mu-<strong>JP2011</strong>-369


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011cho menor. Emplear simples umbrales <strong>de</strong> aceleraciónregistrada para diferenciar los pulsos no es suficiente,por lo que el enfoque empleado será utilizar el valor<strong>de</strong> la integral <strong>de</strong> la función <strong>de</strong>finida como la variación<strong>de</strong> la aceleración respecto al tiempo. Esta aproximaciónsí permite <strong>de</strong>finir umbrales que diferencian consuficiente margen las distintas situaciones. <strong>La</strong> integral<strong>de</strong> la función se aproxima mediante el métodonumérico <strong>de</strong> la regla <strong>de</strong>l trapecio, con la que la integral<strong>de</strong> una función f <strong>de</strong>finida en una serie n <strong>de</strong>intervalos regulares es igual a:∫ xnx 0f(x)dx ≈n∑i=1(x i − x i−1 ) f(x i) − f(x i−1 )2(1)<strong>La</strong> función <strong>de</strong> la aceleración se comienza a integrarcuando se <strong>de</strong>tecta una medición con valor absolutosuperior a un umbral, que está fijado entre3 y 5 Gs (1 G = 9.80665 m/s 2 ) <strong>de</strong>pendiendo <strong>de</strong>ltipo <strong>de</strong> impacto (frontal, lateral o trasero) y <strong>de</strong>l segmentoal que pertenece el vehículo. Tras un periodo<strong>de</strong> tiempo (que aproxima la duración <strong>de</strong>l pulso), elvalor <strong>de</strong> la integral <strong>de</strong>terminará el tipo <strong>de</strong> acci<strong>de</strong>nte<strong>de</strong>pendiendo <strong>de</strong> si superan o no los límites fijados enlas trazas <strong>de</strong> prueba. Si el acci<strong>de</strong>nte ha sido <strong>de</strong> suficientegravedad, la OBU pasará a enviar paquetesUDP con información sobre el suceso a sus vecinospara alertar <strong>de</strong>l peligro <strong>de</strong> la situación. A<strong>de</strong>más, seabrirá una conexión TCP con el punto <strong>de</strong> respuestapara alertar <strong>de</strong>l acci<strong>de</strong>nte y solicitar el envío <strong>de</strong> unoperativo <strong>de</strong> emergencia. Para ello, el mensaje transmitidocontendrá tanta información relevante comosea posible sobre el siniestro.B. Estructura <strong>de</strong>l mensaje <strong>de</strong> avisoLos mensajes que se intercambien entre losvehículos y la Unidad <strong>de</strong> Control <strong>de</strong>berían ser concisosy no incluir información irrelevante, pero no <strong>de</strong>beríanobviar ningún posible dato que pudiera servira los servicios <strong>de</strong> emergencia para <strong>de</strong>terminar los recursosnecesarios. Así, la información <strong>de</strong>stinada alpunto <strong>de</strong> respuesta <strong>de</strong>be incorporar datos sobre lascondiciones en que se produjo el acci<strong>de</strong>nte, sobre losocupantes <strong>de</strong>l vehículo y sobre los diversos sistemas<strong>de</strong> seguridad incluidos. Estos datos están dirigidosa los equipos <strong>de</strong> asistencia para proporcionarles unavisión más <strong>de</strong>tallada <strong>de</strong> las condiciones <strong>de</strong>l siniestroantes <strong>de</strong> llegar a la zona afectada [11]. Para el sistemadiseñado se propone enviar un mensaje quecontenga los siguientes campos, accesibles a través<strong>de</strong> los sensores incluidos en el propio vehículo (verFigura 4):TIEMPO (FECHA/HORA)• para informar exactamente sobre el momento <strong>de</strong>lacci<strong>de</strong>nte.LOCALIZACIÓN• posición geográfica <strong>de</strong>l vehículos, para <strong>de</strong>terminarla localización exacta <strong>de</strong> los heridos.VEHÍCULO-OCUPANTESVehicle &occupantsAcci<strong>de</strong>nt0 31VehiclespeedTimeLocationFeatures ofthe passengers# passengersseat belts and airbagsaccelerationpoint(s) of impactdirectionpositionFig. 4. Formato <strong>de</strong> paquete <strong>de</strong> aviso para el sistema propuesto.• características <strong>de</strong>l vehículos, para a<strong>de</strong>cuar elequipamiento a enviar al escenario <strong>de</strong>l acci<strong>de</strong>ntey avisar al equipo <strong>de</strong> rescate sobre el nivel <strong>de</strong>complejidad y peligros.• número <strong>de</strong> pasajeros, para a<strong>de</strong>cuar el equipomédico requerido para aten<strong>de</strong>rlos.• características <strong>de</strong> los pasajeros: peso, altura,edad, etc. Mejor cuanta más informaciónesté disponible.• información sobre cinturones <strong>de</strong> seguridady airbags, para estimar la severidad <strong>de</strong> los heridos,cómo sucedió el acci<strong>de</strong>nte y la gravedad <strong>de</strong>lmismo.ACCIDENTE• velocidad y aceleración <strong>de</strong>l vehículo justoantes <strong>de</strong>l impacto, para estimar la severidad <strong>de</strong>lsiniestro.• punto/s <strong>de</strong> impacto, es <strong>de</strong>cir, dón<strong>de</strong> exactamentese ha producido el impacto contra otroobjeto <strong>de</strong> la vía.• dirección <strong>de</strong> la fuerza <strong>de</strong> impacto. Éstees un concepto mecánico. Si consi<strong>de</strong>ramos laplanta <strong>de</strong>l vehículo como un reloj, pue<strong>de</strong> <strong>de</strong>scribirsela dirección <strong>de</strong> impacto como una hora:12 para impacto frontal, 3 para impacto lateral<strong>de</strong>recho, 6 para impacto trasero, etc.• posición <strong>de</strong>l vehículo <strong>de</strong>spués <strong>de</strong> la colisiónpara estimar la gravedad <strong>de</strong>l acci<strong>de</strong>nte y avisaral equipo <strong>de</strong> emergencia sobre la complejidad <strong>de</strong>lrescate.C. Diseño <strong>de</strong> la Unidad <strong>de</strong> Control (CU)<strong>La</strong> Unidad <strong>de</strong> Control (CU) está asociada al centro<strong>de</strong> respuesta encargado <strong>de</strong> recibir las notificaciones<strong>de</strong> acci<strong>de</strong>nte provenientes <strong>de</strong> las OBUs instaladas <strong>de</strong>los vehículos. <strong>La</strong> Unidad <strong>de</strong> Control se encarga <strong>de</strong>tratar los mensajes <strong>de</strong> aviso, obtener la informacióncontenida en los mismos y notificar a los servicios <strong>de</strong>emergencia sobre las condiciones en que se ha producidoel acci<strong>de</strong>nte. El prototipo <strong>de</strong> la Unidad <strong>de</strong>Control tiene la estructura que aparece en la Figura5.<strong>JP2011</strong>-370


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 5.Estructura <strong>de</strong>l prototipo <strong>de</strong> Unidad <strong>de</strong> Control.Una vez recibido el mensaje, la CU <strong>de</strong>be almacenarlos datos <strong>de</strong>l acci<strong>de</strong>nte en una base <strong>de</strong> datos pararegistrar que ha sido asistido correctamente. Deberíaexistir a disposición <strong>de</strong> la CU una base <strong>de</strong> datosque aporte diferente información sobre los posiblesmo<strong>de</strong>los y marcas <strong>de</strong> vehículos existentes en el parqueautomovilístico. <strong>La</strong>s áreas críticas <strong>de</strong>l vehículoque <strong>de</strong>ben ser evitadas durante procedimientos <strong>de</strong>rescate (por ejemplo, los <strong>de</strong>pósitos <strong>de</strong> combustible)no están señalizadas en la mayoría <strong>de</strong> los casos ypodrían causar situaciones <strong>de</strong> peligro para el personal<strong>de</strong> emergencia. De esta forma, ante una notificación<strong>de</strong> acci<strong>de</strong>nte pue<strong>de</strong> conocerse la información referenteal vehículo siniestrado (manuales <strong>de</strong> operación,información sobre áreas peligrosas, etc.) antes <strong>de</strong>que los equipos <strong>de</strong> rescate lleguen a la zona en la queocurrió.El prototipo <strong>de</strong> CU incluye una interfaz Web que(con autenticación previa) incluye información sobrelas diversas notificaciones recibidas hasta el momento.De cada una <strong>de</strong> ellas pue<strong>de</strong> obtenerse información<strong>de</strong>tallada y visual sobre posición y condiciones<strong>de</strong> los pasajeros (uso <strong>de</strong> cinturón <strong>de</strong> seguridad,<strong>de</strong>spliegue <strong>de</strong>l airbag, zonas <strong>de</strong> corte para laexcarcelación <strong>de</strong> los ocupantes, etc.), fecha y hora, localización<strong>de</strong>l acci<strong>de</strong>nte (con visualización mediantela API <strong>de</strong> Google Maps [12]), etc. <strong>La</strong> Figura 6 presentaun ejemplo <strong>de</strong> un acci<strong>de</strong>nte simulado con 3 ocupantes.IV. Validación <strong>de</strong>l sistemaEl prototipo diseñado fue validado en las instalaciones<strong>de</strong>l Departamento <strong>de</strong> Seguridad Pasiva <strong>de</strong>Applus+ IDIADA [10] en Santa Oliva (Tarragona).Estas instalaciones albergan uno <strong>de</strong> los laboratorios<strong>de</strong> choque más sofisticados <strong>de</strong>l mundo y constituyenun centro oficial para la homologación según el programaEuroNCAP [13].Debido al coste <strong>de</strong> emplear vehículos reales en losexperimentos <strong>de</strong> choque, las pruebas con el prototipoe-NOTIFY se realizaron empleando una plataforma(conocida como “trineo”) que se <strong>de</strong>splaza sobre raíleshasta impactar contra una serie <strong>de</strong> barras metálicasFig. 6. Captura <strong>de</strong> la interfaz Web con información sobre unacci<strong>de</strong>nte notificado.que simulan la <strong>de</strong>formación que sufriría la carrocería<strong>de</strong>l vehículo para amortiguar el golpe. <strong>La</strong> velocidad ala que se produce el golpe y la configuración <strong>de</strong> barrasutilizada en el test <strong>de</strong>terminan, respectivamente, laclase <strong>de</strong> acci<strong>de</strong>nte <strong>de</strong>tectado y el segmento al quepertenecería el vehículo que se está simulando.<strong>La</strong> Figura 7 muestra el trineo utilizado en las pruebas,al cual se fijaron una serie <strong>de</strong> pesas para completarla simulación <strong>de</strong>l comportamiento <strong>de</strong> un vehículoconvencional. En la Figura 8 aparecen las fijacionesempleadas para instalar el prototipo <strong>de</strong> OBU a laplataforma. Los ensayos consistieron en pruebas <strong>de</strong>colisión frontal (que representaron situaciones <strong>de</strong> acci<strong>de</strong>ntesevero, acci<strong>de</strong>nte leve y no acci<strong>de</strong>nte), colisiónlateral (situaciones <strong>de</strong> acci<strong>de</strong>nte y no acci<strong>de</strong>nte)y colisión trasera (<strong>de</strong> nuevo, situaciones <strong>de</strong> acci<strong>de</strong>ntey no acci<strong>de</strong>nte). <strong>La</strong> clasificación <strong>de</strong> la severidad <strong>de</strong>la colisión viene impuesta por los parámetros queemplea Applus+ IDIADA en los tests EuroNCAP y<strong>JP2011</strong>-371


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 7. Trineo con el prototipo e-NOTIFY instalado antes <strong>de</strong>una prueba <strong>de</strong> <strong>de</strong>tección <strong>de</strong> acci<strong>de</strong>nte.Fig. 8.Primer plano <strong>de</strong>l prototipo montado sobre el trineo.RCAR [14].El sistema <strong>de</strong> prueba incluía un or<strong>de</strong>nador externoal trineo que recibía información periódica (medianteuna red inalámbrica ad hoc) <strong>de</strong> las mediciones registradaspor la OBU para asegurar el correcto funcionamiento<strong>de</strong>l módulo <strong>de</strong> lectura, junto con otroor<strong>de</strong>nador que simulaba la Unidad <strong>de</strong> Control encargada<strong>de</strong> recibir los mensajes <strong>de</strong> alerta. <strong>La</strong> pruebapermitió <strong>de</strong>mostrar que la OBU era capaz <strong>de</strong> <strong>de</strong>tectarcorrectamente tanto la fuerza como la dirección<strong>de</strong>l impacto, así como generar un mensaje <strong>de</strong> avisoa<strong>de</strong>cuado a partir <strong>de</strong> los datos <strong>de</strong> los sensores y enviarlomediante la tecnología UMTS a la Unidad <strong>de</strong>Control en todos los ensayos realizados.V. Conclusiones y Trabajo FuturoEn este artículo se ha presentado el sistema e-NOTIFY, el cual permite mejorar la asistencia <strong>de</strong>los heridos en acci<strong>de</strong>ntes <strong>de</strong> tráfico, mediante la reducción<strong>de</strong>l tiempo <strong>de</strong> respuesta <strong>de</strong> los servicios <strong>de</strong>emergencia y el envío <strong>de</strong> información relevante sobrelas condiciones <strong>de</strong>l siniestro empleando una combinación<strong>de</strong> comunicaciones V2V y V2I. Esta arquitecturasustituye los mecanismos habituales <strong>de</strong> notificación<strong>de</strong> acci<strong>de</strong>nte, basados en testigos presencialesque pue<strong>de</strong>n aportar información incompleta o incorrectaen un tiempo no a<strong>de</strong>cuado. A<strong>de</strong>más, el <strong>de</strong>sarrollo<strong>de</strong> un prototipo <strong>de</strong> costo reducido <strong>de</strong>muestraque es factible la incorporación <strong>de</strong> este sistemaal parque <strong>de</strong> vehículos a gran escala, siempre quese disponga <strong>de</strong> la infraestructura externa a<strong>de</strong>cuada(RSUs, servidores <strong>de</strong>dicados para el tratamiento <strong>de</strong>los mensajes <strong>de</strong> aviso, y bases <strong>de</strong> datos con informaciónsuficiente sobre acci<strong>de</strong>ntes <strong>de</strong> tráfico y procedimientos<strong>de</strong> actuación ante siniestros <strong>de</strong> esta naturaleza).Como trabajo futuro se <strong>de</strong>sarrollará una nuevaversión <strong>de</strong>l sistema utilizando el estándar 802.11p.A<strong>de</strong>más, se preten<strong>de</strong> realizar un <strong>de</strong>spliegue <strong>de</strong>l sistemaen un entorno real con las OBUs instaladas enlos vehículos, para comprobar el comportamiento <strong>de</strong>lsistema con nodos en movimiento a gran<strong>de</strong>s velocida<strong>de</strong>s.Agra<strong>de</strong>cimientosEl presente trabajo ha sido financiado parcialmentepor el Ministerio <strong>de</strong> Ciencia e Innovación mediantela Ayuda TIN2008-06441-C02-01, y por laDiputación General <strong>de</strong> Aragón mediante la Ayuda“Subvenciones <strong>de</strong>stinadas a la formación y contratación<strong>de</strong> personal investigador”.Referencias[1] Dirección General <strong>de</strong> Tráfico (DGT), “<strong>La</strong>sprincipales cifras <strong>de</strong> la siniestralidad vial.España 2009,” 2009, Disponible en:http://www.dgt.es/portal/es/seguridad vial/estadistica.[2] H. Hartenstein and K.P. <strong>La</strong>berteaux, “A tutorial surveyon vehicular ad hoc networks,” Communications Magazine,IEEE, vol. 46, no. 6, pp. 164 –171, june 2008.[3] Hyunseo Oh, Chungil Yae, Donghyon Ahn, and HanbergCho, “5.8 GHz DSRC packet communication system forITS services,” in Vehicular Technology Conference, 1999.VTC 1999 - Fall. IEEE VTS 50th, 1999, vol. 4, pp. 2223–2227 vol.4.[4] Task Group p, “IEEE P802.11p: Wireless access in vehicularenvironments (WAVE),” IEEE Computer Society,2006.[5] Miao Chong, Ajith Abraham, and Marcin Paprzycki,“Traffic Acci<strong>de</strong>nt Analysis Using Machine LearningParadigms,” Informatica, vol. 29, pp. 89–98, 2005.[6] AsusTek Computer Inc., “ASUS EeePC 901 Review,” 2011, Disponible en:http://www.asus.com/Eee/Eee PC/Eee PC 901.[7] Qstarz International Co., “Qstarz BT-Q818XT Bluetooth GPS: Features andSpecification,” 2011, Disponible en:http://www.qstarz.com/Products/GPS%20Products/BT-Q818XT-F.htm.[8] “MBED NXP LPC1768: Información <strong>de</strong> referencia,”2011, Disponible en: http://mbed.org/nxp/lpc1768.[9] Kenneth B. Hornfeck, “A Customizable Socially InteractiveRobot with Wireless Health Monitoring Capability,”M.S. thesis, Case Western Reserve University, Cleveland,OH, USA, 2011.[10] Applus+ IDIADA: Instituto <strong>de</strong> Investigación Avanzada<strong>de</strong>l Automóvil, “Información y recursos,” 2011,Disponible en: http://www.idiada.es.[11] F.J. Martinez, C.-K. Toh, J.-C. Cano, C.T. Calafate, andP. Manzoni, “Emergency services in future intelligenttransportation systems based on vehicular communicationnetworks,” Intelligent Transportation Systems Magazine,IEEE, vol. 2, no. 2, pp. 6 –20, summer 2010.[12] “Google Maps API Family,” 2011, Disponible en:http://co<strong>de</strong>.google.com/apis/maps.[13] EuroNCAP (European New Car AssessmentProgramme), “Procedimientos <strong>de</strong> evaluacióny resultados <strong>de</strong> tests,” 2011, Disponible en:http://www.euroncap.com/testprocedures.aspx.[14] RCAR, the Research Council for Automobile Repairs,“Guías <strong>de</strong> diseño e información para fabricantes,” 2011,Disponible en: http://www.rcar.org.<strong>JP2011</strong>-372


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Hierarchical Analysis of ResilienceBenchmarking Results Using LSP:Ad Hoc Networks As a Case StudyJesús Friginal, Juan-Carlos Ruiz, David <strong>de</strong> Andrés and Pedro Gil 1Abstract— The practical exploitation of ad hoc networkingapproaches in real-life products, such as vehicularad hoc networks and sensor networks, requiresthe <strong>de</strong>finition of benchmarking techniques to gui<strong>de</strong>the selection of suitable routing protocols which fitin each particular context of use. However, experienceshows that such selection process may requirethe analysis of a wi<strong>de</strong> amount of different results,leading the benchmark user to error-prone interpretations.This paper proposes the use of the Logic Scoreof Preferences (LSP) technique to reduce the complexityof the analysis process. LSP enables the systematisationof measures aggregation and establishesa hierarchical approach to their analysis. Althoughthe approach is general and applicable to many differenttypes of systems, it will be illustrated in thiscontribution through a case study where different implementationsof an ad hoc routing protocol are consi<strong>de</strong>redas eligible for a particular application.Keywords— Logic Score of Preferences, Resiliencebenchmarking, Ad hoc networksI. IntroductionRESILIENCE benchmarks are well-specified procedureswhich enrich the notion of traditionalperformance benchmarking to enable the objectiveevaluation, comparison and selection of componentsand systems in the presence of (acci<strong>de</strong>ntal and malicious)faults. This increases the complexity of conventionalbenchmarks. In<strong>de</strong>ed, in addition to thedifferent consi<strong>de</strong>red benchmark targets, the workloadrequired to exercise the system, and the performancemeasures <strong>de</strong>fined to characterise the system’sbehaviour, it is also necessary to establish the set offaults that may impact the system regular behaviourduring operation. The notion of faultload appears inthis context. It reflects the faulty conditions thatmight affect the operation of the system, and theset of measures to characterise the system reactionto consi<strong>de</strong>red faults in terms of <strong>de</strong>pendability andsecurity [1].From a practical viewpoint, this gives rise to someserious challenges in the analysis of the benchmarkoutputs. The problem appears not only when thecombination of the aforementioned aspects lead toan explosion of results, but also when performing ahierarchical analysis requiring the aggregation of aheterogeneous set of different types of measures likethose related to performance, resilience, consumptionand cost. The complexity associated to thesechallenges usually lead to an error-prone interpretationof the benchmark results and restricts the useful-1 STF-ITACA, Universitat Politècnica <strong>de</strong> València, e-mail:{jefrilo, jcruizg, ddandres, pgil}@disca.upv.esness of such result for benchmark users with limitedskills in resilience aspects. In<strong>de</strong>pen<strong>de</strong>ntly from theconsi<strong>de</strong>red benchmark target, this problem affectsthe resilience benchmarking of any type of system,ranging from, e.g., databases to VLSI systems.Measures aggregation is a valuable approach toease the analysis of benchmarked systems or components.The goal of measures aggregation is notreplacing the set of measures obtained during benchmarking,but complementing them with a singleglobal score which gui<strong>de</strong>s and eases the <strong>de</strong>cision makingof system evaluators. However, although the notionof measures aggregation is well-known and appliedin the community of resilience benchmarking, itis surprising that nowadays there is still a lack of unifiedcriteria when addressing the aggregation of measuresand their subsequent analysis. Accordingly, aspectssuch as how to systematically aggregate suchmeasures to capture information of the overall systemand how to ensure the consistency of interpretationsbetween fine- and coarse-grained measures, arestill open questions requiring further research.In this paper, the aforementioned problems arestudied within the scope of ad hoc networks. Adhoc networks are dynamic self-managed wireless networksma<strong>de</strong> of no<strong>de</strong>s which collaborate to maintainnetwork connectivity without requiring any centralisedinfrastructure. According to these promisingproperties, ad hoc networks are increasingly used asan alternative to provi<strong>de</strong> quick and low-cost communications.Nowadays, one can find several examplesof ad hoc networks in our daily lives [2] [3]. Some ofthe most representative examples are Wireless SensorNetworks (WSN) to monitor information of themedia like temperature or humidity; Mobile Ad HocNetworks (MANET) to establish multi-hop communicationsbetween mobile targets like people or vehicles;and Wireless Mesh Networks (WMN), to provi<strong>de</strong>low-cost Internet connection to isolated areas.Routing protocols are essential elements for theoperation of ad hoc networks. In or<strong>de</strong>r to establishmulti-hop communications, routing protocols enableany pair of no<strong>de</strong>s in the network to connect throughintermediate ones acting as routers. Given their criticalrole, the main strengths of such protocols maybecome their main weaknesses since any expositionto acci<strong>de</strong>ntal or malicious faults (or attacks) couldcompromise the whole behaviour of the network.In our prior work, we took an initial step towardsthe analysis of aggregated measures propos-<strong>JP2011</strong>-373


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011ing a qualitative approach to obtain a global visionof the impact of faults on ad hoc routing protocols,the core components of ad hoc networks [4]. In thispaper we take a step beyond to ease the hierarchicalanalysis of resilience benchmarking results by meansof a mathematical-based technique called Logic Scoreof Preferences (LSP). Introduced by Dujmović in [5],LSP is a fuzzy-logic-based approach that computesthe global score of a component through measuresaggregation, easing the hierarchical analysis of thesystem characteristics.Although this technique has been successfully usedfor the quantitative quality evaluation of a wi<strong>de</strong> varietyof software engineering products (ranging fromsearch engines to web browsers), this is the first attempt,to the best of our knowledge, of applying thistechnique in the domain of resilience benchmarkingand ad hoc networks.The rest of this paper is structured as follows. SectionII reports the different alternatives for measuresaggregation and analysis. Secion III introduces theLSP technique. Section IV applies the LSP techniqueto analyse and interpret the results obtainedfrom a case study where different ad hoc routing protocolsare benchmarked. Finally Section V presentsconclusions.II. Measures-Aggregation ApproachesThe literature offers different graphic and analyticalternatives to synthesise the measures obtained duringthe evaluation of a target system.Kiviat or radar diagrams [6] are a graphical toolwhich represent the results of the benchmark inan easy-to-interpret footprint. Kiviat diagrams canshow different measures using only one diagram and,although some training is required, the comparisonof different diagrams is fairly simple. The scalabilityof Kiviat diagrams enables the representation ofup to tens of measures. However, managing such ahuge amount of information may make difficult theinterpretation and analysis of results.The problem previously stated is solved in [6]throughout the use of an analytical technique namedthe figure of merit, which imposing certain restrictionsto the graph axes, synthesises all the measuresinto a unique value related to the footprint shape.However, the problem associated to this solution, asit happens with most techniques using the mean orthe median, is that valuable information could behid<strong>de</strong>n behind a unique number, and consequently,the comparison between protocols could result quitevague [7].Other approaches, like the presented in [8], characterisethe level of goodness of the measures accordingto their ability to fit with a particular statisticaldistribution. Nevertheless, this approach presentstwo main drawbacks. First, it assumes that a measurefollows the same distribution for all the systems,which may not be true <strong>de</strong>pending on the context ofuse. And second, to un<strong>de</strong>rstand this type of characterisation,it is necessary to un<strong>de</strong>rstand the assumedstatistical mo<strong>de</strong>l, which is not straightforward.Finally, other authors, like Al-Sbou [9], proposethe use of custom formulas for the aggregation ofmeasures obtaining a single score which characterisesthe behaviour of the system. However, these typesof formula <strong>de</strong>finition is based on heuristics and lacksformal foundation and validation.In sum, these methodologies lack the ability of aggregatingmeasures into a meaningful result that: i)is easy to explain and interpret; ii) is representativeof real systems and allows their comparison and ranking,and iii) captures enough information to enablethe hierarchical analysis of measures from coarse tofine-grained measures (and vice-versa).III. Logic Score of PreferencesThe LSP technique computes the global score of asystem through the recursive <strong>de</strong>composition of theircharacteristics into subcharacteristics and so on, untilobtaining quantifiable attributes (or measures).However, what makes it interesting with respect toto the rest of approaches presented in Section II accordinga resilience benchmarking viewpoint, is itscapability to navigate from the fine-grained measuresto the coarse-grained scores, without losing the numericalviewpoint of results. Thus, keeping the consistencyin the interpretation and analysis of resultsin<strong>de</strong>pen<strong>de</strong>ntly from the viewpoint (fine or coarse) acquiredby the benchmark user.In general terms, LSP computes the global score(S) of a system using Formula 1.S = (k∑w i s r i ) 1 r /i=1k∑w i = 1 (1)i=1In this formula, each s i represents an elementaryscore (referred to as elementary preference) relatedto each (sub)characteristic of the targeted system.Different criterion functions specify how to quantitativelyevaluate each attribute, i.e., they establishan equivalence between the attribute value and thesystem quality requirements. To cope with this goal,the value of the attribute is scored within a 0-to-100scale, which results in an elementary preference scores i that can be interpreted as the <strong>de</strong>gree of satisfactionof an attribute a i with respect to the qualityrequirements specified by the benchmark performerfor such attribute. Since all the attributes are scoredaccording to the same scale, resulting elementarypreferences are directly comparable. Such equivalencecan be mapped to a discrete function, thusestablishing different quality levels, or to a continuousone. Additionally, as far as the k elementarypreferences that compound the aggregation block <strong>de</strong>finedby each characteristic may not have the sameimportance, a weight w i , illustrating such influence,must be assigned to each elementary preference. Inthis line, it is also necessary to <strong>de</strong>fine the <strong>de</strong>gree ofmandatoriness that must be fulfilled for each aggregationblock. The power r, <strong>de</strong>scribed in <strong>de</strong>tail in[5], represents one logic operator in charge of <strong>de</strong>finingthe type of relationship (from orness to andness)<strong>JP2011</strong>-374


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011required for the different elementary scores withinthe same aggregation block. In [5], the author <strong>de</strong>finesup to 20 different logic operators which <strong>de</strong>scribea mandatoriness------------------------------------------------- Operation Symbolr2r3r4r5gradation among the requirementsof the system. Such gradation ranges from the fullconjunction (logic AND) which illustrates the simultaneityamong all the requirements, to the full disjunction(logic OR) which represents the notion ofreplaceability,SQUAREMEAN DISJUNCTION D+infty+infty+infty+inftyWEAKQD(-) WEAKQD(+) MEDIUMQD STRONGQD(-)D+-5.8026.6757.3167.819STRONGQD(+)D++20.63024.30027.11030.090 DA3.9294.4504.8255.111 D+9.52111.09512.27013.235where meeting just one requirement isenoughARITHMETICMEANA1.0001.0001.0001.000D--1.4491.5191.5651.596 D-+2.7923.1013.3183.479 SQU2.000 D-2.0182.1872.3022.384(see Figure 1).MEDIUMQC STRONGQC(-)C+--1.655-1.550-1.455-1.380 HARMONICMEANHAR-1.000 WEAKQC(+) GEOMETRICMEANGEO0.000 WEAKQC(-) C-+-0.148-0.208-0.235-0.251 CA-0.720-0.732-0.721-0.707 C--0.6190.5730.5460.526STRONGQC(+)C++-9.060-7.639-6.689-6.013 C+-3.510-3.114-2.823-2.606 C-0.2610.1920.1530.129CONJUNCTION C-infty-infty-infty-inftyFig. 1. Aggregation operators proposed by Dujmović, and rvalue for 2, 3, 4 and 5 inputsOnce all the intermediate scores have been computeduntil obtaining a global score, a coarse-grainedanalysis of each target can be performed. Then, theanalysis can be progressively refined using the availableintermediate scores until consi<strong>de</strong>ring the originalbenchmarking results. The benefit of using LSP relieson the fact that it systematises the way in whichscores are obtained from measures and naturally establishesa hierarchical approach for their analysis.The main concepts of LSP are illustrated throughoutFigure 2.Attributes(Benchmark measures)Fig. 2.AggregationAnalysisW·SW·SW·SW·SMeasures are aggregatedattending to a relationshipestrablished by thebenchmark performerW·SW·SS: Intermediate scoresRepresentation of the LSP techniqueIV. Case StudyAs already stated, LSP is a technique that can beapplied to any type of system or component. TheGlobal Scorecase study proposed in this paper emulates the <strong>de</strong>ploymentof a Wireless Mesh Network (WMN) [10],one of the most exten<strong>de</strong>d types of ad hoc network.A. Experimental Set-upOur <strong>de</strong>ployment consisted of 16 wireless no<strong>de</strong>s (includinglaptops and routers). As previously stated,benchmark users must carefully select the most suitablerouting protocol to provi<strong>de</strong> quality communicationswithout <strong>de</strong>lays nor interruptions. olsrd, <strong>de</strong>velopedby the most active and wi<strong>de</strong>r community<strong>de</strong>voted to the <strong>de</strong>velopment of open-source routingprotocols (www.olsr.org), is the most exten<strong>de</strong>d implementationof the popular Optimized Link StateRouting (OLSR) protocol. Accordingly, three differentversions of olsrd, using the same configuration,have been selected as benchmarks targets: v.0.4.10(released in 2006), v.0.5.6 (released in 2008) and currentv.0.6.0 (released in 2010).The applicative traffic addressed to exercise thenetwork was <strong>de</strong>fined in terms of synthetic UDP ConstantBit Rate (CBR) data flows of 200 Kbps, similarto the rates observed in daily scenarios [11].In or<strong>de</strong>r to recreate some of the most importantproblems in the domain of WMNs [10], we selected asubset of 5 of the most harmful faults (both acci<strong>de</strong>ntaland malicious faults or attacks), according to ourprior investigation [4] (see Table I), to be injectedwhile running the workload.TABLE IFaults consi<strong>de</strong>red during the experimentationFault Type OriginAmbient noise (A) Acci<strong>de</strong>ntal NaturalSelective forwarding attack (S) Malicious Human-ma<strong>de</strong>Jellyfish attack (J) Malicious Human-ma<strong>de</strong>Tampering attack (T) Malicious Human-ma<strong>de</strong>Flooding attack (F) Malicious Human-ma<strong>de</strong>B. Aggregation of MeasuresOnce the benchmark experimental conditions havebeen specified, it is necessary to <strong>de</strong>fine the differentmeasures that will be used to assess the quality of theconsi<strong>de</strong>red benchmark target. Conversely to othermeasures-aggregation techniques which are just appliedonce the final measures have been obtained, theLSP technique may assist the benchmark performerto <strong>de</strong>fine a comprehensive hierarchical mo<strong>de</strong>l of measuresapplying a series of refinements. The goal ofthis process is to characterise the quality of the systemthrough a complete and not redundant set ofelemental attributes or variables (a 1 to a n ). This set<strong>de</strong>fines a block and can contain a different amount ofattributes. This blocks composition continues groupingdifferent characteristics until the global score ofthe system is computed.B.1 Measures SelectionApplying this measures-aggregation strategy in anad hoc network involves characterising this particularsystem through its different characteristics. For<strong>JP2011</strong>-375


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011the purpose of this case study we have consi<strong>de</strong>redperformance, resilience and consumption. In addition,different attributes have been i<strong>de</strong>ntified for eachcharacteristic (as <strong>de</strong>picted in Figure 3) in or<strong>de</strong>r to refinethe proposed mo<strong>de</strong>l.Fig. 3.Ad hoc network1. Performance1.1. a 1 : Packet loss (%)1.2. a 2 : Delay (ms)2. Resilience2.1. a 3 : Availability (%)2.2. a 4 : Integrity (%)3. Consumption3.1.a 5 : Energy (J)LSP hierarchy illustrating the case studyResulting attributes will be the fine-grained measureswe are able to obtain throughout our benchmarkingexperiments. The <strong>de</strong>scription of such measuresis listed in Table II.A <strong>de</strong>tailed <strong>de</strong>scription of the testbed used to setupall the no<strong>de</strong>s, execute the workload, inject the selecteddisturbances, and monitor the system to obtainthe required measurements, may be found at[12].TABLE IISelected measuresPerformance DescriptionPacket loss Avg. % of packets that were lost in a communicationroute. The lower the better.(%)Delay (ms) Avg. time required by a packet to traverse a communicationroute from the source to the <strong>de</strong>stinationno<strong>de</strong>. The lower the better.resilience DescriptionAvailability(%)Avg. % of time the communication route establishedbetween sen<strong>de</strong>r and receiver is ready to beused. The higher the better.Integrity (%) Avg. % of packets whose content has not beenunexpectedly modified. The higher the better.Consumption DescriptionEnergy (J) Avg. energy consumed by a no<strong>de</strong>’s Network InterfaceCard which takes part in a communicationroute. The lower the better.B.2 Fine-grained Experimental ResultsTable III shows the results obtained from experimentation.However, estimating and comparing theimpact of the selected faults on each single measureis a complex task given the lack of criteria to <strong>de</strong>terminethe thresholds which separate the correctfrom the incorrect behaviour of the network in termsof the stated measures. Additionally, it is worthnoting that measures cannot be in<strong>de</strong>pen<strong>de</strong>ntly analysed,since this could lead the evaluator to misleadingconclusions, e.g., although some faults like ambientnoise, and selective forwarding attack may benefitno<strong>de</strong>s by reducing its energy consumption, thiscannot be really consi<strong>de</strong>red a benefit for the network,as such faults affect the final service provi<strong>de</strong>d to theuser. This fact may favour that the more measureswe consi<strong>de</strong>r, the more difficult to obtain an accurateglobal vision of the fault impact on the protocol.TABLE IIIMeasures obtained during experimentationPacket Delay Availabi- Integrity EnergyTarget Fault loss (%) (ms) lity (%) (%) (J)A 27.4 48.2 73.6 100.0 8.2S 39.5 42.0 91.2 100.0 8.0v.0.4.10J 7.6 1086.5 88.7 100.0 10.3T 8.2 39.7 93.1 5.2 10.6F 25.5 62.9 72.1 100.0 15.4A 27.3 55.6 73.4 100.0 8.2S 51.8 55.1 88.6 100.0 7.3v.0.5.6J 9.8 1111.3 88.7 100.0 10.5T 9.9 39.9 90.5 7.7 10.5F 27.1 64.5 71.9 100.0 14.9A 27.1 52.3 72.9 100.0 8.1S 54.1 53.4 89.5 100.0 6.8v.0.6.0J 8.7 1178.8 89.5 100.0 10.9T 9.4 56.5 91.4 7.5 10.6F 26.6 66.6 71.5 100.0 14.6B.3 Definition of the Criterion FunctionsIn or<strong>de</strong>r to simplify the application of LSP in ourcase study we have consi<strong>de</strong>red two generic continuouscriterion functions, one increasing (see Figure4), to compute the elementary score of the-higherthe-bettermeasures such as availability and integrity,and one <strong>de</strong>creasing (see Figure 5), to compute thelower-the-bettermeasures such as packet loss, <strong>de</strong>layand energy consumption.Fig. 4.Fig. 5.s i = c i (a i ) =0,a i X minX max Xi min i100 i , X min ”100,≤Xa i min ia< i i ” X maxia i≥ X max iIncreasing criterion function used in the case studys i = c i (a i ) =100, a i≤X min iX max a100 i i,X max XX min ” a< i ” X maxmin i iii0,a i≥ X max iDecreasing criterion function used in the case studyThese functions are parameterised according tothe bounds (X min and X max ) that <strong>de</strong>limit the qualitythreshold for a given attribute. The increasingcriterion function applies to those measures whosequality increases as their value does. In such function,X min establishes a threshold below which thevalue of the measure is of 0% of quality, while X max<strong>de</strong>fines the threshold from which that value is of100% of quality. The reverse interpretation appliesto the <strong>de</strong>creasing criterion function.In or<strong>de</strong>r to <strong>de</strong>termine the aforementioned thresholds,the evaluator should consi<strong>de</strong>r all the networka 1 (Packet loss) ≥100.50* s 1 c1≤45a 2 (Delay)s o 2 1c2≥40≤4000.50*a 3(Availability)≥550.50* s 3 c3 o≤903 S0.45* sa 4 s 4o 3 , 4 (Resilience)(Integrity) ≥950.50* 2≤99c4a 5 s c5 50.45*(Energy)≥110.10*≤15Fig. 6.s 1 , 2(Performance)(Consumption)Aggregation processComplete LSP mo<strong>de</strong>l applied in our case study<strong>JP2011</strong>-376


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011requirements for an acceptable quality of communications,addressing aspects like the number of users,the communication technology, the context of useand the type of service <strong>de</strong>livered. Depending onsuch aspects, the measures obtained may be interpretedin one way or another. For example, let usconsi<strong>de</strong>r the requirements <strong>de</strong>fined in [13] for a votingapplication addressed to enable lecturers to getfeedback from audience in auditoriums or conventioncentres. Regarding the performance constraintsprovi<strong>de</strong>d by authors, a packet loss lower than 10%(X min = 10%) would represent an excellent qualitywhereas a packet loss of 45% (X max = 45%)would be in the bounds for an acceptable communication.In the case of <strong>de</strong>lay, the common limitsof a medium quality communication [14] range from40ms to 400ms (X min = 40ms and X max = 400msrespectively). As far as measuring availability, integrityand energy consumption was not a requirementin [14], such thresholds are estimated by theauthors of this paper. Let us consi<strong>de</strong>r an acceptableavailability between X min = 75% and X max = 90%(“one nine”) where a downtime of 100 millisecondsper second is good enough for the type of applicationconsi<strong>de</strong>red. Concerning the data integrity, adata corruption affecting more than 1% of packetscan compromise the trustworthiness of a voting application.Accordingly, the thresholds were fixed toX min = 99% and X max = 100%. Finally, regardingthe energy consumption, a previous fault-free experimentationshowed a stationary consumption of10J. In or<strong>de</strong>r to compute the thresholds, we assignedthis value to the minimum threshold (X min = 10J)and consi<strong>de</strong>red that an increase of 50% would beenough in our case to compute the maximum threshold(X max = 15J). Table IV summarises thesethresholds.TABLE VResults obtained from applying LSP techniqueTarget F ault Performance Resilience Consumptionv.0.4.10v.0.5.6v.0.6.0Globalscore perfaultA 71.73 73.85 100.00 75.23S 43.75 100.00 100.00 70.46J 7.15 100.00 100.00 37.85T 99.49 7.15 100.00 37.73F 72.11 71.08 0.00 47.91A 70.28 73.49 100.00 74.38S 6.81 97.98 100.00 36.89J 7.15 98.13 100.00 37.44T 98.42 7.15 100.00 37.50F 69.44 70.70 2.50 55.71A 71.21 72.57 100.00 74.40S 6.88 99.28 100.00 37.28J 7.15 99.28 100.00 37.69T 97.69 7.15 100.00 37.34F 70.51 69.94 10.00 60.09the characteristics consi<strong>de</strong>red in our case study, wehave <strong>de</strong>termined that all of them should be compliantto the thresholds <strong>de</strong>fined. One of the functionswhich fits the best with this requirement is the weakquasi-conjunction (<strong>de</strong>noted as C− according to theLSP notation), represented by r = 0.261 for two inputs.This operator <strong>de</strong>notes 60% of mandatorinesswithin the operators scale proposed by Djumović.C. Hierarchical Analysis of ResultsThe multiple intermediate results obtained whenapplying the LSP technique enable to systematisethe analysis of the benchmarking results at differentlevels. Table V lists the scores that represent thequantitative quality, globally and for each selectedcharacteristic, of the consi<strong>de</strong>red protocol versions inpresence of representative faults.C.1 Analysis per global qualityAccording to these results, the best candidateto be integrated into the final <strong>de</strong>ployment is olsrdv.0.4.10, as it maximises the global score (51.81%),whereas the other two versions present similar(lower) results, 46.62% and 47.47% respectively.C.2 Analysis per characteristicAlternatively, evaluators may be interested in justfocusing on one particular characteristic to evaluatethe quality of the protocols and, in that case, olsrdv.0.4.10 obtains the best scores for performance(46.24%), olsrd v.0.6.0 is the best option with respectto consumption (66.43%) and there is a tripledraw (around 32%) for resilience.C.3 Analysis per fault typeIf we focused on the behaviour of each protocolin presence of a particular fault, olsrd v.0.4.10 isstill the best option when <strong>de</strong>aling with ambient noise,and selective forward attacks, but versions 0.5.6 and0.6.0 (in no particular or<strong>de</strong>r) take the lead when subjectedto tampering attacks. Regarding the impactof flooding attacks, version 0.6.0 presented the bestresults. Jellyfish attacks impact all the consi<strong>de</strong>redprotocols in the same way and no one could be takenas the best option to face that particular fault.Globalscore51.8146.6247.47TABLE IVExperimental quality thresholds consi<strong>de</strong>red in theelementary criterion functionsMeasureCriterion X min X maxfunctionPacket loss (a 1) Decreasing 10% 45%Delay (a 2) Decreasing 40ms 400msAvailability (a 3) Increasing 75% 90%Integrity (a 4) Increasing 99% 100%Energy consumption (a 5) Decreasing 10J 15JB.4 Aggregation of PreferencesIn or<strong>de</strong>r to simplify our case study, all the attributes(a i ) have been consi<strong>de</strong>red equally significant,thus performing a fair assignment of weights. However, as far as a low consumption is not usuallya mandatory requirement in fixed networks suchas WMNs, we have reduced its weight (0.1 out of 1)with respect to performance (0.45 out of 1) and resilience(0.45 out of 1), which are more important inthis case. If we had consi<strong>de</strong>red e.g., a WSN, wherethe reduction of battery consumption is a must, thenthe weight assigned would be much more significant.Regarding the aggregation relationship between<strong>JP2011</strong>-377


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011C.4 SummaryFollowing this analysis, the quality of olsrd v.0.5.6and v.0.6.0 do not really differ in presence of the consi<strong>de</strong>redfaults, and they could be used indistinctlybut when the network is perturbed by flooding attacksor consumption is the main concerns of theevaluator, where v.0.6.0 reacts better. Otherwise,olsrd v.0.4.10 is the best candidate to meet the requirementsestablished for this case study.V. ConclusionsTraditional analysis of results performed duringthe resilience benchmarking of components and systemscan be feasible for those cases where a reducedset of measures is consi<strong>de</strong>red. However, as far asthe amount of measures increases, the analysis complexityrises as well. This is an important issue thatcan compromise the analysis thoroughness, <strong>de</strong>spitethe rest of the benchmark process has been correctlycarried out.This paper <strong>de</strong>scribes a practical approach to systematisethe analysis of resilience benchmarkingwith a well-known technique in the domain of softwareengineering: the Logic Score of Preferences(LSP). Conversely to other measures-aggregationtechniques, LSP plays an active role during thebenchmark <strong>de</strong>finition. It addresses how to a<strong>de</strong>quatelyselect and gather the types of measures torepresent the system, thus assisting the benchmarkuser to minimise errors during the results interpretation.In this line of reasoning, the case study selectedto illustrate the applicability of this technique hasbeen been focused on the promising domain of adhoc networks, allowing the rea<strong>de</strong>r to un<strong>de</strong>rstand thatthe steps <strong>de</strong>scribed in the paper can be <strong>de</strong>signed tofit different applications. The LSP technique resultsa very useful approach to overcome the problem ofmeasures scalability and eases a more concise visionof the system. Nevertheless, regarding previous results,the application of this technique requires thea<strong>de</strong>quate <strong>de</strong>finition of the quality thresholds (X minand X max ) for each criterion functions, the weight(w i ) assigned to each score within the same aggregationblock, and the operator type (o i ) in charge of themeasures aggregation. All these aspects highly <strong>de</strong>pendon the applicative context the ad hoc networksis conceived to be <strong>de</strong>ployed.Consi<strong>de</strong>ring the points previously <strong>de</strong>tailed is a firststep towards the characterisation of the wi<strong>de</strong> amountof applicative domains ad hoc networks are presentin, such as Wireless/Un<strong>de</strong>rground and SubaquaticSensor Networks, Wireless Mesh Networks and Mobileand Vehicular Ad hoc Networks, among others.We argue that this type of approaches can be usefulnot only to quantify the impact of faults with respectto the actual application context (where componentsand systems are planned to be <strong>de</strong>ployed),but for the comparison and selection of those targetswhich best fit the system requirements. In the futurework, we ambition to provi<strong>de</strong> evaluators differenttemplates with precomputed parameters that theycould customise for their particular <strong>de</strong>ployments tosemi-automate the application of LSP for the quantitativebenchmarking of ad hoc routing protocols.AcknowledgementsThis work has been fun<strong>de</strong>d by the Spanish Ministryof Science and Innovation through the SEMSE-CAP Project (TIN-2009-13825).References[1] Karama Kanoun and Lisa Spainhower, DependabilityBenchmarking for Computer Systems, Wiley and IEEEComputer Society Press, 2008.[2] Hung-Chin Jang, Yao-Nan Lien, and Tzu-Chieh Tsai,“Rescue information system for earthquake disastersbased on manet emergency communication platform,” inInternational Conference on Wireless Communicationsand Mobile Computing (IWCMC), 2009, pp. 623–627.[3] P. Serrano et al., “A CARMEN mesh experience: <strong>de</strong>ploymentand results,” in 10th IEEE WoWMoM, 2009,pp. 1–8.[4] Jesus Friginal, David <strong>de</strong> Andres, Juan-Carlos Ruiz, andPedro Gil, “On selecting representative faultloads togui<strong>de</strong> the evaluation of ad hoc networks,” in Fifth<strong>La</strong>tin American Symposium on Dependable Computing(LADC), 2011.[5] J.J. Dujmovic and R. Elnicki, A DMS Cost/Benefit DecisionMo<strong>de</strong>l: Mathematical Mo<strong>de</strong>ls for Data ManagementSystem Evaluation, Comparison, and Selection, NationalBureau of Standards, Washington D.C., No. GCR 82-374.NTIS No. PB 82-170150, 1982.[6] M. F. Morris, “Kiviat graphs: conventions and figures ofmerit.,” ACM/Sigmetrics Performance Evaluation Review,vol. 3, no. 3, pp. 2–8, 1974.[7] David <strong>de</strong> Andres, “Using <strong>de</strong>pendability, performance,area and energy consumption experimental measures tobenchmark ip cores,” in Forth <strong>La</strong>tin American Symposiumon Dependable Computing (LADC), 2009.[8] Giulio Concas, Michele Marchesi, Sandro Pinna, andNicola Serra, “Power-laws in a large object-oriented softwaresystem,” IEEE Trans. Softw. Eng., vol. 33, pp.687–708, October 2007.[9] Yazeed A. Al-Sbou, Reza Saatchi, Samir Al-Khayatt,Rebecca Strachan, Moussa Ayyash, and MohammadSaraireh, “A novel quality of service assessment of multimediatraffic over wireless ad hoc networks,” in Proceedingsof the 2008 The Second International Conferenceon Next Generation Mobile Applications, Services, andTechnologies, 2008, pp. 479–484.[10] I. F. Akyildiz and others, “Wireless mesh networks: asurvey,” IEEE Radio Communications, vol. 43, pp. S23–S30, 2005.[11] “Hillsdale WMN,” Online: http://dashboard.openmesh.com/overview2.php?id=Hillsdale,2010.[12] David Andrés, Jesús Friginal, Juan-Carlos Ruiz, andPedro Gil, “An attack injection approach to evaluatethe robustness of ad hoc networks,” in IEEE PacificRim International Symposium on Dependable Computing(PRDC), 2009, pp. 228–233.[13] Jasmeet Chhabra et al., “Real-world experiences withan interactive ad hoc sensor network,” in Proceedings ofthe 2002 International Conference on Parallel ProcessingWorkshops, 2002, pp. 143–151.[14] Weiquan Lu, Winston K. G. Seah, Edwin W. C. Peh,and Yu Ge, “Communications support for disaster recoveryoperations using hybrid mobile ad-hoc networks,”in Proceedings of the 32nd IEEE Conference on LocalComputer Networks, 2007, pp. 763–770.<strong>JP2011</strong>-378


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Protocolo para entrega able <strong>de</strong> contenidos enre<strong>de</strong>s inalámbricas basado en codicaciónRaptorMiguel Báguena, Carlos T. Calafate, Juan-Carlos Cano, Pietro Manzoni 1Resumen De sobra son conocidos los problemas alos que se tienen que enfrentar los protocolos <strong>de</strong> comunicaciónen las re<strong>de</strong>s inalámbricas: pérdida <strong>de</strong> paquetes,mayores retardos, entrega <strong>de</strong> los paquetes fuera <strong>de</strong>or<strong>de</strong>n, etc. También es <strong>de</strong> dominio público las diculta<strong>de</strong>sque tiene TCP para hacer frente a este tipo <strong>de</strong>problemas. Para evitar estos inconvenientes muchosautores han propuesto diversos protocolos basados entécnicas <strong>de</strong> corrección <strong>de</strong> errores, como pue<strong>de</strong> ser lacorrección <strong>de</strong> errores hacia <strong>de</strong>lante (Forward Errorcorrection - FEC), pudiendo recuperar la informacióntransmitida incluso en condiciones <strong>de</strong> pérdida masiva<strong>de</strong> paquetes. En este trabajo se propone un protocolo<strong>de</strong> comunicación que usa una codicación basadaen códigos Raptor a nivel <strong>de</strong> aplicación junto con uncontrol <strong>de</strong> ujo extremo-a-extremo para conseguir unprotocolo inmune a los efectos <strong>de</strong>rivados <strong>de</strong>l uso <strong>de</strong>un control <strong>de</strong> ujo basado en ventana <strong>de</strong>slizante enentornos inalámbricos. El protocolo propuesto se havalidado con un conjunto <strong>de</strong> pruebas estándar que <strong>de</strong>muestranla eciencia <strong>de</strong>l protocolo en este tipo <strong>de</strong>entornos.Palabras clave: re<strong>de</strong>s inalámbricas; códigos Raptor;evaluación <strong>de</strong>l rendimiento.I. IntroducciónLAS tecnologías inalámbricas se están convirtiendoen las gran<strong>de</strong>s protagonistas en el área <strong>de</strong>las comunicaciones actuales. Esto es <strong>de</strong>bido al grannúmero <strong>de</strong> ventajas que las comunicaciones inalámbricasofrecen al usuario, como pue<strong>de</strong>n ser una completamovilidad o una ubicuidad <strong>de</strong> conexión, entreotros. Sin embargo, este nuevo entorno ofreceunas características propias a las que las solucionespropuestas <strong>de</strong>ben adaptarse para conseguir sacarle elmáximo partido. Estas características son una menorcapacidad <strong>de</strong>l canal, un mayor retardo en la entrega<strong>de</strong> paquetes y, en especial, una mayor tasa <strong>de</strong> pérdida<strong>de</strong> paquetes durante las transmisiones.<strong>La</strong> pérdida <strong>de</strong> paquetes es una característica claveya que inuye especialmente en el rendimiento <strong>de</strong>lprotocolo TCP, que está siendo utilizado actualmentecomo protocolo <strong>de</strong> transporte en las comunicacionesinalámbricas. Se ha comprobado que laspérdidas normales producidas en el canal pue<strong>de</strong>n serconfundidas con un síntoma <strong>de</strong> congestión, lo que reducela productividad alcanzada por TCP. Por eso sehan realizado muchos esfuerzos que intentan resolverlos problemas que la pérdida <strong>de</strong> paquetes ocasionaa las comunicaciones actuales, <strong>de</strong>stacándose dos estrategiasprincipales.1 Departamento <strong>de</strong> Ingeniería <strong>de</strong> Sistemas y Computadores,Universitat Politècnica <strong>de</strong> València, Camino <strong>de</strong> VeraS/N, 46022, España, mibaal@upvnet.upv.es, {calafate, jucano,pmanzoni}@disca.upv.es<strong>La</strong> primera <strong>de</strong> las estrategias utilizadas para resolverel problema <strong>de</strong> la pérdida <strong>de</strong> paquetes es eluso <strong>de</strong> técnicas <strong>de</strong> retransmisión. Sin embargo, se hacomprobado que la retransmisión provoca problemas<strong>de</strong> escalabilidad <strong>de</strong>rivados <strong>de</strong> los retardos producidospor las retransmisiones. <strong>La</strong> segunda <strong>de</strong> estas estrategias,que es la utiliza el trabajo que presentamos, esel uso <strong>de</strong> técnicas <strong>de</strong> corrección <strong>de</strong> errores.El uso <strong>de</strong> técnicas <strong>de</strong> corrección <strong>de</strong> errores en lugar<strong>de</strong> técnicas <strong>de</strong> retransmisión nos permite establecerun canal tolerante a pérdidas, con lo que se pue<strong>de</strong> resolverel problema <strong>de</strong> la pérdida <strong>de</strong> paquetes evitandola baja escalabilidad <strong>de</strong> las técnicas <strong>de</strong> retransmisión.A<strong>de</strong>más, usando técnicas AL-FEC (Application <strong>La</strong>yerForward Error Correction) po<strong>de</strong>mos establecer elcanal tolerante a pérdidas a nivel <strong>de</strong> aplicación, ocultandola estrategia al resto <strong>de</strong> capas, como pue<strong>de</strong>nser IP o transporte.En este trabajo se propone un novedoso sistema <strong>de</strong>comunicación basado en técnicas AL-FEC que ofreceuna transmisión <strong>de</strong> datos eciente sobre re<strong>de</strong>s inalámbricas.Nuestra solución usa técnicas <strong>de</strong> extremoa-extremopara estimar el ancho <strong>de</strong> banda y establecerasí la tasa <strong>de</strong> transmisión. A<strong>de</strong>más, evita la retransmisión<strong>de</strong> paquetes haciendo uso <strong>de</strong> un sistema<strong>de</strong> corrección <strong>de</strong> errores FEC, los códigos Raptor [1],reconociendo bloques transmitidos correctamente enlugar <strong>de</strong> los paquetes individualmente, ahorrando asíretardos, esperas y ancho <strong>de</strong> banda en el canal <strong>de</strong> retorno.El documento se estructura <strong>de</strong> la siguiente manera:en la siguiente sección se señalan algunos <strong>de</strong> los trabajosque también han abordado este problema. Enla sección II se pasa a <strong>de</strong>scribir la tecnología Raptorusada en la codicación. <strong>La</strong> sección IV <strong>de</strong>scribe en<strong>de</strong>talle el protocolo presentado. El conjunto <strong>de</strong> pruebasrealizado y los resultados obtenidos se presentanen la sección V. Por último, la sección VI presentalas conclusiones <strong>de</strong>l trabajo.II. Trabajos previos<strong>La</strong> <strong>de</strong>gradación <strong>de</strong> prestaciones <strong>de</strong> TCP sobre re<strong>de</strong>sinalámbricas ha sido un tema estudiado en profundidady se han presentado diferentes propuestaspara intentar mejorar la productividad alcanzadaen este medio. Diferentes estudios [2], [3] realizanpropuestas orientadas a solucionar los problemas<strong>de</strong> transmisión sobre re<strong>de</strong>s inalámbricas. Entreellas se pue<strong>de</strong>n establecer cuatro grupos principales:soluciones a nivel <strong>de</strong> enlace, soluciones para la trans-<strong>JP2011</strong>-379


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011misión <strong>de</strong> datos sobre re<strong>de</strong>s con una parte cableaday una parte inalambrica, soluciones que modican elprotocolo TCP y soluciones para re<strong>de</strong>s ad-hoc.Dentro <strong>de</strong>l primer grupo, la primera <strong>de</strong> las solucionesque encontramos es el protocolo AIRMAIL[4], que combina las retransmisiones y la corrección<strong>de</strong> errores. También aparece el protocolo snoop [5],[6], que presenta un módulo que analizando la transmisiónes capaz <strong>de</strong> <strong>de</strong>tectar pérdidas. Otra es Tulip[7], que acelera la retransmisión a nivel <strong>de</strong> MAC.Para terminar citaremos otras que proponen retrasarel envío <strong>de</strong> los reconocimiento duplicados [8] o un sistema<strong>de</strong> retransmisión able a nivel <strong>de</strong> enlace [9].En el segundo grupo es importante la parte <strong>de</strong> laspropuestas que afecta al tramo inalámbrico <strong>de</strong> la red.Por ejemplo, Mobile TCP [10] usa una estructura <strong>de</strong>tres capas que encamina, reconecta y controla la tasa<strong>de</strong> transmisión. Wireless-TCP [11] evita el uso <strong>de</strong>ventanas como control <strong>de</strong> ujo. A<strong>de</strong>más se han presentadosistemas que usan reconocimientos múltiples[12] que pue<strong>de</strong>n ser completos o parciales.El tercer grupo incluye modicaciones al protocoloTCP. TCP SACK[13] informa <strong>de</strong> manera precisa alemisor <strong>de</strong> los paquetes perdidos. SMART [14] combinalas aproximaciones Go-back-n y Selective ACK.Fast Retransmission [15] se centra en las comunicacionesmóviles. TCP-Santa Cruz [16] calcula la congestión<strong>de</strong>l canal usando los tiempos <strong>de</strong> llegada yenvío <strong>de</strong> los paquetes. A<strong>de</strong>más otras técnicas noticanexplicitamente la congestión [17] mediante el bitCE <strong>de</strong> la cabecera IP o usan tipos <strong>de</strong> paquetes ICMPadicionales [18] para reiniciar un temporizador o retransmitirun paquete.El último grupo se centra en las re<strong>de</strong>s ad-hoc.TCP-F [19] usa los paquetes RFN y RNN para <strong>de</strong>tenere iniciar la transmisión <strong>de</strong> paquetes perdidos.TCP ad-hoc [20] <strong>de</strong>ne diferentes estados en el procesoemisor.Nuestra propuesta diere <strong>de</strong> las anteriores en queusa un sistema <strong>de</strong> codicación FEC, conocido comoRaptor Co<strong>de</strong>s, a nivel <strong>de</strong> aplicación para enviar la informacióncodicada, <strong>de</strong> manera que esta pueda serrecuperada en el <strong>de</strong>stino sin ningún problema aunquese pierdan paquetes. De esta forma no se necesitannodos intermedios en la comunicación, ni modicacionesen el Hardware, ni control <strong>de</strong> ujo basado enventanas y retransmisiones.III. Los códigos RaptorLos códigos Raptor son códigos <strong>de</strong> corrección <strong>de</strong>errores hacia <strong>de</strong>lante (Forward Error Correction) queoperan a nivel <strong>de</strong> aplicación y son capaces <strong>de</strong> recuperarla información transmitida incluso en el caso<strong>de</strong> que se pierdan en parte los paquetes transmitidos.Para conseguir esto es necesario transmitir informaciónredundante tras el conjunto <strong>de</strong> información inicial.El sistema <strong>de</strong> codicación Raptor <strong>de</strong>ne comobloque fuente cada una <strong>de</strong> las porciones <strong>de</strong> tamañoconstante en la que ha <strong>de</strong> dividirse la informacióninicial para su procesado. Este bloque <strong>de</strong> datos seFig. 1. Proceso <strong>de</strong> codicación Raptordivi<strong>de</strong> para su codicación en símbolos fuente, queson paquetes más pequeños <strong>de</strong>l bloque fuente. Comoilustra la gura 1, el proceso <strong>de</strong> codicación <strong>de</strong> lossímbolos se realiza en dos partes. Primero se realizauna pre-codicación para generar los símbolos precodicados.Para generar este primer resultado intermediose lleva a cabo un proceso que realiza unaserie <strong>de</strong> combinaciones lineales entre los símbolos. Enla segunda fase se lleva a cabo la codicación propiamentedicha, haciendo posible una generación bajo<strong>de</strong>manda <strong>de</strong> un ujo ilimitado <strong>de</strong> símbolos codicados,que serán usados para la recuperación <strong>de</strong> lainformación transmitida en <strong>de</strong>stino.El proceso en la <strong>de</strong>codicación es el opuesto. Sevan almacenando los símbolos temporalmente hastaque se haya recibido el número necesario para llevara cabo la recuperación. Éstos se combinan para obtenernuevamente símbolos pre-codicados y, partiendo<strong>de</strong> estos símbolos, se generan los símbolos fuente quese han transmitido. Que la recuperación <strong>de</strong> la informaciónse lleve a cabo correctamente <strong>de</strong>pen<strong>de</strong> <strong>de</strong> quese haya recibido una cantidad suciente <strong>de</strong> símbolos,in<strong>de</strong>pendientemente <strong>de</strong> cuales sean estos símbolos, sison consecutivos o no, etc.A diferencia <strong>de</strong> la técnica <strong>de</strong> retransmisión, estatécnica necesita añadir símbolos codicados al envío<strong>de</strong> los datos. Esto nos obliga a enviar informaciónque no siempre es útil, por lo que la eciencia <strong>de</strong>lsistema pue<strong>de</strong> verse ligeramente reducida especialmenteen canales libres <strong>de</strong> errores. No obstante, eluso <strong>de</strong> códigos rateless o sin tasa ja <strong>de</strong> informaciónredundante, como son los códigos Raptor, reduce almínimo la necesidad <strong>de</strong> envío <strong>de</strong> esta información <strong>de</strong>recuperación. También es importante señalar que estaes una técnica que hace un uso intensivo <strong>de</strong> CPUy memoria. Por ello se ha hecho uso <strong>de</strong> un sistema <strong>de</strong>codicación sistemático. Este tipo <strong>de</strong> codicación secaracteriza por que los símbolos fuente son un subconjunto<strong>de</strong> los símbolos codicados, frente a los sistemas<strong>de</strong> codicación no sistemáticos que no tienenesta característica. Esto nos permite recuperar la informacióncon mucho menos esfuerzo en caso <strong>de</strong> queno se produzcan pérdidas en el canal.<strong>JP2011</strong>-380


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011En cuanto a la transmisión <strong>de</strong> cheros <strong>de</strong> datos,tanto a nivel cableado como inalámbrico, uno <strong>de</strong> losprotocolos más usados en la actualidad es el protocoloHTTP [21], protocolo que opera a nivel <strong>de</strong>aplicación. Este protocolo se combina con el protocoloTCP para ofrecer abilidad en la transmisión <strong>de</strong>dicha información. El problema en este sistema radicaen la incapacidad <strong>de</strong> TCP para distinguir entrepaquetes perdidos <strong>de</strong>bidos a la congestión y paquetesperdidos <strong>de</strong>bido a las características peculiares<strong>de</strong> las re<strong>de</strong>s inalámbricas, ocasionando una sensible<strong>de</strong>gradación <strong>de</strong> las prestaciones obtenidas. Debido aesto, se propone una solución alternativa a TCP parael transporte <strong>de</strong> los datos, sobre el que sería posibleimplementar cualquer protocolo para la transmisión<strong>de</strong> cheros, incluido HTTP.Proponemos un nuevo protocolo basado en códigosRaptor. <strong>La</strong> i<strong>de</strong>a <strong>de</strong>l protocolo es usar técnicasAL-FEC que hagan uso <strong>de</strong> codicación Raptor sobreel protocolo UDP para establecer una conexióninmune a errores en un canal con pérdidas. Así, evitamostambién la necesidad <strong>de</strong> retransmisiones, pueslas características <strong>de</strong> los códigos Raptor nos permitengenerar un ujo <strong>de</strong> símbolos codicados, a partir <strong>de</strong>lcual po<strong>de</strong>mos recuperar los datos originales sin tenerque preocuparnos por los antiguos.Nuestro protocolo usa a<strong>de</strong>más un sistema <strong>de</strong> estimación<strong>de</strong> ancho <strong>de</strong> banda extremo-a-extremo para<strong>de</strong>terminar el ancho <strong>de</strong> banda disponible en el canal.Esta estimación se obtiene midiendo el tiempo transcurridoentre la llegada <strong>de</strong> los paquetes y será remitidaal emisor para que éste ajuste su tasa <strong>de</strong> envío<strong>de</strong> paquetes a las condiciones <strong>de</strong>tectadas en el canal.Para realizar la implementación <strong>de</strong> nuestra propuestase estableció un diseño en cuatro capas comomuestra la gura 2. <strong>La</strong> capa superior ofrece interfazcon la aplicación usando el esquema clásico <strong>de</strong>sockets, la siguiente capa será la encargada <strong>de</strong> realizarla codicación, la tercera capa se encargará <strong>de</strong>lcontrol <strong>de</strong> la tasa <strong>de</strong> transmisión y la última e inferiorserá la encargada <strong>de</strong> proporcionar al sistemauna abstracción <strong>de</strong>l canal UDP facilitando así su implementación.Son la capa <strong>de</strong> codicación Raptor yla capa <strong>de</strong> control <strong>de</strong> la tasa <strong>de</strong> transmisión las queofrecen la mayor relevancia por ser las encargadas<strong>de</strong> realizar las tareas clave <strong>de</strong>l protocolo. <strong>La</strong> capa <strong>de</strong>codicación Raptor ofrece inmunidad a pérdidas, yla capa que realiza control <strong>de</strong> la tasa <strong>de</strong> transmisiónaporta la capacidad <strong>de</strong> adaptarse a los cambios en elcanal.Los <strong>de</strong>talles <strong>de</strong>l protocolo se <strong>de</strong>scriben a continuación.Fig. 2. Estructura en capas <strong>de</strong>l protocolo basado en codicaciónRaptorIV. Un protocolo basado en codificaciónRaptorA. El proceso <strong>de</strong> codicación y <strong>de</strong>codicaciónEl proceso <strong>de</strong> codicación y <strong>de</strong>codicación se llevaa cabo en la segunda capa, la capa <strong>de</strong> codicaciónRaptor. Esta capa recibe la información a enviar <strong>de</strong>la capa <strong>de</strong> interfaz con la aplicación, realiza la codi-cación y distribuye los paquetes creados a las capasinferiores. Esta capa introduce una cabecera alpaquete con la información necesaria para realizarla <strong>de</strong>codicación en el otro extremo. Esta cabeceraconsta <strong>de</strong> cuatro enteros: el número <strong>de</strong> códigos fuenteen el mensaje original, el i<strong>de</strong>nticador <strong>de</strong>l símboloenviado, el i<strong>de</strong>nticador <strong>de</strong>l bloque y el tamaño <strong>de</strong>lbloque a recuperar. Esta cabecera es añadida tantoa símbolos fuente como a los símbolos codicados.El proceso llevado a cabo por el emisor en esta capaes el siguiente: El emisor recibe la información atransmitir <strong>de</strong> la capa superior, divi<strong>de</strong> la informaciónen bloques fuente y estos a su vez en los símbolosfuente. Estos símbolos son empaquetados junto conla cabecera y redirigidos a capas inferiores para suposterior envío. A continuación se comienza con elproceso <strong>de</strong> codicación propiamente dicho, en el quese van generando símbolos codicados hasta que serecibe por parte <strong>de</strong>l cliente la noticación <strong>de</strong> que elbloque se ha recuperado correctamente. Una vez estanoticación se ha recibido, el proceso avanza al siguientebloque <strong>de</strong> información a transmitir y se repiteel proceso nuevamente.El proceso llevado a cabo por el receptor es distintoaunque complementario. El receptor está continuamenteesperando símbolos <strong>de</strong>l emisor, almacenándolosen una memoria temporal. <strong>La</strong> librería <strong>de</strong> codicaciónnos permite <strong>de</strong>tectar que el número <strong>de</strong> bloquesrecibidos es el suciente, momento en el que se iniciael proceso <strong>de</strong> <strong>de</strong>codicación. Una vez nalizadoéste, se notica al emisor la correcta <strong>de</strong>codicación<strong>de</strong>l bloque que se estaba transmitiendo.B. Control <strong>de</strong> la tasa <strong>de</strong> transmisiónEn las re<strong>de</strong>s inalámbricas, el ancho <strong>de</strong> banda <strong>de</strong>lcanal, así como los niveles <strong>de</strong> congestión e incluso laruta seguida por los paquetes son parámetros dinámicosque varían <strong>de</strong>pendiendo <strong>de</strong> diversos factores. Portanto, se <strong>de</strong>be usar una técnica <strong>de</strong> control <strong>de</strong> la tasa<strong>de</strong> transmisión que se adapte rápidamente a los cambiosque puedan producirse en el canal.<strong>La</strong> técnica <strong>de</strong> control <strong>de</strong> la tasa <strong>de</strong> transmisión propuestase basa en estimaciones <strong>de</strong>l ancho <strong>de</strong> bandarealizadas por el receptor durante el proceso <strong>de</strong> transmisión.Estas estimaciones son realizadas en base al<strong>JP2011</strong>-381


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011patrón <strong>de</strong> recepción <strong>de</strong> los paquetes y enviadas alemisor para que este ajuste la tasa <strong>de</strong> transmisión.Siguiendo la estrategia que propusimos en un trabajoprevio [22], los paquetes son enviados en ráfagasque superan la capacidad estimada para el canal.De esta forma, si el canal dispone <strong>de</strong> más ancho <strong>de</strong>banda <strong>de</strong>l que en principio se estimó, los paquetes llegaránantes <strong>de</strong> lo esperado, <strong>de</strong>talle que será <strong>de</strong>tectadopor el receptor que, siguiendo el protocolo, informaráal emisor <strong>de</strong>l nuevo estado <strong>de</strong>l canal. En cambio, siel canal está más congestionado en un <strong>de</strong>terminadomomento, los paquetes llegarán más lentamente.Este hecho también será <strong>de</strong>tectado por el receptorque instará al emisor a reducir su tasa <strong>de</strong> envío.<strong>La</strong> implementación <strong>de</strong>l protocolo es la siguiente:el emisor recibe los informes <strong>de</strong> ancho <strong>de</strong> banda <strong>de</strong>lreceptor (BW i ) y les aplica un factor <strong>de</strong> corrección(β), como se muestra en la ecuación 1, para obtenerla tasa objetivo T O i . El parámetro β varía entre 0y 1 y su propósito es reducir ligeramente la tasa <strong>de</strong>transmisión resultante para evitar saturar el canal,intentando ofrecer espacio al tráco best-eort. <strong>La</strong>tasa objetivo es la que esperamos medir en el lado<strong>de</strong>l receptor.Un segundo factor <strong>de</strong> corrección (α) es aplicado ala tasa objetivo para obtener la tasa <strong>de</strong> transmisión<strong>de</strong> las ráfagas (T R i ), <strong>de</strong> acuerdo a la ecuación 2. Esteparámetro varía también entre 0 y 1. Esta tasa seráutilizada para ajustar la transmisión <strong>de</strong> las ráfagas<strong>de</strong> los paquetes.T O i = β × BW i (1)T R i = 1 α × T O i (2)Cuando una ráfaga es transmitida, se aplica unperiodo <strong>de</strong> inactividad calculado <strong>de</strong> manera que, <strong>de</strong>manera global, la tasa objetivo se mantenga. A nivelglobal obtenemos la tasa <strong>de</strong> transmisión TO mientrasque para paquetes consecutivos <strong>de</strong> una misma ráfagaobtendremos la tasa <strong>de</strong> transmisión TR.C. Detalles <strong>de</strong> implementación<strong>La</strong> arquitectura que <strong>de</strong>seamos implementar hacenecesario un enfoque multihilo para conseguir unasolución eciente y robusta.Para acelerar el <strong>de</strong>sarrollo <strong>de</strong>l protocolo se ha usadocomo esqueleto la implementación <strong>de</strong> una librería<strong>de</strong> comunicaciones, la librería UDT [23], <strong>de</strong>sarrolladaen C++ con soporte para Linux, Solaris y Windows.<strong>La</strong> librería nos ofrece como apoyo las característicastípicas <strong>de</strong> las librerías <strong>de</strong> comunicación, como pue<strong>de</strong>nser un interfaz <strong>de</strong> sockets o una abstracción <strong>de</strong>l canal,y nos permite así concentrar todos los esfuerzos <strong>de</strong><strong>de</strong>sarrollo en el núcleo <strong>de</strong> la propuesta.<strong>La</strong> implementación <strong>de</strong> Raptor utilizada en la actualversión <strong>de</strong>l protocolo es la distribuida por la empresaDigital Fountain, Inc. 1 liberada bajo una licenciaacadémica, en su versión 11 para Linux. Esta libreríaofrece al programador el esquema clásico <strong>de</strong> las1 Licensed by Qualcomm Inc.librerías <strong>de</strong> codicación, permitiéndonos encapsularla funcionalidad <strong>de</strong> codicación y <strong>de</strong>codicación endos clases <strong>de</strong> C++ in<strong>de</strong>pendientes - codicador y <strong>de</strong>codicador-, y abstrayendo la funcionalidad en unacapa in<strong>de</strong>pendiente. Estas clases implementan cadauna el comportamiento <strong>de</strong> un thread in<strong>de</strong>pendienteque realiza todo el proceso <strong>de</strong>scrito en secciones anteriores.Es <strong>de</strong>seable señalar que todo este proceso se realizaa nivel <strong>de</strong> usuario, limitando la interacción con elkernel al envío <strong>de</strong> los paquetes UDP.V. Evaluación <strong>de</strong> la propuestaPara validar el protocolo propuesto, se ha realizadouna comparativa con la solución más ampliamenteutilizada en las re<strong>de</strong>s <strong>de</strong> computadores para el envío<strong>de</strong> información, que consiste en una combinación <strong>de</strong>HTTP y TCP, bajo diferentes condiciones <strong>de</strong>l canal.En ambos casos se ha utilizado un conjunto <strong>de</strong>pruebas idéntico, estableciéndose las mismas condiciones<strong>de</strong> retardo, error y ancho <strong>de</strong> banda en elcanal. Como la implementación se ha realizado sobrela plataforma GNU/Linux, y para asegurar que laspruebas son reproducibles, se creó un entorno controladopara pruebas don<strong>de</strong> se emularon las diferentescondiciones <strong>de</strong>l canal bajo las que se realizarían lasmismas. Este entorno es una caja negra que emulauna conexión <strong>de</strong> red punto-a-punto plenamente con-gurable. Los entornos emulados son los típicos <strong>de</strong>las re<strong>de</strong>s inalámbricas en cuanto a pérdidas, retardoy ancho <strong>de</strong> banda.Para realizar la evaluación se implementó un servidorbajo <strong>de</strong>manda capaz <strong>de</strong> utilizar nuestra propuestao HTTP sobre TCP para distribuir información adiferentes clientes. Se ha creado un esquema híbridoque nos permite hacer uso <strong>de</strong>l protocolo basado encodicación Raptor o <strong>de</strong> una conexión HTTP sobreTCP en función <strong>de</strong> lo que queramos evaluar. En laspruebas los clientes solicitan a sus correspondientesservidores un chero <strong>de</strong> gran tamaño y se calcula laproductividad en Mbps para cada uno <strong>de</strong> los escenarios.En relación a los parámetros α y β, sus valores seestablecieron en 0.5 para el primero <strong>de</strong> ellos (permitiendoadaptarse a uctuaciones rápidas <strong>de</strong>l canal <strong>de</strong>hasta un 100 %) y en 0.9 para el segundo (reservandoun 10 % <strong>de</strong>l ancho <strong>de</strong> banda para evitar saturar elcanal). El tamaño <strong>de</strong> bloque usado en la codicaciónfue <strong>de</strong> 10MB.<strong>La</strong> gura 3 muestra los resultados obtenidos cuandola tasa <strong>de</strong> error <strong>de</strong>l canal varía <strong>de</strong> 0 a 10 %. En estejuego <strong>de</strong> experimentos el ancho <strong>de</strong> banda <strong>de</strong>l canalse limitó a 2Mbps y el retardo se estableció en 10 ms.Como se pue<strong>de</strong> observar, cuando la tasa <strong>de</strong> pérdidas<strong>de</strong>l canal es muy baja el protocolo basado en codicaciónRaptor alcanza únicamente una productividad<strong>de</strong>l 85 % <strong>de</strong>l sistema basado en TCP. Esta diferenciaes <strong>de</strong>bida a los retardos introducidos por el proceso<strong>de</strong> codicación y <strong>de</strong>codicación <strong>de</strong>l protocolo presentado,así como al hecho <strong>de</strong> que se reserva un 10 %<strong>de</strong>l ancho <strong>de</strong> banda <strong>de</strong>l canal mediante el parámetroβ. Sin embargo, cuando la tasa <strong>de</strong> error es superior<strong>JP2011</strong>-382


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 201121.75TCPCodificacion Raptor1816TCPCodificacion Raptor1.514Productividad (Mbit/s)1.2510.75Productividad (Mbit/s)1210860.540.25200 1 2 3 4 5 6 7 8 9 10Tasa <strong>de</strong> perdida <strong>de</strong> paquetes (%)00 5 10 15 20 25 30Ancho <strong>de</strong> banda disponible en el canal (Mbit/s)Fig. 3. Productividad alcanzada conforme varía la tasa <strong>de</strong>error <strong>de</strong>l canal.Fig. 5. Productividad alcanzada conforme varía el ancho <strong>de</strong>banda disponible.Productividad (Mbit/s)21.751.51.2510.750.50.25TCPCodificacion Raptor00 10 20 30 40 50 60 70 80 90 100Retardo (ms)Fig. 4. Productividad alcanzada conforme varía el retardo <strong>de</strong>lcanal.al 4 %, el protocolo basado en codicación Raptorsupera en rendimiento a la solución tradicional. Enparticular, para una tasa <strong>de</strong> pérdidas <strong>de</strong> un 10 %, semejora a la implementación sobre TCP en un 122 %.A<strong>de</strong>más, las prestaciones se mantienen mucho másestables en el protocolo propuesto, presentando unacaída <strong>de</strong> un 12 % cuando pasamos <strong>de</strong> un 0 % a un10 % <strong>de</strong> pérdidas frente al 71 % que ofrece la soluciónTCP.<strong>La</strong> gura 4 muestra los resultados obtenidos cuandose varía el retardo extremo-a-extremo <strong>de</strong> 0 a100ms, estableciendo una tasa <strong>de</strong> pérdidas <strong>de</strong> un 2 %y limitando el ancho <strong>de</strong> banda disponible a 2Mbps.Para retardos <strong>de</strong>l canal muy bajos (menores <strong>de</strong> 20ms), la solución implementada sobre TCP se comportamejor que el protocolo basado en codicaciónRaptor <strong>de</strong>bido a las consi<strong>de</strong>raciones <strong>de</strong>talladas previamente.Sin embargo, para valores superiores a 20ms, se invierten los resultados hasta el punto <strong>de</strong>que la implementación basada en codicación Raptorofrece una mejora <strong>de</strong> un 64 %. También pue<strong>de</strong> volvera <strong>de</strong>stacarse la estabilidad <strong>de</strong> la solución basada encodicación Raptor, que arroja diferencias <strong>de</strong> un 8 %en el caso peor frente al 50 % <strong>de</strong> su competidora.<strong>La</strong> gura 5 muestra la productividad obtenidacuando variamos el ancho <strong>de</strong> banda disponible enel canal entre 0.5 y 30 Mbps. En este tercer conjunto<strong>de</strong> experimentos el retardo extremo-a-extremo seestableció en 10 ms y la tasa <strong>de</strong> pérdidas <strong>de</strong>l canalen un 2 %. En la gura se observa como las pérdidas<strong>de</strong> paquetes y el retardo tienen un fuerte impactoen el rendimiento <strong>de</strong> la solución basada en TCP, impidiéndolesuperar el umbral <strong>de</strong> productividad <strong>de</strong> los5.44 Mbps. Por el contrario, la solución propuesta,basada en codicación Raptor, escala mucho mejorconforme mejoran las condiciones <strong>de</strong> ancho <strong>de</strong> banda<strong>de</strong>l canal, logrando mejoras signicativas cuando elancho <strong>de</strong> banda disponible va más allá <strong>de</strong> los 5 Mbps.En particular, en un canal con un ancho <strong>de</strong> banda<strong>de</strong> 30 Mbps, la mejora obtenida bajo las condiciones<strong>de</strong>nidas anteriormente es <strong>de</strong> un 207 %.Resumiendo, las pruebas realizadas muestran queambas soluciones presentan una <strong>de</strong>gradación <strong>de</strong>prestaciones conforme las condiciones <strong>de</strong>l canal empeoran.Sin embargo, la reducción <strong>de</strong> prestacionesque presenta la solución basada en codicación Raptores en todos los casos mucho menos pronunciadaque la que presenta la solución basada en TCP. Enparticular, la reducción <strong>de</strong> prestaciones que ofreceesta última pue<strong>de</strong> consi<strong>de</strong>rarse excesiva cuando losvalores <strong>de</strong> retardo o <strong>de</strong> pérdida <strong>de</strong> prestaciones sonsignicativos. Estos resultados ponen en evi<strong>de</strong>ncia lafalta <strong>de</strong> efectividad <strong>de</strong> las implementaciones tradicionalesbasadas en TCP para operar en escenarioscon un alto nivel <strong>de</strong> pérdidas o con un alto retardo,características éstas propias <strong>de</strong> escenarios inalámbricos.Por el contrario, la solución basada en codicaciónRaptor mantiene la productividad en un nivelmucho más estable, haciéndose casi inmune a lapérdida <strong>de</strong> paquetes y mejorando claramente a lassoluciones tradicionales. <strong>La</strong>s diferencias entre ambasimplementaciones se hacen mucho más pronunciadascuando el canal supera los 5Mbps, poniendo <strong>de</strong> mani-esto la incapacidad <strong>de</strong>l protocolo TCP para hacerun uso eciente <strong>de</strong>l ancho <strong>de</strong> banda disponible encanales inalámbricos.VI. Conclusiones<strong>La</strong> transmisión <strong>de</strong> datos en entornos inalámbricos,que típicamente presentan un alto nivel <strong>de</strong> pérdida<strong>de</strong> paquetes o <strong>de</strong> retardo, requieren <strong>de</strong> nuevas técnicasque sean capaces <strong>de</strong> mejorar las prestaciones<strong>JP2011</strong>-383


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011en este tipos <strong>de</strong> entornos. Los esquemas basados enFEC se han revelado como la solución más a<strong>de</strong>cuadadada su capacidad para evitar las retransmisiones <strong>de</strong>paquetes perdidos.En este documento se propone un nuevo protocolobasado en una codicación Raptor que es capaz <strong>de</strong>mejorar el rendimiento en la transmisión <strong>de</strong> cheros,especialmente en entornos con pronunciadas pérdidas<strong>de</strong> datos. Este protocolo consigue evitar las retransmisiones<strong>de</strong> paquetes aplicando técnicas FECen la capa <strong>de</strong> aplicación.Nuestra propuesta realiza un control <strong>de</strong> la tasa <strong>de</strong>transmisión basado en las estimaciones <strong>de</strong> ancho <strong>de</strong>banda realizadas por el proceso receptor. Nuestrasolución permite al protocolo adaptar rápidamentela tasa <strong>de</strong> transmisión a la congestión <strong>de</strong>l canal y aotros factores que varian a lo largo <strong>de</strong>l tiempo.<strong>La</strong> propuesta ha sido implementada sobre un sistemaGNU/Linux. Esta implementación a compararel rendimiento <strong>de</strong> este nuevo protocolo basado en codicaciónRaptor con la solución basada en el protocoloTCP bajo diferentes condiciones <strong>de</strong>l canal, paralo que se diseñaron y realizaron una serie <strong>de</strong> experimentos.Los resultados ponen <strong>de</strong> maniesto la superioridad<strong>de</strong> la solución propuesta cuando se tratacon altos niveles <strong>de</strong> retardo y alta tasa <strong>de</strong> pérdidasen el canal, diferencias que se hacen especialmenteevi<strong>de</strong>ntes cuando el ancho <strong>de</strong> banda <strong>de</strong>l canal se incrementapor encima <strong>de</strong> los 5 Mbps.Agra<strong>de</strong>cimientosEste trabajo ha sido parcialmente nanciado porel Ministerio <strong>de</strong> Ciencia e Innovación, España, bajola subvencion TIN2008-06441-C02-01.Referencias[1] A. Shokrollahi, Raptor co<strong>de</strong>s, Information Theory,IEEE Transactions on, vol. 52, no. 6, pp. 25512567,2006.[2] A. Natani, J. Jakilinki, M. Mohsin, and V. Sharma, TCPfor Wireless Networks, Project Report, Univ. of Texasat Dallas, USA, 2001.[3] K. Pentikousis, TCP in wired-cum-wireless environments,IEEE Communications Surveys, vol. 3, no. 4,pp. 214, 2000.[4] E. Ayanoglu, S. Paul, T.F. <strong>La</strong>Porta, K.K. Sabnani, andR.D. Gitlin, AIRMAIL: A link-layer protocol for wirelessnetworks, Wireless Networks, vol. 1, no. 1, pp. 4760,1995.[5] H. Balakrishnan, S. Seshan, and R.H. Katz, Improvingreliable transport and hando performance in cellularwireless networks, Wireless Networks, vol. 1, no. 4, pp.469481, 1995.[6] S. Vangala and M.A. <strong>La</strong>brador, Performance of TCPover wireless networks with the Snoop protocol, in CON-FERENCE ON LOCAL COMPUTER NETWORKS.Citeseer, 2002, vol. 27, pp. 600604.[7] C. Parsa, TULIP: A link-level protocol for improvingTCP over wireless links, in Wireless Communicationsand Networking Conference, 1999. WCNC. 1999 IEEE.IEEE, 2002, pp. 12531257.[8] M.N. Mehta and N.H. Vaidya, Delayed Duplicate-Acknowledgments: A Proposal to Improve Performanceof TCP on Wireless Links, Tech. Rep., Citeseer, 1998.[9] Z. Jing and N. Zhisheng, A reliable TCP-aware link layerretransmission for wireless networks, in CommunicationTechnology Proceedings, 2000. WCC-ICCT 2000. InternationalConference on. IEEE, 2002, vol. 1, pp. 900905.[10] K. Brown and S. Singh, M-TCP: TCP for mobile cellularnetworks, ACM SIGCOMM Computer CommunicationReview, vol. 27, no. 5, pp. 1943, 1997.[11] P. Sinha, T. Nandagopal, N. Venkitaraman, R. Sivakumar,and V. Bharghavan, WTCP: A reliable transportprotocol for wireless wi<strong>de</strong>-area networks, Wireless Networks,vol. 8, no. 2/3, pp. 301316, 2002.[12] S. Biaz, M. Mehta, S. West, and N.H. Vaidya, TCP overwireless networks using multiple acknowledgements,Texas A&M University, Technical Report 97, vol. 1, pp.97001.[13] M. Mathis, J. Mahdavi, S. Floyd, and A. Romanow,RFC2018: TCP Selective Acknowledgement Options,RFC Editor United States, 1996.[14] S. Keshav and SP Morgan, SMART retransmission:Performance with overload and random losses, in IN-FOCOM'97. Sixteenth Annual Joint Conference of theIEEE Computer and Communications Societies. ProceedingsIEEE. IEEE, 2002, vol. 3, pp. 11311138.[15] R. Caceres and L. Ifto<strong>de</strong>, Improving the performanceof reliable transport protocols in mobile computing environments,Selected Areas in Communications, IEEEJournal on, vol. 13, no. 5, pp. 850857, 2002.[16] C. Parsa, Improving TCP congestion control over internetswith heterogeneous transmission media, in NetworkProtocols, 1999.(ICNP'99) Proceedings. Seventh InternationalConference on. IEEE, 2002, pp. 213221.[17] R. Ramani and A. Karandikar, Explicit congestion noti-cation (ECN) in TCP over wireless network, in PersonalWireless Communications, 2000 IEEE InternationalConference on. IEEE, 2002, pp. 495499.[18] S. Goel and D. Sanghi, Improving TCP performanceover wireless links, in TENCON'98. 1998 IEEE Region10 International Conference on Global Connectivity inEnergy, Computer, Communication and Control. IEEE,2002, vol. 2, pp. 332335.[19] K. Chandran, S. Ragbunathan, S. Venkatesan, andR. Prakash, A feedback based scheme for improvingTCP performance in ad-hoc wireless networks, in DistributedComputing Systems, 1998. Proceedings. 18th InternationalConference on. IEEE, 2002, pp. 472479.[20] J. Liu and S. Singh, ATCP: TCP for mobile ad hoc networks,Selected Areas in Communications, IEEE Journalon, vol. 19, no. 7, pp. 13001315, 2002.[21] R. Fielding, J. Gettys, J. Mogul, H. Frystyk, L. Masinter,P. Leach, and T. Berners-Lee, Hypertext TransferProtocol HTTP/1.1, RFC 2616, June 1999.[22] Carlos T. Calafate, Pietro Manzoni, and Manuel P.Malumbres, Supporting soft real-time services inMANETs using distributed admission control and IEEE802.11e technology, in The 10th IEEE Symposium onComputers and Communications, <strong>La</strong> Manga <strong>de</strong>l MarMenor, Cartagena, Spain, June 2005.[23] Y. Gu and R.L. Grossman, Supporting congurable congestioncontrol in data transport services, in Proceedingsof the 2005 ACM/IEEE conference on Supercomputing.2005, IEEE Computer Society.<strong>JP2011</strong>-384


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Evaluating vi<strong>de</strong>o streaming performance inMANETs using a testbedTim Bohrloch † , Carlos T. Calafate ‡ , Alvaro Torres ‡ , Juan-Carlos Cano ‡ , Pietro Manzoni ‡1Abstract— The complexity of evaluating vi<strong>de</strong>o <strong>de</strong>liverystrategies in mobile ad-hoc networks (MANETs)has led most researchers to rely on simulation experimentsalone. However, in most cases, simulationsfail to replicate realistic conditions, and so the resultsobtained and the conclusions drawn from such resultsare not accurate. In this paper we <strong>de</strong>scribe a methodologythat allows evaluating the effectiveness of vi<strong>de</strong>oco<strong>de</strong>cs in MANETs. Our methodology is based on awell-<strong>de</strong>fined vi<strong>de</strong>o quality evaluation framework thatconsi<strong>de</strong>rs different vi<strong>de</strong>o co<strong>de</strong>cs and transmission environments.We validate our methodology by comparingthe H.264/AVC and the MPEG-4/ASP vi<strong>de</strong>oco<strong>de</strong>cs, showing that, in general, the former outperformsthe later in terms of vi<strong>de</strong>o quality. For veryhigh loss rates, though, the differences between bothbecome minimal. We also show that the number ofhops between vi<strong>de</strong>o transmitter and receiver is a <strong>de</strong>cisivefactor affecting performance when the channelexperiences congestion. Moreover, in mobile scenarios,we find that the impact of congestion and routing<strong>de</strong>lay affects vi<strong>de</strong>o streaming quality in different manners:while congestion is mainly responsible for randomlosses, routing <strong>de</strong>lay is usually associated withlong loss bursts.Keywords— Vi<strong>de</strong>o streaming; MANET; QoS;testbed; H.264 / AVC; MPEG-4 / ASP; ad-hocI. IntroductionVIDEO streaming in mobile ad-hoc networks(MANETs) is consi<strong>de</strong>red one of the most challengingresearch goals due to the combined effects ofwireless communications characteristics (multipathfading and shadowing, interferences, collisions, etc.)and topology maintenance in the presence of no<strong>de</strong>mobility, all of which negatively affect on-going vi<strong>de</strong>osessions. In particular, topology changes provokeintermittent connectivity, causing large packet lossbursts. Thus, assessing the effectiveness of vi<strong>de</strong>otransmission systems in ad-hoc networks is a relevantissue. In the past, most works addressing this issuehave resorted to simulation due to the complexity of<strong>de</strong>ploying real testbeds. However, this approach doesnot allow for a thorough validation since results tendto be too optimistic. Additionally, the few works <strong>de</strong>scribingreal testbed experiments do not <strong>de</strong>al withthe IEEE 802.11e technology, which impe<strong>de</strong>s offeringQoS support to vi<strong>de</strong>o streams.In this work we introduce a methodology basedon emulation that allows evaluating vi<strong>de</strong>o streamingperformance in real, 802.11e-based MANETs. Theproposed methodology relies on a vi<strong>de</strong>o quality evaluationframework to assess the effectiveness of differentvi<strong>de</strong>o co<strong>de</strong>cs when transmitted over IP net-1† HfT Leipzig, Germanye-mail: Tim.Bohrloch@gmx.net‡ Universitat Politècnica <strong>de</strong> València, Spaine-mail: calafate@disca.upv.es, atcortes@batousay.com,{jucano, pmanzoni}@disca.upv.esworks. When focusing on MANET scenarios, wepropose performing an initial evaluation using a controlledpoint-to-point wireless channel to have a clearoverview of the vi<strong>de</strong>o co<strong>de</strong>c’s error resilience performance.Afterward, static multi-hop communicationscenarios are used to <strong>de</strong>termine of impact of factorssuch as congestion and hop count on performance.Finally, we introduce mobile multi-hop communications,typical of MANET environments, to study theeffects of topology updating <strong>de</strong>lays on the vi<strong>de</strong>o qualityperceived by the user.To validate our methodology we assess the effectivenessof two well-known vi<strong>de</strong>o coding standards -H.264/AVC [1] and MPEG-4 Part 2 [2] - followingthe proposed procedure. Experimental results showthat the H.264/AVC co<strong>de</strong>c offers higher vi<strong>de</strong>o qualityand, more important, they evi<strong>de</strong>nce how the differentsources of vi<strong>de</strong>o data losses in MANETs impactthe vi<strong>de</strong>o <strong>de</strong>coding process.This paper is organized as follows: in section IIwe present some related works, evi<strong>de</strong>ncing how ourwork differs from previous ones. In section III weintroduce the proposed vi<strong>de</strong>o evaluation methodology.Section IV <strong>de</strong>scribes the vi<strong>de</strong>o sequences usedfor testing, along with the experimental results obtainedin an emulated point-to-point channel whenvarying the loss rate. The results obtained in ourad-hoc network testbed are then presented in sectionV, comprising both static and mobile scenarios.Finally, section VI presents the main conclusions ofthis paper.II. Related worksIn the literature we can find works addressingvi<strong>de</strong>o streaming performance in MANETs from differentperspectives.Schierl et al. [3] presented a scheme based on RaptorFEC that uses different sources for reliable mediastreaming in MANET scenarios with high route lossprobability. Their evaluation is based on ns-2 simulation.Sheltami [4] evaluates the performance of H.264protocol using two routing protocols: the Neighbor-Aware Clusterhead (NAC) and the Dynamic SourceRouting (DSR) protocols. The author shows thatit is feasible to have vi<strong>de</strong>o over MANETs within anaverage distance of 6 hops, and requiring 5.5 Mbpson average.Calafate et al. [5] propose a QoS frameworkfor MANETs combining IEEE 802.11e technology, amultipath routing algorithm, and a distributed admissioncontrol algorithm. Their solution was testedvia simulation, and Peak Signal-to-Noise Ratio re-<strong>JP2011</strong>-385


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 1. Steps involved in obtaining vi<strong>de</strong>o quality in<strong>de</strong>xes forvi<strong>de</strong>o streaming environments.sults were obtained un<strong>de</strong>r different network congestionconditions.More recently, Lee and Song [6] propose an effectivecross layer optimized vi<strong>de</strong>o streaming algorithmover multi-hop mobile ad hoc networks. Their algorithmattempts to satisfy an end-to-end <strong>de</strong>lay constraint,while maintaining packet loss rate within atolerable range at the receiver.Despite the aforementioned works address problemssimilar to those we focus on this work, our proposaldiffers from previous ones by providing: (i) anIEEE 802.11e enabled MANET testbed, while mostproposals are simulation based, and the real testbeds<strong>de</strong>ployed (e.g. [7]) lack any QoS support at the MAClayer; (ii) a methodology for assessing vi<strong>de</strong>o streamingeffectiveness in MANET environments based onemulation.III. Our proposed vi<strong>de</strong>o evaluationmethodologyIn this section we introduce our methodology toevaluate vi<strong>de</strong>o streaming effectiveness in MANETswhen relying on different vi<strong>de</strong>o co<strong>de</strong>cs, and un<strong>de</strong>rdifferent network conditions. We first <strong>de</strong>scribe thevi<strong>de</strong>o quality measurement framework adopted, includingthe different target vi<strong>de</strong>o quality metrics.Based on this framework, we then propose differenttransmission environments over which performanceis assessed. In particular, preliminary evaluationsare ma<strong>de</strong> using an emulated point-to-point wirelesschannel; the goal is to have a clear characterizationof the vi<strong>de</strong>o co<strong>de</strong>c’s behavior un<strong>de</strong>r different loss conditions.These preliminary evaluations are followedby tests in a real wireless ad-hoc network testbed,both static and mobile, to evaluate the impact ofcongestion, hop count and mobility on performance.A. Vi<strong>de</strong>o quality measurement frameworkMeasuring the quality of a transmitted vi<strong>de</strong>o is aprocess that involves several steps. In particular, retrievingvi<strong>de</strong>o quality in<strong>de</strong>xes usually requires doinga frame-by-frame comparison of the original vi<strong>de</strong>oagainst the received vi<strong>de</strong>o, both in the raw format.Figure 1 presents the steps involved in obtainingvi<strong>de</strong>o quality in<strong>de</strong>xes for a specific combinationof vi<strong>de</strong>o enco<strong>de</strong>r/<strong>de</strong>co<strong>de</strong>r and transmission channel.The original vi<strong>de</strong>o is a raw vi<strong>de</strong>o sequence, typicallyin the YUV 4:2:0 format. The encoding process relieson one of the available vi<strong>de</strong>o co<strong>de</strong>cs for datacompression prior to transmission. Notice that, toenable a fair performance comparison between differentvi<strong>de</strong>o co<strong>de</strong>cs, it is very important to performdatarate control to get the same target bitrate fortransmission. Otherwise, any qualitative comparisonwould be <strong>de</strong>emed unfair.For the transmission process, we propose connectinga VLC [8] client to a VLC server through an IPnetwork, since this tool is compatible with a wi<strong>de</strong>variety of formats and vi<strong>de</strong>o co<strong>de</strong>cs. For the <strong>de</strong>codingprocess, we can use a tool such as Menco<strong>de</strong>r [9]to obtain a raw vi<strong>de</strong>o sequence in the YUV 4:2:0format. In addition, and to account for lost framesin the transmission process, frame freezing is performed.The latter is the process through which asame frame is replicated to fill-in for missing frames,thereby generating a raw vi<strong>de</strong>o sequence with thesame length as the original one. This is a strict requirementto obtain a meaningful output from thequality measurement process.To <strong>de</strong>termine the impact of the different transmissionimpairments on the quality of streamed vi<strong>de</strong>osequences as experienced by the receiver, we haverelied on different metrics. In particular, the metricswe consi<strong>de</strong>red were: (i) Peak Signal-to-Noise Ratio(PSNR), (ii) Packet loss ratio, and (iii) Framelosses. According to different authors [7], [10], thisset of metrics is quite a<strong>de</strong>quate in the context ofvi<strong>de</strong>o transmission over lossy IP networks since theyassess vi<strong>de</strong>o quality from different perspectives. Inparticular, the last two metrics are more appropriateto discriminate between different vi<strong>de</strong>o transmissionimpairments when losses grow above the 15-20%threshold. Notice that all other vi<strong>de</strong>o-specific metrics,both objective and subjective, usually fail todifferentiate between different scenarios when transmissionconditions become very poor, experiencinga saturation effect at the lower edge of the metrics’range.In the following sections we <strong>de</strong>scribe the differentnetworks introduced in the Transmission processstep according to the proposed evaluation methodology.B. Point-to-point wireless channel emulationOur experiments were ma<strong>de</strong> with real workingsoftware for both GNU/Linux and Windows platforms.To make sure that the test sequences wererepeatable and reproducible, we created a controlledtest environment where we emulated different channelconditions. With this purpose, we interconnectedtwo computers using Fast Ethernet, and, using theGNU/Linux traffic control tool (tc), we set the channel<strong>de</strong>lay and the packet loss ratio. This way, we wereable to emulate different channel conditions to assessthe impact on performance at the application layer.In this process, it is important to highlight that thepacket loss events introduced were completely random,meaning that no loss burst effects were present.In contrast, the wireless ad-hoc network environmentsthat we <strong>de</strong>scribe below will mostly introducebursty losses.<strong>JP2011</strong>-386


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011C. Wireless ad-hoc network testbedTesting vi<strong>de</strong>o transmission in a real wireless adhocnetwork testbed is a complex task. In fact, themere setup process of such a testbed requires configuringno<strong>de</strong>s to share the same IEEE 802.11 parameters,as well as being within the same IP network,and running a same routing protocol in casemobility is introduced. Additionally, relying on usersto move mobile terminals around makes the processambiguous by impeding repeatability and strict controlof experiments. Instead, we propose using on theCastadiva tool [11] to setup both static and mobilescenarios in a seamless and straightforward manner,while providing experiment repeatability. Through agraphical user interface, Castadiva allows setting upany static or mobile scenario, <strong>de</strong>fining both the layer2 and layer 3 setup for no<strong>de</strong>s, providing start/stoptraffic control, and gathering experimental results atthe end.IV. Performance evaluation in lossywireless channelsFollowing the proposed methodology, in this sectionwe proceed with the first set of experimentswhere we assess vi<strong>de</strong>o streaming performance in apoint-to-point wireless channel un<strong>de</strong>r different lossconditions. We first introduce the two vi<strong>de</strong>o sequencesused as input for our tests, and then presentexperimental results when transmitting in an emulatedwireless channel.A. Selected vi<strong>de</strong>o co<strong>de</strong>cs and sequencesFor our experiments we used two different vi<strong>de</strong>osequences with different characteristics (see table I).The first vi<strong>de</strong>o sequence, taken from the “Die hard 4”movie, is an action sequence with a very high <strong>de</strong>greeof motion and many scene changes, being particularly<strong>de</strong>manding for vi<strong>de</strong>o co<strong>de</strong>cs. The second vi<strong>de</strong>osequence, taken from the “Sunshine” movie trailer,has less motion and less scene changes, but it has ahigher resolution compared to the first one (720p vs576p). Instead of the standard VQEG [12] vi<strong>de</strong>o sequences1 , we opted for the aforementioned sequencessince they introduce more scene changes than the latterones. Notice that scene changes cause bandwidthpeaks, which are <strong>de</strong>sirable for our study in or<strong>de</strong>r tostress the network.The two vi<strong>de</strong>o sequences are enco<strong>de</strong>d using boththe H.264/AVC and the MPEG-4 vi<strong>de</strong>o co<strong>de</strong>cs. Inparticular, we relied on the “XMedia Reco<strong>de</strong>” tool[13] for the vi<strong>de</strong>o encoding task.B. Experimental resultsIn this first set of experiments the goal was tocompare the error resilience of both vi<strong>de</strong>o co<strong>de</strong>cs un<strong>de</strong>ranalysis when facing different channel conditions.With this purpose we relied on our point-to-pointchannel emulator to introduce a variable loss rate1 Available at: ftp://ftp.crc.ca/crc/vqeg/between vi<strong>de</strong>o sen<strong>de</strong>r and receiver, while setting <strong>de</strong>layto 10 ms. In our experiments we used both theH.264/AVC and the MPEG-4/ASP (Advanced SimpleProfile) vi<strong>de</strong>o co<strong>de</strong>cs, setting the target data rateof both vi<strong>de</strong>o sequences to 900 kbit/s. We variedthe packet loss rate between 0,1% and 10%, sincethis range is <strong>de</strong>emed a<strong>de</strong>quate by most authors [10]when performing vi<strong>de</strong>o quality assessment. For eachcombination of vi<strong>de</strong>o sequence, co<strong>de</strong>c and packet lossrate, we repeated the experiment 10 times. In thecharts that follow, each point represents the meanvalue of these 10 experiments.Figure 2 shows the PSNR results obtained for bothvi<strong>de</strong>o sequences using the two different vi<strong>de</strong>o co<strong>de</strong>cs.Concerning vi<strong>de</strong>o sequence #1 (see Figure 2, left), wefound that the H.264/AVC co<strong>de</strong>c achieves an incrementof 2 dBs, on average, compared to the MPEG-4/ASP vi<strong>de</strong>o co<strong>de</strong>c. With respect to vi<strong>de</strong>o sequence#2, we find that the differences between both co<strong>de</strong>cs,although initially high (5.9 dB), become negligiblefor packet loss rates above 2%. Compared to vi<strong>de</strong>osequence #1, this effect only occurred for a packetloss rate of 10%. Also, we find that the PSNR valuesfor vi<strong>de</strong>o sequence #2 experience a faster <strong>de</strong>gradationcompared to the first one, and that PSNR valuesat 10% loss are up to 5 dB lower, approaching noiselevels (20 dB threshold).Concerning frame losses, figure 3 shows the impactof packet loss on the frame loss ratio. We cansee that there is some relationship between packetlosses and frame losses. We also find that both vi<strong>de</strong>oco<strong>de</strong>cs follow a similar trend, although, for the firstvi<strong>de</strong>o sequence, the MPEG-4/ASP co<strong>de</strong>c performsquite poorly, with a frame loss ratio of 12% when thepacket loss ratio is of 10%. The H.264/AVC co<strong>de</strong>coffers more consistent operation, achieving a maximumframe loss ratio of 8%, and always maintainingthe frame loss ratio below the packet loss ratio. Thisis the expected behavior, and clearly evi<strong>de</strong>nces thesuperior error resilience offered by the H.264/AVCco<strong>de</strong>c.Overall we find that, although the H.264/AVCco<strong>de</strong>c is expected to offer a much better performancecompared to its pre<strong>de</strong>cessor (MPEG-4/ASP),the PSNR difference becomes somehow attenuatedwhen the packet loss ratio becomes too high. Wealso find that the impact of packet loss on frame lossratio is maintained consistent for H.264/AVC, whileMPEG-4/ASP improved its behavior with a highervi<strong>de</strong>o resolution sequence (#2).V. Performance evaluation in a realwireless ad-hoc network testbedEndowed with the knowledge acquired in the experimentsof the previous section, and followingthe proposed evaluation methodology, we now proceedwith our study by <strong>de</strong>ploying an ad-hoc networktestbed composed of low cost netbooks, allof which are equipped with IEEE 802.11g wirelesscards. The laptops were configured to enable QoSsupport through IEEE 802.11e, meaning that vi<strong>de</strong>o<strong>JP2011</strong>-387


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLE IDetails about the different vi<strong>de</strong>o sequences used (source formats).Vi<strong>de</strong>o sequence Resolution Degree of motion Scene changes Frame rate DurationSequence #1 768×576 high very frequent 25 fps 18 sSequence #2 1280× 720 mo<strong>de</strong>rate frequent 25 fps 20 s45H.264/AVCMPEG-4/ASP45H.264/AVCMPEG-4/ASP4040Peak Signal-to-Noise Ratio (dB)3530Peak Signal-to-Noise Ratio (dB)35302525200.1 1 10Packet loss rate (%)200.1 1 10Packet loss rate (%)Fig. 2. PSNR values for vi<strong>de</strong>o sequence #1 (left) and vi<strong>de</strong>o sequence #2 (right) when varying the packet loss rate on thechannel.12H.264/AVCMPEG-4/ASP12H.264/AVCMPEG-4/ASP1010Frame loss ratio (%)864Frame loss ratio (%)8642200.1 1 10Packet loss rate (%)00.1 1 10Packet loss rate (%)Fig. 3. Frame loss ratio values for vi<strong>de</strong>o sequence #1 (left) and vi<strong>de</strong>o sequence #2 (right) when varying the packet loss rateon the channel.traffic can be transmitted at a higher priority categorycompared to best effort traffic.Due to the complexity of the experiments and thetime involved, the tests presented in this section usevi<strong>de</strong>o sequence #1 alone. We now present experimentalresults consi<strong>de</strong>ring both a static and a mobiletopology.A. Static topology testsIn this section we perform some experiments in astatic ad-hoc network environment. In our tests weassess performance when varying the number of hopsbetween vi<strong>de</strong>o transmitter and receiver. For the networkto operate un<strong>de</strong>r realistic assumptions, we alsocreate best-effort traffic flows. These flows consist ofconstant bitrate UDP traffic regulated to produce amo<strong>de</strong>rate/high <strong>de</strong>gree of congestion in the network.In particular, each of these background traffic clientswill generate about 8 Mbit/s using 1400 byte packets,although the number of hops associated with eachflow differs (see Figure 4). With this purpose, thevi<strong>de</strong>o streaming client connects to a different streamingserver in each test.Figure 5 shows the packet loss ratio experiencedat different hops for both two vi<strong>de</strong>o co<strong>de</strong>cs. NoticeFig. 4. Static testbed environment used for multi-hop ad-hocnetwork performance tests.that, since the target bitrate is the same for bothvi<strong>de</strong>o co<strong>de</strong>cs, the packet loss rate is expected to besimilar in both cases. In fact, the differences <strong>de</strong>tectedare mostly related to the variability of the wirelesschannel’s capacity in the presence of other sources ofinterference.Overall, we find that losses grow proportionally tothe hop count, being the most significant growth <strong>de</strong>tectedwhen increasing the hop count from one to twohops. For a greater number of hops, the packet lossratio increase becomes proportionally less significantcompared to this initial growth.Concerning PSNR values, figure 6 (left) shows thatvi<strong>de</strong>o quality at one hop is very good, as expected.<strong>JP2011</strong>-388


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 6. PSNR values (left) and Frame loss ratio (right) for both vi<strong>de</strong>o co<strong>de</strong>cs when increasing the number of hops betweensource and <strong>de</strong>stination.Fig. 5. Packet loss ratio values for both vi<strong>de</strong>o co<strong>de</strong>cs whenincreasing the number of hops between source and <strong>de</strong>stination.However, as the number of hops increases, the PSNRvalues <strong>de</strong>crease at a rate of about 2 dB per hop for theH.264/AVC vi<strong>de</strong>o co<strong>de</strong>c. In the case of the MPEG-4/ASP enco<strong>de</strong>d stream, the per-hop <strong>de</strong>cay is greater,although it levels out at three hops (almost no differencecompared to the four hops case).The frame loss results are coherent with the packetloss and PSNR results, again evi<strong>de</strong>ncing that theH.264/AVC vi<strong>de</strong>o co<strong>de</strong>c is again able to offer a betterperformance (see fig. 6, right). Nevertheless, andin<strong>de</strong>pen<strong>de</strong>ntly of which co<strong>de</strong>c is used, we find thatframe losses at high hop counts become excessive forgood quality vi<strong>de</strong>o streaming.Overall, we find that the H.264/AVC co<strong>de</strong>c offersa consistent improvement compared to the MPEG-4/ASP enco<strong>de</strong>r, and that the number of hops is a factorwhich drastically affects quality when the channelis congested.B. Mobile topology testsThe last target scenario <strong>de</strong>fined in the proposedmethodology is a mobile ad-hoc network environment.The chosen setting is similar to the previoussection, being the main difference that now the vi<strong>de</strong>ostreaming client will be moving across the scenario.This client is initially located away from the streamingserver (4-hop distance) and, when the experimentbegins, it will start moving towards the streamingserver at a constant speed (10 or 15 m/s in our ex-Fig. 7. Mobile testbed environment used for multi-hop ad-hocnetwork performance tests. Emulated distance betweenstatic stations is of 200 meters.periments), meaning that the hop count will be graduallyreduced (see figure 7). We rely on the OLSRrouting protocol [14] for topology maintenance.In our experiments, we perform tests both withand without background traffic. The former adoptthe same flow characteristics used in the previoussection for the static testbed. Each experiment lastsfor 40 seconds, which in our setting corresponds tomoving the streaming client until it is within rangeof the streaming server (optimal conditions).Table II shows the results obtained for the differentscenarios consi<strong>de</strong>red. These results show how mobilityand congestion affect vi<strong>de</strong>o performance. We findthat, while mobility is the most important sourceof packet losses, congestion has a greater impact onthe average PSNR since losses are more distributedthroughout frames. Another important conclusionthat can be directly drawn from these results is thatpacket losses experienced in the presence of both highmobility and congestion are basically the sum of boththese causes of loss, meaning that mobility and channelcongestion are basically additive factors for thepacket loss metric. In terms of frame loss ratio, thismetric is strictly related to packet losses, where againwe confirm the higher performance offered by theH.264/AVC co<strong>de</strong>c.VI. ConclusionsIn this paper we presented a methodology for assessingvi<strong>de</strong>o streaming quality in MANET environ-<strong>JP2011</strong>-389


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLE IIExperimental results obtained in the mobile testbed scenario.Vi<strong>de</strong>o No<strong>de</strong> speed Background Packet loss PSNR Frame lossco<strong>de</strong>c (m/s) traffic ratio (%) (dB) ratio (%)H.264/AVC 10 NO 0.22 41.52 0.39MPEG-4/ASP 10 NO 0.21 43.36 0.26H.264/AVC 15 NO 22.72 36.62 20.71MPEG-4/ASP 15 NO 22.38 36.69 22.34H.264/AVC 10 YES 8.75 34.40 10.22MPEG-4/ASP 10 YES 8.98 35.42 12.21H.264/AVC 15 YES 31.17 29.24 30.28MPEG-4/ASP 15 YES 32.08 29.19 32.08ments. Our proposal inclu<strong>de</strong>s a well-<strong>de</strong>fined vi<strong>de</strong>oevaluation framework that allows assessing performancewhen combining different vi<strong>de</strong>o co<strong>de</strong>cs anddifferent transmission scenarios. In particular, wepropose performing the evaluation in several phases,where in the first phase we make an in-<strong>de</strong>pth evaluationin a point-to-point lossy channel to <strong>de</strong>terminethe co<strong>de</strong>c error resilience un<strong>de</strong>r different channel conditions,and, in a second phase, performance assessmentanalysis is carried out in a real ad-hoc networktestbed to <strong>de</strong>termine the impact of congestion, hopcount and mobility on performance. Our testbed offersfull QoS support through IEEE 802.11e, and relieson emulation to <strong>de</strong>vise test scenarios un<strong>de</strong>r bothstatic and dynamic network conditions.By following our methodology, we comparedthe performance of two state-of-the-art co<strong>de</strong>cs:H.264/AVC and MPEG-4/ASP. The performancein<strong>de</strong>xes gathered evi<strong>de</strong>nce the better performanceof H.264/AVC when compared to MPEG-4/ASP.Nevertheless, we find that the differences betweenco<strong>de</strong>cs become minimal as we increase the packetloss rate and the vi<strong>de</strong>o resolution. Experimentaltestbed results show that, for a static environment,the amount of losses experienced un<strong>de</strong>r mo<strong>de</strong>ratebest-effort loads do not compromise vi<strong>de</strong>o transmission,although vi<strong>de</strong>o quality may experience a <strong>de</strong>gradationof up to 14 dB when the number of hops increasesfrom one to four hops. In the presence ofmobility, and using the OLSR protocol for routingtasks, we find that performance is quite good whenthe <strong>de</strong>gree of mobility and congestion is low. Whencongestion increases, the vi<strong>de</strong>o sequence experiencesa significant quality <strong>de</strong>gradation due mostly to randomlosses. Instead, mobility is prone to cause longloss bursts due to route disruption. We also foundthat, in scenarios characterized by both high <strong>de</strong>greesof mobility and congestion, the vi<strong>de</strong>o stream experiencesa loss pattern that is basically an additivecombination of the effects of these two parameters.Overall, we find that the proposed methodologyoffers a comprehensive analysis of vi<strong>de</strong>o streamingperformance in MANETs, allowing to discriminatelosses according to their particular origin so that anyimprovement efforts point to the right direction.AcknowledgmentsThis work was partially supported by the Ministerio<strong>de</strong> Ciencia e Innovación, Spain, un<strong>de</strong>r GrantTIN2008-06441-C02-01.References[1] “Draft ITU-T Recommendation and Final Draft InternationalStandard of Joint Vi<strong>de</strong>o Specification (ITU-TRec. H.264 | ISO/IEC 14496-10 AVC),” oint Vi<strong>de</strong>o Team(JVT) of ISO/IEC MPEG and ITU-T VCEG, JVTG050,March 2003.[2] ISO/IEC IS, “Coding of Audio-Visual Objects, Part 2:Visual (MPEG-4),” Information Technology, November2001.[3] T. Schierl, C. Hellge, K. Ganger, T. Stockhammer, andT. Wiegand, “Multi Source Streaming for Robust Vi<strong>de</strong>oTransmission in Mobile Ad-Hoc Networks,” in IEEEInternational Conference on Image Processing, Atlanta,GA, USA, Oct. 2006.[4] Tarek Sheltami, “Performance Evaluation of H.264 Protocolin Ad hoc Networks,” Journal of Mobile Multimedia,vol. 4, no. 1, pp. 59–70, 2008.[5] C.T. Calafate, M.P. Malumbres, J. Oliver, J.C. Cano,and P. Manzoni, “QoS Support in MANETs: a ModularArchitecture Based on the IEEE 802.11e Technology,”IEEE Transactions on Circuits and Systems for Vi<strong>de</strong>oTechnology, vol. 19, no. 5, pp. 678–692, May 2009.[6] Gyeongcheol Lee and Hwangjun Song, “Cross layer optimizedvi<strong>de</strong>o streaming based on ieee 802.11 multi-rateover multi-hop mobile ad hoc networks,” Mob. Netw.Appl., vol. 15, pp. 652–663, October 2010.[7] M. Martinez-Rach, O. López, P. Piñol, M.P. Malumbres,J. Oliver, and Carlos T. Calafate, “Quality AssessmentMetrics vs. PSNR un<strong>de</strong>r Packet Loss Scenariosin MANET Wireless Networks,” in International Workshopon Mobile Vi<strong>de</strong>o (MV 2007), Augsburg, Germany,2007.[8] The Vi<strong>de</strong>oLAN Project, “Vlc: open-source multimediaframework, player and server,” Available at:http://www.vi<strong>de</strong>olan.org.[9] The MPlayer Project, “Mplayer - the movie player,”Available at: http://www.mplayerhq.hu/.[10] Janio M. Monteiro, Carlos T. Calafate, and Mario S.Nunes, “Evaluation of the H.264 Scalable Vi<strong>de</strong>o Codingin Error Prone IP Networks,” IEEE Transactionson Broadcasting, vol. 54, no. 3, pp. 652–659, September2008.[11] Jorge Hortelano, Marga Nacher, Juan-Carlos Cano, CarlosT. Calafate, and Pietro Manzoni, “Castadiva: A Test-Bed Architecture for Mobile Ad hoc Networks,” in 18thAnnual IEEE International Symposium on Personal, Indoorand Mobile Radio Communications (PIMRC’07),Athens, Greece, September 2007.[12] “The Vi<strong>de</strong>o Quality Experts Group (VQEG),” Availableat: http://www.its.bldrdoc.gov/vqeg/.[13] Sebastian Dorfler, “Xmedia reco<strong>de</strong> 2.2.9.7,” Available at:http://www.xmedia-reco<strong>de</strong>.<strong>de</strong>/.[14] T. Clausen and P. Jacquet, “Optimized link state routingprotocol (OLSR),” Request for Comments 3626, MANETWorking Group, http://www.ietf.org/rfc/rfc3626.txt,October 2003, Work in progress.<strong>JP2011</strong>-390


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Statistical Mo<strong>de</strong>ling of Transmission Path Lossin Un<strong>de</strong>rwater Acoustic NetworksJesús Llor and Manuel Pérez Malumbres 1Abstract—Propagation conditions in an un<strong>de</strong>rwateracoustic channel are known to vary in time, causing thereceived signal strength to <strong>de</strong>viate from the nominal valuepredicted by a <strong>de</strong>terministic propagation mo<strong>de</strong>l. Tofacilitate large-scale system <strong>de</strong>sign in such conditions (e.g.power allocation), we <strong>de</strong>velop a statistical propagationmo<strong>de</strong>l in which the transmission loss is treated as a randomvariable. By repetitive computation of acoustic field usingray tracing for a set of varying environmental conditions(surface height, wave activity, small displacements oftransmitter and receiver around nominal locations), anensemble of transmission losses is compiled which is thenused to infer the statistical mo<strong>de</strong>l parameters. A reasonableagreement is found with log-normal distribution whosemean is taken as the nominal transmission loss, and whosevariance appears to be constant for a certain range ofinter-no<strong>de</strong> distances in a given <strong>de</strong>ployment location. Thestatistical mo<strong>de</strong>l is <strong>de</strong>emed useful for higher-level systemplanning, where simulation is nee<strong>de</strong>d to assess theperformance of candidate network protocols un<strong>de</strong>r variousresource allocation policies, i.e. to <strong>de</strong>termine the transmitpower and bandwidth allocation necessary to achieve a<strong>de</strong>sire.Keywords—Un<strong>de</strong>rwater acoustics, Acoustic channelmo<strong>de</strong>l, Wireless sensor networks, Network simulation.TI. INTRODUCTIONHE growing need for ocean observation and remotesensing has recently motivated a surge in researchpublications as well as several experimental efforts (e.g.[1]) in the area of un<strong>de</strong>rwater acoustic networks. Crucialto these <strong>de</strong>velopments is the un<strong>de</strong>rstanding ofpropagation conditions that <strong>de</strong>fine the time-varying andlocation-sensitive acoustic environment, not only fromthe viewpoint of small-scale, rapid signal fluctuationsthat affect the performance of the physical layertechniques, but also from the viewpoint of large-scale,slow fluctuations of the received signal power thataffect the performance of higher network layers. Thisfact has been gaining recognition in the researchcommunity, leading to an increased awareness about theneed for network simulators that take into account thephysics of acoustic propagation [1]-[4]. As a result, thefirst publicly available acoustic network simulators haveemerged [2], and more are likely to come.One of the challenges in the <strong>de</strong>sign of un<strong>de</strong>rwateracoustic networks is the allocation of power acrossdifferent network no<strong>de</strong>s. This task is exacerbated by the1 All authors are with the Dept. of Physics and Computer Engineeringat the Miguel Hernan<strong>de</strong>z University (Spain). E-mails: {jllor,mels}@umh.esspatial and temporal variation of the large-scaletransmission loss, and the lack of statistical mo<strong>de</strong>ls thatcapture these apparently random phenomena.While it is well known from field experiments that thereceived power varies in time around the nominal valuepredicted by a <strong>de</strong>terministic propagation mo<strong>de</strong>l, little isknown about the statistical nature of these variations.Literature on this topic is scarce; however, several recentreferences indicate that the received signal strengthobeys a log-normal distribution (e.g. [5][6]). A goodsystem <strong>de</strong>sign has to budget for signal strengthvariations in or<strong>de</strong>r to ensure a <strong>de</strong>sired level of networkperformance (e.g. connectivity), and the budgeting taskcan be ma<strong>de</strong> much easier if the statistics of theun<strong>de</strong>rlying process are known.In this paper, we analyze those random variations inthe large-scale transmission loss that are mainlygoverned by the environmental factors such as surfaceactivity (waves) for a particular network scenario. Webegin by employing a prediction mo<strong>de</strong>l based on theBellhop ray tracing tool [7]. Such a <strong>de</strong>terministic mo<strong>de</strong>lprovi<strong>de</strong>s accurate results for a specific geometry of thesystem, but does not reflect the changes that occur as thegeometry changes slightly due to either surface motionor transmitter/receiver motion. Fig.1 illustrates thissituation for a point-to-point link. It shows an ensembleof transmission losses calculated by the Bellhop mo<strong>de</strong>lfor a set of varying surface conditions, each slightlydifferent from the nominal.While it is possible in principle to run a <strong>de</strong>terministicpropagation mo<strong>de</strong>l for a large number of differentsurface conditions, the un<strong>de</strong>rlying computational<strong>de</strong>mands are high. In a large network, it is ineffective,and possibly not even feasible, to run a complexprediction mo<strong>de</strong>l for each packet transmission. Astatistical prediction mo<strong>de</strong>l then becomes necessary.The goal of our work is to employ an existing<strong>de</strong>terministic prediction mo<strong>de</strong>l (DPM) such as the raytracer [7] to generate an ensemble of channel responsescorresponding to varying propagation conditions in agiven network. Using the so-obtained values, we thenconduct a statistical analysis to obtain the probability<strong>de</strong>nsity function (pdf) of the large-scale transmissionloss. The result is a statistical prediction mo<strong>de</strong>l (SPM)that is easy to employ for network <strong>de</strong>sign and analysis.The rest of this paper is organized as follows. In Sec.IIwe outline a specific system example, and discuss thecomputational <strong>de</strong>mands of <strong>de</strong>terministic propagationmo<strong>de</strong>ling. In Sec.III, we present the results of<strong>de</strong>terministic mo<strong>de</strong>ling and <strong>de</strong>velop an un<strong>de</strong>rlying<strong>JP2011</strong>-391


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011statistical mo<strong>de</strong>l. In Sec.IV we discuss the implicationsthat statistical mo<strong>de</strong>ling can have on networksimulation, and we conclu<strong>de</strong> in Sec.V.6563Transmission Loss (dB)61595755530 500 1000 1500 2000 2500 3000 3500Run Time (seconds)Fig. 1. An ensemble of transmission losses obtained from Bellhopmo<strong>de</strong>l. Solid line indicates the average over the total run time.Dashed lines indicate the values of one standard <strong>de</strong>viation σ.II. SYSTEM SET-UPThe network of interest is located in coastal watersnear Valencia, Spain, at coordinates 39°48'13.14"N and0°4'34.53"W. It consists of eight no<strong>de</strong>s arranged in alinear topology, as illustrated in Fig.2.In general, an arbitrary network location can beconsi<strong>de</strong>red, for which the bathymetry, floor sedimentand sound speed profile can be found in the onlinedatabases [8], [9], [10]. In our example, the source isassumed to be at one end, and the rest of the no<strong>de</strong>s areplaced at different distances ranging from 500m to3,700m. The no<strong>de</strong>s are at a <strong>de</strong>pth of 10 meters, while thewater <strong>de</strong>pth varies from 25m to 35m within the coveragearea. Table I summarizes the system parameters.We assume a fixed network topology, and vary theparameters that are related to the wave activity (waveheight and wave length). The surface parameters aretaken from historical and prediction values fromNational Geophysical Data Center databases [11], [12].We also account for the fact that an acousticcommunication signal does not consist of a singlefrequency, but occupies a (possibly wi<strong>de</strong>) bandwidth.The overall transmission loss is thus computed over theentire frequency range, which is taken here to be 5 kHz– 15 kHz.Each execution of the Bellhop tool [7] takes about 5minutes on an Intel Core 2 Duo CPU 2.10 GHzprocessor running on a standard laptop computer with 3GB of RAM memory. Consi<strong>de</strong>ring 14 different waveheights and 14 different wave lengths, i.e. 196 differentscenarios, the complete analysis lasts about 16 hours fora single source location and a single frequency withinthe signal bandwidth.Each simulation run produces the acoustic field valuesin a 5km x 5km x 30m volume, with a resolution of0.33m 3 . The values corresponding to selected receivingno<strong>de</strong> locations are then extracted, and a statisticalanalysis is performed for each location.Fig. 2. Network <strong>de</strong>ployment in Valencia, Spain.TABLE ISYSTEM PARAMETERSTransmission range 500 m to 3700 m (in steps of ~500 m)Area5000 m x 5000 mSediment floorFrequencyMonthGravel5-15 kHzAugustWave height 1 m to 3 m (in steps of 0.15 m)Wave length 100 m 150 m (in steps of 3.5 m)Water <strong>de</strong>pth25 m to 35 mIII. STATISTICAL PROPAGATION MODELThe statistical propagation mo<strong>de</strong>l is built bycompiling the transmission loss values obtained from the<strong>de</strong>terministic mo<strong>de</strong>l. The values of transmission loss,expressed in dB (logarithmic scale) are treated asrandom variables, and it is implicitly assumed that allsurface conditions are equally likely.Fig. 3 shows the histogram of the values obtained forNo<strong>de</strong> 2, which is 500 m away from the source, and Fig.4 shows the histogram obtained for No<strong>de</strong> 3, which is1100 m away from the source. Shown also in thesefigures is a normal distribution with mean and varianceequal to the ensemble averages of the transmission loss(solid curves).18016014012010080604020025 30 35 40 45 50 55 60 65 70Transmission Loss (dB)Fig. 3. Histogram of the transmission loss calculated for No<strong>de</strong> 2 usingthe <strong>de</strong>terministic propagation mo<strong>de</strong>l for varying surfaceconditions.<strong>JP2011</strong>-392


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 4. Histogram of the transmission loss calculated for No<strong>de</strong> 3 usingthe <strong>de</strong>terministic propagation mo<strong>de</strong>l for varying surfaceconditions.Transmission Loss (dB)16014012010080604020025 30 35 40 45 50 55 60 65 7080706050403020Transmission Loss (dB)500 1100 1600 2100 2600 3200 3700Distance (meters)Fig. 5. Transmission loss mean value and standard <strong>de</strong>viation (boxed)versus distance.The mean and variance obtained for different rangesfrom the source (different locations of the receivingno<strong>de</strong>) are shown in Fig.5. We note that the mean valueof transmission loss increases with distance, as dictatedby the energy spreading, assumed here to be cylindrical.The variance, however, does not change much with thedistance. This fact motivates us to assume the samevariance for all the distances consi<strong>de</strong>red. Namely, wetake the standard <strong>de</strong>viation to be the average of allobserved values, 5.91 dB (a negligibly different result isobtained if the variances are averaged).A statistical mo<strong>de</strong>l is now assumed, which generatesthe transmission loss as a normally distributed randomvariable on a logarithmic scale (or equivalently, lognormallydistributed on a linear scale). The mean valuefor this mo<strong>de</strong>l can be taken as the ensemble averageobtained from the <strong>de</strong>terministic mo<strong>de</strong>l for a givendistance, but another approach is possible as well.Namely, we take the mean transmission loss for thestatistical mo<strong>de</strong>l to be the value obtained from a singlerealization of the <strong>de</strong>terministic mo<strong>de</strong>l for nominalsystem geometry with no waves. The goal in doing so isto further reduce the computational <strong>de</strong>mands involved inbuilding the statistical mo<strong>de</strong>l for a given <strong>de</strong>ploymentgeometry.No<strong>de</strong>TABLE IITRANSMISSION LOSS PARAMETERS OBTAINED FROM THEDETERMINISTIC PROPAGATION MODEL AND STATISTICALPROPAGATION MODELDistance[m]DPMSPMmean [dB] σ [dB] mean [dB] σ [dB]2 500 41.78 6.14 41.653 1,100 47.82 5.91 48.014 1,600 50.83 5.60 50.795 2,100 53.81 6.12 53.806 2,600 56.52 5.74 56.327 3,200 59.01 5.88 58.988 3,700 60.50 5.96 60.41TABLE IIIKULLBACK-LEIBLER DISTANCE.No<strong>de</strong> Distance [m] KL distance2 500 0.0303 1,100 0.0214 1,600 0.0185 2,100 0.0176 2,600 0.0157 3,200 0.0145.918 3,700 0.013In Table II, we can see that nominal transmission loss(mean value listed for SPM) differs very little from thevalue calculated by ensemble averaging of the<strong>de</strong>terministic mo<strong>de</strong>l’s outputs (mean value listed forDPM). The pdf resulting from the statistical mo<strong>de</strong>l isshown in Figs.3 and 4 as a dashed curve.We note that the distributions resulting from the twomo<strong>de</strong>ls are quite similar. In or<strong>de</strong>r to quantitatively judgethe validity of the hypothesized statistical mo<strong>de</strong>l, wehave calculated the Kullback-Leibler (KL) distance [13]between the pdf estimated from the <strong>de</strong>terministic mo<strong>de</strong>l(histogram of Fig.3 and 4) and the Gaussian pdf used forthe statistical mo<strong>de</strong>l. This distance is zero when the twodistributions are i<strong>de</strong>ntical. In Table III, we list the KLdistance for every source-<strong>de</strong>stination pair consi<strong>de</strong>red.IV. IMPLICATIONS FOR NETWORK PLANNINGThe apparent match between the results of<strong>de</strong>terministic and statistical mo<strong>de</strong>ls motivates the use ofSPM for network <strong>de</strong>sign and analysis via simulation.Consi<strong>de</strong>r, for example, network simulation over aprolonged interval of time that spans varyingpropagation conditions and involves transmission of alarge number of data packets over multiple hops. If<strong>de</strong>terministic mo<strong>de</strong>ling is used, each packet transmissionrequires one execution of the Bellhop ray tracer, whichsoon becomes excessively long for a growing number ofdata packets (assuming 5 minutes for each Bellhop runand a single frequency, 100,000 packets would takeabout a year). Although the DPM offers an exactsolution for the particular geometry observed at anygiven moment in time, its execution makes thesimulation times unaffordable for benchmarking andtesting of the upper layer protocols.In contrast, a statistical mo<strong>de</strong>l can take several hoursto compute (16 hours in the example we presented) thepath loss statistical mo<strong>de</strong>l for the entire networkscenario, but once computed, each realization (packet<strong>JP2011</strong>-393


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011transmission) requires only a single call to a Gaussianrandom number generator. Moreover, if the networktopology changes slightly, or if a new no<strong>de</strong> is ad<strong>de</strong>d, thestatistical mo<strong>de</strong>l needs to be augmented only by thecorresponding set of nominal transmission losses, eachof which requires a single Bellhop run.Most importantly, the statistical mo<strong>de</strong>l can easily beused to assess transmit power allocation that willguarantee successful data packet reception with a<strong>de</strong>sired level of performance (e.g. link reliability).Namely, the SPM can easily be used to calculate thetransmission loss values that are not excee<strong>de</strong>d with agiven probability (i.e cumulative distribution function).For example, a 90% transmission loss is that valuewhich is not excee<strong>de</strong>d for 90% of time, i.e. in 90% ofchannel realizations. Fig.6 shows the 50%, 75% and90% transmission loss for our system example. Weobserve a good match between the values predicted bythe <strong>de</strong>terministic mo<strong>de</strong>l, and those of the statisticalmo<strong>de</strong>l. Note that the X% values of the SPM arecomputed analytically, based only on the knowledge ofthe mean and standard <strong>de</strong>viation.The availability of X% values is significant for<strong>de</strong>termining the transmit power necessary to achieve acertain level of performance. Typically, networkplanning is based on the nominal ray trace, i.e. on the50% transmission loss to which some margin may bead<strong>de</strong>d. If transmit power allocation is based on adifferent value, say 90% transmission loss instead of thenominal 50%, data packets will be more likely to reachtheir <strong>de</strong>stinations. More power will be nee<strong>de</strong>d at thesame time, but the overall network performance mayimprove. We say may improve, because a highertransmit power also implies higher levels ofinterference. The resulting performance tra<strong>de</strong>-offs aregenerally hard to address analytically, and are insteadassessed via simulation. A statistical propagation mo<strong>de</strong>lthat directly links the transmit power to the X%transmission loss then becomes a meaningful and usefultool for system <strong>de</strong>sign.Transmission Loss (dB)706560555045DPM 90%SPM 90%DPM 75%SPM 75%DPM 50%SPM 50%400 500 1000 1500 2000 2500 3000 3500 4000Distance (meters)Fig. 6. Transmission loss value that is not excee<strong>de</strong>d with a givenprobability (50 %, 70%, 90%) is shown versus distance. The solidand dashed curves show the results obtained from the<strong>de</strong>terministic and the statistical propagation mo<strong>de</strong>ls, respectively.V. CONCLUSIONS<strong>La</strong>rge-scale <strong>de</strong>sign of an un<strong>de</strong>rwater acoustic networkrequires a judicious allocation of the transmit poweracross different links to ensure a <strong>de</strong>sired level of systemperformance (connectivity, throughput, reliability, etc.).Because of the inherent system complexity, simulationanalyses are normally conducted to assess theperformance of candidate protocols un<strong>de</strong>r differentresource allocation policies. These analyses are oftenrestricted to using <strong>de</strong>terministic propagation mo<strong>de</strong>ls,which, although accurate, do not reflect the randomlytime-varying nature of the channel.While it is possible in principle to examine thenetwork performance for a large set of perturbedpropagation conditions, the computational complexityinvolved in doing so is extremely high. To facilitatenetwork simulation in the presence of channel fading,we investigated a statistical mo<strong>de</strong>ling approach. Ourapproach is based on establishing the nominal systemparameters for a <strong>de</strong>sired <strong>de</strong>ployment location (water<strong>de</strong>pth, sediment composition, operational frequencyrange) and using ray tracing to compute an ensemble oftransmission losses for typical inter-no<strong>de</strong> distances. Anensemble is generated by consi<strong>de</strong>ring a set of perturbedsurface conditions, <strong>de</strong>fined by varying wave activity(height, period). The so-obtained ensemble is then usedto <strong>de</strong>termine the statistical parameters of a hypothesizedlog-normal distribution of the transmission loss. For arepresentative example of a small network operating ina 5 km x 5 km area with inter-no<strong>de</strong> distances rangingbetween 500 m and 3.5 km, it was found that the meancan be well approximated by the value obtained usingnominal system parameters, while the variance can bemo<strong>de</strong>led as distance-in<strong>de</strong>pen<strong>de</strong>nt. Mo<strong>de</strong>ls that are moreelaborated and more accurate than the log-normal onecan also be <strong>de</strong>veloped using this approach.This kind of statistical mo<strong>de</strong>ling allowscomputationally-efficient inclusion of fading effects intoa network simulator. Namely, to assess the averagesystem performance, network operation has to besimulated over a large set of channel realizations (e.g.varying surface conditions). Whereas repeatedcomputation of the ray trace for different hops that eachof the data packets traverses in a given network may becomputationally prohibitive, statistical mo<strong>de</strong>lingrequires only a single call to the Gaussian randomgenerator for each packet transmission. The overallsimulation time is thus consi<strong>de</strong>rably reduced, allowing asystem <strong>de</strong>signer to freely experiment with varyingprotocols and resource allocation strategies in anefficient manner. The ultimate goal of such experimentsis to choose the best upper-layer protocol suite and torelate the necessary system resources (power,bandwidth) to the propagation conditions, i.e. to thestatistical parameters of the transmission loss (e.g. X%value), which can in turn be easily generated using theproposed method of statistical mo<strong>de</strong>ling<strong>JP2011</strong>-394


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011ACKNOWLEDGMENTSThis work was supported by the Ministry of Science andEducation of Spain un<strong>de</strong>r Project DPI2007-66796-C03-03.REFERENCES[1] J.A. Rice, W.O. Che, “A Discovery Process for InitializingUn<strong>de</strong>rwater Acoustic Networks,” in Proc. IEEE Sensorcomm,pp.408-415, July 2010.[2] F. Guerra, P. Casari, M. Zorzi, “A performance comparison ofMAC protocols for un<strong>de</strong>rwater networks using a realistic channelsimulator,” in Proc. IEEE Oceans Conf, pp.1-8, Oct. 2009.[3] G. Xie, J. Gibson, L. Diaz-Gonzalez, “Incorporating RealisticAcoustic Propagation Mo<strong>de</strong>ls in Simulation of Un<strong>de</strong>rwaterAcoustic Networks: A Statistical Approach,” in Proc. IEEEOceans Conf, pp.1-9, Sept. 2006.[4] J. Llor, M. Malumbres, “Performance Evaluation of Un<strong>de</strong>rwaterWireless Sensor Networks with OPNET,” in Proc. ACMSimutools. ICST, Barcelona, Spain, March 2011.[5] B. Tomasi, P. Casari, L. Badia, M. Zorzi, “A Study ofIncremental Redundancy Hybrid ARQ over Markov ChannelMo<strong>de</strong>ls Derived from Experimental Data,” in Proc. ACMWUWNet, Woods Hole, MA, Sep. 2010.[6] W.-B. Yang, T.C. Yang, “Characterization and Mo<strong>de</strong>ling ofUn<strong>de</strong>rwater Acoustic Communications Channels for Frequency-Shift-Keying Signals,” in Proc. IEEE Oceans Conf, pp.1-6, Sept.2006.[7] M. Porter et al., “Bellhop co<strong>de</strong>.” [Online]. Available: http://oalib.hlsresearch.com/ Rays/in<strong>de</strong>x.html.[8] “National geophysical data center, seafloor surficial sediment<strong>de</strong>scriptions”. [Online]. Available:http://www.ngdc.noaa.gov/mgg/ geology/<strong>de</strong>ck_41.html.[9] “General bathymetric chart of the oceans”. [Online]. Available:http:// www.gebco.net.[10] “World ocean atlas”. [Online]. Available:http://www.nodc.noaa.gov/ OC5/WOA05/pr_woa05.html.[11] “METEOSIM”, [Online]. Available: http://www.meteosim.com.[12] Puertos <strong>de</strong>l Estado, [Online]. Available: http://www.puertos.es.[13] A. Rényi, Probability Theory. New York: Elsevier, 1970.<strong>JP2011</strong>-395


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-396


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Predictive and Distributed Routing Balancingfor High Speed Interconnection NetworksCarlos Núñez Castillo, Diego Lugones 1 Daniel Franco,Emilio Luque 2Abstract— Current parallel applications in parallelcomputing systems require an interconnection networkto provi<strong>de</strong> low and boun<strong>de</strong>d communication <strong>de</strong>lays.Communication characteristics such as trafficpattern and communication load change over timeand, eventually, they may exceed available networkcapacity causing congestion and performance <strong>de</strong>gradation.Congestion control based on adaptive routingshould be applied in or<strong>de</strong>r to adapt quickly tochanging traffic conditions. Studies on a vast rangeof parallel applications show repetitive behavior andthat they can be characterized by a set of representativephases. This work presents a Predictive andDistributed Routing Balancing technique (PR-DRB)to control network congestion based on adaptive trafficdistribution. PR-DRB uses speculative routingbased on application repetitiveness. PR-DRB monitorsmessages latencies on routers and logs solutionsto congestion, to quickly respond in future similar situations.Experimental results show that the predictiveapproach could be used to improve performance.keywords— Interconnection networks, predictiverouting, parallel applications, application aware routing.I. IntroductionIN the early days of High Performance Computing(HPC) systems, interconnection network highlatency and low bandwidth bottleneck significantlyaffected applications execution. Advances in currentinterconnection technologies such as InfiniBand(IBA) [1] allowed higher transmission rate and lowerlatency, fulfilling with HPC requirements. HPC communicationsare characterized by bursty traffic, asopposite to a constant packet injection [2]. Burstytraffic can produce Hot-Spot situations, where somenetwork resources are congested while others remainsidle. If congestion is not efficiently controlled, messagelatency is increased and performance is <strong>de</strong>gra<strong>de</strong>d.One solution to this problem are the adaptiverouting algorithms. Communication patterns inHPC applications are repetitive [3]. This repetitivenesscould be useful to the routing module in or<strong>de</strong>rto solve future network situations based on past information.We propose a Predictive and DistributedRouting Balancing algorithm (PR-DRB) after consi<strong>de</strong>ringrouting algorithm limitations and requirementstogether with applications repetitiveness. Ourmain goal is to reduce latency un<strong>de</strong>r repetitive communicationpatterns. PR-DRB is based on DRB[4], but enhanced with a predictive routing module.1 Computer Architecture and Operating Systems Department,UniversitatAutónoma <strong>de</strong> Barcelona, Spain, e-mail:{carlos.nunez, diego.lugones}@caos.uab.es2 Computer Architecture and Operating Systems Department,UniversitatAutónoma <strong>de</strong> Barcelona, Spain, e-mail:{daniel.franco, emilio.luque}@uab.esDRB adapt itself to congestion by opening alternativepaths. This stabilization process is costly intime.The main contributions of this work is the capabilityto learn from a parallel application communicationpattern, solve congestion and then use this solutionwhen similar congestion is <strong>de</strong>tected again. Thisapproach allows fast reaction to repetitive congestionpatterns. Repetitive communication patternsalternated with computation is a typical HPC applicationfeature[2], and it represents an applicationphase [3]. Applications alternate between phases,which causes specific traffic patterns (e.g. a set ofsource/<strong>de</strong>stinations pairs) to reappear. PR-DRBstrategy is shown in Fig. 1. During application firstphase, PR-DRB has high latency values (1) becauseit is searching alternative paths. At the end of phase1 (2), latency is stable and the best solutions foundare saved at the source no<strong>de</strong>. Best solutions are i<strong>de</strong>ntifiedwhen latency curve starts <strong>de</strong>creasing. <strong>La</strong>terphases do not reach its highest historical latencyvalue. Here, PR-DRB has i<strong>de</strong>ntified similar communicationpatterns again(3) and best paths saved areused(4). PR-DRB approach is to maintain stable latencyvalues during the whole application execution.The rest of this paper is organized as follows. In Sec.2 congestion control, parallel application repetitivenessand their relation to this work are given. InSec. 3 the PR-DRB methodology is <strong>de</strong>scribed. Sec.4 shows the performance evaluation. Conclusion areexplained in Sec. 5.II. Background and JustificationA. Congestion ControlCongestion control is based on monitoring, <strong>de</strong>tectionand further control. To evaluate congestion,point to point latency [5], buffer occupation level [6]or backpressure [7] are used. One control techniqueis message Throttling [8], that stops (or reduces)packet injection until packets that belong to a congestedarea are <strong>de</strong>livered. Message throttling keepbuffer occupation boun<strong>de</strong>d but latency is increasedbecause packets must remain at source no<strong>de</strong>s longer.Finally, congestion control techniques based on adaptiverouting algorithms [4], [9], [10] work by sendingmessages from source to <strong>de</strong>stination through alternativepaths. Adaptive routing advantage is that congestedarea is avoi<strong>de</strong>d and message injection is upheld.The overhead resulting from information monitoring,the path changing and the need to guaranteeboth: <strong>de</strong>adlock freedom [11] and ’in-or<strong>de</strong>r’ packet<strong>de</strong>livery are some disadvantages.<strong>JP2011</strong>-397


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011B. Parallel Application RepetitivenessStudies of parallel applications in HPC revealthey have repetitive behavior, based on computingand communications phases [3]. Programs tend tobe written in a modular fashion, and have a verystrong periodic behavior [12]. On Fig. 2 the repetitivebehavior of the NAMD application is shown.This repetitive behavior represented by fundamentalphases of the entire application can lead to situationswhere specific traffic patterns reappear (e.g. a setof source/<strong>de</strong>stination pairs). Representative phasesfrom parallel applications can be extracted with thePAS2P performance prediction tool [3]. For example,the NAS CG benchmark has four representativephases and they consume 99.10% of execution time.Each phase here is repeated 2600 times on averageduring execution. The SMG2000: SemicoarseningMultigrid Solver, also has 4 representative phases,and they consume 99.99% of total execution time.Here, phases 1 to 4 are repeated 1, 1, 1185 and 15times, respectively. Here only phase 3 is relevant tocommunications. SWEEP3D: 3D Discrete OrdinatesNeutron Transport application has approximately 80different phases, but only 5 phases are representativeby consuming 96.17% of total time. Each of thesephases repeats 14874, 14257, 14930, 2062 and 12890times during the application execution.C. JustificationBased on previous examples of communicationpatterns repetitiveness, we can say that High SpeedInterconnection Networks (HSIN) routing performance<strong>de</strong>pends mostly on the communication patternused and the application mapping of no<strong>de</strong>s toprocessors. Some routing techniques use static applicationinformation, such as bandwidth, to help performrouting <strong>de</strong>cisions [13]. To improve communicationperformance, hence applications currently runningin the network, a technique capable to combineadaptive algorithms and communication patterns isnee<strong>de</strong>d, so that routing and congestion control canperform as fast as possible and minimize the overhead.III. Predictive-Distributed RoutingBalancingWe propose a routing algorithm, PR-DRB, basedon the study of communication latencies and repetitiveapplication patterns in HPC applications. PR-DRB internals is covered here in more <strong>de</strong>tails.A. PR-DRB Working SchemePR-DRB seeks better system response time by usingcached communication information and a set ofalternative paths. The proposed mo<strong>de</strong>l performs fourbasic tasks: Monitoring, Notification, Path Configurationand Path selection procedures. Monitoring inclu<strong>de</strong>sthe tasks of latency values accumulation andcontending flows i<strong>de</strong>ntification, performed at intermediaterouters. Notification is initiated at <strong>de</strong>sti-<strong>La</strong>tency behavior (s)(1) and (3) Congestion Detected(2) and (4) Stable <strong>La</strong>tencyHighCongestion(2)Stable latency valueTime (s)PR-DRB(latency)Traffic(1) Application (3) Application ApplicationPhase 1Phase 2Phase nLow Congestion(4)Fig. 1: PR-DRB-ProcessFig. 2: Repetitiveness in Parallel Applicationsnation endno<strong>de</strong>s. Here, and Acknowledge (ACK)message with path information is created and sentback to source endno<strong>de</strong>. The third task involves theconfiguration of new alternative paths, according tolatency values. This task is named Metapath Configurationand is also performed at source no<strong>de</strong>s. Ifthere are saved solutions for a congestion situation,the paths are taken from the saved solution database.Otherwise, new alternative paths are created. <strong>La</strong>ter,the fourth task is accomplished when new messagesare injected into the network. Here, selection procedureschoose best paths among those configured inprevious task.At the monitoring phase, latency values are accumulatedin messages at every intermediate router.The aggregate latency value will be used later at thesource no<strong>de</strong> to i<strong>de</strong>ntify congested regions. An intermediaterouter contains information about sourcesand <strong>de</strong>stinations currently enqueued. This informationrepresents contending flows for PR-DRB. Congestionand conflictive pattern <strong>de</strong>tection are also performedin the monitoring phase. When aggregatelatency value surpasses a threshold in the path, contendingflows are i<strong>de</strong>ntified and saved in the messagetogether with latency values. When at <strong>de</strong>stination,an acknowledge message (ACK) with contendingflows and latencies is sent to the source. At theconfiguration phase, calculation of all possible pathsavailable to tackle congestion is performed. Selectionthen performs dynamic path expansion controlled bycongestion level in each source/<strong>de</strong>stination path.Each alternative path is created, schematically, usinga three step path (multi step path, MSP) by selectingtwo intermediate no<strong>de</strong>s, near by the source(IN1) and <strong>de</strong>stination (IN2) no<strong>de</strong>s. PR-DRB buildsalternative paths around the original path. Each singlepath is traversed using original routing <strong>de</strong>finedfor the topology. <strong>La</strong>tency information is used to <strong>de</strong>-Load (bits/s)<strong>JP2011</strong>-398


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011ci<strong>de</strong> the number of alternative paths and how to distributemessages among these paths. Afterwards, latency,alternative paths used and conflictive communicationpatterns are all cached at source. With thisprocedure, best paths for each source/<strong>de</strong>stinationpair un<strong>de</strong>r a particular congestion situation are beingsaved. In future similar congestion situation, thebest known solution will be re-applied directly. PR-DRB working scheme is shown in Fig. 3. Detectionand latency logging as well as the pattern that causedcongestion are shown in Fig. 3 (a). Configuration ofa set of possible start no<strong>de</strong>s for alternative paths (theMeta path) is shown in Fig. 3 (b), and a set of alternativepaths used at the MSP are shown in Fig.3(c).B. PR-DRB FunctionalityFig. 4 shows PR-DRB functionality. The fourtasks of PR-DRB are also highlighted in Fig. 4.When a source no<strong>de</strong> wants to send some data, <strong>de</strong>pictedin Source Endno<strong>de</strong>, a message is built andinjected into the network. Then, as seen in MessageRouting, the multi-hea<strong>de</strong>r message is forwar<strong>de</strong>dthrough intermediate routers. As shown in the Monitoringbox in Fig. 4, the <strong>de</strong>lay suffered in switchbuffers (queuing latency) is logged into the message.If queuing latency values exceeds a threshold whilestill at intermediate routers, contending flows patternsare also logged by PR-DRB. This allows similartraffic pattern recognition in future communications.Once the message reaches <strong>de</strong>stination, as seen in DestinationEndno<strong>de</strong>, Notification takes place. The Notificationbox <strong>de</strong>picts the task involved in this procedure.Here, latency as well as conflictive communicationpatterns found are sent back to the source inan acknowledge message (Ack). Not all contendingflows are notified, but only those which contributesmost to congestion. At source no<strong>de</strong>s latency valueand contending flows are analyzed. The analysis procedureis shown in the Fig. 4, at the Metapath Configurationbox. This module configures alternativepaths to be used accordingly to latency value. If latency<strong>de</strong>notes congestion, then new alternative pathsare nee<strong>de</strong>d. PR-DRB then looks for an already analyzedcongestion situation. If this is the case, the setof optimal alternative paths used previously is obtainedfrom the database. If no solutions are found,then alternative paths opening procedures are initiated.If latency values <strong>de</strong>notes congestion stabilization,then alternative paths closing procedures areinvoked. Here, information about contending flowsduring congestion situations is also updated. Basedon parallel application repetitiveness, meta path configurationcan be simplified to use cached informationfrom the first phase of the program execution.<strong>La</strong>ter, when a message is ready to be injected intothe network PR-DRB performs the Path Selection.This module selects a multi step path (MSP) for eachmessage. Here, PR-DRB selects which paths are goingto be used from those configured in the MetapathConfiguration step. A distribution of communicationload over the meta path is accomplished in or<strong>de</strong>r toperform the dynamic traffic balancing. Paths havinglower latency values are more frequently used,and they receive proportionally a greater number ofmessages. Path expansion is performed gradually.Given a source no<strong>de</strong> with N alternative paths, let’sbe L c i(i : 1..N) the latency recor<strong>de</strong>d by path Ci. Thealternative path Cx will be selected in the followinginjection according to the probability:p(Cx) =(1/L Cx)∑ Ni=1 1/L Ci(1)When congestion first appears in the network, PR-DRB learns from those situations. As parallel scientificapplication do have repetitive communicationpatterns in time, when PR-DRB i<strong>de</strong>ntify a similaralready analyzed situation, it looks for a set of optimalpaths into its database of saved solutions. Theprocess of <strong>de</strong>tecting already analyzed situations isbased on similarity. PR-DRB is based on contendingflows comparisons during congestion. As statedin section III-A, a router logs latency values and contendingflows during congestion situations. Whena new packet arrives, congestion level in the pathis evaluated, and contending flows involved are updated.PR-DRB compares the saved list of contendingflows against the new list arriving. Similarity isbased on approximation matching. If some pre<strong>de</strong>finedpercentage of no<strong>de</strong>s matches in both lists, thenPR-DRB marks this situation as already analyzed.As shown in Fig. 4, a message is forwar<strong>de</strong>d withoutany overhead when the output port is free (thickarrows). Otherwise, packet is queued and latencyis simultaneously accumulated until the message isready to be forwar<strong>de</strong>d again. As PR-DRB is basedon the DRB algorithm, already proposed congestioncontrol technique for Infiniband [11] could be alsoFig. 3: PR-DRB working scheme<strong>JP2011</strong>-399


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 4: PR-DRB-ProcessFig. 5: PR-DRB Final solution savedused. As IBA already has many of the functionalitiesrequired by PR-DRB, integration of the predictivemodule is fairly feasible. For example, IBAswitches already have monitoring functions. Also aprocedure for congestion notification (CN) is availableand path opening procedures can be configuredby the Congestion Control Agents (CCA).C. Contending Flows and Solution RepresentationA complete path expansion process is given in Fig.5. We can see that PR-DRB, for this example, goesthrough three steps in or<strong>de</strong>r to find the proper setof alternative paths to alleviate congestion. Thisset of alternative paths conform the best solutionfound so far. In or<strong>de</strong>r to reuse the same known solutionafterwards, PR-DRB saves contending flowsand best solutions information. Contending flowspairs (S1-D1, S2-D2) are i<strong>de</strong>ntified, as well as thepaths opened for this solution (P1, P2, P3). The inforegistered is given in Fig. 5 “No<strong>de</strong> S1 - Saved Solution”.This diagram corresponds to what the no<strong>de</strong> S1knows about the congestion situation, and the pathsit should open once it contends again against no<strong>de</strong>S2. Because the no<strong>de</strong>s involved in congestion willbe correctly notified, each source involved should fillits own table with particular paths opened for thissituation.D. PR-DRB Consi<strong>de</strong>rationsThe Ack generation is invoked only when congestionis <strong>de</strong>tected, and its operations are performedwhen messages are waiting in the queue. Hence, computingthese operations and packet <strong>de</strong>livery are performedconcurrently, as shown in Fig. 4. PR-DRBno<strong>de</strong> level operations have not a high overhead becausethese operations are performed locally, they aresimple (comparisons and accumulations for latencyevaluation, logging small traffic info), and they donot <strong>de</strong>lay send/receive primitives. During multi steppath creation, <strong>de</strong>adlock freedom is ensured by havinga separate escape channel for each segment. Withtwo intermediate no<strong>de</strong>s, one escape channel is usedfrom S to IN1, another from IN1 to IN2, and a thirdone from IN2 to D. This way, each segment <strong>de</strong>finesa virtual network, and the packets change virtualnetwork at each intermediate no<strong>de</strong>. Although eachvirtual network relies on a different escape channel,they all share the same adaptive channel(s). The useof adaptive routing algorithms can cause out of or<strong>de</strong>r<strong>de</strong>livery of packets. If an application requires inor<strong>de</strong>rpacket <strong>de</strong>livery, a possible solution is to reor<strong>de</strong>rpackets at the <strong>de</strong>stination no<strong>de</strong> using the well knownsliding window protocol, as used in other routingpolicies like [9]. The following section presents theperformance evaluation of PR-DRB policy. The evaluationmethodology is <strong>de</strong>signed to compare PR-DRBbehavior against DRB [4], which has been alreadycompared against other traditional algorithms, un<strong>de</strong>rdifferent interconnection network scenarios.IV. PR-DRB EvaluationThis section presents the performance evaluationof PR-DRB. <strong>La</strong>tency is evaluated in or<strong>de</strong>r to assessPR-DRB. <strong>La</strong>tency is the time elapsed since a packetis created until it reaches its <strong>de</strong>stination, and it ismeasured in seconds. Evaluation is divi<strong>de</strong>d in twoparts. For the first, simulations were conducted for a64 no<strong>de</strong>s network arranged in an 8x8 mesh topologyun<strong>de</strong>r hotspot traffic. Second part was conductedfor fat tree topologies with 32 and 64 no<strong>de</strong>s un<strong>de</strong>rdifferent permutation traffic.A. Mo<strong>de</strong>ling EnvironmentPR-DRB operations, together with network componentswere mo<strong>de</strong>led [14] using the standard simu-<strong>JP2011</strong>-400


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011lation and mo<strong>de</strong>ling tool OPNET Mo<strong>de</strong>ler [15]. OP-NET provi<strong>de</strong>s a Discrete Event Simulator (DES) engineand a hierarchical mo<strong>de</strong>ling environment. Thisallows <strong>de</strong>fining network components behavior by aFinite State Machine approach (FSM), and it supports<strong>de</strong>tailed specification of protocols, algorithms,and queuing policies among others. We have assumedvirtual Cut-through flow control [16]. LinkBandwidth was set to 2Gbps, packet size was set to1024 bits and the size of routers buffers was 2MB.B. Hotspot AnalysisThe first part evaluates network response analysisun<strong>de</strong>r bursty Hot-spot traffic using a mesh topology,to evaluate traffic load distribution. This Hotspotexperiment establishes some fixed <strong>de</strong>stinations toproduces network congestion. Remaining networkno<strong>de</strong>s inject uniform load to create ”noisy” traffic.DRB response to the repetitive bursty traffic is alwaysthe same, due to its inability to learn frompast communications. On the other hand, PR-DRBi<strong>de</strong>ntifies repeated communication patterns and usescached solutions to congestion. Figs. 6 and 7 showaverage latency map of the mesh network after theexecution of the whole bursty simulation. The surfaceis the average contention latency at buffers. Fig.6 shows DRB behavior, which exhibits high latencyvalues un<strong>de</strong>r congested areas. Also, load distributionat routers in coordinates (x,y) (0,1), (6,2) and(6,4) are high, because DRB uses these routers inits alternative paths. Fig. 7 shows the latency mapfor PR-DRB; where its highest value is lower thanDRB. Better load distribution is accomplished byPR-DRB, because it used the best solutions saved,and unnecessary load at routers are avoi<strong>de</strong>d.Fig. 6: Mesh network latency map - DRBFig. 7: Mesh network latency map - PR-DRBC. Analysis with Permutation TrafficIn this section PR-DRB is evaluated against DRB,un<strong>de</strong>r the fat tree topology with 32 and 64 no<strong>de</strong>s.Communication patterns such as: ”Matrix Transpose”and ”Perfect Shuffle” were used. Fig. 8 showslatency behavior with 32 no<strong>de</strong>s. Fig. 8a and 8bshows the performance un<strong>de</strong>r Matrix transpose pattern,with traffic load from 400 to 600 mbps/no<strong>de</strong>respectively. PR-DRB latency reduction achieved is24% un<strong>de</strong>r both load scenarios. The Increased trafficinjection is handled properly by PR-DRB. Propercommunication balancing procedures and packetssent through optimal alternative paths from the beginning,keep congestion at minimum. Un<strong>de</strong>r 600mbps/no<strong>de</strong> injection, PR-DRB uses progressivelythe maximum number of alternative paths to <strong>de</strong>livermessages. For repetitive traffic patterns, maximumpath expansion is done directly. By avoidingintermediate path expansion, unnecessary ACK messagesare not generated and overhead is minimizedat source and intermediate no<strong>de</strong>s. With at most 4 alternativepaths for these experiments, PR-DRB performsa remarkable lower latency than DRB. Fig. 9ashows results with 64 communicating no<strong>de</strong>s. <strong>La</strong>tencyreduction un<strong>de</strong>r the perfect shuffle pattern is 32%.Fig. 9b shows the result un<strong>de</strong>r the Matrix Transposepattern. Higher traffic load is injected into thenetwork and latency remains boun<strong>de</strong>d. <strong>La</strong>tency isconsi<strong>de</strong>rable reduced here, around 40%, comparedto DRB. PR-DRB uses less network resources fora given load, because those resources are efficientlyhandled. Recall that PR-DRB will behave similarlyto DRB only un<strong>de</strong>r the execution of the first phaseof the parallel application, because in this stage PR-DRB is learning from the paths opening procedures.In later phases of parallel applications, like thoseshown here, PR-DRB will apply directly the best solutionsencountered previously. From approximatelytime 1.015 latency values of both algorithms tend tobecome stable and converge.V. ConclusionIn this paper we proposed the Predictive and DistributedRouting Balancing PR-DRB. This strategyuses alternative paths un<strong>de</strong>r congestion situation toreduce latency and increase bandwidth availability,by consi<strong>de</strong>ring time as well as traffic dynamic behaviorconstraints. Routing algorithms try to adaptparallel applications traffic load to network topology.These applications that run on an HSIN possessrepetitive behavior, and PR-DRB is capable to learnfrom it and save information for later use. PR-DRBhas been <strong>de</strong>veloped to fulfill HSIN <strong>de</strong>sign objectivessuch as all-to-all connection, and low and uniform latencybetween any pair of no<strong>de</strong>s un<strong>de</strong>r any messagetraffic load. The proposed method is also in line withcurrent approaches used in commercial interconnects(as InfiniBand [1]). Our policy allows heavier communicationload in the network, or in cost-boun<strong>de</strong>d<strong>JP2011</strong>-401


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011(a) 400 mbps(b) 600 mbpsFig. 8: Permutation patterns - Fat tree 32 no<strong>de</strong>s. Range from 400 to 600 mbps/no<strong>de</strong>(a) 400 mbps(b) 600 mbpsFig. 9: Permutation patterns - Fat tree 64 no<strong>de</strong>s.data centers it allows using less network components,because they are more efficiently handled. The evaluationperformed to validate PR-DRB has revealedvery good improvements in latency. Saturation isreduced allowing the use of the network at higherloads. We have shown that PR-DRB is a fast androbust method with a very low overhead. Additionally,PR-DRB is useful for permutation and burstycommunication patterns, which are commonly createdby parallel applications and can produce theworst hot-spot situations. As future work, we planto predict future congestion before it has effectivelyappeared based on latency trend analysis.ACKNOWLEDGMENTThis research has been supported by the MEC-MICINN Spain un<strong>de</strong>r contract TIN2007-64974.References[1] Infiniband, “Iba,” http://www.infinibandta.org/, 2011.[2] German Rodriguez et al., “Exploring pattern-aware routingin generalized fat tree networks,” in ICS ’09: Procs ofthe 23rd int. conf. on Supercomputing, New York, USA,2009, pp. 276–285, ACM.[3] A. Wong et al., “Parallel application signature,” CLUS-TER ’09. IEEE Int. Conf. on, vol. 1, pp. 1–4, 2009.[4] D. Franco et al., “A new method to make communicationlatency uniform: distributed routing balancing,” inICS ’99: Procs of the 13th int. conf. on Supercomputing,USA, 1999, pp. 210–219, ACM.[5] D. Lugones et al., “Dynamic and distributed multipathrouting policy for high-speed cluster networks,” in CC-GRID ’09: Procs of the 2009 9th IEEE/ACM Int. Symp.on Cluster Computing and the Grid, USA, 2009, pp. 396–403.[6] P.J. Garcia et al., “Recn-dd: A memory-efficient congestionmanagement technique for advanced switching,”Parallel Proc., Int. Conf. on, vol. 0, pp. 23–32, 2006.[7] Elvira Baydal et al., “A family of mechanisms for congestioncontrol in wormhole networks,” IEEE Trans. ParallelDistrib. Syst., vol. 16, no. 9, pp. 772–784, 2005.[8] Shihang Yan et al., “An enhanced congestion controlmechanism in infiniband networks for high performancecomputing systems,” Adv. Inf. Networks and App., Int.Conf. on, vol. 1, pp. 845–850, 2006.[9] Arjun Singh et al., “Globally adaptive load-balancedrouting on tori,” IEEE Comput. Archit. Lett., vol. 3,no. 1, pp. 2, 2004.[10] Christopher J. Glass et al., “The turn mo<strong>de</strong>l for adaptiverouting,” SIGARCH Comput. Archit. News, vol. 20, no.2, pp. 278–287, 1992.[11] D. Lugones et al., “Dynamic routing balancing on infinibandnetworks,” in Journal of Comp. Science & Tech.(JCS&T), 2008, Cluster Computing ’08, pp. 104–110.[12] Timothy Sherwood et al., “Basic block distribution analysisto find periodic behavior and simulation points in applications,”in PACT ’01: Procs of the 2001 Int. Conf.on Par. Arch. and Compil. Tech., USA, 2001, pp. 3–14,IEEE Comp. Soc.[13] Michel. Kinsy et al., “Application-aware <strong>de</strong>adlock-freeoblivious routing,” in ISCA’09: Procs of the 36th annualint. symp. on Comp. arch., USA, 2009, pp. 208–219,ACM.[14] D. Lugones et al., “Mo<strong>de</strong>ling adaptive routing protocolsin high speed interconnection networks,” OPNETWORK2008 Conf., 2008.[15] Technologies. OPNET, “Opnet mo<strong>de</strong>ler accelerating networkr&d,” http://www.opnet.com, June 2008, OPNET.[16] Jose Duato et al., Interconnection Networks: An EngineeringApproach, Morgan Kaufmann Publishers Inc.,USA, 2002.<strong>JP2011</strong>-402


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Evaluación <strong>de</strong> una alternativa para aumentarel número <strong>de</strong> puertos <strong>de</strong> los conmutadoresJuan A. Villar, Francisco J. Andújar, José L. Sánchez, Francisco J. Alfaro 1 y José Duato 2Resumen— En las re<strong>de</strong>s <strong>de</strong> interconexión basadasen conmutadores, el aumento <strong>de</strong>l número <strong>de</strong> puertos<strong>de</strong> un conmutador conlleva una reducción <strong>de</strong>l númerototal <strong>de</strong> componentes <strong>de</strong> la red, lo que provocauna reducción significativa <strong>de</strong>l coste total <strong>de</strong>l sistema.A<strong>de</strong>más, los conmutadores high-radix suponen una alternativainteresante para mejorar el rendimiento <strong>de</strong>la red en términos <strong>de</strong> latencia pues reducen el número<strong>de</strong> saltos <strong>de</strong> los paquetes. Sin embargo, existen variosproblemas relacionados con la escala <strong>de</strong> integraciónpara diseñar estos conmutadores en un único chip.En este artículo se explica y evalúa una alternativa <strong>de</strong>construcción <strong>de</strong> conmutadores high-radix más allá <strong>de</strong>los límites permitidos por la escala <strong>de</strong> integración actual.<strong>La</strong> i<strong>de</strong>a consiste básicamente en combinar variosconmutadores, cada uno en un chip, obteniendo unconmutador con un número <strong>de</strong> puertos agregado mayor.Esta propuesta es in<strong>de</strong>pendiente <strong>de</strong> la evolución<strong>de</strong> los conmutadores <strong>de</strong> un único chip y seguirá siendoválida conforme la escala <strong>de</strong> integración continúeevolucionando. Los resultados <strong>de</strong> simulación han mostradoque con un diseño a<strong>de</strong>cuado <strong>de</strong>l conmutador, lasre<strong>de</strong>s construidas con conmutadores que implementanesta alternativa pue<strong>de</strong>n alcanzar un rendimiento similaral rendimiento <strong>de</strong> re<strong>de</strong>s construidas con conmutadoresen un chip que proporcionen el mismo número<strong>de</strong> puertos, pero dichos conmutadores no existen enla actualidad en el mercado porque la escala <strong>de</strong> integraciónno permite construirlos en un único chip.Palabras clave— Conmutadores High-Radix, Re<strong>de</strong>s<strong>de</strong> Altas Prestaciones, Evaluación <strong>de</strong> Rendimiento.I. IntroducciónLAS re<strong>de</strong>s <strong>de</strong> interconexión son un componenteclave para una amplia gama <strong>de</strong> sistemas multiprocesadorque van <strong>de</strong>s<strong>de</strong> los supercomputadores achips multinúcleo. <strong>La</strong>s re<strong>de</strong>s <strong>de</strong> alto rendimiento sonesenciales para estos sistemas, don<strong>de</strong> se requiere unafiabilidad alta, a<strong>de</strong>más <strong>de</strong> gran<strong>de</strong>s tasas <strong>de</strong> transferenciay latencias muy bajas. A menudo, la red <strong>de</strong>interconexión es el subsistema que requiere un diseñopersonalizado. Por ejemplo, el superor<strong>de</strong>nadorTianhe-1A [1], número uno <strong>de</strong>l Top500 (noviembre2011), está compuesto por procesadores comunes, yuna red <strong>de</strong> interconexión personalizada. El diseño <strong>de</strong>dicha red ha eliminado los cuellos <strong>de</strong> botella contribuyendosignificativamente al rendimiento global <strong>de</strong>lTianhe-1A.El diseño <strong>de</strong> la red está <strong>de</strong>terminado por la tecnología<strong>de</strong> integración cuyos avances han mejoradosustancialmente el rendimiento <strong>de</strong> sus componentesbásicos: enlaces y conmutadores. Estos últimos sonresponsables <strong>de</strong> gran parte <strong>de</strong>l nivel <strong>de</strong> prestaciones<strong>de</strong> la red, por lo que son objeto <strong>de</strong> mayor investiga-1 Departamento <strong>de</strong> Sistemas Informáticos. <strong>Universidad</strong><strong>de</strong> Castilla-<strong>La</strong> Mancha. Albacete. España. e-mail:{juanan,fandujar,falfaro,jsanchez}@dsi.uclm.es2 Departamento <strong>de</strong> Informática <strong>de</strong> Sistemas y Computadores.<strong>Universidad</strong> Politécnica <strong>de</strong> Valencia. Valencia. España.e-mail: jduato@disca.upv.esción. Uno <strong>de</strong> los principales parámetros que caracterizana los conmutadores es su número <strong>de</strong> puertos (ogrado), el cual tiene una fuerte influencia en el coste,consumo y rendimiento en todo el sistema.Dado un sistema multiprocesador con un númeroelevado <strong>de</strong> terminales conectados, aumentar el grado<strong>de</strong> los conmutadores resulta en una disminución enel número <strong>de</strong> conmutadores y enlaces <strong>de</strong> red. Puestoque el coste <strong>de</strong> la red es proporcional al número<strong>de</strong> conmutadores, es evi<strong>de</strong>nte que el coste se reducemediante el uso <strong>de</strong> conmutadores <strong>de</strong> mayor grado.Por otra parte, el consumo total <strong>de</strong> la red tambiénse reduce consi<strong>de</strong>rablemente, ya que es directamenteproporcional al número <strong>de</strong> conmutadores en la red.Con respecto al rendimiento, por ejemplo, es evi<strong>de</strong>nteque en términos <strong>de</strong> latencia el uso <strong>de</strong> conmutadorescon más puertos implica una reducción enel tiempo medio para transferir datos a través <strong>de</strong> lared. En particular, con menos conmutadores para conectarel mismo número <strong>de</strong> terminales se reduce elnúmero <strong>de</strong> saltos y el número <strong>de</strong> posibles colisiones<strong>de</strong> paquetes en la red, y por lo tanto el tiempo queellos emplean para llegar a sus <strong>de</strong>stinos. A<strong>de</strong>más, conmenos conmutadores, el tiempo <strong>de</strong> procesamiento total<strong>de</strong> los paquetes en los conmutadores a lo largo <strong>de</strong>sus caminos también se reduce.Por lo tanto, el diseño <strong>de</strong> conmutadores con un elevadonúmero <strong>de</strong> puertos es una opción atractiva paramejorar el rendimiento y reducir el coste <strong>de</strong> la red <strong>de</strong>interconexión, especialmente para sistemas multiprocesador<strong>de</strong> gran tamaño. Sin embargo, hay algunosproblemas en el diseño <strong>de</strong> éstos. Uno <strong>de</strong> ellos está relacionadocon la complejidad <strong>de</strong> su lógica pues sevuelve más compleja a medida que aumenta el grado[2]. El equilibrio entre el coste y la eficiencia no esfácil <strong>de</strong> tratar, requiriendo un estudio profundo sobreesta disyuntiva. Por un lado, el tamaño <strong>de</strong> algunas estructuras<strong>de</strong>l conmutador crece cuadráticamente conel grado. Por ejemplo, tal es el caso <strong>de</strong>l espacio <strong>de</strong> losbuffers [3], o <strong>de</strong> los planificadores [4]. Por otra parte,las políticas tradicionales <strong>de</strong> control <strong>de</strong> flujo tambiénse ven afectadas por el grado <strong>de</strong>l conmutador en dosaspectos [5]: el tiempo roundtrip aumenta drásticamente,y las memorias para el almacenamiento <strong>de</strong>créditos <strong>de</strong>l control <strong>de</strong> flujo son linealmente <strong>de</strong>pendientes<strong>de</strong>l roundtrip. Por otro lado, el número <strong>de</strong>pines <strong>de</strong>l chip (pincount) aumentará lentamente enla próxima década según el ITRS [6], y por tanto elnúmero <strong>de</strong> puertos aumentará ligeramente. Por otraparte, existen dificulta<strong>de</strong>s para aplicar algunas técnicascuando el número <strong>de</strong> puertos es alto. Así, VirtualOutput Queuing (VOQ) [7] es inviable para los conmutadorescon un grado alto. Para superar estos problemas,se han propuesto diferentes soluciones pero<strong>JP2011</strong>-403


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011en realidad, éstas están posponiendo el problema paralas generaciones veni<strong>de</strong>ras <strong>de</strong> conmutadores.En cualquier caso, las restricciones <strong>de</strong> tamaño <strong>de</strong>lconmutador están <strong>de</strong>terminadas principalmente porla escala <strong>de</strong> integración actual y número <strong>de</strong> pines <strong>de</strong>lchip. Para ir más allá <strong>de</strong> los límites <strong>de</strong> la escala <strong>de</strong> integración,una solución alternativa para la construcción<strong>de</strong> conmutadores high-radix es la combinación<strong>de</strong> varios conmutadores <strong>de</strong> grado menor.<strong>La</strong> i<strong>de</strong>a principal es implementar conmutadores <strong>de</strong>m ′ puertos a partir <strong>de</strong> varios conmutadores más pequeños<strong>de</strong> m puertos. Por ejemplo, un conmutador <strong>de</strong>m ′ puertos compuesto por dos conmutadores idénticos<strong>de</strong> m puertos (m ′ /2 < m < m ′ ), interconectadosinternamente por medio <strong>de</strong> m − m ′ /2 puertos,empleando los puertos restantes para las conexionescon el exterior (figura 1a). Nótese que esta estrategiaseguirá siendo válida conforme la tecnología <strong>de</strong>integración continúe evolucionando.Una consecuencia <strong>de</strong>stacable es que el conmutadorresultante ya no es homogéneo. Su rendimiento <strong>de</strong>pen<strong>de</strong>rá<strong>de</strong> la configuración interna. Así, la interconexión<strong>de</strong> los conmutadores internos pue<strong>de</strong> convertirseen un cuello <strong>de</strong> botella si éstos tienen que soportarla mayoría <strong>de</strong>l tráfico manejado por el conmutador.Por lo tanto, es esencial minimizar el impacto <strong>de</strong> estecuello <strong>de</strong> botella, <strong>de</strong> lo contrario la latencia <strong>de</strong> lared aumentará. Así, el patrón <strong>de</strong> conexión a nivel <strong>de</strong>conmutador 1 (SCP) se convierte en una <strong>de</strong>cisión <strong>de</strong>diseño importante en la construcción <strong>de</strong> este tipo <strong>de</strong>conmutadores. Un patrón arbitrario probablementeproducirá una <strong>de</strong>gradación significativa <strong>de</strong> prestaciones,y por ello, es necesario <strong>de</strong>terminar el patrón másconveniente para po<strong>de</strong>r extraer el mayor rendimiento<strong>de</strong>l conmutador.En este artículo, se <strong>de</strong>scribe y evalúa esta alternativapara obtener conmutadores high-radix. Tambiénse discuten cuestiones clave que <strong>de</strong>terminan su rendimiento.De hecho, se mostrará que el SCP y el ancho<strong>de</strong> banda <strong>de</strong> comunicación entre los conmutadoresinternos son cruciales para el comportamiento <strong>de</strong>lconmutador. Se <strong>de</strong>be alcanzar un compromiso entreambos aspectos para obtener diseños <strong>de</strong> conmutadoreseficientes.Este artículo está organizado como sigue: la secciónII repasa brevemente las propuestas existentessobre conmutadores high-radix. Tras ello, en la secciónIII se dan <strong>de</strong>talles sobre la alternativa propuestapara la construcción <strong>de</strong> conmutadores high-radix,y en la sección IV se incluyen los resultados <strong>de</strong> laevaluación realizada. Finalmente, se aportan algunasconclusiones en la sección V.II. Trabajo RelacionadoEn esta sección se revisan las propuestas existentes<strong>de</strong> conmutadores high-radix que se han centrado1 En a<strong>de</strong>lante, se diferenciará entre patrón <strong>de</strong> conexión a nivel<strong>de</strong> red y patrón <strong>de</strong> conexión a nivel <strong>de</strong> conmutador. Elprimero es el patrón <strong>de</strong> interconexión tradicional utilizado enre<strong>de</strong>s basadas en conmutadores (por ejemplo, la permutaciónbutterfly utilizada para conectar los conmutadores en las re<strong>de</strong>smultietapa); y el segundo patrón hace referencia a cómo lospuertos externos <strong>de</strong> un conmutador high-radix se mapean enlos puertos <strong>de</strong> los conmutadores internos.principalmente en resolver problemas con los diseñostradicionales.El conmutador YARC [8] es el conmutador highradixutilizado por el Cray BlackWidow [9]. Trata <strong>de</strong>incrementar el número <strong>de</strong> puertos consi<strong>de</strong>rando enlacesmás <strong>de</strong>lgados en lugar <strong>de</strong> enlaces anchos. Los diseños<strong>de</strong> conmutadores tradicionales con pocos puertosno pue<strong>de</strong>n adaptarse a conmutadores high-radixporque los diseños tradicionales emplean una organizacióncentralizada que no escala apropiadamente.Por otra parte, Partitioned Crossbar Input Queued[10] es más reciente y propone una organización interna<strong>de</strong> conmutadores high-radix, y trata con una <strong>de</strong>las restricciones principales en el diseño <strong>de</strong> conmutadoreshigh-radix: los excesivos requerimientos <strong>de</strong>memoria.Con respecto a la alternativa <strong>de</strong> construcción <strong>de</strong>conmutadores high-radix combinados por dos conmutadoreslow-radix, el conmutador Sun Bla<strong>de</strong> 6048Infiniband QDR Switched Network Express Module(NEM) [11] ya implementa esta estrategia que permiteconectar hasta 12 bla<strong>de</strong>s duales en un único shelf.Cada NEM suministra 12 conexiones por cada uno<strong>de</strong> los dos conmutadores InfiniScale IV <strong>de</strong> 36 puertos.En total, proporciona 24 conexiones para comunicarsecon los dos nodos por cada bla<strong>de</strong>, y utiliza9 puertos para que los dos conmutadores internos secomuniquen entre ellos. Los 30 puertos restantes (15por InfiniScale IV) se usan como enlaces con otrosNEMs, o conmutadores externos.Por otra parte, la topología Dragonfly [12] utilizaun grupo <strong>de</strong> conmutadores como router virtual paraincrementar el grado efectivo <strong>de</strong> la red. <strong>La</strong>mentablemente,no se aporta ningún análisis formal <strong>de</strong>l tráficoque cruza el router virtual.En resumidas cuentas, y hasta don<strong>de</strong> tenemos conocimiento,no hay estudios formales publicados sobrela obtención <strong>de</strong>l SCP óptimo.III. Conmutadores High-Radix medianteConmutadores Low-RadixComo se ha mencionado, es posible construir conmutadoreshigh-radix combinando varios conmutadoreslow-radix. Esta estrategia hace posible a<strong>de</strong>lantarsea la tecnología <strong>de</strong> integración y acortar drásticamenteel time-to-market. Nótese que esta estrategiaseguirá siendo válida conforme la tecnología <strong>de</strong>integración continúe evolucionando.Esta estrategia abre una serie <strong>de</strong> nuevos problemasque <strong>de</strong>ben estudiarse. En las siguientes secciones, serepasan brevemente estos problemas que han sidoanalizados en [13] <strong>de</strong> un modo más formal. No obstante,en este artículo también se realiza una cuantificaciónexperimental <strong>de</strong> su influencia en el rendimiento<strong>de</strong> la red.A. Conmutadores CombinadosEn esta sección se formalizan los conmutadorescombinados mediante una <strong>de</strong>finición general. Trasella, la atención se centra en una subclase particular<strong>de</strong> conmutadores combinados la cual se usará paramostrar las características <strong>de</strong> estos conmutadores y<strong>JP2011</strong>-404


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20110...m'-1switch-level connection pattern......0m-1m-m'/20m-10...m'-1switch-level connection pattern......0m-1m-m'/20m-10...m'-1switch-level connection pattern......0m-1m-m'/20m-10...m'-1switch-level connection pattern......0m-1m-m'/20m-1(a) Diagrama <strong>de</strong> bloquesbásico.(b) Situación i<strong>de</strong>al.(c) Situación mala.(d) Situación más común.Fig. 1: T -switch: diagrama <strong>de</strong> bloques y posibles situaciones.para evaluar el rendimiento <strong>de</strong> las re<strong>de</strong>s construidascon estos conmutadores.Definición 1: Un conmutador combinado, o simplementeC-switch, es un conmutador formado porvarios conmutadores (conmutadores internos) máspequeños interconectados. Los puertos ofrecidos porel C-switch se obtienen a partir <strong>de</strong> los puertos libres<strong>de</strong> los conmutadores internos <strong>de</strong>spués <strong>de</strong> que se hayaninterconectado entre sí.Esta <strong>de</strong>finición es muy genérica porque no especificani la cantidad <strong>de</strong> conmutadores internos ni cuáles su grado. Por tanto, cualquier conmutador obtenidopor combinación <strong>de</strong> otros conmutadores <strong>de</strong> menorgrado cae <strong>de</strong>ntro <strong>de</strong> esta categoría. Sin embargo,existen varias dificulta<strong>de</strong>s para construir C-switchesque tengan varios conmutadores internos y un gradoalto <strong>de</strong> heterogeneidad.Para que la latencia interna sea baja, es preferibleutilizar una topología completamente conectada parala interconexión <strong>de</strong> todos los conmutadores internos.Conforme el número <strong>de</strong> conmutadores internos crezca,el número <strong>de</strong> puertos <strong>de</strong>dicados a las conexionesentre los conmutadores internos crecerá tan rápidamentecomo el número <strong>de</strong> puertos <strong>de</strong>stinados a la interconexiónexterior <strong>de</strong>crecerá, <strong>de</strong> modo que esta forma<strong>de</strong> construir conmutadores high-radix per<strong>de</strong>rá interés.Por tanto, parece razonable que el número <strong>de</strong>conmutadores internos no sea muy alto.Por otra parte, un diseño interno sencillo <strong>de</strong>l C-switch se pue<strong>de</strong> alcanzar cuando todos los conmutadoresinternos son idénticos. Aunque este aspecto noes tan restrictivo como el número <strong>de</strong> conmutadoresinternos, es recomendable que todos los conmutadoresinternos tengan el mismo grado.Un caso interesante es aquel don<strong>de</strong> los C-switchesse construyen a partir <strong>de</strong> dos conmutadores internosidénticos. Esta subclase <strong>de</strong> C-switches todavía ofreceun incremento importante en el número <strong>de</strong> puertosmientras la topología entre los conmutadores internoses la más simple.Definición 2: Un conmutador gemelo, o simplementeT -switch (Twin), es un conmutador formadopor dos conmutadores internos idénticos <strong>de</strong> menorgrado interconectados entre sí. Los puertos obtenidospor el T -switch se obtienen a partir <strong>de</strong> los puertoslibres <strong>de</strong> sus dos conmutadores internos <strong>de</strong>spués<strong>de</strong> que éstos se hayan interconectado entre sí.Consi<strong>de</strong>rando que los dos conmutadores internos yel T -switch tienen respectivamente m y m ′ puertos,la figura 1a muestra un diagrama básico <strong>de</strong> bloques<strong>de</strong> un T -switch, don<strong>de</strong> los conmutadores internos senombran como α y β. Aunque los T -switches parecensimples, hay retos significativos en su diseño. Dos<strong>de</strong> ellos <strong>de</strong>stacan especialmente: (1) obtener el SCPapropiado para la estructura interna <strong>de</strong>l T -switch,(2) <strong>de</strong>terminar el número a<strong>de</strong>cuado <strong>de</strong> puertos parainterconectar los conmutadores internos α y β.El SCP tiene una influencia importante en la latencia<strong>de</strong> los paquetes. El tiempo empleado por lospaquetes para cruzar un T -switch será mínimo cuandosólo crucen uno <strong>de</strong> los conmutadores internos (αo β). <strong>La</strong> figura 1b muestra esta situación. <strong>La</strong>s flechasrepresentan los caminos seguidos por los paquetes yel ancho <strong>de</strong> la flecha es proporcional a la cantidad<strong>de</strong> caminos. El peor caso es aquel en el que todoslos caminos cruzan los dos conmutadores internos enel T -switch (figura 1c). Obtener el mejor caso no estrivial y requiere un estudio en profundidad don<strong>de</strong><strong>de</strong>ben consi<strong>de</strong>rarse varios factores como por ejemplo,la topología <strong>de</strong> la red, el algoritmo <strong>de</strong> encaminamientoy el patrón <strong>de</strong> tráfico. En [13] se muestraformalmente como se obtiene el patrón <strong>de</strong> conexiónóptimo consi<strong>de</strong>rando dichos factores.Respecto al segundo reto, el número <strong>de</strong> puertosinternos <strong>de</strong>be ser tal que evite la aparición <strong>de</strong> uncuello <strong>de</strong> botella entre los conmutadores internos α yβ. Obviamente, el número <strong>de</strong> puertos y el SCP tieneuna clara inter<strong>de</strong>pen<strong>de</strong>ncia.<strong>La</strong>s situaciones mostradas en las figuras 1b y 1cson apropiadas para mostrar los retos <strong>de</strong> diseño <strong>de</strong>los T -switches, pero la situación más común es lamostrada en la figura 1d, don<strong>de</strong> los casos anteriorescoexisten. Es esta situación, el objetivo principalcuando se diseña un SCP para los T -switches es minimizarel uso <strong>de</strong> los puertos que interconectan losconmutadores internos.Por lo tanto, puesto que en muchos casos la comunicaciónnecesitará usar ambos conmutadores internos(eso es, un camino que cruce un T -switch pasarápor los conmutadores α y β), se tiene que evitarque la interconexión entre los conmutadores α y β seconvierta en un cuello <strong>de</strong> botella. A<strong>de</strong>más, se <strong>de</strong>be<strong>de</strong>terminar el número <strong>de</strong> puertos a<strong>de</strong>cuado para cadaconmutador interno. Está claro que cuanto mayor seael número <strong>de</strong> puertos usados para interconectar losconmutadores internos menor será la probabilidad <strong>de</strong>que aparezca un cuello <strong>de</strong> botella en estos puertos.Sin embargo, y tal como se ha mencionado anteriormente,conforme el número <strong>de</strong> puertos <strong>de</strong>dicados ainterconectar los conmutadores α y β aumenta, el<strong>JP2011</strong>-405


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011grado <strong>de</strong>l T -switch disminuye. Se <strong>de</strong>berá encontrarun compromiso entre ambos aspectos. Nótese que seestá asumiendo que todos los puertos proveen el mismoancho <strong>de</strong> banda (<strong>de</strong> otra forma en lugar <strong>de</strong> usarel número <strong>de</strong> puertos se <strong>de</strong>bería consi<strong>de</strong>rar el ancho<strong>de</strong> banda total agregado).En resumen, la configuración interna <strong>de</strong> los T -switches se convierte en un aspecto clave en el diseño<strong>de</strong> esta clase <strong>de</strong> conmutadores high-radix. <strong>La</strong>configuración óptima <strong>de</strong> un T -switch <strong>de</strong>pen<strong>de</strong> <strong>de</strong> lascondiciones bajo las que esté funcionando, es <strong>de</strong>cir:tipo <strong>de</strong> red, topología <strong>de</strong> red, algoritmo <strong>de</strong> encaminamiento,patrón <strong>de</strong> tráfico, etc. A continuación seesboza una metodología para obtener la mejor configuración<strong>de</strong> esta clase <strong>de</strong> conmutadores cuando seusan en re<strong>de</strong>s <strong>de</strong> interconexión <strong>de</strong> altas prestaciones.El propósito <strong>de</strong> esta metodología es <strong>de</strong>terminar elSCP óptimo para los T -switches.B. Metodología para Configurar ConmutadoresCombinadosNuestra metodología para <strong>de</strong>terminar el SCP óptimopara C-switches consiste en los siguientes pasos:Análisis <strong>de</strong> los caminos en la red. El propósito <strong>de</strong>este paso es <strong>de</strong>terminar las conexiones necesariasen cada C-switch a nivel <strong>de</strong> red y la cantidad<strong>de</strong> veces que se utilizan todas ellas teniendo encuenta todos los posibles caminos usados por lospaquetes.Clasificación <strong>de</strong>l conmutador. Dependiendo <strong>de</strong>las características y carga <strong>de</strong> la red, se pue<strong>de</strong>nobtener una o varias configuraciones diferentespara los C-switches. En este paso, los C-switchesse agrupan según los requisitos <strong>de</strong> conexión, ypor tanto, se distinguirán varios tipos <strong>de</strong> C-switches.Como resultado <strong>de</strong>l paso anterior, pue<strong>de</strong> suce<strong>de</strong>rque varias <strong>de</strong> las posibles conexiones en elC-switch soporten uno o más caminos, y sin embargo,al mismo tiempo existan conexiones quenunca se establezcan.En la topología fat-tree, por ejemplo, los C-switches <strong>de</strong> diferentes etapas pue<strong>de</strong>n requerirdistintos SCPs, y lo mismo pue<strong>de</strong> ocurrir con losC-switches <strong>de</strong> la misma etapa. Cuando se dé unpatrón <strong>de</strong> tráfico simple y se emplee un algoritmo<strong>de</strong> encaminamiento que balancee la carga,es probable que todos los C-switches <strong>de</strong> la redpuedan configurarse con el mismo SCP.Configuración <strong>de</strong>l conmutador. A partir <strong>de</strong> losrequisitos <strong>de</strong> conexión y dado un número <strong>de</strong> conmutadoresinternos <strong>de</strong> un C-switch, este últimopaso consiste en encontrar el SCP óptimo paracada tipo <strong>de</strong> C-switch, intentando minimizar eluso <strong>de</strong> los enlaces que interconectan los conmutadoresinternos.En [13] se ha aplicado dicha metodología a un casoparticular: topología k-ary n-tree, algoritmo <strong>de</strong> encaminamiento<strong>de</strong>terminista, y patrón <strong>de</strong> tráfico uniforme.Como resultado, se ha obtenido la configuraciónóptima para todos sus C-switches.IV. Evaluación <strong>de</strong> RendimientoEn esta sección se evalúa el potencial <strong>de</strong> los C-switches estudiando los T -switches. <strong>La</strong> evaluación seha realizado por simulación y se ha centrado en losdos aspectos clave que se discutieron anteriormente:el SCP, y el ancho <strong>de</strong> banda disponible entre losconmutadores internos.En las siguientes subsecciones, en primer lugar se<strong>de</strong>scribe el mo<strong>de</strong>lo <strong>de</strong> red simulado, y a continuaciónse establecen las diferentes configuraciones <strong>de</strong> red ylos SCPs empleados en las simulaciones. Finalmente,se aportan y analizan en <strong>de</strong>talle los resultados <strong>de</strong> lassimulaciones obtenidos.A. Mo<strong>de</strong>lo SimuladoPara llevar a cabo la evaluación se ha utilizadoun simulador <strong>de</strong>tallado conducido por eventos que escapaz <strong>de</strong> mo<strong>de</strong>lar distintos tipos <strong>de</strong> re<strong>de</strong>s basadas enconmutadores, y en particular, T -switches.Se ha elegido la topología k-ary n-tree que es unasubclase particular <strong>de</strong> los fat-trees. Se ha seleccionadoporque actualmente es una <strong>de</strong> las más usadasentre los supercomputadores <strong>de</strong>l Top500.Se ha implementado el algoritmo <strong>de</strong>terministaDESTRO [14] a nivel <strong>de</strong> red. Se ha consi<strong>de</strong>rado interesanteeste algoritmo por sus características: unaimplementación en hardware sencilla, tiempo <strong>de</strong> encaminamientoreducido y reparto <strong>de</strong> paquetes en or<strong>de</strong>n.A<strong>de</strong>más, DESTRO es capaz <strong>de</strong> balancear uniformementeel tráfico en la red y <strong>de</strong> reducir la contenciónen la red. Como carga <strong>de</strong> red se ha asumidoun patrón <strong>de</strong> tráfico uniforme porque es uno <strong>de</strong> lospatrones clásicos utilizados en este tipo <strong>de</strong> evaluaciones.Con respecto a los conmutadores, según lo mencionadoen la sección III, se han simulado T -switches.En este estudio <strong>de</strong> evaluación, <strong>de</strong>bido a los fuertes requisitostemporales sólo se han simulado T -switches<strong>de</strong> 32 puertos. Estos conmutadores se forman con dosconmutadores internos <strong>de</strong> 24 puertos cada uno, <strong>de</strong> loscuales 16 puertos se utilizan para la comunicación <strong>de</strong>lT -switch con el exterior y 8 puertos se <strong>de</strong>stinan parala comunicación <strong>de</strong> los dos conmutadores internos(m = 24 y m ′ = 32 en la figura 1). Se han consi<strong>de</strong>radoconmutadores internos <strong>de</strong> 24 puertos porqueestán disponibles en el mercado (por ejemplo, el chipInfiniScale III [15]). No obstante, actualmente la herramienta<strong>de</strong> simulación se está mejorando para quesoporte conmutadores <strong>de</strong> mayor grado.Se han evaluado re<strong>de</strong>s <strong>de</strong> distinto tamaño. Debidoa la limitación <strong>de</strong> espacio, aquí sólo se han incluidolos resultados para las re<strong>de</strong>s <strong>de</strong> 4096 terminales.Otras suposiciones son que los conmutadores soportanvirtual output queuing a nivel <strong>de</strong> conmutador;todos los enlaces son bidireccionales y tienen unancho <strong>de</strong> banda <strong>de</strong> 1 GByte/s; existe un planificadorround-robin por puerto <strong>de</strong> salida; el tamaño <strong>de</strong> paquetees <strong>de</strong> 2 KBytes; todos los buffers tienen unacapacidad para almacenar 64 paquetes, entre otros.<strong>JP2011</strong>-406


..................<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20110k/2-1k/2k-1(a) Patrón óptimo.k3k/2-13k/22k-10k-1k2k-1(b) Patrón arbitrario y/omaloFig. 2: Patrones <strong>de</strong> conexión a nivel <strong>de</strong> conmutador.B. Casos <strong>de</strong> EstudioA fin <strong>de</strong> evaluar la viabilidad y potencial <strong>de</strong> losconmutadores combinados, se ha estimado el rendimiento<strong>de</strong> la red <strong>de</strong>scrita en la sección IV-A, consi<strong>de</strong>randoT -switches con el SCP que se ha <strong>de</strong>mostradosiguiendo la metodología propuesta en la secciónIII-B que es el óptimo 2 para los T -switches bajolas condiciones <strong>de</strong> simulación (esta red se etiqueta enlas figuras como O-BMIN). Tras ello, el rendimiento<strong>de</strong> esta red se compara con el rendimiento alcanzadopor una red equivalente que emplea conmutadores enun chip <strong>de</strong>l mismo grado que los T -switches. Dichared será referenciada como U-BMIN y representa unacota superior <strong>de</strong> rendimiento.A<strong>de</strong>más, para poner <strong>de</strong> manifiesto la importancia<strong>de</strong>l SCP también se ha consi<strong>de</strong>rado otro caso <strong>de</strong> estudioque representa a un patrón arbitrario y/o malo,referenciado como B-BMIN en la figuras. <strong>La</strong>s re<strong>de</strong>s<strong>de</strong> los casos O-BMIN y B-BMIN usan T -switchescon los patrones <strong>de</strong> conexión a nivel <strong>de</strong> conmutadorOSCP y BSCP, respectivamente. Ambos patronespue<strong>de</strong>n verse en la figura 2 para un T -switch arbitrario<strong>de</strong> k×k puertos y r puertos internos entre losconmutadores internos. También se incluye un cuartocaso <strong>de</strong> estudio: una red (L-BMIN) que conecta lamisma cantidad <strong>de</strong> terminales, pero con conmutadoresen chip <strong>de</strong> menor grado que también son viablescon la escala <strong>de</strong> integración actual.Otro propósito <strong>de</strong> esta evaluación es saber si ladiferencia <strong>de</strong> rendimiento entre los casos <strong>de</strong> estudioes significativa, y en caso afirmativo, medirla.Obsérvese que aunque en todos los casos la redinterconecta 4096 terminales, los casos U-BMIN, O-BMIN y B-BMIN, son re<strong>de</strong>s 16-ary 3-tree formadaspor un total <strong>de</strong> 768 conmutadores <strong>de</strong> 32 puertos. Sinembargo, la red <strong>de</strong>l caso L-BMIN es una 8-ary 4-treecon 2048 conmutadores <strong>de</strong> 16 puertos cada uno.C. Resultados <strong>de</strong> SimulaciónSe han realizado dos tests distintos. El primero sirvepara medir la diferencia <strong>de</strong> rendimiento entre losdistintos casos <strong>de</strong> estudio mencionados anteriormente.Recuér<strong>de</strong>se que el objetivo global <strong>de</strong> esta evaluaciónes i<strong>de</strong>ntificar problemas potenciales que limitanla eficiencia <strong>de</strong> los T -switches (y en general <strong>de</strong> losC-switches).<strong>La</strong> figura 3 muestra los valores medios <strong>de</strong> la productividady latencia con los intervalos <strong>de</strong> confianzaal 95 % <strong>de</strong> 30 simulaciones para cada nivel <strong>de</strong> carga.Se pue<strong>de</strong>n observar algunos <strong>de</strong>talles:2 Debido a la falta <strong>de</strong> espacio, aquí no se han incluido lascorrespondientes <strong>de</strong>mostraciones, que está disponibles en [13].Normalized Throughput (%)<strong>JP2011</strong>-407100806040U−BMIN20O−BMINB−BMINL−BMIN00 0.2 0.4 0.6 0.8 1Normalized Load(a) Productividad.Network <strong>La</strong>tency (cycles)10000800060004000U−BMIN2000O−BMINB−BMINL−BMIN00 0.2 0.4 0.6 0.8 1Normalized Load(b) <strong>La</strong>tencia.Fig. 3: Resultados <strong>de</strong>l primer test para todos los casos<strong>de</strong> estudio.Cuando se ha consi<strong>de</strong>rado el SCP óptimo, lared basada en T -switches (O-BMIN) es capaz<strong>de</strong> ofrecer un rendimiento similar al que ofrecela red (U-BMIN) cuyos conmutadores high-radixse integran en un único chip. Por tanto, los conmutadorescombinados se confirman como unabuena alternativa para la construcción <strong>de</strong> conmutadoreshigh-radix.Sin embargo, la red B-BMIN alcanza el punto<strong>de</strong> saturación con sólo el 40 % <strong>de</strong> la carga. Elrendimiento dispar obtenido es <strong>de</strong>bido al hecho<strong>de</strong> que los T -switches configurados con el patrónBSCP producen que la longitud <strong>de</strong>l camino <strong>de</strong>la mayoría <strong>de</strong> los paquetes se incremente en unsalto extra. De tal modo, también se confirmaque es esencial la <strong>de</strong>terminación en cada caso<strong>de</strong>l SCP óptimo para cada tipo <strong>de</strong> conmutadorcombinado.Cuando se comparan los casos U-BMIN y L-BMIN, se ha observado que la latencia en el casoL-BMIN es superior a la latencia en el casoU-BMIN (por ejemplo, un 14 % al 50 % <strong>de</strong> carga).Este incremento es causado porque la redL-BMIN tiene una o más etapas que la red U-BMIN, por lo que los caminos son más largos.A<strong>de</strong>más, se pue<strong>de</strong> ver que el número <strong>de</strong> puertos<strong>de</strong>stinados para la interconexión entre los conmutadoresinternos α y β no producen ningúntipo <strong>de</strong> <strong>de</strong>gradación en el rendimiento <strong>de</strong> la red.En el primer test se han empleado 8 puertos <strong>de</strong>cada conmutador interno para la interconexión entreellos. Sin embargo, se necesita asignar un número <strong>de</strong>puertos suficiente para disponen <strong>de</strong> ancho <strong>de</strong> bandaentre los conmutadores internos, pero al mismo tiempoevitar sobredimensionar esta cantidad. De no lograrse,es probable que se produzca una <strong>de</strong>gradación<strong>de</strong> prestaciones en la comunicación entre el interiory el exterior <strong>de</strong>l T -switch. Para encontrar el mismoóptimo <strong>de</strong> puertos, se ha realizado un segundo testque estima cómo dicha cantidad <strong>de</strong> puertos influyeen el rendimiento global <strong>de</strong> la red.En la figura 4 se pue<strong>de</strong>n ver los resultados <strong>de</strong> productividad<strong>de</strong> la red cuando la carga <strong>de</strong> la red está al80 % para todos los casos <strong>de</strong> estudio excepto paraL-BMIN. A fin <strong>de</strong> realizar el segundo test, se ha configuradoel simulador para que varíe el número <strong>de</strong>puertos entre los conmutadores internos entre 1 y16, mientras que el número <strong>de</strong> puertos al exterior semantiene constante.De modo similar al primer test, se pue<strong>de</strong>n resaltar


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Normalized Throughput (%)10080604020U−BMINO−BMIN0B−BMIN0 2 4 6 8 10 12 14 16Number of Internal PortsFig. 4: Productividad <strong>de</strong> la red en función <strong>de</strong>l número<strong>de</strong> puertos entre los conmutadores internos.algunos <strong>de</strong>talles importantes en este segundo test:Se pue<strong>de</strong> <strong>de</strong>terminar el número mínimo <strong>de</strong> puertosentre los conmutadores internos para evitarla creación <strong>de</strong> un cuello <strong>de</strong> botella entre dichosconmutadores. Se pue<strong>de</strong> observar que el SCP esel factor clave que influye en el rendimiento globaly en cambio, el número concreto <strong>de</strong> puertosno es tan relevante.Cuando el número <strong>de</strong> puertos entre los conmutadoresinternos pasa <strong>de</strong> 4, O-BMIN alcanza elmismo rendimiento que U-BMIN. Sin embargo,cuando se consi<strong>de</strong>ra B-BMIN, el cuello <strong>de</strong> botellano <strong>de</strong>saparece hasta que el número <strong>de</strong> puertosentre los conmutadores internos es igual a laaridad <strong>de</strong>l T -switch (k = 16).Es importante remarcar que en los resultadosmostrados en la figura 3 el número <strong>de</strong> puertosentre los conmutadores internos es 8, pero cuandoel T -switch se configura con el SCP óptimosólo son necesarios 4 puertos para alcanzar lasprestaciones máximas. En tal caso, estos 4 puertosextra podrían emplearse en la comunicacióncon el exterior en lugar <strong>de</strong> hacerlo para la comunicaciónentre conmutadores internos, y portanto, el grado <strong>de</strong>l T -switch se incrementará <strong>de</strong>un modo más efectivo.V. ConclusionesEn este artículo se ha <strong>de</strong>scrito una alternativa parala construcción <strong>de</strong> conmutadores high-radix consistenteen combinar varios conmutadores low-radix.Aunque aparentemente es simple, esta estrategiaplantea unos retos <strong>de</strong> diseño claves a fin <strong>de</strong> que estosconmutadores high-radix alcancen su mejor rendimiento.En este sentido, se han discutido aspectosimportantes relacionados con la estructura interna<strong>de</strong> esta clase <strong>de</strong> conmutadores.Los puertos ofrecidos por estos conmutadores seobtienen a partir <strong>de</strong> los puertos <strong>de</strong> sus conmutadoresinternos con los que se construye el conmutador.<strong>La</strong>s conexiones internas entre ambos grupos <strong>de</strong> puertos<strong>de</strong>termina el patrón <strong>de</strong> conexión que se convierteen crucial para el comportamiento <strong>de</strong>l conmutadorhigh-radix. Por otra parte, también es esencial po<strong>de</strong>r<strong>de</strong>terminar la interconexión más apropiada paraevitar la aparición <strong>de</strong> un cuello <strong>de</strong> botella entre losconmutadores internos.Para comprobar el potencial <strong>de</strong> esta alternativase han evaluado varias re<strong>de</strong>s bajo ciertas condicionespara medir su rendimiento. Son re<strong>de</strong>s construidascon conmutadores <strong>de</strong> un único chip y también sehan consi<strong>de</strong>rado re<strong>de</strong>s con T -switches. Los resultados<strong>de</strong> las re<strong>de</strong>s con T -switches y el patrón <strong>de</strong> conexiónóptimo, se han visto que son idénticos que las re<strong>de</strong>scon conmutadores construidos con conmutadores enun único chip. A<strong>de</strong>más, los resultados han puesto <strong>de</strong>manifiesto la importancia <strong>de</strong> seleccionar un númeroa<strong>de</strong>cuado <strong>de</strong> puertos para la interconexión entre losconmutadores internos.Agra<strong>de</strong>cimientosEste trabajo ha sido cofinanciado por el MEC yMICINN <strong>de</strong> España, fondos FEDER <strong>de</strong> la ComisiónEuropea, con subvenciones “Consoli<strong>de</strong>r Ingenio-2010CSD2006-00046”y“TIN2009-14475-C04”; y la Junta<strong>de</strong> Comunida<strong>de</strong>s <strong>de</strong> Castilla-<strong>La</strong> Mancha con proyectos“PEII 11-0229-2343”y“POII 10-0289-3724”.Referencias[1] J.J. Dongarra, “TOP500 Supercomputer Sites,” 10/2010.[2] H. Wang, L.-S. Peh, and S. Malik, “Power-driven <strong>de</strong>sign ofrouter microarchitectures in on-chip networks,” in Proc.of the 36th annual IEEE/ACM International Symposiumon Microarchitecture, Washington, DC, USA, 2003[3] M. Gusat, F. Abel, F. Gramsamer, et al., “Stability <strong>de</strong>greeof switches with finite buffers and non-negligible roundtriptime,” International Conference on Computer, Communicationand Networking, vol. 27, no. 5–6, 2003.[4] C. Minkenberg, F. Abel, P. Muller, et al. “Control pathimplementation for a low-latency optical HPC switch,” inProc. of the 13th Symposium on High Performance Interconnects,Washington, DC, USA, 2005, HOTI’05, pp.29–35, IEEE Computer Society.[5] C. Minkenberg and M. Gusat, “Speculative flow control forhigh-radix datacenter interconnect routers,” Parallel andDistributed Processing Symposium, International, vol. 0,pp. 1–10, 2007.[6] “International Technology Roadmap for Semiconductors.2010,” www.itrs.net/Links/2010ITRS/Home2010.htm.[7] W.J. Dally, “Virtual-channel flow control,” IEEE Transactionson Parallel and Distributed Systems, vol. 3, no.2, pp. 194 –205, mar 1992.[8] J. Kim, W.J. Dally, B. Towles, and A.K. Gupta, “Microarchitectureof a high-radix router,” SIGARCH Comput.Archit. News, vol. 33, no. 2, pp. 420–431, 2005.[9] S. Scott, D. Abts, J. Kim, and W.J. Dally, “The BlackWidowhigh-radix Clos network,” SIGARCH Comput. Archit.News, vol. 34, no. 2, pp. 16–28, 2006.[10] G. Mora, J. Flich, J. Duato, et al., “Towards an efficientswitch architecture for high-radix switches,” in Proc.of the 2006 ACM/IEEE symposium on Architecture fornetworking and communications systems, New York, NY,USA, 2006, pp. 11–20, ACM.[11] “Sun datacenter Infiniband switch 36, Sun datacenter Infinibandswitch 72, Sun datacenter Infiniband switch 648:Architecture and <strong>de</strong>ployment,” April 2010.[12] J. Kim, W.J. Dally, S. Scott, and D. Abts, “Technologydriven,highly-scalable Dragonfly topology,” in ISCA ’08:Proc. of the 35th Annual International Symposium onComputer Architecture, Washington, DC, USA, 2008, pp.77–88, IEEE Computer Society.[13] J.A. Villar, F.J. Andújar, F.J. Alfaro, J.L. Sánchez,and J. Duato, “An alternative for building highradixswitches: Formalization and configuration methodology,”Tech. Rep. DIAB-11-02-1, Dpt. of ComputingSystems. University of Castilla-<strong>La</strong> Mancha,2011, www.dsi.uclm.es/<strong>de</strong>scargas/thecnicalreports/DIAB-11-02-1/diab-11-02-1.pdf.[14] C. Gómez, F. Gilabert, M.E. Gómez, P. Lopez, and J.Duato, “Deterministic versus adaptive routing in fattrees,”Los Alamitos, CA, USA, 2007, IEEE ComputerSociety.[15] Mellanox Technologies Inc., “Infiniscale III 3rd generationinfiniband switch architecture,” www.mellanox.com/related-docs/prod_silicon/PB_InfiniScale_III.pdf.<strong>JP2011</strong>-408


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Combinando diferentes enfoques para elcontrol <strong>de</strong> congestión en re<strong>de</strong>s <strong>de</strong>interconexión <strong>de</strong> altas prestacionesJesus Escu<strong>de</strong>ro-Sahuquillo 1 , Ernst Gunnar Gran 2 , Pedro Javier Garcia 1 , Jose Flich 3 ,Tor Skeie 2 , Olav Lysne 2 , Francisco Jose Quiles 1 and Jose Duato 31 Dept. Sistemas Informáticos, <strong>Universidad</strong> <strong>de</strong> Castilla-<strong>La</strong> Mancha. E-mail:{jesus.escu<strong>de</strong>ro, pedrojavier.garcia, francisco.quiles}@uclm.es2 Simula Research <strong>La</strong>boratory. Oslo (Noruega). E-mail:{ernstgr, tskeie, olav.lysne}@simula.no3 Dept. <strong>de</strong> Informática <strong>de</strong> Sistemas y Computadores, Universitat Politècnica <strong>de</strong> València. E-mail:{jflich,jduato}@gap.upv.esResumen— Muchos <strong>de</strong> los mecanismos más populares para el cuando el paquete en cabeza <strong>de</strong> una cola está <strong>de</strong>tenidocontrol <strong>de</strong> congestión en re<strong>de</strong>s <strong>de</strong> interconexión <strong>de</strong> altas prestacionesse ajustan a uno <strong>de</strong> dos enfoques básicos: la limitacióny bloquea el avance <strong>de</strong> los paquetes situados <strong>de</strong>trás <strong>de</strong> el.<strong>de</strong> inyección en las fuentes generadoras <strong>de</strong> tráfico en la red Nótese que esta situación afecta con mayor gravedad a loso el aislamiento explícito <strong>de</strong> los flujos congestionados en colas flujos <strong>de</strong> paquetes que van dirigidos hacia otros puertosdinámicamente asignadas para ellos. Ambos enfoques presentan inconvenientes,si bien éstos son diferentes en cuanto a su naturaleza y<strong>de</strong> salida distintos al solicitado por el paquete en cabeza<strong>de</strong> la cola, ya que estos otros puertos pue<strong>de</strong>n estar libres.su repercusión en las prestaciones <strong>de</strong> la red. En este artículo se presentauna nueva propuesta que combina la limitación <strong>de</strong> inyección Estos flujos “no congestionados” se convierten en flujosy el aislamiento explícito <strong>de</strong> flujos congestionados. Dicha propuesta “víctimas” <strong>de</strong> la congestión [3].es capaz <strong>de</strong> extraer lo mejor <strong>de</strong> ambos enfoques, dando como resultadouna reacción rápida ante los efectos efectos negativos <strong>de</strong>El control <strong>de</strong> la congestión (CC) es, en <strong>de</strong>finitiva, unala congestión y una mayor escalabilidad. A<strong>de</strong>más, esta propuesta tarea clave en el diseño <strong>de</strong> las re<strong>de</strong>s <strong>de</strong> interconexión.minimiza los problemas <strong>de</strong> los enfoques in<strong>de</strong>pendientes.Aunque en los últimos tiempos se han propuesto variosPalabras clave— Re<strong>de</strong>s <strong>de</strong> Interconexión, Encaminamiento Distribuido,HoL-blocking, Control <strong>de</strong> Congestión.gestión (ver sección II), hay dos <strong>de</strong> ellos que han tenidoenfoques para resolver los problemas asociados a la con-I.una especial aceptación. Por un lado, <strong>de</strong>staca la limitación<strong>de</strong> inyección <strong>de</strong> las fuentes que generan la con-INTRODUCCIÓNEN las re<strong>de</strong>s <strong>de</strong> interconexión <strong>de</strong> altas prestaciones actualesla congestión pue<strong>de</strong> disminuir el rendimiento <strong>de</strong> red basadas en la especificación InfiniBand [4]. Porgestión, que actualmente está presente en las tecnologíasglobal <strong>de</strong> la red, y por tanto el <strong>de</strong>l sistema que interconectadicha red, si no se toman las medidas apropiadas.En este sentido, la congestión es simplemente el resultado<strong>de</strong> una carga <strong>de</strong> tráfico <strong>de</strong>ntro <strong>de</strong> la red que supera prolongadamenteotro lado, existe otro enfoque basado en el aislamientoexplícito <strong>de</strong> flujos congestionados, usando para ello recursosadicionales asignados dinámicamente para almacenardichos flujos [5], [6].la capacidad <strong>de</strong> los enlaces y buffers en ciertos En concreto, la limitación <strong>de</strong> inyección consiste en <strong>de</strong>-puntos (Hot-Spots). A<strong>de</strong>más, las re<strong>de</strong>s <strong>de</strong> interconexión tectar un punto <strong>de</strong> congestión e informar a las fuentes<strong>de</strong> altas prestaciones actuales requieren alta productividady latencias mínimas en la transmisión <strong>de</strong> paquetes, su tasa <strong>de</strong> inyección. De esta forma las fuentes elim-que contribuyen a generar ese punto para que reduzcanpor lo que no se permite el <strong>de</strong>scarte y retransmisión <strong>de</strong> los inan el árbol <strong>de</strong> congestión, así como el HoL-blockingmismos. A esto hay que unir que los diseños <strong>de</strong> red actualesreducen el número <strong>de</strong> componentes y recursos para Sin embargo, entre la <strong>de</strong>tección <strong>de</strong> la congestión y el mo-que surge por la presencia <strong>de</strong> dicho árbol <strong>de</strong> congestión.reducir coste y consumo, por lo que nos encontramos con mento en que las fuentes comienzan a reducir el árbolque la red alcanza su punto <strong>de</strong> saturación con una carga transcurre un intervalo <strong>de</strong> tiempo que podría ser muy elevado,ya que para cuando la tasa <strong>de</strong> inyección se reduzca<strong>de</strong> tráfico menor. En este contexto, la congestión aparecey se propaga <strong>de</strong>ntro <strong>de</strong> la red con mucha más facilidad y, la congestión pue<strong>de</strong> haber remitido, o bien cuando dichasi no se toman las medidas oportunas, las prestaciones <strong>de</strong> tasa se recupere, la congestión a vuelto a surgir. Estala red <strong>de</strong> interconexión se verán seriamente afectadas. situación, <strong>de</strong>nominada “efecto sierra” como se <strong>de</strong>scribeEspecíficamente, <strong>de</strong>ntro <strong>de</strong> un conmutador la congestiónaparece cuando varios paquetes solicitan elmismo puerto <strong>de</strong> salida. En general, mientras uno <strong>de</strong> estospaquetes cruza hacia dicho puerto <strong>de</strong> salida, los otrosmás a<strong>de</strong>lante, se produce por la lenta reacción ante lacongestión y ocasiona que el HoL-blocking y sus efectosnegativos no <strong>de</strong>saparezcan por completo <strong>de</strong> la red yafecten al rendimiento <strong>de</strong> la misma.<strong>de</strong>ben esperar en sus respectivas colas. Esta situación <strong>de</strong> Por otro lado, el enfoque basado en aislar“contención”, si se prolonga en el tiempo, produce quelas colas con paquetes “<strong>de</strong>tenidos” se llenen rápidamente,generándose así la “congestión”. En las re<strong>de</strong>s sin <strong>de</strong>scarte<strong>de</strong> paquetes (como es el caso <strong>de</strong> la mayoría <strong>de</strong> tecnologías<strong>de</strong> red <strong>de</strong> interconexión actuales), el control <strong>de</strong> flujoimpi<strong>de</strong> el envío <strong>de</strong> paquetes hacia conmutadores con susexplícitamente los flujos congestionados no eliminael árbol <strong>de</strong> congestión en sí, sino que <strong>de</strong>tecta la congestióny, <strong>de</strong> forma instantánea, aisla en colas especialesasignadas dinámicamente los flujos congestionados (losárboles <strong>de</strong> congestión), para que no interfieran con losflujos <strong>de</strong> paquetes no congestionados. De esta maneracolas llenas. Por tanto, la congestión se propaga <strong>de</strong>s<strong>de</strong> se elimina <strong>de</strong> forma sustancial el HoL-blocking. Esteeste conmutador “raíz” hacia las fuentes que están enviandopaquetes hacia dicho conmutador, formando losllamados “árboles <strong>de</strong> congestión” [1].<strong>La</strong> presencia <strong>de</strong> los árboles <strong>de</strong> congestión introduceen la red el principal efecto negativo <strong>de</strong> la congestión:el Head-Of-Line (HoL) blocking, que pue<strong>de</strong> limitar elrendimiento <strong>de</strong> un conmutador hasta en un 58% <strong>de</strong> suenfoque reacciona <strong>de</strong> forma instantánea a la aparición<strong>de</strong> la congestión, pero necesita un número suficiente <strong>de</strong>colas especiales en cada puerto, para aislar todos losposibles flujos congestionados. Si dicho número <strong>de</strong> flujossobrepasa el número <strong>de</strong> colas disponibles en ese puerto,no todos podrán ser aislados y generarán HoL-blocking,que afectará al rendimiento <strong>de</strong> la red <strong>de</strong> interconexión.valor máximo [2]. En general, el HoL-blocking aparece En<strong>JP2011</strong>-409este artículo se <strong>de</strong>scribe CCFIT (Combined


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Congested-Flow Isolation and Throttling) [7], unatécnica <strong>de</strong> CC basada en la combinación <strong>de</strong> los enfoquesmencionados que ofrece sus ventajas y minimiza sus inconvenientes.Por un lado, el aislamiento <strong>de</strong> los flujoscongestionados en colas especiales reacciona <strong>de</strong> formainmediata a la congestión y elimina el HoL-blocking, inclusoantes <strong>de</strong> que los nodos fuente sepan que hay congestión<strong>de</strong>ntro <strong>de</strong> la red. Por otro lado, la limitación<strong>de</strong> inyección elimina el árbol <strong>de</strong> congestión y reduce laposibilidad <strong>de</strong> que aparezcan muchas ramas <strong>de</strong> árboles<strong>de</strong> congestión distintos en un mismo puerto. Por tanto,se reduce la posibilidad <strong>de</strong> que el número <strong>de</strong> colas especialespor puerto sea insuficiente. CCFIT mejora elrendimiento <strong>de</strong> los dos enfoques en los que está basado,y es una técnica eficiente y escalable al mismo tiempo.El resto <strong>de</strong> este artículo se organiza como sigue: lasección II <strong>de</strong>scribe las diferentes propuestas en el campo<strong>de</strong>l control <strong>de</strong> congestión (CC); la sección III <strong>de</strong>scribela nueva propuesta CCFIT y en la sección IV se evalúansus prestaciones. Finalmente, la sección V muestra lasconclusiones <strong>de</strong> este trabajo.II. TRABAJOS RELACIONADOSEl control <strong>de</strong> congestión (CC) basado en la inhibición<strong>de</strong> la inyección es un enfoque bastante popular cuya i<strong>de</strong>abásica, como se ha <strong>de</strong>scrito, es <strong>de</strong>tectar la congestión queaparece en la red <strong>de</strong>ntro <strong>de</strong> los propios conmutadores, einformar a los nodos fuente para que reduzcan su tasa <strong>de</strong>inyección <strong>de</strong> tráfico. Esta filosofía <strong>de</strong> “bucle cerrado” esbásica para muchas <strong>de</strong> las técnicas propuestas, las cuales,por otro lado, también presentan diferencias entre ellas.Por ejemplo, las notificaciones <strong>de</strong> congestión se pue<strong>de</strong>nenviar a todos los nodos origen [8] o sólo a los nodos quegeneran la congestión [9]. Otros mecanismos propuestosnotifican la congestión sólo a los nodos locales directamenteconectados al conmutador don<strong>de</strong> se <strong>de</strong>tecta la congestión[10]. <strong>La</strong> manera <strong>de</strong> notificar a los nodos fuente <strong>de</strong>esta situación y la política <strong>de</strong> reacción <strong>de</strong> las fuentes anteesas notificaciones varía según las técnicas. Por ejemplo,hay estrategias que reducen la inyección cuando sereciben las notificaciones <strong>de</strong> congestión y la aumentanconforme ésta va <strong>de</strong>sapareciendo [11], [12].En este sentido, la limitación <strong>de</strong> inyección <strong>de</strong> la nuevapropuesta CCFIT se inspira en el mecanismo propuestoen la especificación InfiniBand (IB) [4] (evaluado en [13],[14]). En concreto, IB <strong>de</strong>fine dos bits en la cabecera <strong>de</strong>lpaquete para notificar la congestión. Si un paquete contribuyea la congestión, el bit FECN (Forward ExplicitCongestion Notification) se activa en su cabecera. Estebit permanece activo hasta que el paquete alcanza su <strong>de</strong>stino.Cuando un <strong>de</strong>stino recibe un paquete “marcado”con el bit FECN, genera una notificación <strong>de</strong> congestióncuya cabecera contiene el bit BECN (Backward ExplicitCongestion Notification) activo. Cualquier nodo fuenteque recibe un paquete con el bit BECN activo reducirá sutasa <strong>de</strong> inyección <strong>de</strong> tráfico según el algoritmo establecidoa tal efecto, con el objetivo <strong>de</strong> reducir <strong>de</strong> la maneramás rápida posible el árbol <strong>de</strong> congestión.Aunque este mecanismo <strong>de</strong> CC <strong>de</strong> IB es capaz <strong>de</strong> eliminar<strong>de</strong> la red el árbol <strong>de</strong> congestión, presenta un serioproblema: el retardo entre la <strong>de</strong>tección <strong>de</strong> la congestión yla reacción <strong>de</strong> las fuentes para reducir la tasa <strong>de</strong> inyecciónocasiona que el mecanismo no funcione <strong>de</strong> forma inmediata.Por tanto, la reducción <strong>de</strong> la inyección pue<strong>de</strong> estarbasada en información obsoleta <strong>de</strong>l estado <strong>de</strong> la red.Un enfoque distinto al anterior se basa en eliminar elHoL-blocking sin eliminar el árbol <strong>de</strong> congestión, medianteel aislamiento <strong>de</strong> los flujos congestionados, <strong>de</strong> maneraque, si estos no interfieren con los flujos no congestionados,la congestión no será perjudicial [1].Existe un gran número <strong>de</strong> técnicas que atacan directamenteal HoL-blocking. Muchas <strong>de</strong> ellas establecen colasen cada puerto <strong>de</strong>l conmutador, para separar paquetes <strong>de</strong>diferentes flujos. Por ejemplo, una técnica muy conocida<strong>de</strong>ntro <strong>de</strong> este campo es Virtual Output Queues (VOQs),bien a nivel <strong>de</strong> conmutador (VOQsw) [15], o bien a nivel<strong>de</strong> red (VOQnet) [16]. Mientras la primera versión requieretantas colas por puerto como puertos tenga el conmutador,la segunda establece tantas colas como nodos<strong>de</strong>stino haya en la red. En este sentido, VOQnet eliminacompletamente el HoL-blocking, ya que en cada puertoguarda todos los paquetes dirigidos a un mismo <strong>de</strong>stino<strong>de</strong>ntro <strong>de</strong> una misma cola y, por tanto, los paquetes dirigidosa <strong>de</strong>stinos distintos no interfieren entre sí. Nóteseque VOQnet no escala con el tamaño <strong>de</strong> la red. Porotro lado, VOQsw requiere un número reducido <strong>de</strong> colasy guarda un paquete en una cola u otra en función <strong>de</strong>lpuerto <strong>de</strong> salida solicitado. Aunque VOQsw es escalablecon el tamaño <strong>de</strong> la red y elimina el HoL-blocking <strong>de</strong>ntro<strong>de</strong>l conmutador don<strong>de</strong> surge la congestión, el problemasurge cuando esa congestión se propaga hacia otros conmutadores.Por tanto, VOQsw reduce sólo parcialmenteel HoL-blocking, al igual que otras técnicas similarescomo Dynamically Allocated Multi-queues (DAMQs)[17], Destination-Based Buffer Management (DBBM)[18], Dynamic Switch Buffer Management (DSBM) [19]y Output-Based Queue-Assignment (OBQA) [20].Todas estas técnicas no i<strong>de</strong>ntifican explícitamente losflujos <strong>de</strong> paquetes congestionados, sino que separan “ciegamente”paquetes <strong>de</strong> flujos diferentes tanto como esposible en función <strong>de</strong>l número <strong>de</strong> colas <strong>de</strong>l que disponenen cada puerto. Es <strong>de</strong>cir los flujos congestionadostienen la misma probabilidad <strong>de</strong> ser aislados que el resto<strong>de</strong> flujos y, por tanto, la efectividad en eliminar el HoLblocking<strong>de</strong>pen<strong>de</strong> <strong>de</strong>l número <strong>de</strong> colas por puerto. Por elcontrario, existen otras técnicas que <strong>de</strong>tectan e i<strong>de</strong>ntifican<strong>de</strong> forma explícita los flujos <strong>de</strong> paquetes congestionados,para aislarlos en colas especiales que se asignan <strong>de</strong> formadinámica a estos flujos. Este aislamiento beneficia a losflujos no congestionados que no sufrirán HoL-blocking<strong>de</strong> forma significativa, ya que no interfieren con los flujoscongestionados. A<strong>de</strong>más, puesto que los flujos nocongestionados pue<strong>de</strong>n compartir colas sin sufrir HoLblockingrelevante, se reduce el número <strong>de</strong> colas necesariaspara eliminar el HoL-blocking. Esta es la estrategiabásica seguida por Regional Explicit Congestion Notification(RECN) [5], [3], Regional Explicit CongestionNotification-Input Queued (RECN-IQ) [21] and Flow-Based Implicit Congestion Notification (FBICM) [6].Aunque estas técnicas son bastante efectivas presentanciertos inconvenientes. El más importante es que elnúmero <strong>de</strong> colas especiales por puerto para los flujos congestionadoses limitado y pue<strong>de</strong> no ser suficiente paramanejar todas las ramas <strong>de</strong> los diferentes árboles <strong>de</strong> congestiónque aparecen en un puerto <strong>de</strong>terminado bajo ciertascondiciones <strong>de</strong> tráfico. Evi<strong>de</strong>ntemente, estas situacionesno se dan <strong>de</strong> forma general en todos los puertos <strong>de</strong>la red. Sin embargo, una rama <strong>de</strong> un árbol <strong>de</strong> congestiónque no sea aislada pue<strong>de</strong> generar HoL-blocking y lastrarel rendimiento global <strong>de</strong> la red.En conclusión, nótese que dos <strong>de</strong> los enfoques máspopulares para el CC (limitación <strong>de</strong> inyección y aislamiento<strong>de</strong> flujos congestionados) presentan inconve-<strong>JP2011</strong>-410


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 1. Organización <strong>de</strong> los Puertos <strong>de</strong> Entrada con CCFIT.nientes, como ya se ha mencionado. En este artículo se<strong>de</strong>scribe y evalúa CCFIT, que combina ambos enfoquesy consigue minimizar sus respectivos problemas.III. DESCRIPCIÓN DE LA TÉCNICA CCFITCCFIT se basa en el mecanismo <strong>de</strong> inhibición <strong>de</strong> inyecciónespecificado en IB y en FBICM, una <strong>de</strong> lastécnicas que aislan explícitamente los flujos congestionados.Por tanto, se supone el uso <strong>de</strong> los bits FECN y BECNen los paquetes, el uso <strong>de</strong> encaminamiento distribuidoy el uso <strong>de</strong> conmutadores IQ (Input-Queued), don<strong>de</strong> lasmemorias existen sólo en los puertos <strong>de</strong> entrada.A. Arquitectura <strong>de</strong>l ConmutadorComo, por un lado, CCFIT incluye la limitación <strong>de</strong> inyeccióny, por otro, aisla flujos congestionados, los conmutadoresCCFIT son responsables tanto <strong>de</strong> <strong>de</strong>tectar lacongestión y notificarla a los nodos fuente, como <strong>de</strong> aislarlos paquetes congestionados lo más rápidamente posible.Básicamente, al <strong>de</strong>tectar la congestión, el conmutador<strong>de</strong>be establecer el puerto correspondiente como congestionadoy activar el bit FECN <strong>de</strong> los paquetes que pasanpor él. A<strong>de</strong>más, el conmutador <strong>de</strong>be asignar en los puertos<strong>de</strong> entrada una colas aparte (CFQs) don<strong>de</strong> guardar lospaquetes dirigidos al puerto <strong>de</strong> salida congestionado.Al igual que FBICM, CCFIT no limita el número <strong>de</strong>puertos por conmutador, y cada memoria RAM <strong>de</strong> unpuerto <strong>de</strong> entrada se organiza según el diagrama <strong>de</strong> lafig. 1, dividiéndose en dos tipos <strong>de</strong> colas: una cola NFQ(Normal Flow Queue) para almacenar los paquetes nocongestionados, y un conjunto reducido <strong>de</strong> colas CFQ(Congested-Flow Queues) para los congestionados.Al igual que FBICM, CCFIT usa memorias CAM(Content-Addressable Memory), situadas en los puertos<strong>de</strong> entrada y en los <strong>de</strong> salida, que se encargan <strong>de</strong> almacenarla información <strong>de</strong> los flujos congestionados y el estado<strong>de</strong> las CFQs. Nótese que cada línea <strong>de</strong> una CAM<strong>de</strong> un puerto se asocia con una CFQ <strong>de</strong> dicho puerto.Aunque los puertos <strong>de</strong> salida no tienen ni NFQ ni CFQs,CCFIT necesita una memoria CAM para propagar la información<strong>de</strong> congestión <strong>de</strong>s<strong>de</strong> el puerto <strong>de</strong> entrada <strong>de</strong>lconmutador vecino al que está conectado ese puerto <strong>de</strong>salida hasta los puertos <strong>de</strong> entrada <strong>de</strong>l conmutador local.En referencia al arbitraje <strong>de</strong> los puertos <strong>de</strong> entrada,CCFIT usa iSlip [22], un algoritmo <strong>de</strong> tipo Round-Robin(RR) que consigue un arbitraje igualitario <strong>de</strong>ntro <strong>de</strong>l conmutador(como se <strong>de</strong>muestra en [14]). En concreto, unpuerto <strong>de</strong> entrada que solicita un puerto <strong>de</strong> salida, noobtendrá el acceso hasta ese mismo puerto hasta que todoslos <strong>de</strong>más puertos <strong>de</strong> entrada que solicitan el mismopuerto <strong>de</strong> salida, hayan sido atendidos. Hay otros <strong>de</strong>tallesacerca <strong>de</strong> la igualdad y equidad en la planificación que semejoran con iSlip y el mecanismo <strong>de</strong> inhibición <strong>de</strong> inyecciónen el que se basa CCFIT ([7]).B. Arquitectura <strong>de</strong> los Nodos <strong>de</strong> ProcesamientoFig. 2. Arquitectura <strong>de</strong> los Nodos <strong>de</strong> Procesamiento.activo <strong>de</strong>be, a la mayor brevedad, notificar al nodo emisor<strong>de</strong> ese paquete acerca <strong>de</strong> la situación <strong>de</strong> congestión, paraque ajuste lo antes posible su tasa <strong>de</strong> inyección. Paraello, <strong>de</strong>vuelve un paquete <strong>de</strong> notificación <strong>de</strong> la congestión(CNP) con el bit BECN activo 1 . <strong>La</strong> fig. 2 muestra la arquitectura<strong>de</strong> los nodos <strong>de</strong> procesamiento que proponeCCFIT, que permite generar el tráfico, emitir/recibir losBECNs y reducir/ajustar la tasa <strong>de</strong> inyección <strong>de</strong> tráfico.De ahora en a<strong>de</strong>lante nos referiremos a los nodos <strong>de</strong>procesamiento como IAs (Input Adapters).En la figura se observa que los IAs tienen tantas colas<strong>de</strong> admisión <strong>de</strong> paquetes generados (AdVOQs) comonodos hay en la red. No hay HoL-blocking en la generación,ya que cada cola AdVOQ i guarda sólo los paquetesdirigidos hacia el <strong>de</strong>stino i. Como en los puertos<strong>de</strong> entrada <strong>de</strong> los conmutadores, los IAs tienen unamemoria RAM <strong>de</strong> salida dividida en colas (una NFQ yvarias CFQs) y una memoria CAM. Cada IA incluye estructurasespecíficas para la limitación <strong>de</strong> la inyección,según el mecanismo <strong>de</strong> CC <strong>de</strong> IB. En concreto, la tasa <strong>de</strong>inyección <strong>de</strong> un flujo congestionado se reduce aplicandoun retardo IRD (Injection Rate Delay) entre dos paquetesconsecutivos. Cada IA guarda una lista <strong>de</strong> posiblesIRDs en una tabla llamada CCT (Congestion Control table),y cada AdVOQ i guarda un índice (CCTI) a esa tabla(IRD i = CCT [CCT I[i]]). Los valores <strong>de</strong> la CCT serellenan con el criterio <strong>de</strong> que, a mayor índice, mayor esel retardo <strong>de</strong> inyección, y mayor <strong>de</strong>be ser la inhibición <strong>de</strong>la tasa <strong>de</strong> inyección <strong>de</strong> los paquetes <strong>de</strong> esa AdVOQ i . Alrecibirse un BECN, el CCTI aumenta en tantas unida<strong>de</strong>scomo establece el parámetro CCTI Increase. Por tanto,el IRD i aumenta si se reciben varios BECNs. Por el contrario,el CCTI se reduce en una unidad cuando un temporizador(configurado con el parámetro CCTI Timer) expira.Por tanto, al no recibirse BECNs, el IRD <strong>de</strong> esaAdVOQ i disminuye. Finalmente, la tabla LTI (<strong>La</strong>st Timeof Injection) se encarga <strong>de</strong> guardar el instante <strong>de</strong> tiempoen el que una AdVOQ i inyectó un paquete por última vez.Mediante una política RR, el árbitro <strong>de</strong>l IA inspeccionalas AdVOQs, y usa el LTI, junto con el IRD, para <strong>de</strong>cidirsi el paquete en cabeza <strong>de</strong> una AdVOQ i se pue<strong>de</strong> inyectaro no. A<strong>de</strong>más, dicho árbitro utiliza la CAM <strong>de</strong>l IA parasaber si un árbol <strong>de</strong> congestión concreto llega hasta dichoIA, en cuyo caso no se inyectan paquetes. De esta forma,la tasa <strong>de</strong> inyección <strong>de</strong> los flujos congestionados se reducecuando hay congestión y se incrementa cuando ésta<strong>de</strong>saparece. En la Sección III-C se muestra un ejemplo<strong>de</strong>l comportamiento <strong>de</strong> CCFIT en los IAs.Al igual que la inhibición <strong>de</strong> inyección tipo IB, un nodo 1 El paquete BECN tiene prioridad en los conmutadores a la hora <strong>de</strong><strong>de</strong> procesamiento que recibe un paquete con el bit FECN ser transmitido, y sólo se pue<strong>de</strong> guardar en las NFQs.<strong>JP2011</strong>-411


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011C. Funcionamiento <strong>de</strong> CCFIT<strong>La</strong> fig. 3 muestra un ejemplo <strong>de</strong>l funcionamiento <strong>de</strong>CCFIT. En el conmutador B (Evento #2) se <strong>de</strong>tecta unpunto <strong>de</strong> congestión al sobrepasar la NFQ el umbral <strong>de</strong><strong>de</strong>tección, por lo que se asigna una CFQ para aislar elflujo <strong>de</strong> paquetes dirigidos a ese punto y una línea CAMque se usa para al almacenar la localización <strong>de</strong> ese punto(según el <strong>de</strong>stino <strong>de</strong>l paquete en cabeza <strong>de</strong> la NFQ) 2 .CCFIT utiliza el mismo mecanismo <strong>de</strong> postprocesamiento(Evento #3) que FBICM, el cual <strong>de</strong>tectasi un paquete en la cabeza <strong>de</strong> la NFQ está congestionadoy, en ese caso, lo mueve hacia su CFQ correspondiente.En caso contrario, el paquete se mantiene en la NFQ,<strong>de</strong>s<strong>de</strong> don<strong>de</strong> será encaminado hacia el puerto <strong>de</strong> salidasolicitado. El post-procesamiento <strong>de</strong>ja en la cabeza <strong>de</strong>la NFQ los paquetes no congestionados, eliminando asíel HoL-blocking. A<strong>de</strong>más, este mecanismo <strong>de</strong>ci<strong>de</strong> quécola, bien NFQ o bien CFQs, pue<strong>de</strong> transmitir el paquetehacia el puerto <strong>de</strong> salida solicitado.Por otra parte, el post-procesamiento se encarga <strong>de</strong> <strong>de</strong>cidirsi un puerto <strong>de</strong> salida <strong>de</strong>be entrar en el estado <strong>de</strong>“congestionado” y así marcar paquetes 3 . Para cada CFQalojada en la raíz <strong>de</strong>l árbol <strong>de</strong> congestión (es <strong>de</strong>cir, a unsalto <strong>de</strong>l puerto <strong>de</strong> salida congestionado), CCFIT mira elnivel <strong>de</strong> ocupación <strong>de</strong> la CFQ y, si éste sobrepasa ciertoumbral (“High”), el puerto <strong>de</strong> salida correspondiente seactiva como congestionado, y éste comenzará a marcarpaquetes (activando el bit FECN). Sin embargo, si elpuerto hubiese entrado en ese estado previamente, CCFITaumenta su contador <strong>de</strong> puertos <strong>de</strong> entrada que apuntanal puerto congestionado. En cambio, si el nivel <strong>de</strong> ocupación<strong>de</strong> una cola <strong>de</strong>crece hasta cierto umbral (“Low”),dicho contador disminuye en una unidad. Cuando estecontador llega a cero, el puerto <strong>de</strong>ja <strong>de</strong> estar en estado“congestionado” y, por tanto, <strong>de</strong> marcar paquetes. Nóteseque, si una cola está a dos o más saltos <strong>de</strong>l punto congestionado(e.g. fig. 3, CFQ 0 <strong>de</strong>l P2 en el conmutador A),su puerto <strong>de</strong> salida asociado no entrará en el estado congestionadoy no se marcarán paquetes en dicho puerto.Para la propagación <strong>de</strong> la información <strong>de</strong> congestión,CCFIT sigue la misma política que FBICM, basada en uncontrol <strong>de</strong> flujo Stop/Go (Eventos #4 y #5) entre las CFQ<strong>de</strong> diferentes conmutadores, a lo largo <strong>de</strong>l camino quesigue una rama <strong>de</strong> un árbol <strong>de</strong> congestión. Así, CCFITaisla los flujos congestionados y elimina el HoL-blockinggenerado por los árboles <strong>de</strong> congestión. Como FBICM,cuando la congestión remite, CCFIT <strong>de</strong>saloja los recursosasignados <strong>de</strong> forma dinámica y distribuida (Evento #6).<strong>La</strong> fig. 4 muestra un ejemplo <strong>de</strong>l comportamiento <strong>de</strong>los IAs que usan CCFIT. En concreto, un IA está conectadocon el conmutador A, que acaba <strong>de</strong> <strong>de</strong>tectar unasituación <strong>de</strong> congestión (Eventos <strong>de</strong>l #1 al #4), similar ala <strong>de</strong> la figura anterior, pero la información <strong>de</strong> congestiónse propaga <strong>de</strong>s<strong>de</strong> el conmutador A hacia un IA.Si se activa el bit FECN <strong>de</strong> los paquetes que pasanpor el puerto congestionado P3 <strong>de</strong>l conmutador A, el IArecibirá notificaciones BECN (Evento #6). Al recibir unBECN, CCFIT calcula la AdVOQ i que envía paquetescongestionados hacia el <strong>de</strong>stino generador <strong>de</strong>l BECN (<strong>de</strong>notadopor i), e incrementa el CCTI[i] en una unidad.Esto produce que el IRD i se incremente para la AdVOQ i2 Al igual que FBICM, CCFIT sólo guarda en cada línea CAM el <strong>de</strong>stino<strong>de</strong>l paquete como información <strong>de</strong> congestión. Se pue<strong>de</strong> consultarinformación adicional acerca <strong>de</strong> las líneas CAM <strong>de</strong> FBICM en [6], [23].3 El bit FECN se activará o no <strong>de</strong>pendiendo <strong>de</strong> los parámetrosPacket Size (tamaño mínimo <strong>de</strong> los paquetes a marcar) y Marking Rate(tasa <strong>de</strong> marcado <strong>de</strong> paquetes congestionados).y se reduzca su tasa <strong>de</strong> inyección. A<strong>de</strong>más, el valor <strong>de</strong>Timer[i] (fig. 2) se inicializa con el valor CCTI Timery, cuando dicho timer expira (Evento #7), el CCTI[i]se <strong>de</strong>crementa en una unidad y el IRD i se reduce. Portanto, la tasa <strong>de</strong> inyección se aumenta. Nótese que, siuna situación <strong>de</strong> congestión es prolongada, se recibiránnumerosos BECNs y por tanto los IRD i <strong>de</strong> los <strong>de</strong>stinosi congestionados se aumentarán, limitándose así la inyecciónhacia esos puntos. El árbitro <strong>de</strong>l IA toma la <strong>de</strong>cisión<strong>de</strong> qué paquete <strong>de</strong>be inyectarse (Evento #8), segúnuna política RR entre todas las AdVOQs, el IRD i y elúltimo instante en que cada AdVOQ i transmitió (LTI[i]).De este modo, CCFIT reduce la tasa <strong>de</strong> inyecciónpara los <strong>de</strong>stinos congestionados durante las situaciones<strong>de</strong> congestión y elimina los árboles <strong>de</strong> congestión <strong>de</strong> lared. Los recursos que ocupan esos árboles (principalmenteCFQs y líneas CAM), se liberan <strong>de</strong> forma rápiday quedan disponibles para aislar nuevos árboles <strong>de</strong> congestión.Cuando la congestión <strong>de</strong>saparece la tasa <strong>de</strong> inyecciónse incrementa. Por otro lado, el mecanismo <strong>de</strong>inhibición <strong>de</strong> inyección <strong>de</strong> CCFIT necesita ajustar ciertosparámetros, al igual que se hace en IB. Un estudio másexhaustivo <strong>de</strong> la configuración <strong>de</strong> dichos parámetros sepue<strong>de</strong> consultar en [7], [13], [14].IV. EVALUACIÓN<strong>La</strong> principal contribución <strong>de</strong> CCFIT es el aumento significativo<strong>de</strong> sus prestaciones si se compara con FBICM ola técnica CC <strong>de</strong> IB (limitación <strong>de</strong> inyección), sobre todoen situaciones <strong>de</strong> congestión persistente y con muchosárboles <strong>de</strong> congestión. En estos casos FBICM se quedasin CFQs, y la técnica <strong>de</strong> inhibición <strong>de</strong> la inyección reacciona<strong>de</strong> forma muy lenta a la congestión, produciéndoseun “efecto sierra” en la productividad, <strong>de</strong>bido a esa lentitud.En esta sección se evalúan las prestaciones <strong>de</strong> CCFITque se han obtenido mediante simulaciones.En primer lugar, la herramienta <strong>de</strong> simulación es unsimulador dirigido por eventos, programado en lenguajeC + +, que mo<strong>de</strong>la re<strong>de</strong>s <strong>de</strong> interconexión a nivel <strong>de</strong> ciclo,nodos finales, enlaces, etc. A<strong>de</strong>más, para nuestrosexperimentos, se ha mo<strong>de</strong>lado una red <strong>de</strong> interconexión<strong>de</strong> 64 nodos con patrón <strong>de</strong> conectividad 4-ary 3-tree yenlaces <strong>de</strong> 2.5 GBytes/s, 48 conmutadores IQ <strong>de</strong> grado8 puertos, con Virtual Cut-Through (VCT) como política<strong>de</strong> conmutación, control <strong>de</strong> flujo basado en créditos y iSlipcomo algoritmo <strong>de</strong> planificación. El encaminamientoes distribuido, <strong>de</strong>terminista, basado en tablas y usa el algoritmoDESTRO [24]. A<strong>de</strong>más, las memorias <strong>de</strong> lospuertos <strong>de</strong> entrada <strong>de</strong> los conmutadores son <strong>de</strong> 64 KB yel tamaño <strong>de</strong> paquete es <strong>de</strong> 2048 bytes.Por otro lado, se han mo<strong>de</strong>lado tres escenarios <strong>de</strong>tráfico para la anterior configuración <strong>de</strong> red, con un 25%<strong>de</strong> los nodos <strong>de</strong> procesamiento que generan 1, 4 y 6árboles <strong>de</strong> congestión respectivamente, entre los instantes<strong>de</strong> tiempo [1ms,2ms]. Estos escenarios sirven para comprobarque CCFIT aisla y elimina los árboles <strong>de</strong> congestióncuando no hay CFQs suficientes. Finalmente, sehan mo<strong>de</strong>lado las siguientes técnicas <strong>de</strong> CC:* Una cola (1Q) por puerto que guarda todos los paquetes.Al no existir eliminación <strong>de</strong> HoL-blocking, 1Qpermite evaluar la red en el peor <strong>de</strong> los casos.* FBICM. Se usan 2 CFQs por puerto <strong>de</strong> entrada.* Limitación <strong>de</strong> inyección (ITh). Se asumen 8 VOQs(Virtual Output Queues, ya que el grado <strong>de</strong> los conmutadoreses <strong>de</strong> 8 puertos. Los umbrales High/Low (fijadosa 4 y 2 paquetes), así como los <strong>de</strong>más parámetros <strong>de</strong> losIAs, se han fijado tal y como se analiza en [14]).<strong>JP2011</strong>-412


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 3. Ejemplo <strong>de</strong> funcionamiento <strong>de</strong> CCFIT en los Conmutadores.* CCFIT asume 2 CFQs por puerto <strong>de</strong> entrada y usalos mismos valores, para los parámetros <strong>de</strong> limitación <strong>de</strong>inyección <strong>de</strong> los IAs, que la técnica ITh. Nótese que sólo2 CFQs aislarán flujos <strong>de</strong> paquetes y pondrán puertos <strong>de</strong>salida en estado congestionado, mientras que la técnicaITh usa 8 VOQs, para el mismo cometido.* VOQnet (teóricamente la más efectiva) necesitamemorias <strong>de</strong> mayor tamaño por puerto <strong>de</strong> entrada, ya quecada memoria se divi<strong>de</strong> en 64 colas (64 nodos <strong>de</strong>stinoposibles). Si consi<strong>de</strong>ramos las restricciones <strong>de</strong>l control<strong>de</strong> flujo, tamaño <strong>de</strong> paquete y ancho <strong>de</strong> banda <strong>de</strong>l enlace,el tamaño mínimo <strong>de</strong> la cola será <strong>de</strong> 4 KB y las memoriasserán <strong>de</strong> 256 KB. Por tanto VOQnet es poco realistay sólo se mo<strong>de</strong>la para obtener la máxima productividadteórica <strong>de</strong> la red con eliminación <strong>de</strong>l HoL-blocking.A. Análisis <strong>de</strong> la Productividad<strong>La</strong> fig. 5 muestra la productividad global <strong>de</strong> la red enfunción <strong>de</strong>l tiempo, para la red y el patrón <strong>de</strong> tráfico <strong>de</strong>scritosanteriormente. En general, se aprecia claramentecómo CCFIT (con 2 CFQs por puerto) consigue un buencomportamiento, aún cuando el número <strong>de</strong> árboles <strong>de</strong>congestión pasa <strong>de</strong> 1 a 6. En la fig. 5a (un único árbol<strong>de</strong> congestión), FBICM con 2 CFQs tiene recursos suficientespara almacenar los arboles <strong>de</strong> congestión. Nóteseque a<strong>de</strong>más <strong>de</strong>l árbol <strong>de</strong> congestión generado, pue<strong>de</strong>naparecer situaciones <strong>de</strong> congestión eventuales (que surgeny <strong>de</strong>saparecen <strong>de</strong> forma muy rápida), las cuales introducencierto HoL-blocking que sólo pue<strong>de</strong> eliminarsecon una técnica que reaccione rápidamente ante la congestión.<strong>La</strong> técnica ITh, que a<strong>de</strong>más tiene 8 VOQs porpuerto, no es capaz <strong>de</strong> reaccionar tan rápido a la situación<strong>de</strong> congestión como FBICM o CCFIT. Por otro lado, VO-Fig. 4. Ejemplo <strong>de</strong> funcionamiento <strong>de</strong> CCFIT en los IAs.<strong>JP2011</strong>-413Qnet alcanza la máxima productividad pero, como se ha<strong>de</strong>scrito, a costa <strong>de</strong> usar 64 colas por puerto y memorias<strong>de</strong> 256 KB, mientras CCFIT y las otras técnicas usanmenos colas y menos memoria. En todos los casos, elesquema 1Q consigue los peores resultados, ya que se veafectado por el HoL-blocking.Al aumentarse el número <strong>de</strong> árboles <strong>de</strong> congestión enla red (fig. 5b), FBICM no tiene CFQs suficientes paraalmacenar todos los árboles <strong>de</strong> congestión que aparecenen la red y, por tanto, surge HoL-blocking que lastra susprestaciones. Por otra parte, CCFIT mejora sustancialmenteel comportamiento <strong>de</strong> FBICM, gracias al efecto <strong>de</strong>la limitación <strong>de</strong> la inyección, que es capaz <strong>de</strong> liberar lasCFQs y líneas CAM asignadas, antes <strong>de</strong> que sean necesariaspara aislar nuevos árboles <strong>de</strong> congestión. Finalmente,ITh reacciona mejor ante este tipo <strong>de</strong> tráfico, conrespecto al escenario <strong>de</strong> la fig. 5a, pero se pue<strong>de</strong> observarclaramente la oscilación su eficiencia (el “efecto sierra”).Finalmente, con 6 árboles <strong>de</strong> congestión en la red (fig.5c), se obtienen conclusiones similares. Este patrón <strong>de</strong>tráfico representa una situación don<strong>de</strong> el tráfico congestionadose balancea mejor en la red (téngase en cuentaque hay 6 árboles repartidos en un 25% <strong>de</strong> tráfico congestionado).Nuevamente CCFIT mejora a FBICM, mientrasITh necesita más tiempo para ajustar la tasa <strong>de</strong> inyección.En conclusión, CCFIT mejora sustancialmente otrosenfoques <strong>de</strong> CC, incluido FBICM, máxime si los árboles<strong>de</strong> congestión en la red no pue<strong>de</strong>n ser aislados en lasCFQs disponibles; consigue liberar las CFQs utilizadas<strong>de</strong> forma más rápida, gracias a la limitación <strong>de</strong> inyeccióny, por tanto, esas CFQs pue<strong>de</strong>n ser usadas para aislarnuevos flujos congestionados <strong>de</strong> forma inmediata.


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Productividad <strong>de</strong> la red (normalizada)0.80.70.60.50.40.30.20.11QIThFBICM-2CFQCCFIT-2CFQVOQnet00 1e+06 2e+06 3e+06 4e+06 5e+06Tiempo (nanosegundos)(a) 1 Árbol <strong>de</strong> Congestión.Productividad <strong>de</strong> la red (normalizada)0.80.70.60.50.40.31Q0.2IThFBICM-2CFQ0.1CCFIT-2CFQVOQnet00 1e+06 2e+06 3e+06 4e+06 5e+06Tiempo (nanosegundos)(b) 4 Árboles <strong>de</strong> Congestión.Fig. 5. Productividad vs. Tiempo (Configuración #3, Tráfico #4).Productividad <strong>de</strong> la red (normalizada)0.80.70.60.50.40.31Q0.2IThFBICM-2CFQ0.1CCFIT-2CFQVOQnet00 1e+06 2e+06 3e+06 4e+06 5e+06Tiempo (nanosegundos)(c) 6 Árboles <strong>de</strong> Congestión.V. CONCLUSIONESEn la actualidad, las re<strong>de</strong>s <strong>de</strong> interconexión <strong>de</strong> altasprestaciones son más simples y sencillas, ya que se handiseñado con el objetivo <strong>de</strong> ahorrar coste y consumo.Esto ocasiona que la congestión surja y se propague conmás facilidad, <strong>de</strong> un modo más rápido, lo que hace necesarioel uso <strong>de</strong> mecanismos <strong>de</strong> control <strong>de</strong> la congestión.De entre todos los enfoques propuestos para el control<strong>de</strong> la congestión, <strong>de</strong>stacan la inhibición <strong>de</strong> la inyeccióny el aislamiento explícito <strong>de</strong> los flujos congestionados.El primer enfoque reduce el árbol <strong>de</strong> congestión paraminimizar su principal efecto negativo, el HoL-blocking,pero entre el momento en que se <strong>de</strong>tecta la congestión, yel momento en que se reduce el árbol existe un retardosignificativo. Por otro lado, el segundo enfoque aisla<strong>de</strong> forma inmediata los árboles <strong>de</strong> congestión, usandopara ello colas especiales, dinámicamente asignadas atal efecto, con lo que elimina completamente el HoLblocking.Sin embargo, dichos recursos, al ser limitados,no pue<strong>de</strong>n almacenar todos los árboles <strong>de</strong> congestión.En este artículo se ha <strong>de</strong>scrito CCFIT (CombinedCongestion-Flow Isolation and Throttling, una nuevatécnica que combina ambos enfoques <strong>de</strong> control <strong>de</strong> congestión,y que está pensada para mantener las ventajas<strong>de</strong> ambos y minimizar sus inconvenientes. En concreto,CCFIT reacciona <strong>de</strong> forma inmediata a la congestión, aislandolos árboles <strong>de</strong> congestión. A su vez, la limitación<strong>de</strong> inyección reduce el árbol <strong>de</strong> congestión y libera losrecursos utilizados para el aislamiento <strong>de</strong> esos árboles<strong>de</strong> congestión <strong>de</strong> forma más rápida, tal y como ha <strong>de</strong>mostradola evaluación <strong>de</strong> prestaciones.AGRADECIMIENTOSEste trabajo ha sido parcialmente financiado por elMEC y el MICINN, así como por la Comisión Europeaa través <strong>de</strong> los fondos FEDER, mediante los proyectosCSD2006-00046 y TIN2009-14475-C04. A<strong>de</strong>más,también ha sido parcialmente financiado por la JCCM,mediante los proyectos PEII11-0229-2343, POII10-0289-3724 y la beca <strong>de</strong> doctorado A08/048.REFERENCIAS[1] Pedro J. García, J. Flich, J. Duato, I. Johnson, Francisco J. Quiles,and F. Naven, “Dynamic evolution of congestion trees: Analysisand impact on switch architecture,” Proc. 1st HiPEAC Conf., pp.266–285, November 2005.[2] M. J. Karol, M. G. Hluchyj, and S. P. Morgan, “Input versusoutput queueing on a space-division packet switch,” IEEE Trans.on Commun., vol. COM-35, pp. 1347–1356, 1987.[3] Pedro J. García, J. Flich, J. Duato, I. Johnson, Francisco J. Quiles,and F. Naven, “Efficient, scalable congestion management forinterconnection networks,” IEEE Micro, vol. 26, no. 5, pp. 52–66,September 2006.[4] InfiniBand Tra<strong>de</strong> Association, InfiniBand architecture specification.Release 1.2.1, Nov. 2007.[5] J. Duato, I. Johnson, J. Flich, F. Naven, Pedro J. García, and T. Nachiondo,“A new scalable and cost-effective congestion managementstrategy for lossless multistage interconnection networks,”in Proceedings of the 11th Symposium on High Performance ComputerArchitecture (HPCA), 2005.[6] J. Escu<strong>de</strong>ro-Sahuquillo, Pedro J. García, Francisco J. Quiles,J. Flich, and J. Duato, “FBICM: Efficient congestion managementfor high-performance networks using distributed <strong>de</strong>terministicrouting,” in LNCS Series - 15th Conference on High PerformanceComputing - (HiPC 2008), Bangalore, India, December.[7] J. Escu<strong>de</strong>ro-Sahuquillo, E. G. Gran, Pedro J. García, J. Flich,T. Skeie, O. Lysne, F. J. Quiles, and J. Duato, “Combiningcongested-flow isolation and injection throttling in hpc interconnectionnetworks,” in Proceedings of the 40th InternationalConference on Parallel Processing (ICPP 2011), Taipei, Taiwan,september 2011.[8] M. Thottetodi, A.R. Lebeck, and S.S. Mukherjee, “Self-tunedcongestion control for multiprocessor networks,” in Proc. of 7th.HPCA, February 2001.[9] J.H. Kim, Ziqiang Liu, and A.A. Chien, “Compressionless routing:a framework for adaptive and fault-tolerant routing,” Paralleland Distributed Systems, IEEE Transactions on, vol. 8, no. 3, pp.229 –244, Mar. 1997.[10] Elvira Baydal and Pedro López, “A robust mecahnism for congestioncontrol: Inc,” in Euro-Par, 2003, pp. 958–968.[11] Santos J. R, Y. Turner, and G. J. Janakiraman, “End-to-end congestioncontrol for InfiniBand,” in INFOCOM, 2003.[12] Joan-Lluís Ferrer, Elvira Baydal, Antonio Robles, Pedro López,and José Duato, “On the influence of the packet marking andinjection control schemes in congestion management for MINs,”in Euro-Par, 2008, pp. 930–939.[13] E.G. Gran, M. Eimot, S.-A. Reinemo, T. Skeie, O. Lysne, L.P.Huse, and G. Shainer, “First experiences with congestion controlin InfiniBand hardware,” in Parallel Distributed Processing(IPDPS), IEEE International Symposium on, 2010, pp. 1–12.[14] Ernst Gunnar Gran, Eitan Zahavi, Sven-Arne Reinemo, Tor Skeie,Gilad Shainer, and Olav Lysne, “On the relation between congestioncontrol, switch arbitration and fairness,” in InternationalSymposium on Cluster, Cloud and Grid Computing (CC-Grid 2011) [Pending of publishing].[15] T. An<strong>de</strong>rson, S. Owicki, J. Saxe, and C. Thacker, “High-speedswitch scheduling for local-area networks,” ACM Transactions onComputer Systems, vol. 11, no. 4, pp. 319–352, November 1993.[16] W. Dally, P. Carvey, and L. Dennison, “Architecture of the Aviciterabit switch/router,” in Proc. 6th Hot Interconnects, 1998, pp.41–50.[17] Y. Tamir and G.L. Frazier, “Dynamically-allocated multi-queuebuffers for vlsi communication switches,” IEEE Transactions onComputers, vol. 41, no. 6, June 1992.[18] Teresa Nachiondo, Jose Flich, and Jose Duato, “Buffer managementstrategies to reduce hol blocking,” IEEE Transactions onParallel and Distributed Systems, vol. 21, pp. 739–753, 2010.[19] Wla<strong>de</strong>k Olesinski, Hans Eberle, and Nils Gura, “Scalable alternativesto virtual output queueing,” in Proc. IEEE InternationalConference on Communications, 2009.[20] J. Escu<strong>de</strong>ro-Sahuquillo, Pedro J. García, Francisco J. Quiles, andJ. Duato, “An efficient strategy for reducing head-of-line blockingin fat-trees,” in 16th International Euro-Par Conference, Ischia,Italy, september 2010, pp. 413–427.[21] G. Mora, Pedro J. García, J. Flich, and J. Duato, “RECN-IQ:A cost-effective input-queued switch architecture with congestionmanagement,” in Proc. ICPP, 2007.[22] N. McKeown, “The iSLIP scheduling algorithm for input-queuedswitches,” IEEE/ACM Transactions on Networking, vol. 7, no. 2,pp. 188–201, Apr. 1999.[23] J. Escu<strong>de</strong>ro-Sahuquillo, Pedro J. García, Francisco J. Quiles,J. Flich, and J. Duato, “Cost-effective congestion management forinterconnection networks using distributed <strong>de</strong>terministic routing,”in Proc.16th International Conference on Parallel and DistributedSystems (ICPADS 2010), Shanghai, China, <strong>de</strong>cember 2010.[24] C. Gomez, F. Gilabert, M.E. Gomez, P. Lopez, and J. Duato, “Deterministicversus adaptive routing in fat-trees,” in Workshop onCommunication Architecture on Clusters, as a part of IPDPS’07,March 2007, p. 235.<strong>JP2011</strong>-414


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Un acercamiento a la eficacia <strong>de</strong> las técnicas<strong>de</strong> control <strong>de</strong> congestión en re<strong>de</strong>s <strong>de</strong>interconexión con topologías directasDaniel Gómez-García 1 , Pedro Javier García 1 , Francisco José Quiles 1 , JesúsEscu<strong>de</strong>ro-Sahuquillo 1 , Juan Antonio Villar 1 , José Flich 2 , José Duato 21 Dept. Sistemas Informáticos, <strong>Universidad</strong> <strong>de</strong> Castilla-<strong>La</strong> Mancha. E-mail:{Daniel.Gomez,PedroJavier.Garcia,Francisco.Quiles,Jesus.Escu<strong>de</strong>ro,JuanAntonio.Villar}@uclm.es2 Dept. <strong>de</strong> Informática <strong>de</strong> Sistemas y Computadores, Universitat Politècnica <strong>de</strong> València. E-mail:{jflich,jduato}@gap.upv.esResumen—<strong>La</strong>s re<strong>de</strong>s <strong>de</strong> interconexión juegan un papel cada díamás importante en el rendimiento global <strong>de</strong> los sistemas <strong>de</strong> computaciónparalela y <strong>de</strong> comunicaciones. De hecho, hoy en día, la red<strong>de</strong> interconexión suele limitar el rendimiento global <strong>de</strong>l sistema. Asu vez, las prestaciones <strong>de</strong> la red se ven afectadas por la aparición<strong>de</strong> situaciones <strong>de</strong> congestión. En re<strong>de</strong>s sin <strong>de</strong>scarte <strong>de</strong> paquetes, laaparición <strong>de</strong> situaciones <strong>de</strong> congestión <strong>de</strong>grada gravemente la productividad<strong>de</strong> la red, <strong>de</strong>bido a que los flujos no congestionados seven afectados por la lentitud <strong>de</strong>l avance <strong>de</strong> los flujos congestionados,que hacen que los primeros avancen más <strong>de</strong>spacio <strong>de</strong> lo que<strong>de</strong>berían. Esto es un caso particular <strong>de</strong>l fenómeno conocido comobloqueo <strong>de</strong> cabeza <strong>de</strong> línea (HoL blocking).Aunque se han propuesto muchas técnicas para reducir o eliminarel HoL blocking, sólo algunas se consi<strong>de</strong>ran realmente eficientesy escalables. Sin embargo, habitualmente la evaluación <strong>de</strong> estastécnicas se ha realizado solamente en re<strong>de</strong>s multietapa. En esteartículo se realiza una comparación entre las técnicas más comunes<strong>de</strong> eliminación <strong>de</strong>l HoL blocking mediante resultados <strong>de</strong> simulaciónobtenidos en escenarios que mo<strong>de</strong>lan re<strong>de</strong>s directas, <strong>de</strong> cara a comprobarla vali<strong>de</strong>z <strong>de</strong> estas técnicas para estas topologías.Palabras clave—Re<strong>de</strong>s <strong>de</strong> Interconexión; Control <strong>de</strong> Congestión;Topologías DirectasFig. 1HOL BLOCKING DEBIDO A LOS FLUJOS CONGESTIONADOSI. INTRODUCCIÓNEN los últimos años las re<strong>de</strong>s <strong>de</strong> interconexión hanido jugando un papel cada vez más importante enel rendimiento global <strong>de</strong> los sistemas <strong>de</strong> computación paralelay <strong>de</strong> comunicaciones. Hoy en día, los principalessistemas cuyo rendimiento <strong>de</strong>pen<strong>de</strong> en gran medida <strong>de</strong> lared <strong>de</strong> interconexión son: procesadores masivamente paralelos(MPPs), sytem area networks (SANs), clusters <strong>de</strong>PCs y estaciones <strong>de</strong> trabajo, routers IP y re<strong>de</strong>s en chip(NoCs). De hecho, el rendimiento global <strong>de</strong> estos sistemasse encuentra limitado por las prestaciones <strong>de</strong> la red<strong>de</strong> interconexión que posee.Uno <strong>de</strong> los fenómenos que más impacto pue<strong>de</strong> teneren las prestaciones <strong>de</strong> una red es la aparición <strong>de</strong> situaciones<strong>de</strong> congestión. Estas situaciones se dan cuando variosflujos <strong>de</strong> datos <strong>de</strong>ntro <strong>de</strong> la red requieren simultánea ypersistentemente los mismos recursos para alcanzar sus<strong>de</strong>stinos. En una red sin pérdidas, como es el caso <strong>de</strong> lamayoría <strong>de</strong> tecnologías <strong>de</strong> red actuales, la eliminación <strong>de</strong>paquetes no está permitida, por lo que cuando las colas<strong>de</strong> los conmutadores que se encuentran en ese camino sellenan, el control <strong>de</strong> flujo propaga la congestión “haciaatrás” en el camino <strong>de</strong> los datos. Cuando esto suce<strong>de</strong>, elrendimiento <strong>de</strong> la red se <strong>de</strong>grada rápidamente. Estas situaciones<strong>de</strong> congestión se han evitado tradicionalmentesobredimensionando la red <strong>de</strong> interconexión, pero en laactualidad esta práctica se ha vuelto inviable <strong>de</strong>bido a losaltos costes y al alto consumo <strong>de</strong> los componentes <strong>de</strong> in-terconexión <strong>de</strong> la red.De hecho, las re<strong>de</strong>s <strong>de</strong> interconexión actuales, <strong>de</strong>bido arestricciones económicas, <strong>de</strong> consumo y <strong>de</strong> memoria, sondiseñadas usando el mínimo número <strong>de</strong> componentes <strong>de</strong>red posible. Esto nos lleva a una mayor probabilidad <strong>de</strong>que aparezcan situaciones <strong>de</strong> congestión. Debido a esto,usar técnicas <strong>de</strong> control <strong>de</strong> congestión en re<strong>de</strong>s <strong>de</strong> interconexiónse ha vuelto prácticamente imprescindible. Eneste sentido, se han propuesto varias técnicas que tratan<strong>de</strong> evitar la aparición <strong>de</strong> situaciones <strong>de</strong> congestión o <strong>de</strong>eliminarlas cuando aparecen (por ejemplo, la inhibición<strong>de</strong> inyección [1]).Cabe aclarar que, <strong>de</strong>s<strong>de</strong> nuestro punto <strong>de</strong> vista, la congestiónen sí no es el problema. El problema real llegacuando los flujos congestionados y los no congestionadoscomparten recursos <strong>de</strong> la red (colas, enlaces). Concretamente,cuando las colas <strong>de</strong> los conmutadores almacenanpaquetes pertenecientes a flujos congestionados y no congestionados,los primeros hacen que los flujos no congestionadosavancen por la red a la misma velocidad que lohacen los congestionados. En general este efecto es uncaso particular <strong>de</strong>l fenómeno conocido como bloqueo <strong>de</strong>cabeza <strong>de</strong> línea (HoL blocking) y se pue<strong>de</strong> observar en lafigura 1. Cabe remarcar que en los esquemas <strong>de</strong> colas enlos que éstas no son compartidas, los flujos <strong>de</strong> paquetesno congestionados no se ven afectados por el HoL blocking.Para eliminar el HoL blocking se han propuesto mu-<strong>JP2011</strong>-415


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011chas técnicas, como pue<strong>de</strong>n ser: Virtual Output Queuesa nivel <strong>de</strong> red (VOQnet) [2], Virtual Output Queues a nivel<strong>de</strong> conmutador (VOQsw) [3], Destination-Based BufferManagement (DBBM) [4], Regional Explicit CongestionNotification (RECN) [5], Flow-Based Implicit CongestionManagement (FBICM) [6], Output-Based QueueAssignment (OBQA) [7] o Dynamically Allocated Multiqueues(DAMQS) [8].Entre todas las técnicas mencionadas, probablementelas técnicas que más económica y satisfactoriamente eliminanel HoL blocking son RECN y FBICM. Estas técnicascomparten el mismo planteamiento y son capaces <strong>de</strong>reducir en gran medida los efectos perjudiciales <strong>de</strong>l HoLblocking sin requerir una gran cantidad <strong>de</strong> recursos extra.El funcionamiento básico <strong>de</strong> ambas propuestas será explicadoen la siguiente sección.Sim embargo, ambas técnicas han sido evaluadas casiexclusivamente en re<strong>de</strong>s multietapa. <strong>La</strong> finalidad <strong>de</strong> esteartículo es evaluar diversas técnicas para reducir el HoLblocking en topologías directas tipo malla o toro, <strong>de</strong> caraa comprobar si las ventajas <strong>de</strong>l enfoque seguido porRECN y FBICM se mantienen en estas topologías.El resto <strong>de</strong>l artículo se organiza así: en la sección II,se resume el funcionamiento <strong>de</strong> las técnicas <strong>de</strong> control<strong>de</strong> congestión RECN y FBICM. Luego, en la sección IIIse verán los resultados <strong>de</strong> las simulaciones realizadas yse comentarán los resultados obtenidos. Por último, en lasección IV se exponen las conclusiones y las motivacionespara seguir trabajando en esta línea.II. RECN Y FBICMEsencialmente, la diferencia entre las técnicas RECN yFBICM radica en que RECN ha sido propuesto para re<strong>de</strong>sque usan encaminamiento fuente, mientras que FBICMasume el uso <strong>de</strong> encaminamiento distribuido <strong>de</strong>terministabasado en tablas. <strong>La</strong> segunda diferencia más importanteentre ambos recae en la arquitectura <strong>de</strong> conmutadorusada. Mientras que FBICM ha sido específicamente diseñadopara conmutadores IQ (Input Queued, o colas solamenteen los puertos <strong>de</strong> entrada), existen versiones <strong>de</strong>RECN tanto para conmutadores IQ como para conmutadoresCIOQ (Combined Input and Output Queued, o concolas tanto en los puertos <strong>de</strong> entrada como en los <strong>de</strong> salida).Aparte <strong>de</strong> estas diferencias y algún otro <strong>de</strong>talle, elfuncionamiento básico es el mismo.Ambas propuestas se basan en la misma i<strong>de</strong>a clave:si el HoL blocking es eliminado completamente, pue<strong>de</strong>ser que la congestión siga existiendo en la red, pero esinocua. Hay que tener en cuenta que si los flujos no congestionadosno se ven afectados por los congestionados,todos los flujos <strong>de</strong> datos <strong>de</strong> la red cruzarán la red a lavelocidad máxima que ésta permita. Teniendo en cuentaesto, ambas técnicas tratan <strong>de</strong> eliminar el HoL blockingsiguiendo los mismos procedimientos básicos: se <strong>de</strong>tectaexplícitamente el punto don<strong>de</strong> se está produciendo lacongestión y luego se separan los flujos congestionadosy los no congestionados asignando dinámicamente colaspara almacenar únicamente los paquetes <strong>de</strong> los flujoscongestionados. De esta manera se evita el HoL blockingproducido por los paquetes congestionados a los que nolo están. Por otro lado, los paquetes no congestionadospue<strong>de</strong>n seguir compartiendo colas entre ellos sin que elloproduzca un HoL blocking significativo. De esta forma,estas técnicas no requieren <strong>de</strong>masiadas colas para atacarel problema <strong>de</strong>l HoL blocking, siempre teniendo en menteque al aumentar el tamaño <strong>de</strong> la red, el número <strong>de</strong> flujos<strong>de</strong> paquetes que pasan por un punto <strong>de</strong> la red aumenta.<strong>La</strong> <strong>de</strong>tección <strong>de</strong> la congestión se produce cuando laocupación <strong>de</strong> una cola en un puerto <strong>de</strong> entrada <strong>de</strong> un conmutadoralcanza un cierto nivel, al que llamaremos nivel<strong>de</strong> <strong>de</strong>tección. Llegar a este nivel indica que pue<strong>de</strong> haberciertos paquetes que no están avanzando tan rápido como<strong>de</strong>berían y eso pue<strong>de</strong> llevarnos al <strong>de</strong>sbordamiento <strong>de</strong> lacola.Una vez <strong>de</strong>tectada la situación <strong>de</strong> congestión, el proceso<strong>de</strong> aislamiento <strong>de</strong>l flujo <strong>de</strong> paquetes congestionadoscomienza: se asigna una nueva cola para aquellos paquetescuyo puerto <strong>de</strong> salida sea el puerto que se ha <strong>de</strong>tectadocomo punto <strong>de</strong> congestión. Para la gestión <strong>de</strong> la nueva colase creará también una nueva entrada en una MemoriaDireccionable por Contenido (CAM). Esta CAM almacenarála ruta hasta el punto <strong>de</strong> congestión, bien <strong>de</strong> maneraexplícita (RECN) o bien implícita (FBICM).Cuando la congestión persiste durante un largo periodo<strong>de</strong> tiempo, estas nuevas colas creadas para almacenarlos paquetes <strong>de</strong> los flujos congestionados, pue<strong>de</strong>n, a suvez, llegar a un nivel muy alto <strong>de</strong> ocupación y sufrir peligro<strong>de</strong> <strong>de</strong>sbordamiento. Para evitar esta situación se usaun umbral <strong>de</strong> “Stop”. Una vez que una cola alcanza estepunto, la información <strong>de</strong> congestión <strong>de</strong>be ser propagada alos conmutadores prece<strong>de</strong>ntes. Con esta información, unconmutador que la recibe sabe que hay un conmutador enel siguiente salto que está al límite <strong>de</strong> su capacidad paraalmacenar paquetes congestionados <strong>de</strong> una cola concreta,lo que le lleva a asignar él una cola para almacenar lospaquetes <strong>de</strong> este flujo congestionado y a parar su envíohasta que se reciba una señal <strong>de</strong> “Go“. Con este mecanismo<strong>de</strong> propagación conseguimos aislar los flujos <strong>de</strong>paquetes congestionados a lo largo <strong>de</strong> su camino hasta elpunto don<strong>de</strong> son generados, evitando así el HoL blockingque pue<strong>de</strong>n producir los no congestionados.Finalmente, cuando la congestión va <strong>de</strong>sapareciendo,otro mecanismo se encarga <strong>de</strong> liberar las colas que yano son necesarias. De esta forma estas colas pue<strong>de</strong>n serreutilizadas para almacenar los paquetes <strong>de</strong> nuevos flujoscongestionados que puedan aparecer.Se ha <strong>de</strong>mostrado que tanto RECN como FBICM eliminan<strong>de</strong> manera eficiente el HoL blocking [5] [6], perotambién cabe <strong>de</strong>cir que estas técnicas han sido evaluadasbásicamente en Re<strong>de</strong>s <strong>de</strong> Interconexión Multietapa (MultistageInterconnection Networks, MINs). En la siguientesección se evalúa la vali<strong>de</strong>z <strong>de</strong> este enfoque en re<strong>de</strong>s directas.III. EVALUACIÓN EN REDES DIRECTASA. Entorno <strong>de</strong> simulaciónLos siguiente resultados y figuras han sido obtenidosmediante simulación. Para ello se ha utilizado un simuladorad-hoc, dirigido por eventos, que mo<strong>de</strong>la re<strong>de</strong>s<strong>de</strong> interconexión a nivel <strong>de</strong> ciclo. Este simulador es capaz<strong>de</strong> mo<strong>de</strong>lar las diferentes técnicas <strong>de</strong> reducción <strong>de</strong>lHoL blocking como VOQnet, VOQsw, DBBM, RECN y<strong>JP2011</strong>-416


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA IIPATRONES DE TRÁFICO SINTÉTICO EVALUADOSTráfico uniformeTrafico Hot-SpotCaso % Fuentes Destino Tasa <strong>de</strong> generación % Fuentes N o Destinos Tasa <strong>de</strong> generación Tiempo inicio Tiempo fin1 100 % aleatorio incremental 0 % - - - -2 75 % aleatorio 100 % 25 % 1 100 % 1000µS 1300µSTABLA ICONFIGURACIONES DE RED EVALUADASCaso Tamaño Topología N o Conmutadores1 8x8 Malla 2D 642 8x8x8 Malla 3D 5123 8x8 Toro 2D 644 8x8x8 Toro 3D 512FBICM. Aparte <strong>de</strong> mo<strong>de</strong>lar los diferentes mecanismos,nuestro simulador también es capaz <strong>de</strong> mo<strong>de</strong>lar diferentestopologías <strong>de</strong> red, entre las que usaremos las topologíasdirectas mostradas en la tabla I.En todas las configuraciones <strong>de</strong> red se han mo<strong>de</strong>ladoenlaces bidireccionales segmentados con 2.5 GByte/s <strong>de</strong>ancho <strong>de</strong> banda y 4 nanosegundos <strong>de</strong> retardo, tanto paraenlaces entre conmutadores, como para enlaces entrenodos finales y conmutador.Para todas la re<strong>de</strong>s evaluadas el algoritmo <strong>de</strong> encaminamientoes dimension-or<strong>de</strong>r routing [9]; por lo tanto, lainformación necesaria para encaminar un paquete está situadaen los conmutadores y está basada en tablas <strong>de</strong> encaminamiento.Debido a esto y a que los resultados obtenidosen otros estudios para las técnicas RECN y FBICMson muy similares, para las comparativas <strong>de</strong> las simulacionesusaremos solamente la técnica FBICM. Como seha explicado en la sección II, el funcionamiento básico esel mismo para ambas técnicas.<strong>La</strong> arquitectura <strong>de</strong> los conmutadores mo<strong>de</strong>lados sigueel esquema IQ (Input Queued), don<strong>de</strong> las memorias <strong>de</strong>datos están presentes sólo en los puertos <strong>de</strong> entrada. El tamaño<strong>de</strong> dicha memoria se ha <strong>de</strong>jado en 128 KB (menospara VOQnet, don<strong>de</strong> <strong>de</strong>pen<strong>de</strong> directamente <strong>de</strong>l tamaño <strong>de</strong>la red) y su organización <strong>de</strong>pen<strong>de</strong> <strong>de</strong>l mecanismo <strong>de</strong> eliminación<strong>de</strong> HoL blocking elegido. Para las simulacionesse han mo<strong>de</strong>lado las siguientes técnicas <strong>de</strong> eliminación<strong>de</strong>l HoL blocking: Single Queue (1Q), que usa una únicacola por puerto (no elimina el HoL blocking pero muestrala eficiencia pura <strong>de</strong>l algoritmo <strong>de</strong> encaminamiento<strong>de</strong>terminista); DBBM, con 8 colas por puerto <strong>de</strong> entrada;VOQsw, que usa una memoria con 4 colas por puerto parala configuración 1 y 3; y 6 colas por puerto para la configuración2 y 4. VOQnet necesita tantas colas por puertocomo <strong>de</strong>stinos hay en la red. Esta última técnica suponeuna elevada complejidad a la hora <strong>de</strong> ser implementada,y sólo se ha consi<strong>de</strong>rado como referencia <strong>de</strong> la máximaeficacia teórica en la eliminación <strong>de</strong>l HoL blocking.Respecto a la política <strong>de</strong> conmutación, se ha mo<strong>de</strong>ladoVirtual Cut-Through en todos los conmutadores.A<strong>de</strong>más, la política <strong>de</strong> control <strong>de</strong> flujo está basada encréditos. Dentro <strong>de</strong> cada conmutador se ha mo<strong>de</strong>lado un“crossbar” multiplexado con una aceleración <strong>de</strong> 1 (estoes, el ancho <strong>de</strong> banda <strong>de</strong>l enlace es el mismo que el <strong>de</strong>lcrossbar).Los nodos finales están conectados a los conmutadoresmediante adaptadores <strong>de</strong> red (Input Adapters, IAs).Cada IA se mo<strong>de</strong>la con un número <strong>de</strong> fijo <strong>de</strong> colas <strong>de</strong> generación(una por cada <strong>de</strong>stino), don<strong>de</strong> se <strong>de</strong>positan lospaquetes correspondientes a cada mensaje generado conel objetivo <strong>de</strong> eliminar el HoL blocking antes <strong>de</strong> la inyección.Los IAs también tienen un número <strong>de</strong>terminado <strong>de</strong>colas <strong>de</strong> inyección que siguen el mismo esquema que lascolas <strong>de</strong> los puertos <strong>de</strong> entrada <strong>de</strong> los conmutadores. Portanto, un mensaje es <strong>de</strong>scompuesto en paquetes y guardadoen una cola <strong>de</strong> generación asignada para su <strong>de</strong>stino,y <strong>de</strong>spués el árbitro interno <strong>de</strong>l IA llevará los paquetesa la cola <strong>de</strong> inyección correspondiente (el tamaño <strong>de</strong> lospaquetes es <strong>de</strong> 2048 bytes).Respecto a la carga <strong>de</strong> tráfico, se han usado los patrones<strong>de</strong> tráfico sintético <strong>de</strong>scritos en la tabla II. Básicamente,se han mo<strong>de</strong>lado dos tipos <strong>de</strong> tráfico sintético: tráficocompletamente uniforme (caso 1), don<strong>de</strong> la tasa <strong>de</strong> inyección<strong>de</strong> todos los nodos varía <strong>de</strong>s<strong>de</strong> un 0 % hasta un100 % <strong>de</strong>l ancho <strong>de</strong> banda <strong>de</strong>l enlace; y tráfico congestionado“Hot-Spot” (caso 2), don<strong>de</strong> un porcentaje <strong>de</strong> losnodos fuente (en concreto un 25 %) inyecta tráfico a unúnico <strong>de</strong>stino, con el objetivo <strong>de</strong> crear una situación persistente<strong>de</strong> congestión, mientras las fuentes restantes (un75 %), inyectan tráfico uniforme. Estos patrones <strong>de</strong> tráficose han usado para obtener resultados en función <strong>de</strong>ltiempo (caso 1) y resultados en función <strong>de</strong> la carga (caso2). Ambos patrones <strong>de</strong> tráfico se han aplicado a todas lasconfiguraciones <strong>de</strong> red <strong>de</strong> la tabla I.A<strong>de</strong>más, se han usado trazas reales <strong>de</strong> tipo autorelacionado,basadas en el conjunto <strong>de</strong> aplicaciones LINPACK(HPL) [10], que es uno <strong>de</strong> los tests estándar para clasificarlos supercomputadores <strong>de</strong>l Top-500 [11]. <strong>La</strong>s trazas LIN-PACK han sido generadas modificando la herramienta <strong>de</strong>captura <strong>de</strong> trazas <strong>de</strong> la librería MPE (Multi-ProccessingEnvironment) incluída en MPICH, para así po<strong>de</strong>r registrartodos los mensajes punto-a-punto, incluyendo aquellos<strong>de</strong> las operaciones colectivas, que no se incluían por<strong>de</strong>fecto [12]. Aunque este tipo <strong>de</strong> trazas producen sólouna congestión mo<strong>de</strong>rada en la red, es suficiente para obtenerresultados que muestren el rendimiento <strong>de</strong> las diferentestécnicas evaluadas. Falta <strong>de</strong>cir que este tipo <strong>de</strong>tráfico sólo lo tenemos disponible para tamaños <strong>de</strong> red <strong>de</strong>64 nodos. Respecto al patrón <strong>de</strong> tráfico real utilizado, suevaluación es diferente, pues la carga a la que somete a lared este tipo <strong>de</strong> tráfico no es suficiente para producir congestión.Con este tipo <strong>de</strong> tráfico lo que se hace es evaluarel tiempo total que se tarda en ejecutar toda la traza conlas diferentes técnicas <strong>de</strong> control <strong>de</strong> congestión y compararlasentre ellas para ver la ganancia real <strong>de</strong> utilizar una uotra técnica. Como ya se ha comentado, al no producirse,<strong>JP2011</strong>-417


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20110.70.5Eficiencia <strong>de</strong> red (normalizada)0.60.50.40.30.21QDBBM0.1FBICMVOQsw0VOQnet0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1Trafico Generado NormalizadoEficiencia <strong>de</strong> red (normalizada)0.450.40.350.30.250.20.151Q0.1DBBMFBICM0.05VOQsw0VOQnet0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1Trafico Generado Normalizado(a) Configuración <strong>de</strong> red 1(b) Configuración <strong>de</strong> red 20.80.8Eficiencia <strong>de</strong> red (normalizada)0.70.60.50.40.31Q0.2DBBM0.1FBICMVOQsw0VOQnet0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1Trafico Generado NormalizadoEficiencia <strong>de</strong> red (normalizada)0.70.60.50.40.31Q0.2DBBM0.1FBICMVOQsw0VOQnet0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1Trafico Generado Normalizado(c) Configuración <strong>de</strong> red 3(d) Configuración <strong>de</strong> red 4Fig. 2EFICIENCIA DE RED NORMALIZADA EN FUNCIÓN DE LA CARGA. PATRÓN DE TRÁFICO 1con este tipo <strong>de</strong> tráfico, mucha congestión en la red, lasmejoras ofrecidas por las técnicas evaluadas no son tanvisibles como cuando se crea una gran congestión en lared.Finalmente, aunque el simulador ofrece muchas métricas,la evaluación se ha basado en una <strong>de</strong> las principalesmétricas consi<strong>de</strong>radas para la medición <strong>de</strong>l rendimiento:la productividad (normalizada). Por tanto, en los siguientesapartados se analizará por medio <strong>de</strong> esta métrica elrendimiento ofrecido por la red, para cada una <strong>de</strong> las propuestas<strong>de</strong> eliminación <strong>de</strong>l HoL blocking.B. Resultados para tráfico uniforme<strong>La</strong> figura 2 nos muestra la eficiencia <strong>de</strong> red en función<strong>de</strong> la carga. Estas 4 configuraciones <strong>de</strong> red mostradas sontodas las configuraciones <strong>de</strong> la tabla II. En la figura 2a vemosque <strong>de</strong>spués <strong>de</strong> VOQnet, la técnica FBICM es la quemás tarda en saturar, ya que ésta es capaz <strong>de</strong> aislar mejorlos flujos congestionados. El resto <strong>de</strong> técnicas se comportanalgo peor, como DBBM, aunque con sus 8 colas porpuerto <strong>de</strong> entrada también consigue eliminar en parte elHoL blocking. <strong>La</strong>s técnicas más básicas como VOQsw o1Q presentan los peores rendimientos. En la figura 2b laproductividad alcanza valores más bajos <strong>de</strong>bido a que eltamaño <strong>de</strong> la red es mayor que el <strong>de</strong> la figura 2a, entonceslos caminos para llegar <strong>de</strong> un punto a otro <strong>de</strong> la red sonmás largos y ello provoca que los árboles <strong>de</strong> congestiónsean más mayores también y afecten más al rendimiento<strong>de</strong> la red. Con tráfico uniforme, una <strong>de</strong> las características<strong>de</strong> los árboles <strong>de</strong> congestión que se forman es que éstos<strong>de</strong>saparecen muy rápido, pues no se insiste en enviar tráficopor una zona <strong>de</strong>terminada <strong>de</strong> la red. Esto favorece acualquier técnica en general, pues la red no sufre <strong>de</strong>masiadolos problemas <strong>de</strong>rivados <strong>de</strong> la aparición <strong>de</strong> árboles<strong>de</strong> congestión.Se pue<strong>de</strong> observar rápidamente que las figuras 2c y 2dson bastante similares a las anteriores. En estos casos, supunto <strong>de</strong> saturación es más alto <strong>de</strong>bido a que, al tener másconexiones, los árboles son más gran<strong>de</strong>s y la red aceptamás trafico antes <strong>de</strong> saturarse. Vemos en la figura 2c queFBICM aguanta mejor el punto <strong>de</strong> saturación, no cayendosu rendimiento, aunque cuando el tamaño <strong>de</strong> la redaumenta (figura 2d), la productividad <strong>de</strong> todas las técnicascae algo más en todos <strong>de</strong> los casos. En el caso másconcreto <strong>de</strong> FBICM, el problema radica en que el número<strong>de</strong> árboles <strong>de</strong> congestión aumenta y las colas especialesno son suficientes para guardar todos los flujos congestionadosque pasan a través <strong>de</strong> un punto (no sin necesitaruna gran cantidad <strong>de</strong> colas). Es <strong>de</strong>cir, a mayor tamaño <strong>de</strong>la red hay un mayor número <strong>de</strong> árboles <strong>de</strong> congestión,a<strong>de</strong>más <strong>de</strong> que se pue<strong>de</strong>n exten<strong>de</strong>r en mayor medida <strong>de</strong>bidoa que el árbol <strong>de</strong> congestión tiene más caminos porlos que expandirse. Todo esto, junto a las características<strong>de</strong>l algoritmo <strong>de</strong> encaminamiento, hacen que, incluso contráfico uniforme, los árboles <strong>de</strong> congestión tar<strong>de</strong>n un mayortiempo en <strong>de</strong>saparecer y provoquen un mayor <strong>de</strong>caimientoen la eficiencia <strong>de</strong> la red.C. Resultados para tráfico Hot-Spot<strong>La</strong> figura 3 nos muestra ahora la eficiencia <strong>de</strong> la re<strong>de</strong>n función <strong>de</strong>l tiempo. Todas las configuraciones <strong>de</strong> redmostradas son nuevamente las 4 configuraciones <strong>de</strong> la ta-<strong>JP2011</strong>-418


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20110.60.6Eficiencia <strong>de</strong> red (normalizada)0.50.40.30.21QDBBM0.1Generacion <strong>de</strong> Hot-Spot FBICMVOQsw0VOQnet0 2e+06 4e+06 6e+06 8e+06 1e+07Tiempo (nanosegundos)Eficiencia <strong>de</strong> red (normalizada)0.50.40.30.20.1Generacion <strong>de</strong> Hot-Spot1QDBBMFBICMVOQswVOQnet00 2e+06 4e+06 6e+06 8e+06 1e+07Tiempo (nanosegundos)(a) Configuración <strong>de</strong> red 1(b) Configuración <strong>de</strong> red 20.70.7Eficiencia <strong>de</strong> red (normalizada)0.60.50.40.30.21QDBBM0.1Generacion <strong>de</strong> Hot-SpotFBICMVOQsw0VOQnet0 2e+06 4e+06 6e+06 8e+06 1e+07Tiempo (nanosegundos)Eficiencia <strong>de</strong> red (normalizada)0.60.50.40.30.20.1Generacion <strong>de</strong> Hot-Spot1QDBBMFBICMVOQswVOQnet00 2e+06 4e+06 6e+06 8e+06 1e+07Tiempo (nanosegundos)(c) Configuración <strong>de</strong> red 3(d) Configuración <strong>de</strong> red 4Fig. 3EFICIENCIA DE RED NORMALIZADA EN FUNCIÓN DEL TIEMPO. PATRÓN DE TRÁFICO 2bla II, aunque ahora se estudia la eficiencia <strong>de</strong> las técnicasevaluadas cuando se produce un ”Hot-Spot” claro ypersistente en un punto <strong>de</strong> la red. Como se <strong>de</strong>scribió anteriormente,para producir este “Hot-Spot“, el 25 % <strong>de</strong> lasfuentes <strong>de</strong> la red mandan tráfico dirigido a un sólo nodo<strong>de</strong> la red durante 300µS <strong>de</strong>s<strong>de</strong> el instante 1000µS.Como se pue<strong>de</strong> observar en todas las figuras, en el momentoen el que se produce la congestión, el rendimiento<strong>de</strong> las técnicas <strong>de</strong>cae en mayor o menor medida. Para elcaso <strong>de</strong> la figura 3a, suce<strong>de</strong> algo similar a lo que pasabapara tráfico uniforme en la figura 2a. En este caso VOQnetno se ve afectado por el árbol, pues separa totalmentetodos los flujos <strong>de</strong> datos. FBICM tampoco acusa en granmedida la congestión, pero esto es <strong>de</strong>bido a que la red espequeña y es capaz <strong>de</strong> aislar correctamente los flujos congestionados;aun así queda bastante por <strong>de</strong>bajo <strong>de</strong> VOQnet.El mismo razonamiento se podría dar en DBBM, yaque éste también es capaz <strong>de</strong> aislar bien los flujos congestionadosgracias a sus 8 colas por puerto <strong>de</strong> entrada.El esquema peor parado en todos los casos es 1Q, puesno es capaz <strong>de</strong> eliminar el HoL blocking en absoluto, ycuando los árboles son muy gran<strong>de</strong>s, como suce<strong>de</strong> en lostoros, este esquema se ve aún más afectado.Respecto a la configuración <strong>de</strong> red <strong>de</strong> la figura 2b seve cómo VOQnet no tiene ninguna pérdida en el rendimientoen el momento <strong>de</strong>l ”Hot-Spot”. Esto es <strong>de</strong>bido,como ya se dijo en la sección anterior, a que VOQnet escapaz <strong>de</strong> aislar todos los árboles <strong>de</strong> congestión. Luego seobserva cómo FBICM junto a DBBM son capaces <strong>de</strong> aislarmejor los flujos congestionados, pero en re<strong>de</strong>s gran<strong>de</strong>svolvemos a sufrir el problema <strong>de</strong> la falta <strong>de</strong> colas para aislartodos los flujos congestionados. Analizando ahora losresultados para toros en las figuras 3c y 3d se observa lagran diferencia y la principal motivación <strong>de</strong> este artículo(y <strong>de</strong>l futuro trabajo). Como se ve en la figura 3c, sies posible aislar todos los flujos congestionados, como esel caso <strong>de</strong> FBICM, el rendimiento no se ve penalizado.En caso <strong>de</strong> que no sea posible, la aparición <strong>de</strong> árboles<strong>de</strong> congestión, junto a las topologías <strong>de</strong> tipo toro en lasque estos árboles son mayores, da lugar a un rendimientobastante pobre. Si aparte <strong>de</strong> esto, aumentamos el tamaño<strong>de</strong> la red a unas dimensiones más acor<strong>de</strong>s a una gran red<strong>de</strong> interconexión (como la <strong>de</strong> la figura 3d), vemos queel rendimiento <strong>de</strong> FBICM también cae <strong>de</strong>bido a que noes capaz <strong>de</strong> albergar tantos <strong>de</strong>stinos en sus CFQs como<strong>de</strong>bería. Esto nos lleva a la conclusión <strong>de</strong> que este algoritmono es escalable con respecto al tamaño <strong>de</strong> la red ypor en<strong>de</strong> <strong>de</strong>bemos buscar soluciones más óptimas a esteproblema.D. Resultados para tráfico real<strong>La</strong> evaluación <strong>de</strong> trazas reales la hemos realizado a partir<strong>de</strong> las razas LINPACK, que han sido <strong>de</strong>scritas en elapartado III-A. El tiempo total <strong>de</strong> ejecución ha sido normalizadocon respecto al caso más lento, que como era<strong>de</strong> esperar es el obtenido por el esquema 1Q, pues en estecaso no se aplican mecanismos <strong>de</strong> eliminación <strong>de</strong>l HoLblocking. Con estos resultados se pue<strong>de</strong>n ver comparadoslos diferentes tiempos <strong>de</strong> ejecución y se ve claramentecómo VOQnet es la que menos tiempo consume (≈3 %menos), pues es la técnica que elimina completamente elHoL blocking. Cabe comentar que estos resultados están<strong>JP2011</strong>-419


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 4TIEMPO NORMALIZADO DE EJECUCIÓN DE TRAZAS LINPACKrealizados en una red <strong>de</strong> tipo malla <strong>de</strong> tamaño 8x8, lo queinfluye también en que el resto <strong>de</strong> técnicas mejoren a 1Q,pero su mejoría no sea muy gran<strong>de</strong>.Pue<strong>de</strong> parecer que las diferencias no son significativas,pero hay que tener en cuenta que, aparte <strong>de</strong>l tamaño <strong>de</strong>la red utilizada, este tipo <strong>de</strong> trazas no someten a la reda una gran carga. Esto hace que no se produzca muchacongestión en la red y por eso la aparición <strong>de</strong>l fenómeno<strong>de</strong>l HoL blocking es menos probable. Por ello las técnicasestudiadas no mejoran en gran medida con respecto alpeor resultado.IV. CONCLUSIONES<strong>La</strong>s técnicas actuales basadas en aislar explícitamentelos flujos congestionados presentan problemas en re<strong>de</strong>sdirectas <strong>de</strong>bido a que al aumentar el tamaño <strong>de</strong> la red,el número <strong>de</strong> flujos <strong>de</strong> paquetes que pue<strong>de</strong>n pasar porun punto aumenta. Esto pue<strong>de</strong> producir una cantidad importante<strong>de</strong> árboles <strong>de</strong> congestión distintos en un mismopunto, llegando a alcanzar el número máximo <strong>de</strong> colasespeciales que po<strong>de</strong>mos reservar, pues la memoria <strong>de</strong> losconmutadores no es infinita. Este problema pue<strong>de</strong> verseclaramente si consi<strong>de</strong>ramos el tipo <strong>de</strong> árboles <strong>de</strong> congestiónque se forman en esta clase <strong>de</strong> re<strong>de</strong>s, que tien<strong>de</strong>n aser más largos y ramificados, como el que se muestra enla figura 5, lo que hace aumentar el número <strong>de</strong> flujos congestionadosen un punto <strong>de</strong> la red. Este hecho nos animaa replantear las técnicas basadas en el aislamiento <strong>de</strong> flujoscongestionados, que han sido orientadas a topologíasindirectas <strong>de</strong>l tipo MIN, para intentar optimizarlas en re<strong>de</strong>sdirectas. Como trabajo futuro se plantea el estudiomás a fondo <strong>de</strong>l rendimiento <strong>de</strong> las técnicas basadas enel aislamiento <strong>de</strong> flujos congestionados y el posible <strong>de</strong>sarrollo<strong>de</strong> nuevas técnicas orientadas <strong>de</strong>s<strong>de</strong> el principio altratamiento <strong>de</strong>l problema <strong>de</strong>l HoL blocking en topologíasdirectas.AGRADECIMIENTOSEste trabajo ha sido parcialmente financiado por elMEC y el MICINN, así como por la Comisión Europeaa través <strong>de</strong> los fondos FEDER, mediante los proyectosCSD2006-00046 y TIN2009-14475- C04. A<strong>de</strong>más, tambiénha sido parcialmente financiado por la JCCM, mediantelos proyectos POII10-0289-3724, PEII11-0229-Fig. 5FLUJOS CONGESTIONADOS EN UNA MALLA O TORO2343 y la beca <strong>de</strong> doctorado A10/002.REFERENCIAS[1] J. Escu<strong>de</strong>ro-Sahuquillo, E. G. Gran, Pedro J. García, J. Flich,T. Skeie, O. Lysne, F. J. Quiles, and J. Duato, “Combiningcongested-flow isolation and injection throttling in hpc interconnectionnetworks,” in Proceedings of the 40th International Conferenceon Parallel Processing (ICPP 2011), Taipei, Taiwan, september2011.[2] W. Dally, P. Carvey, and L. Dennison, “Architecture of the Aviciterabit switch/router,” in Proc. of 6th Hot Interconnects, 1998, pp.41–50.[3] T. An<strong>de</strong>rson, S. Owicki, J. Saxe, and C. Thacker, “High-speedswitch scheduling for local-area networks,” ACM Transactions onComputer Systems, vol. 11, no. 4, pp. 319–352, November 1993.[4] Teresa Nachiondo, Jose Flich, and Jose Duato, “Buffer managementstrategies to reduce hol blocking,” IEEE Transactions onParallel and Distributed Systems, vol. 21, pp. 739–753, 2010.[5] Pedro J. García, J. Flich, J. Duato, I. Johnson, Francisco J. Quiles,and F. Naven, “Efficient, scalable congestion management forinterconnection networks,” IEEE Micro, vol. 26, no. 5, pp. 52–66,September 2006.[6] Jesús Escu<strong>de</strong>ro-Sahuquillo, Pedro Javier García, FranciscoJosé Quiles, José Flich, and José Duato, “Cost-effectivecongestion management for interconnection networks usingdistributed <strong>de</strong>terministic routing,” in ICPADS ’10: Proceedingsof the 16th International Conference on Parallel and DistributedSystems, Shanghai, China, 2010.[7] Jesús Escu<strong>de</strong>ro-Sahuquillo, Pedro Javier García García, FranciscoJosé Quiles Flor, José Flich Cardo, and José Duato Marín,“Cost-effective queue schemes for reducing head-of-line blockingin fat-trees,” Concurrency and Computation: Practice & Experience,2011.[8] Y. Tamir and G.L. Frazier, “Dynamically-allocated multi-queuebuffers for vlsi communication switches,” IEEE Transactions onComputers, vol. 41, no. 6, June 1992.[9] Herbert Sullivan and T R Bashkow, “A large scale, homogeneous,fully distributed parallel machine, i,” SIGARCH Comput. Archit.News, vol. 5, no. 7, pp. 105–117, 1977.[10] J. Dongarra, “Performance of various computers using standardlinear equations software,” Tech. Rep. Computer Science TechnicalReport Number CS-89-85, University of Tennessee, KnoxvilleTN, 37996, http://www.netlib.org/benchmark/performance.ps.[11] Top 500 List, ,” Web Page at: http://www.top500.org.[12] F. J. Ridruejo, A. Gonzalez, and J. Miguel-Alonso, “Trgen: Atraffic generation system for interconnection network simulators,”in Proceedings of the 2005 International Conference on ParallelProcessing Workshops, Washington, DC, USA, 2005, ICPPW ’05,pp. 547–553, IEEE Computer Society.<strong>JP2011</strong>-420


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Peripheral twists for torus topologies witharbitrary aspect ratioEnrique Vallejo 1 , Miquel Moretó 2 , Carmen Martínez 3 , and Ramón Beivi<strong>de</strong> 4Abstract—A torus is a common topology used insupercomputer networks. Asymmetric Tori suffer fromresource usage imbalance, which translates to reducedperformance. Twisted Tori employ a twist in theperipheral links of one or more dimensions to improve thetopological parameters and overall performance ofasymmetric networks. 2D and 3D twisted tori with aspectratios 2:1 and 2:1:1 have been studied in <strong>de</strong>tail.However, commercial machines do not necessarilyemploy those aspects ratios. In this work we present anearly study of the effect of peripheral link twisting inmultidimensional twisted tori with arbitrary aspect ratios.We observe that, in the general case, it is impossible to finda specific twist that minimizes all the interestingtopological parameters of the network. We also introduce arequirement for the use of several twists inmultidimensional torus with adaptive routing.Keywords—Twisted torus, network topologyAI. INTRODUCTION 1234N N-dimensional torus is the Cartesian productof N rings. The torus topology has been wi<strong>de</strong>lyemployed for the interconnection of large-scalesupercomputers, since it provi<strong>de</strong>s competitivetopological properties, it fits naturally to the taskmapping of many supercomputing problems and issimple to un<strong>de</strong>rstand from the programmer's view.Symmetric tori are built from rings of the same length,what un<strong>de</strong>r uniform traffic leads to a balanced use of thenetwork resources. A restriction of symmetric tori is thatthe number of no<strong>de</strong>s must be a certain power, D N , whereD is the number of no<strong>de</strong>s in the ring.Asymmetric (or mixed-radix) tori are those generatedfrom the product of N rings with different lengthsD 1 , D 2 , . . . , D N . This builds a torus topology withvariable number of network no<strong>de</strong>s, D 1 × D 2 ×. . .× D N ,and thus has been commonly used in commercialmachines such as the IBM BlueGene [1], the Cray XK6[5] or the Tofu interconnect in the K computer [2],currently the Top1. There are several reasons to useasymmetric torus, ranging from <strong>de</strong>siring a given numberof network no<strong>de</strong>s, increasing the size of an existingmachine or even mechanical limitations such as in theCray T3D network [6]. However, asymmetric tori sufferfrom congestion in the longest dimension, what cancause performance bottlenecks in the network. Un<strong>de</strong>rrandom uniform traffic, the average number of hopstraversed on each dimension of the torus is proportionalto its length, but the number of links per dimension oneach router is constant. Therefore, the links on thelongest dimension are the first ones to reach saturation,limiting the performance of the overall network. Othertypes of traffic are also limited by the differencebetween the different lengths.The use of a twist in the peripheral links of one of thedimensions was first proposed in [7] as a mechanism toimprove the topological properties and the performanceof the network. Subsequent work [3], [4] has formallycharacterized such topology, called Twisted Torus (TT),in the specific cases of 2: 1 (2D) or 2: 1: 1 (3D) aspectratios. Specifically, 2: 1 Rectangular Tori (RT) havetwice as many no<strong>de</strong>s in the long dimension than in theshort one; therefore, un<strong>de</strong>r uniform traffic, the links inthe long dimension are saturated, but the utilization ofthe links in the shortest dimension is limited to 50% [4].In this case, the optimal twist is the length of the shortdimension: Adding a twist of a columns to theperipheral vertical links of a 2a × a RT regains thesymmetry of the X and Y dimensions, and allows for fulllink utilization. The resulting layout of these topologiesis presented in Figure 1 for a 8 × 4 torus. The twistedvertical links in Figure 2 modify the no<strong>de</strong> distancedistribution and resulting link utilization, leading tothroughput increases of 50% un<strong>de</strong>r uniform traffic.Other traffic patterns are also improved with differentfactors [4].Fig. 1. 8 × 4 Rectangular Torus.1Grupo <strong>de</strong> Arquitectura y Tecnología <strong>de</strong> Computadores,<strong>Universidad</strong> <strong>de</strong> Cantabria. Email: enrique.vallejo@unican.es2Dep. Arquitectura <strong>de</strong> Computadores, UPC. Email:mmoreto@ac.upc.edu3Grupo <strong>de</strong> Arquitectura y Tecnología <strong>de</strong> Computadores,<strong>Universidad</strong> <strong>de</strong> Cantabria. Email: carmen.martinez@unican.es4Grupo <strong>de</strong> Arquitectura y Tecnología <strong>de</strong> Computadores,<strong>Universidad</strong> <strong>de</strong> Cantabria. Email: ramon.beivi<strong>de</strong>@unican.esFig. 2. 8 × 4 Rectangular Twisted Torus, with a twist of 4 columns.<strong>JP2011</strong>-421


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Recent technological improvements have largelyincreased the router pin bandwidth, allowing theconstruction of high-<strong>de</strong>gree routers [5]. In the case ofusing torus topologies, this leads to the construction ofmulti-dimensional torus. Nowadays, machines using 5Dor 6D torus are already being <strong>de</strong>ployed, such as thenewest BlueGene/Q [9] or the Tofu 6D torus [2]. Anyasymmetry in the dimensions of these topologies is evenmore important, since un<strong>de</strong>r uniform traffic it is thesingle longest dimension which limits performance.The optimal application of twists to the peripherallinks of asymmetric torus of arbitrary aspect ratio hasnot been studied yet. In this paper we present an earlystudy of the topological properties of asymmetrictwisted torus based on exhaustive search of the optimaltwist values. Specifically, this paper has two maincontributions:• We perform an exhaustive search of the optimaltwist values and observe that there is no singletwist that optimizes all the relevant topologicalparameters of asymmetric tori with arbitraryaspect ratio, such as diameter, average distanceor link imbalance.• We show how certain combinations of twists ina multidimensional twisted tori lead totopologies which are not no<strong>de</strong>-symmetric, andthus do not allow for adaptive routing.The rest of the paper is organized as follows. InSection II we introduce the parameters and notation thatwill be used in the rest of the paper. Section III studiesthe twist values that optimize different networkparameters of 2D TT, showing that for arbitrary aspectratios there is no optimal twist for all parameters.Section IV <strong>de</strong>als with multiple twists inmultidimensional TT, showing that not any combinationof twists leads to no<strong>de</strong>-symmetric networks. Finally,Section V conclu<strong>de</strong>s the paper and presents the ongoingwork.II. NOTATION AND NETWORK PARAMETERSIn this paper, we consi<strong>de</strong>r N-dimensional torus.Typical values for N are N = 2 for the RectangularTorus (RT) or N = 3 for the Prismatic Torus (PT),following the terminology introduced in [4]. Highervalues of N lead to Hypertorus (HT), or, in general, toruswith N dimensions.The different dimensions are typically labeled usingthe letters X, Y and Z. The number of no<strong>de</strong>s on eachdimension will be <strong>de</strong>noted as d X , d Y , d Z . Withhypertorus the dimensions are typically labeledD 1 , D 2 … , D N and the size of each dimensiond 1 , d 2 , … , d N . The aspect ratio represents the relationbetween the number of no<strong>de</strong>s on the differentdimensions.No<strong>de</strong> labeling — Each no<strong>de</strong> in the network will belabeled with a tuple (x, y, z) or (x 1 , x 2 , … , x N ), witheach element indicating the coordinate in thecorresponding dimension in the range [0, d i ). Anexample of this notation in a 2D torus is shown inFigures 1 and 2, with d X = 8 and d Y = 4 .Peripheral links — In a traditional torus, a link indimension J joins no<strong>de</strong>s with coordinates(x 1 , … , x j , … , x N ) and (x 1 , … , (x j ± 1) mmm d J , … , x N ).It can be observed that the modulo operation is onlyused for peripheral links, and that peripheral linksalways join no<strong>de</strong>s from the same row or column.Peripheral twists — A twisted peripheral link breaksthe previous rule. We will use the expression t JJ to referto the twist of dimension J over the dimension K withJ ≠ K. A nonzero value in t JJ means that the peripherallink on dimension J also modifies the coordinate indimension K. The modification is called the value of thetwist, or skew. Specifically, consi<strong>de</strong>ring only thedimensions J and K, the no<strong>de</strong> with coordinates d J −1, x K will be connected with 0, x K + t JJ mmmmalong the peripheral link on dimension J. The twist t JJdoes not modify other coordinates.The example in Figure 2 shows a 2D Twisted Toruswith d X = 8, d Y = 4, t XX = 0 (no twist on the horizontalperipheral links) and t YY = 4. Observe how the no<strong>de</strong> (0,3) is connected to (4, 0), while no<strong>de</strong> (0,0) is connectedto (4,3). In an N-dimensional torus the number ofpossible twists is N(N − 1), regardless their value. For2D, these are only t XX and t YY . For 3D, these aret XX , t XX , t YY , t YY , t ZZ and t ZZ . In general, we will onlycite those twists that are nonzero.Consi<strong>de</strong>ring this notation, the previous work in [4]studied three different twisted topologies:• Rectangular Twisted Tori (RTT): A 2Dtwisted torus with d X = 2a, d Y = a andt YY = a.• Prismatic Twisted Tori (PTT): A 3D twistedtori with d X = 2a, d Y = d Z = a and t YY = a.• Prismatic Doubly Twisted Tori (PDTT): A 3Dtwisted tori with d X = 2a, d Y = d Z = a,t YY = a and t ZX = a.The interest of the peripheral twists relies on the factthat they allow modifying the topological parameters ofthe interconnection network, and thus its performance,without altering the internal mesh interconnectionpattern. In or<strong>de</strong>r to quantify the performanceimprovement or penalty <strong>de</strong>rived from the introduction ofa certain twist, we need to measure its effect.The key performance indicator of any network is theexecution time of a set of parallel applicationsappropriately tuned. However, such execution time<strong>de</strong>pends on many factors, such as the data partitioningand task mapping mechanisms employed, which shouldalso <strong>de</strong>pend on the specific topology being used. Suchstudy is out of the scope of the current paper. In or<strong>de</strong>r toperform an early evaluation, synthetic random uniformtraffic is typically used, which reflects on average thetopological parameters of the network. The mostinteresting topological parameters will be:Diameter — <strong>de</strong>noted k, it is the length of the longestminimum path between any two no<strong>de</strong>s in the network.The diameter of the network conditions the maximumlatency in the network. Then, it can also affect thelatency of certain operations, such as collectiveoperations implemented using broadcast trees.<strong>JP2011</strong>-422


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011The diameter in a traditional torus without twists is thesum of the diameters of the individual rings, k = k X +k y + k Z + ⋯. However, when a twist is applied on anyof the dimensions the diameter must be recalculatedfrom the resulting distance distribution.Average distance — <strong>de</strong>noted k, it is the averagelength of all minimum paths. The average distance is anindicator of the base network latency, this is, the latencywithout congestion in the network.The average distance will be an indicator of themaximum throughput in the network. The lower thenumber of hops a packet has to travel, the higher thenumber of packets accepted.In a torus topology there are different classes of links,separated according to their dimension. The averagedistance k can be divi<strong>de</strong>d into the individual averagedistances per dimension, k = k X + k Y + k Z + ⋯. Eachof these individual distances represents the averagenumber of hops that a packet has to traverse along thelinks in a given dimension. Since there are the samenumber of links on each dimension, the highest averagedistance per dimension will indicate the dimension thatwill first suffer from saturation and will limitperformance.In a perfectly balanced network all the individual perdimensiondistances are the same. However,asymmetries in the network dimensions lead to differentaverage distances per dimension. The application of atwist on the peripheral links of a torus modifies theaverage distances per dimension; the selection of theappropriate twist to minimize these distances is studiedin this paper.Based on the average distances per dimension, we<strong>de</strong>fine two additional metrics:Maximum Average distance per dimension —<strong>de</strong>noted maxk ı . This value is the maximum of theindividual distances k X , k Y , k Z , …. As argued before, thisparameter will <strong>de</strong>termine the saturation limit of thenetwork; therefore, the expected throughput <strong>de</strong>pends onthis value as discussed in [4].Imbalance — The imbalance is <strong>de</strong>fined here as thequotient I = N×max(k ) ı. I<strong>de</strong>ally, I = 1 meaning that allklinks are equally used. A high imbalance value meansthat there is a significant <strong>de</strong>viation in the usage of thenetwork dimensions.distances in the network. Even more, the twist equals thelength of the shorter dimension, what might bebeneficial for the resource balancing. This conditiononly occurs when the aspect ratio is 2: 1.In this section we study for different aspect ratios howeach of these network parameters varies with theselected twist. We will focus on the 2D TT. Our initialtests showed that the results are similar for differentnetwork sizes when the aspect ratio is similar. Then, wewill fix the number of rows in the topology to a constantreference value (for example d Y = 12 in ourexperiments), and vary the number of columns d X fromd Y to 4 · d Y , to sweep an aspect ratio ranging from 1: 1to 4: 1.For each configuration, we explore the topologicalparameters of the network with all the possible twistsfrom t YY = 0 to t YY = d X /2 (higher values lead tosymmetric results). With each twist, we use a breadthfirstsearch algorithm to find the shortest paths betweenno<strong>de</strong> 0 and any other no<strong>de</strong> in the TT. For each of theseshortest paths, we record the number of hops perdimension, and when the same <strong>de</strong>stination can bereached by different routes, we average the result amongthem all. With all the routes in the network we calculatethe diameter, average distance, maximum averagedistance per dimension and network imbalance for eachpossible twist t YY . Finally, we calculated the twist thatoptimized each of the four parameters of interest.The next plots show the results for each parameter. Oneach graph we plot the results corresponding to fourtwisting strategies:- Not using a twist, t YY = 0, labeled no_tw.- The optimum twist for that given parameter,opt_tw.- The twist equals half of the longest dimension,t YY = d X /2, labeled tw_mid.- The twist equals the shortest dimension, t YY = d Y ,labeled tw_rows.Figure 3 shows the results for the diameter. The linesfor no_tw and opt_tw are shown in gray. We observe thatthere is a significant improvement in the diameter whenthe optimum twist is applied, especially as the aspectratio grows. It can be also observed that the twist thatprovi<strong>de</strong>s the optimum diameter is the one with t YY =The application of a certain twist will modify thedistance distribution in the network, and all the previousparameters with it. The next section presents a search forthe optimum twists in terms of the different topologicalparameters introduced in this section.III. OPTIMUM TWISTS FOR 2D TORUS WITHARBITRARY ASPECT RATIOIn this section we focus on 2D Twisted Torus (TT)with d X ≥ d Y (with more no<strong>de</strong>s on the X dimension thanin the Y dimension), and a single twist of dimension Yover dimension X. The work in [4] proves that theoptimal twist in terms of the previous parameters for a2a × a Twisted Torus is t YY = a. This twist equals themiddle of the longest dimension, connecting the firstcolumn with the middle one, thereby reducing theFig. 3. Diameter of a network with different twisting strategies, asthe aspect ratio increases from 1:1 to 4:1. The number of rowsis always 12.<strong>JP2011</strong>-423


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 4. Diameter of a network with different twisting strategies,as the aspect ratio increases from 1:1 to 4:1, normalized to theoptimum value on each case. The number of rows is always 12.Fig. 5. Average distance with different twisting strategies, as theaspect ratio increases from 1:1 to 4:1, normalized to theoptimum value on each case. The number of rows is always 12.240%Normalized Imbalance220%200%180%160%140%120%opt_twno_twtw_midtw_rows100%Fig. 6. Maximum partial distance with different twisting strategies,as the aspect ratio increases from 1:1 to 4:1, normalized to theoptimum value on each case. The number of rows is always 12d X /2, labeled tw_mid. Finally, we can observe how withd X = 24 columns, the three values meet: this isprecisely the 2: 1 aspect ratio network studied in [4].How much diameter reduction can we expect from anoptimum twist? Figure 4 shows the previous plots,normalized to the value obtained in each case with theoptimum twist. It is clear that a twist equal to half thelongest dimension always provi<strong>de</strong>s the optimum value interms of diameter, and that the diameter can be reducedin more than 40%.Figures 5 to 7 show the results of the other threeparameters of interest, in all cases normalized to theoptimum value per network size.Figure 5 shows the results for the average distance. Asimilar study was already presented in [3]. As with thediameter, the twist to the middle of the longestdimension provi<strong>de</strong>s the best performance, except for thecase of a very high aspect ratio. The improvement overthe RT increases from 5% to 40% as the aspect ratiogrows. In the case of the twist tw_rows, the performanceremains within 5% of the optimal value for aspect ratioslower than 3: 1, increasing to up to 14% for larger aspectratios.The maximum partial distance per dimension ispresented in Figure 6. It is very relevant the highdifference between the original, untwisted torus, and the80%12 16 20 24 28 32 36 40 44 48Columns (dX)Fig. 7. Imbalance of a network with different twisting strategies, asthe aspect ratio increases from 1:1 to 4:1, normalized to theoptimum value on each case. The number of rows is always 12.best result that can be obtained. Depending on the aspectratio, the original torus is more than an 80% slower interms of throughput (which <strong>de</strong>pends on this parameter).A proper twist reduces the maximum distance perdimension and increases throughput. With a twist oftw_rows or tw_mid, this metric is within 10% of theoptimal twist, and within 5% of the optimal twist foraspect ratios lower than 3: 1.Finally, Figure 7 shows the imbalance. If no twist isused, the imbalance grows linearly with the aspect ratioas expected. When the proper twist is applied, the usageof the links on each dimension can be almost perfectlybalanced. Also, it is interesting to notice that from aspectratio 2: 1, the tw_rows approach obtains the optimumresult.All the previous figures have presented the results ofthe different parameters; however, the specific twist thatobtains the best result in each case was not presented.Figure 8 shows the twists that get the best results foreach of these 4 parameters.From this figure we can observe that, in general, for agiven aspect ratio there is no single twist value thatoptimizes all the network parameters. For example,diameter and average distance are approximatelyoptimum with tw_mid. However, for large aspect ratiosthe optimum twist to reduce the average distance<strong>JP2011</strong>-424


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 8. Optimal twist value for each parameter with different aspectrations. The number of rows is always 12.<strong>de</strong>creases. Regarding the maximum partial distance perdimension (which conditions the performance un<strong>de</strong>rsaturation) we observe that the optimum skew is similarto tw_mid. up to aspect ratios close to 2: 1, but it later<strong>de</strong>creases. Finally, it is really interesting that the bestimbalance in a network with aspect ratio higher than2: 1 is provi<strong>de</strong>d by the tw_rows approach, regardless thenumber of columns.The interesting conclusion to be drawn from thisfigure is that for arbitrary topologies there is no singletwist value that minimizes all the interestingperformance related metrics. For example, this impliesthat, with a large aspect ratio such as 4:1, there is a twistthat provi<strong>de</strong>s a higher throughput un<strong>de</strong>r saturation(maximum partial distance lower) although the traffic isnot as balanced as possible (best imbalance); bycontrast, the balanced approach makes the same usage ofboth horizontal and vertical channels, but since theoverall average distance in that case is higher, theperformance is lower.IV. USE OF MULTIPLE TWISTSSection III studies the selection of an optimum twist ina 2D Twisted Torus (TT) <strong>de</strong>pending on differenttopological parameters of interest. However, the study inthat section assumes a 2D TT with d X ≥ d Y and a singletwist t YX . The first assumption can be done without anyloss of generality; the selection of the twist (dimensionY over dimension X) is the one that reduces the averagedistance on the longest dimension X. A similar studyusing t XY does not provi<strong>de</strong> better results.In this section we consi<strong>de</strong>r the case of applyingmultiple twists to the same torus network. We willinitially study the case in 2D (similarly to [3]), and thenconsi<strong>de</strong>r higher dimensions.The graph in Figure 9 represents a 4 × 4 TT withtwists t XY = −1 and t YX = 1. Thus, all the peripherallinks have some twist.Although the topological parameters of this graphcould be studied as in the previous section, the problemnow is that the graph is not no<strong>de</strong>-symmetric. The no<strong>de</strong>symmetryproperty in a graph of this kind implies thatthe routing between any pair of no<strong>de</strong>s source and<strong>de</strong>stination can be computed from the difference of theircoordinates, rather than consi<strong>de</strong>ring the whole topologyand the specific i<strong>de</strong>ntity of the source and <strong>de</strong>stinationFig. 9. 4 × 4 Twisted Torus with t XX = −1 and t YY = 1.no<strong>de</strong>s. Specifically, without no<strong>de</strong>-symmetry the routingfunction cannot be performed by means of a routingrecordcomputed at the source no<strong>de</strong>, and adaptiverouting is not allowed.We show this case with an example similar to the onein [3]. Consi<strong>de</strong>r the graph in Figure 9 and the routingfrom no<strong>de</strong> (0,2) to (3,0). One possibility is to go up(Y +) to the intermediate no<strong>de</strong> (0,3) and then left (X −)to the <strong>de</strong>stination no<strong>de</strong> (3,0) through the peripheraltwisted link. However, if the sequence of jumps isfollowed in the opposite or<strong>de</strong>r, then the first jump goesleft (X −) to (3,3) using a peripheral link, and then up(Y +) to (0,0) using another peripheral link. The finalno<strong>de</strong> differs <strong>de</strong>pending on the or<strong>de</strong>r of the dimensionsfollowed, because the number of peripheral twisted linksvaries and each peripheral link modifies the othercoordinate. Therefore, routing in the graph of Figure 9must be either table-based, or use source routing withfull knowledge of the network topology, what restrictsmany of the benefits of the torus topology.We consi<strong>de</strong>r now the case of multiple twists inmultidimensional torus. Cámara et al present in [4] two2a × a × a 3D twisted torus topologies using one twist(PTT, t YX = a) or two twists (PDTT, t YX = a andt ZX = a). Both cases are no<strong>de</strong>-symmetric, so they do notsuffer from the restrictions consi<strong>de</strong>red above for the 2DTT with two twists.The obvious question now is, which combinations oftwists break the no<strong>de</strong>-symmetry of a torus topology?The following result characterizes it.Theorem — A multidimensional twisted torus is notno<strong>de</strong>-symmetric if there exists a dimension J such thatt IJ , t JJ ≠ 0 for some other dimensions I and K.Proof — The lack of no<strong>de</strong>-symmetry can be proven byfinding a source no<strong>de</strong> from which a sequence of jumpsleads to different <strong>de</strong>stination no<strong>de</strong>s <strong>de</strong>pending on theor<strong>de</strong>r of the jumps.Assume the condition is true. For simplicity, we willassume t IJ , t JJ > 0. First, we consi<strong>de</strong>r the case I ≠ K.Specifically, we will only consi<strong>de</strong>r the no<strong>de</strong> labels(i, j, k); the rest of coordinates, if they exist, shouldremain constant. The source no<strong>de</strong> of the proof will bed I − 1, d J − t IJ − 1,0 and the routing record (1,1,0).If the jump on dimension I is taken first, a twistedperipheral link will be used to reach the intermediateno<strong>de</strong> 0, d J − 1,0. The second jump on the dimension J<strong>JP2011</strong>-425


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011uses another twisted peripheral link, leading to the<strong>de</strong>stination no<strong>de</strong> 0, 0, t JJ .By contrast, if the jump on dimension J was takenfirst, then an internal link goes to d I − 1, d J − t IJ , 0,and the second jump on I goes through a twistedperipheral link to (0,0,0).Finally, the case of I = K also leads to a graph whichis not no<strong>de</strong>-symmetric, as presented in the example ofFigure 9 with I = K = X. As in the previous case, if weconsi<strong>de</strong>r the source no<strong>de</strong> d I − 1, d J − t IJ − 1 androuting record (1,1), we will reach <strong>de</strong>stination no<strong>de</strong>st IJ , 0 or (0,0) <strong>de</strong>pending on the or<strong>de</strong>r of the jumps. ∎We conjecture that the condition in the previoustheorem is sufficient and necessary, but do not have aformal proof yet.With the previous theorem we can consi<strong>de</strong>r thenumber of combinations of twists that maintain theno<strong>de</strong>-symmetry for an N-dimensional torus. The numberof possible twists is N(N − 1) as discussed in Section II.However, with no<strong>de</strong>-symmetry there will be at mostN − 1 concurrent twists; otherwise, some dimensionwill necessarily have a twist in its peripheral links andreceive the effect of a twist in another dimension, whatbreaks the no<strong>de</strong>-symmetry according to the theorem. Wewill consi<strong>de</strong>r the lower-gra<strong>de</strong> cases next.In the 2D case there are two possibilities, t XY or t YX ,but not both twists simultaneously. We can assumewithout loss of generality that the topology is set so thatall twists are applied over lower-or<strong>de</strong>r dimensions (anyother combination will be isomorphic), so the onlysingle possible twist to study will be t YX .In the 3D torus there are two combinations of twotwists: (t YX , t ZX ) and (t ZX , t ZY ). The first one wasapplied for torus with 2: 1: 1 aspect ratio in [4] to buildthe PDTT. We do not know of any use of the secondcombination in previous work. Also, there are three<strong>de</strong>generated cases when one of these twists is 0: t YX , t ZXand t ZY . Without forcing a dimension or<strong>de</strong>r in the twists,the number of combinations would be much higher.For multidimensional torus, the combinations of validtwists grows very quickly. Any study to optimize theparameters of the network using twists should consi<strong>de</strong>rall these possibilities with all their possible values. Thus,an empirical study based on a breadth-first searchappears very costly as the number of dimensions grow.V. CONCLUSIONS AND FUTURE WORKIn this paper we have i<strong>de</strong>ntified four topologicalparameters of torus topologies that condition differentaspects of the network behavior. The use of twists insome of the peripheral links modifies these topologicalparameters and can improve the performance of thenetwork, but in the general case, it is impossible tooptimize all of the parameters at the same time becausethe required twists differ.We have also introduced a clear notation for the twistsand criteria to consi<strong>de</strong>r which combinations of twistsbuild no<strong>de</strong>-symmetric networks from multidimensionaltorus, which are expected to be more used in the nearfuture.We have many lines of ongoing work. A formal proofof the conjecture in Section IV is critical to validate thework. Also, the high number of combinations ofpossible twists (and their specific values) formultidimensional torus makes an empirical study likethe one in this paper not feasible. It would be interestingto formalize the twisted torus topology and study itsproperties using graph theory.Regarding the impact on performance, we havediscussed how the applications should be aware of theun<strong>de</strong>rlying topology to optimize data partitioning andtask mapping. Performing these tasks for amultidimensional torus with arbitrary twists is nottrivial, and currently un<strong>de</strong>r study.ACKNOWLEDGMENTThis work has been sponsored by the Ministry ofScience and Innovation un<strong>de</strong>r Projects TIN2010-21291-C02-02 and TIN2007-60625, the HiPEAC network ofExcelence and the Supercomputing and e-scienceConsoli<strong>de</strong>r Project.REFERENCES[1] N.R. Adiga, M.A. Blumrich, D. Chen, P. Coteus, A. Gara, M.E.Giampapa, P. Hei<strong>de</strong>lberger, S. Singh, B.D. Steinmacher-Burow,T. Takken, M. Tsao, and P. Vranas, “Blue Gene/L TorusInterconnection Network,” IBM J. Research and Development,vol. 49, nos. 2/3, pp. 265-276, 2005.[2] Y. Ajima, S. Sumimoto, T. Shimizu, "Tofu: A 6D Mesh/TorusInterconnect for Exascale Computers," Computer, pp. 36-40,November, 2009[3] J. M. Cámara, “Desplazamiento <strong>de</strong> enlaces periféricos paramejorar las prestaciones <strong>de</strong> re<strong>de</strong>s toroidales con dimensiones<strong>de</strong>siguales”. PhD dissertation. Santan<strong>de</strong>r, 2010.[4] J. M. Camara, M. Moreto, E. Vallejo, R. Beivi<strong>de</strong>, J. Miguel-Alonso, C. Martinez, J. Navaridas, "Twisted Torus Topologiesfor Enhanced Interconnection Networks," IEEE Transactions onParallel and Distributed Systems, pp. 1765-1778, Dec. 2010.[5] Cray Inc. Cray XK6 specifications, available online athttp://www.cray.com/Products/XK6/Specifications.aspx,Retrieved June 2011.[6] J. Kim, W. Dally, B. Towles, A. Gupta. “Microarchitecture of aHigh-radix Router,” Proceedings of the 32nd InternationalSymposium on Computer Architecture (ISCA-32), pp. 420–431,Madison,WI June 2005[7] S. Scott and G. Thorson, “The Cray T3E network: adaptiverouting in a high performance 3D torus”, IEEE HotInterconnects, 1996.[8] C. H. Sequin. 1981. “Doubly twisted torus networks for VLSIprocessor arrays”. In Proceedings of the 8th annual symposiumon Computer Architecture (ISCA '81). IEEE Computer SocietyPress, Los Alamitos, CA, USA, 471-480.[9] T. Budnik, B. Knudson, M. Megerian, S. Miller, M. Mundy, W.Stock<strong>de</strong>ll. "Blue Gene/Q Resource Management Architecture",3 rd IEEE Workshop on Many-Task Computing on Grids andSupercomputers (MTAGS10), 2010.<strong>JP2011</strong>-426


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Performance analysis of an IEEE 802.21 basedVertical Handover protocol using ns-2Johann Márquez-Barja, Carlos T. Calafate, Juan-Carlos Cano and Pietro Manzoni 1Abstract— Currently, due to the ubiquity of wirelesstechnologies, users <strong>de</strong>mand continuous connectivityguaranteeing the Quality of Service (QoS) requiredfor their communications. In or<strong>de</strong>r to choosethe best network among different alternatives, theIEEE 802.21 standard has been <strong>de</strong>veloped. It offersresources to perform Vertical Handover (VHO)among heterogeneous wired and wireless networks.We present experiments in or<strong>de</strong>r to evaluate the verticalhandover performance when relying on the IEEE802.21 standard in scenarios where Wi-Fi, WiMAXand UMTS technologies are available. Experimentalresults show that a technology-aware vertical handovermechanism is able to achieve an a<strong>de</strong>quate performancewhen traffic congestion is low.Keywords— IEEE 802.21, Wi-Fi, WiMAX, UMTS,Vertical handover (VHO), Vertical Handoff, RoamingI. IntroductionNOWADAYS there are different wireless accesstechnologies allowing users to stay “always on”.Mobile computing is <strong>de</strong>man<strong>de</strong>d to perform our tasksand duties, which can be as simple as reading thenews, or as complex as medical monitoring applications.Due to the mobility offered by wireless technologies,users not only <strong>de</strong>mand continuous connectivity,but also QoS for their communications. Un<strong>de</strong>r the“always best connected” paradigm [1], users <strong>de</strong>mandto be connected while they cross over the coverageof the access points of different technologies. Tofulfill their requirements, Vertical Handover (VHO)techniques make possible to switch from one wirelesstechnology to another in a seamless manner, offeringmobile users the possibility of remaining connectedun<strong>de</strong>r certain QoS criteria. Figure 1 illustrates theconcept of VHO where a mobile <strong>de</strong>vice crosses differentcoverage areas, seamlessly switching from onetechnology to another. The complete VHO processtakes into account service continuity, network discovery,network selection, security, mobility management,and QoS issues [2], focusing mostly on the latter.In this work we present a performance evaluationof a technology-aware Vertical Handover DecisionAlgorithm (VHDA) which takes into account theavailability and network capacity as its main <strong>de</strong>cisionparameters in a scenario composed of multiple accesspoints of Wireless Fi<strong>de</strong>lity (Wi-Fi), Worldwi<strong>de</strong>interoperability for Microwave Access (WiMAX),and Universal Mobile Telecommunications System(UMTS) technologies. In this scenario, the mobile1 Universitat Politècnica <strong>de</strong> València, Cami <strong>de</strong> Vera, s/n,46022 Valencia, España. {jomarba, calafate, jucano,pmanzoni}@disca.upv.esFig. 1.Horizontal and Vertical Handover.<strong>de</strong>vices are able to connect to these technologies byrelying on multi-interfaces un<strong>de</strong>r the IEEE 802.21standard [3]. We evaluate the VHO latency, throughput,packet loss, and the end-to-end latency in or<strong>de</strong>rto assess the effectiveness of the VHO process.The rest of this paper is organized as follows: SectionII presents the most relevant works in the literaturecovering VHDA and VHO strategies. Anoverview of the VHO is also presented in Section III.Section IV presents a <strong>de</strong>scription of the VHDA used.The simulation framework set used for experimentationis <strong>de</strong>scribed in Section V. Performance evaluationresults are presented in Section VI. Finally,Section VII presents the conclusions of this researchwork.II. Related WorkIn the late nineties, the first approaches offeringconnectivity among heterogeneous networks were introducedby Stemm and Katz [4]. These authors<strong>de</strong>veloped an application based on Mobile IP androuting which was able to manage handovers amongdifferent networks such as the IBM Infrared WirelessLAN, the AT&T WaveLAN and the Metricom RicochetNetwork as in-building, campus, and wi<strong>de</strong> areaun<strong>de</strong>rlying wireless technologies, respectively.Nowadays, several works can be found in the literatureand industry covering VHO among differenttechnologies such as Wi-Fi, Wireless Broadband<strong>JP2011</strong>-427


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011(WiBro), WiMAX, UMTS and Low Earth Orbit(LEO). Due to the broad variety of solutions forthese technologies, no single VHO technology embracesthem all. Nevertheless, the IEEE 802.21Working Group is working on the Media In<strong>de</strong>pen<strong>de</strong>ntHandover Services Protocol [3] which provi<strong>de</strong>sa homogeneous function-interface between heterogeneousnetwork technologies.De la Oliva et al. [5] present a study case where themobile terminal is capable of operating in conjunctionwith the IEEE 802.21 protocol. Although theproposed scenario only consi<strong>de</strong>rs Wi-Fi and UMTSas un<strong>de</strong>rlying wireless networking technologies, theuse of the Received Signal Strength (RSS) and theservices offered by the IEEE 802.21 present a usefulevaluation when the VHO is initiated by themobile no<strong>de</strong> (Mobile-Initiated Handover (MIHO))evaluating the VHO <strong>La</strong>tency as well as the VHOPacket loss. Nevertheless, Buburuzan and Nyamen[6] present an evaluation of VHO initiation processeseither initiated by the mobile no<strong>de</strong> (MIHO) or thenetwork (Network-Initiated Handover (NIHO)) when<strong>de</strong>aling with WiMAX and Wi-Fi technologies un<strong>de</strong>rthe IEEE 802.21 protocol. A VHO evaluation basedon the performance of the Session Initiated Protocol(SIP) in an inter-domain and inter-technology scenariopowered by the IEEE 802.21 is presented byDutta et al. [7], showing the performance of theVHO while voice is being transmitted and evi<strong>de</strong>ncingthe continuity of the service and the effect of theVHO latencies.Our work focuses on three technologies: Wi-Fi,WiMAX and UMTS, and it uses a VHDA whichtakes into account not only the RSS and the IEEE802.21 services, but also the capacity offered by thedifferent technologies. We have used Constant BitRate (CBR) traffic in or<strong>de</strong>r to evaluate VHO in aninter-domain and inter-technology scenario evaluatingVHO latency, end-to-end latency, packet loss,and throughput.III. VHO OverviewIn the literature we can find VHO proposals [8],[9] that divi<strong>de</strong> the complete VHO process into threephases: i) Handover information gathering, ii) Handover<strong>de</strong>cision, and iii) Handover execution. Figure2 shows the interactions among these three phases.Every phase is in charge of performing some specificduties. The handover information gathering phasecollects information from diverse sources of the systemsuch as network properties, access points, mobile<strong>de</strong>vices, and user preferences. The handover <strong>de</strong>cisionphase is one of the most critical processes duringthe handover. Once the gathered informationis processed by the VHDA, the resulting process <strong>de</strong>ci<strong>de</strong>sWhen and Where to trigger the handover. This<strong>de</strong>cision takes into account several parameters in or<strong>de</strong>rto choose the best candidate network to handoverto. Concerning algorithms that allow evaluatingmulti-parameters, we can find techniques suchas fuzzy logic, neural networks, and pattern recognition,among others [10]. Finally, the execution phasecommits the VHO itself, leaving the first networkand attaching to the access point of the second network;this process must be done seamlessly, reachinglow latencies and minimal packet loss. Usually,to manage mobility at this phase, the Mobility forIP (MIP) protocol is used in or<strong>de</strong>r to guarantee theseamless feature.Fig. 2.Handover Management Procedure.A. Media In<strong>de</strong>pen<strong>de</strong>nt Handover Function (MIHF)The MIHF protocol <strong>de</strong>fined by the IEEE 802.21standard establishes the messages exchanged betweenpeer MIH entities for handover, offering a commonmessage payload across different media (802.3,802.11, 802.16, Cellular). The standard refers aslower layers to the technology <strong>de</strong>pen<strong>de</strong>nt components,and as upper layers to the requesting modules.These lower layers can be accessed by different functionsto retrieve information for <strong>de</strong>tecting, preparingand executing the VHO, while the upper ones <strong>de</strong>mandthat information; therefore, the latter are alsoreferred to as the Media In<strong>de</strong>pen<strong>de</strong>nt Handover User(MIHU). The MIHF offers to both lower and upperlayers a Service Access Point (SAP) in or<strong>de</strong>r toexchange the service messages. Figure 3 shows thebasic 802.21 architecture. The basic services offeredby the MIHF are briefly <strong>de</strong>scribed below:A.1 Media In<strong>de</strong>pen<strong>de</strong>nt Event Service (MIES)This service <strong>de</strong>tects the changes on the lower layers,e.g. changes on the physical and data link layer.The MIHF notifies events occurring in the lower layersto the MIHUs as they have requested. The MIEScovers events such as:• State change events (link up, link down, link pa-<strong>JP2011</strong>-428


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011rameter changes).• Predictive events (link going down).• Network initiated events (load balancing, operatorpreferences).A.2 Media In<strong>de</strong>pen<strong>de</strong>nt Information Service (MIIS)The MIIS allows the MIHF to discover its networkenvironment gathering information that the upperlayers make use of to make <strong>de</strong>cisions. The informationelements refers to the list of available networks,location of Point of Attachment (PoA), operator ID,roaming partners, cost, security, QoS, PoA capabilities,and Vendor specific information, among others.A.3 Media In<strong>de</strong>pen<strong>de</strong>nt Command Service (MICS)The MICS allows the MIHU to take control overthe lower layers through a set of commands. Withthe information gathered by the MIES and MIIS, theMIHU <strong>de</strong>ci<strong>de</strong> to switch from one PoA to another.The commands allow not only to execute the handover,but to set different parameters in the lowerlayers elements. Depending on which entity has thehandover control, some services are more useful thanothers. The following commands are typically usedby the MICS:• MIH Handover Initiate. Used between networkand mobile <strong>de</strong>vice.• MIH Handover Prepare. Used between the oldnetwork (PoA) and the new network.• MIH Handover Commit. Used between networkand mobile <strong>de</strong>vice.• MIH Handover Complete. Used between networkand mobile <strong>de</strong>vice and network to network.A.4 AmendmentsIn or<strong>de</strong>r to fully provi<strong>de</strong> handover services, the802.21 must be implemented into network <strong>de</strong>vicesand mobile <strong>de</strong>vices. The media specific amendmentsrequired by MIHF are <strong>de</strong>fined as follows• Container for MIH messages for 802.11 are <strong>de</strong>finedin the 802.11u [11]• Container for MIH messages for 802.16 are <strong>de</strong>finedin the 802.16g [12]• The 3GPP-SAE (System Architecture Evolution)is working for 3GPP. [13]• The IEFT MIPSHOP (Mobility for IP: Performance,Signaling and Handoff Optimization) ishas <strong>de</strong>fined the Transport for MIH Protocol [14]• 802.3 is <strong>de</strong>sired.IV. Overview of the Vertical HandoverDecision Algorithm (VHDA)The VHO process consi<strong>de</strong>red in our experimentsuses the IEEE 802.21 standard at the first phase inor<strong>de</strong>r to gather information, notify events and executecommands. For the <strong>de</strong>cision phase, we haveused a VHDA that consi<strong>de</strong>rs the availability and thebandwidth offered for the <strong>de</strong>cision making process.Figure 4 shows the state diagram of the VHDA whenUpper <strong>La</strong>yers (L3 and above)SIP MIPv4 MIPv6 HIP ....Mobility ManagementMIHEventsLinkEventsMIH_SAPSmartTriggersMIH_Link_SAPMIH UsersMIHCommandsLinkCommandsLower <strong>La</strong>yers (L2 and below)Handover Management802.21 MIH FunctionHandoverMessagesInformationServiceInformationServiceProtocol and Device Hardware802.3 802.11 3GPP 802.16Fig. 3.InformationServiceIEEE 802.21 Architecture.selecting a candidate network to switch to. As observed,the MIHF set at the User Equipment (UE) iscontinuously sensing the interfaces. When an eventis triggered, and <strong>de</strong>pending on the type of event, theVHDA performs different routines and subroutinesbased in MICS and MIES in or<strong>de</strong>r to select the bestcandidate network, or simply chooses the UMTS networkby <strong>de</strong>fault, due to the full UMTS coverage. Finally,consi<strong>de</strong>ring the execution phase of the VHOprocess, we use Mobility support for Internet Protocolv.6 (MIPv6) to manage the mobility issues. Itis important to emphasize that the 802.21 events:LINK UP and LINK DOWN, <strong>de</strong>termine the behaviorof the VHDA. When a LINK DETECTED eventoccurs, the user equipment will trigger other eventssuch as LINK UP if the technology <strong>de</strong>tected is ableto offer more bandwidth, negotiating with the newbase station for the IP address; MIPv6 is in chargeof this negotiation and notification to different componentsof the system. All these processes requirecomplex actions which imply latency. On the otherhand, when a LINK DOWN event is <strong>de</strong>tected, onlya notification is performed by the MIPv6 agent sincethe interface was already configured in a previousLINK UP. So, there is no ad<strong>de</strong>d latency to theseprocesses.V. Simulation frameworkConsi<strong>de</strong>ring networking in general, there are severaltools for simulation. Nevertheless, consi<strong>de</strong>ringVHO in particular, there are only a few simulationtools available. To address this shortage, the NationalInstitute of Standards and Technology (NIST)has <strong>de</strong>veloped a tool for seamless mobility [15] based....<strong>JP2011</strong>-429


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20111500UMTSDistance (m)1200AWiMAX(1)Wi-Fi(2)Wi-Fi(1)WiMAX(2)Wi-Fi(3)900600ComponentFig. 4.VHDA state diagram.TABLE IVHO scheme components.Wi-FiWiMAX UMTSAccess Point 3 2 1Theoretical Bw 54 70 5(Mbps)Bw offered (Mbps) 28.2 16.3 2.7Advertisement Interval100 5000 -(ms)Coverage (m) 250 500 1000in a wi<strong>de</strong>ly used simulator for wired and wireless networks:the Network Simulator (ns-2). The NISTmobility package for the ns-2 allows to simulate Wi-Fi, WiMAX, and UMTS technologies, as well asperforming handovers among these technologies ina seamless manner. Moreover, it allows operatingun<strong>de</strong>r the IEEE 802.21 standard offering most of itsfeatures.For our experiments we have evaluated the VHDAby setting up a scheme consi<strong>de</strong>ring three wirelesstechnologies: Wi-Fi, WiMAX, and UMTS. Our scenariois a square area of 3000 m 2 area where 6 accesspoints (1 no<strong>de</strong> B for UMTS, 2 base stationsfor WiMAX, and 3 access points for Wi-Fi) havebeen <strong>de</strong>ployed. Each element of the network has anMIH entity to manage the 802.21 protocol directives.Table I presents the elements and the configurationused. Moreover, Figure 5 shows the scenario used forour studies where the user equipment <strong>de</strong>mands CBRtraffic. The mobile terminal has always UMTS connectivityand, while it moves, it discovers new wirelessnetworks; it performs a VHO if any of the newnetworks offers a higher performance, or if the networkbeing used disappears. Since our work focuseson VHO itself, the coverage areas of each technologydoes not extend over a very large area to avoid longperiods un<strong>de</strong>r only one technology. Figure 6 presentsthe position of each access point and its coveragearea. The initial position for the user equipment isrepresented by point A; the user equipment moves tothe right in a straight line across the different coverageareas at a constant speed of 3 meters per second.0 300 600 900 1200 1500 1800 2100 2400 2700 3000 3300Distance (m)Fig. 6.Wireless technologies coverage areas.VI. Performance evaluationTo evaluate the performance of the VHO schemewe used the following metrics: i) latency, ii) throughput,iii) and packet loss. In or<strong>de</strong>r to obtain reliableresults, we performed several experiments varyingrandomly the seed. By obtaining several simulationresults per test we assure that the obtained meanvalues are within strict confi<strong>de</strong>nce intervals.Concerning VHO performance, there exist differentpoints of view about the evaluation metrics tobe used in or<strong>de</strong>r to perform an accurate analysis.However, it is important to establish two evaluationlines: the un<strong>de</strong>rlying wireless technologies and theVHO itself.A. Wireless Technologies performanceIn or<strong>de</strong>r to evaluate the performance of each wirelessnetwork, we evaluated the performance experiencedby a mobile terminal throughout the simulationtime. Figure 7 shows the network being usedwhen moving along the scenario at a speed of 3m/s. For the period of time that the user equipmentis connected to a network, the throughputreached is the maximum for each technology. Figure8 clearly shows the throughput reached by each networkwithin a certain period of time. Wi-Fi offers thehighest bandwidth, reaching up to 28.2 Mbps. ThenWiMAX offers up to 11 Mbps, while UMTS offers a2.04 Mbps datarate. These values confirm the trendof the results obtained in one of our previous works[16]. Concerning latency, Figure 9 presents the <strong>de</strong>layperformance of each wireless network throughout thesimulation time. As observed, UMTS takes an averageof 29.96 ms to <strong>de</strong>liver one packet, while WiMAXand Wi-Fi offer lower latencies: 0.81 and 0.23 ms,respectively.B. VHO performanceFinally, we have performed several simulations toevaluate the performance of the VHO itself. Weevaluate VHO latency and the un<strong>de</strong>livered packets.Table II shows the latency we obtained forevery VHO process. When it is associated with aLINK UP event, the latencies vary between 1.71 and8.40 milliseconds <strong>de</strong>pending on the technologies involved.Concerning the VHO latency associated with<strong>JP2011</strong>-430


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011RouterRNCUMTSServerWiMAX(1)Wi-Fi(1)Wi-Fi(2)WiMAX(2)Wi-Fi(3)User EquipmentFig. 5.VHO scheme.1000UMTS WiMAX Wi-FiWireless TechnologiesUMTSWiMAXWi-Fi<strong>La</strong>tency per packet (ms)1001010 200 400 600 800 1000 1200Time (s)Fig. 7. Wireless technologies usage.0.10 200 400 600 800 1000 1200Time (s)Fig. 9. Wireless technologies latency.Throughput (kbps)30000250002000015000100005000UMTS WiMAX Wi-Fi00 200 400 600 800 1000 1200Fig. 8.Time (s)Wireless technologies throughput.LINK DOWN events, we can observe that latenciesreached by the latter processes are between 0.04 and0.11 milliseconds. The difference among these latenciesis due to the number of processes performed,as mentioned before. Concerning packet loss, TableII also presents the number of packets that havenot been <strong>de</strong>livered while the VHO process was beingperformed. The amount of un<strong>de</strong>livered data isrelated to the bandwidth available at the new network.As shown in the referred table, VHO processesthat switch from a network with higher bandwidth toa network with lower bandwidth experience a higheramount of packet losses.The results were obtained un<strong>de</strong>r “best-case” conditions,since there are no other user equipmentsrequesting services or <strong>de</strong>creasing the performanceof the available networks. Therefore, the resultingmean values of the different metrics measured mustbe consi<strong>de</strong>red as optimistic results, in or<strong>de</strong>r to avoidany erroneous conclusion.VII. ConclusionsIn this paper we have performed several experimentsin or<strong>de</strong>r to evaluate a technology-aware VHDAwhich consi<strong>de</strong>rs availability and capacity of the networkfor the <strong>de</strong>cision making process. The frameworkused for experimentation is based on the NetworkSimulator (ns-2), allowing us to evaluate theVHO process un<strong>de</strong>r the IEEE 802.21 standard.Experiments showed that VHO processes reachhigher latencies when <strong>de</strong>aling with newly discoveredcandidate networks due to the processes triggeredin or<strong>de</strong>r to perform a seamless VHO. Concerningpacket loss, VHO processes drop packets due to therestriction of bandwidth availability whenever downgradingfrom a network to another. Results were optimisticdue to the “best-case” conditions offered bythe different wireless technologies, since at the scenariono other traffic was <strong>de</strong>creasing the performanceof each network.We conclu<strong>de</strong> that different improvements canbe suggested to outperform the current evaluatedVHDA whenever the conditions differ from thoseconsi<strong>de</strong>red in this paper. In particular, high <strong>de</strong>greesof congestion, as well as other parameters (user preferences,mobile capabilities, etc.), will require a more<strong>JP2011</strong>-431


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLE IISimulation results.VHO Event Type ofEventVHO <strong>La</strong>tency(ms)UMTS-WiMAX(1) Link Up 6.51043 0WiMAX(1)-Wi-Fi(1) Link Up 1.71175 0Wi-Fi(1)-WiMAX(1) Link Down 0.04578 81WiMAX(1)-UMTS Link Down 0.11723 679UMTS-WiFi(2) Link Up 1.75597 0Wi-Fi(2)-WiMAX(2) Link Up 8.40820 0WiMAX(2)-Wi-Fi(3) Link Up 1.88742 0Wi-Fi(3)-UMTS Link Down 0.10205 664Un<strong>de</strong>liveredPacketssophisticated <strong>de</strong>cision algorithm.AcknowledgmentsThis work was partially supported by the Ministerio<strong>de</strong> Ciencia e Innovación, Spain, un<strong>de</strong>r GrantTIN2008-06441-C02-01.References[1] E. Gustafsson and A. Jonsson, “Always best connected,”IEEE Wireless Communications, vol. 10, no. 1, pp. 49–55, Feb. 2003.[2] Yu C. Chen, Ja H. Hsia, and Yi J. Liao, “Advanced seamlessvertical handoff architecture for WiMAX and WiFiheterogeneous networks with QoS guarantees,” ElsevierComputer Communications, vol. 32, no. 2, pp. 281–293,Feb. 2009.[3] “IEEE standard for local and metropolitan areanetworks- part 21: Media in<strong>de</strong>pen<strong>de</strong>nt handover,” Tech.Rep., 2009.[4] Mark Stemm and Randy H. Katz, “Vertical handoffs inwireless overlay networks,” Springer Mobile Networksand Applications., vol. 3, no. 4, pp. 335–350, 1998.[5] Antonio De-<strong>La</strong>-Oliva, Telemaco Melia, Albert Vidal,Carlos J. Bernardos, Ignacio Soto, and Albert Banchs,“IEEE 802.21 enabled mobile terminals for optimizedWLAN/3G handovers: a case study,” ACM Mobile Computingand Communications Review, vol. 11, no. 2, pp.29–40, 2007.[6] Teodor Buburuzan and Liliane N. Nyamen, “Performanceevaluation of an enhanced IEEE 802.21 handovermo<strong>de</strong>l,” in 1st Workshop on Wireless Broadband Accessfor Communities and Rural Developing Regions, Karlstad,2008.[7] Ashutosh Dutta, Subir Das, David Famolari, YoshihiroOhba, Kenichi Taniuchi, Victor Fajardo, Rafa M. Lopez,Toshikazu Kodama, and Henning Schulzrinne, “Seamlessproactive handover across heterogeneous access networks,”Springer Wireless Personal Communications,vol. 43, no. 3, pp. 837–855, Nov. 2007.[8] Meriem Kassar, Brigitte Kervella, and Guy Pujolle, “Anoverview of vertical handover <strong>de</strong>cision strategies in heterogeneouswireless networks,” Elsevier Computer Communications,vol. 31, no. 10, June 2008.[9] E. Stevens-Navarro, Yuxia Lin, and V. W. S. Wong, “AnMDP-based vertical handoff <strong>de</strong>cision algorithm for heterogeneouswireless networks,” IEEE Transactions onVehicular Technology, vol. 57, no. 2, pp. 1243–1254, 2008.[10] Anita Singhrova and Nupur Prakash, “A review of verticalhandoff <strong>de</strong>cision algorithm in heterogeneous networks,”in 4th ACM International Conference on mobiletechnology, applications, and systems, New York, NY,USA, 2007, pp. 68–71.[11] IEEE 802.11, “IEEE P802.11u: Interworking with externalnetworks Task Group U,” IEEE Computer Society,2004.[12] IEEE 802.16, “IEEE P802.16g: Management plane proceduresand services (MobileMan),” IEEE Computer Society,2007.[13] 3GPP, “3GPP-SAE: Third generation partnershipproject - system architecture evolution,” 2006.[14] MIPSHOP, “IETF mobility for ip: Performance, signalingand handoff optimization,” 2004.[15] Advanced Network Technology Division- NationalInstitute of Standards and Technology,“Seamless and Secure Mobility,”http://www.antd.nist.gov/seamlessandsecure/.[16] Johann Marquez, Carlos T. Calafate, Juan-Carlos Cano,and Pietro Manzoni, “Evaluating the performanceboundaries of Wi-Fi, WiMAX and UMTS using the NetworkSimulator ns-2,” in 5-th ACM Workshop on PerformanceMonitoring and Measurement of HeterogeneousWireless and Wired Networks, Oct. 2010, pp. 25–30.<strong>JP2011</strong>-432


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Mecanismos <strong>de</strong> Comunicación Eficientes enRe<strong>de</strong>s <strong>de</strong> Altas Prestaciones para Bibliotecas<strong>de</strong> Paso <strong>de</strong> Mensajes en JavaRoberto R. Expósito, Guillermo L. Taboada, Juan Touriño y Ramón Doallo 1Resumen— Este trabajo presenta el diseño e implementación<strong>de</strong> mecanismos <strong>de</strong> comunicación eficientesen re<strong>de</strong>s <strong>de</strong> altas prestaciones para bibliotecas <strong>de</strong>paso <strong>de</strong> mensajes en Java. El auge <strong>de</strong> las arquitecturasclúster y el aumento exponencial <strong>de</strong>l número<strong>de</strong> núcleos en los procesadores actuales hacen quesea necesario el uso <strong>de</strong> middleware <strong>de</strong> comunicacióneficiente para obtener la mayor escalabilidad posibleen las aplicaciones paralelas y distribuidas, especialmenteen presencia <strong>de</strong> re<strong>de</strong>s <strong>de</strong> altas prestaciones. Entreestas re<strong>de</strong>s <strong>de</strong> interconexión <strong>de</strong> clusters <strong>de</strong>stacanInfiniBand, Myrinet y High Speed Ethernet (10/40Gigabit Ethernet). <strong>La</strong>s especiales características <strong>de</strong>Java para computación paralela, entre las que <strong>de</strong>stacanun completo soporte multithread y <strong>de</strong> comunicacionesen red, han favorecido el <strong>de</strong>sarrollo <strong>de</strong> bibliotecasJava para computación <strong>de</strong> altas prestaciones(HPC), entre las que <strong>de</strong>staca el paradigma <strong>de</strong> paso <strong>de</strong>mensajes en Java (MPJ). No obstante, las bibliotecasMPJ adolecen, al igual que las soluciones estándar enJava, <strong>de</strong> soporte directo y eficiente sobre re<strong>de</strong>s <strong>de</strong> bajalatencia. <strong>La</strong> evaluación experimental <strong>de</strong> los mecanismos<strong>de</strong> comunicación <strong>de</strong>sarrollados en este trabajoha mostrado aumentos significativos <strong>de</strong>l rendimientocomparados con las soluciones previamente existentesen Java.Palabras clave— Java, Paso <strong>de</strong> Mensajes, Clúster,Re<strong>de</strong>s <strong>de</strong> Altas Prestaciones, InfiniBand, Myrinet,High Speed Ethernet, Remote Direct Memory Access(RDMA).I. IntroducciónEL lenguaje <strong>de</strong> programación Java es ampliamenteutilizado en el ámbito académico así comoen la industria por sus especiales características talescomo seguridad, robustez, portabilidad, expresividad,sencillez, gestión automática <strong>de</strong> memoria yuna mayor productividad <strong>de</strong>rivada <strong>de</strong> su orientacióna objetos, lo que le ha llevado a convertirse enuna <strong>de</strong> las plataformas <strong>de</strong> <strong>de</strong>sarrollo <strong>de</strong> aplicacionesmás extendidas <strong>de</strong> la actualidad. No obstante, enámbitos don<strong>de</strong> el rendimiento es crítico, como encomputación <strong>de</strong> altas prestaciones (HPC), no es tanpopular, aunque su rendimiento se ha ido incrementandosignificativamente al pasar <strong>de</strong> una ejecucióninterpretada a la compilación a código nativo entiempo <strong>de</strong> ejecución realizada por compiladores JIT(Just-In-Time) y máquinas virtuales HotSpot. Deesta forma, Java alcanza rendimientos similares a loslenguajes compilados a código nativo, convirtiéndoseen una alternativa competitiva en HPC.Una <strong>de</strong> las arquitecturas paralelas más populareshoy en día en HPC es el clúster, un sistema <strong>de</strong> memo-1 Grupo <strong>de</strong> Arquitectura <strong>de</strong> Computadores, Dpto. <strong>de</strong>Electrónica y Sistemas, <strong>Universidad</strong>e da Coruña, e-mail:rreye,taboada,juan,doallo@udc.es.ria distribuida escalable y económico formado porcomponentes comerciales que presenta una buena ratiocoste/rendimiento. Entre los mo<strong>de</strong>los <strong>de</strong> programación<strong>de</strong> memoria distribuida, la interfaz <strong>de</strong> paso<strong>de</strong> mensajes MPI (Message Passing Interface) es lamás popular y usada por la mayoría <strong>de</strong> las aplicacionesHPC, habiéndose convertido en el estándar <strong>de</strong>facto para <strong>de</strong>sarrollar aplicaciones paralelas portables,tradicionalmente utilizando los lenguajes C yFortran. El auge <strong>de</strong> las arquitecturas clúster yel aumento exponencial <strong>de</strong>l número <strong>de</strong> núcleos enlos procesadores actuales hacen que sea necesario eluso <strong>de</strong> middleware <strong>de</strong> comunicación eficiente paraobtener la mayor escalabilidad posible en las aplicacionesparalelas y distribuidas, especialmente enpresencia <strong>de</strong> re<strong>de</strong>s <strong>de</strong> altas prestaciones (también <strong>de</strong>nominadasre<strong>de</strong>s <strong>de</strong> baja latencia y alto ancho <strong>de</strong>banda). Entre estas re<strong>de</strong>s <strong>de</strong> interconexión <strong>de</strong> clusters<strong>de</strong>stacan InfiniBand, Myrinet y la familia HighSpeed Ethernet (10/40 Gigabit Ethernet).Por otro lado, las especiales características <strong>de</strong> Javapara computación paralela, entre las que <strong>de</strong>stacanun completo soporte multithread y <strong>de</strong> networkingjunto con su importante popularidad, han favorecidoel <strong>de</strong>sarrollo <strong>de</strong> numerosas bibliotecas para paso <strong>de</strong>mensajes MPJ (Message-Passing in Java). En esteaspecto, la evaluación <strong>de</strong> las bibliotecas MPJ másimportantes [1], analizando los distintos mecanismos<strong>de</strong> comunicaciones que implementan, ha constatadoque no soportan <strong>de</strong> forma eficiente las re<strong>de</strong>s <strong>de</strong> interconexión<strong>de</strong> clusters <strong>de</strong> baja latencia.Este artículo presenta el diseño e implementación<strong>de</strong> mecanismos <strong>de</strong> comunicación eficientes en re<strong>de</strong>s <strong>de</strong>altas prestaciones para bibliotecas <strong>de</strong> paso <strong>de</strong> mensajesen Java. Estos han sido integrados en la bibliotecaF-MPJ [2] con el fin <strong>de</strong> analizar experimentalmentela eficiencia <strong>de</strong> los mecanismos <strong>de</strong>sarrollados yasí po<strong>de</strong>r comparar su rendimiento respecto <strong>de</strong> otrasimplementaciones, utilizando para ello diversos clusterscon distintas re<strong>de</strong>s <strong>de</strong> baja latencia (InfiniBand,10 Gigabit Ethernet, y Myrinet).II. Paso <strong>de</strong> Mensajes en JavaEl paradigma <strong>de</strong> paso <strong>de</strong> mensajes es el másutilizado en programación paralela, <strong>de</strong>bido a suportabilidad, escalabilidad y relativamente buenrendimiento. En los lenguajes compilados a códigonativo MPI es la interfaz estándar para bibliotecas<strong>de</strong> paso <strong>de</strong> mensajes. En cuanto a Java, existen numerosasbibliotecas MPJ [1], aunque en este caso no<strong>JP2011</strong>-433


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011existe una interfaz estándar, con lo que la mayoríahan optado por implementar su propia API, similara la <strong>de</strong> MPI. Actualmente, MPJ Express [3] y nuestrabiblioteca F-MPJ [2] son los proyectos MPJ másactivos.El soporte para paso <strong>de</strong> mensajes sobre re<strong>de</strong>s <strong>de</strong>altas prestaciones suele estar implementado en dispositivos<strong>de</strong> comunicaciones a bajo nivel que proporcionanoperaciones <strong>de</strong> comunicación básicas. Ejemplos<strong>de</strong> APIs implementadas en lenguajes compiladosson ADI (Abstract Device Interface) y BTL (ByteTransfer <strong>La</strong>yer), utilizadas en las implementacionesMPICH2 [4] y OpenMPI [5], respectivamente. En elcaso <strong>de</strong> MPJ x<strong>de</strong>v es el API utilizada por MPJ Express,proporcionando operaciones básicas sobre lasque implementar las comunicaciones MPJ. Sin embargo,x<strong>de</strong>v utiliza una capa <strong>de</strong> buffering [6] adicionalen la comunicación que limita <strong>de</strong> forma importantesu rendimiento y escalabilidad, siendo este el principalcuello <strong>de</strong> botella <strong>de</strong> MPJ Express. <strong>La</strong> bibliotecaF-MPJ solventa este problema presentando unanueva API, xx<strong>de</strong>v, mostrada en la Figura 1, que extien<strong>de</strong>x<strong>de</strong>v permitiendo la comunicación directa <strong>de</strong>cualquier objeto serializable en Java en lugar <strong>de</strong> estarrestringida a bufers MPJ como en MPJ Express,a<strong>de</strong>más <strong>de</strong> presentar un diseño más modular y extensible.public c l a s s Device{s t a t i c public Device n e wInstance ( S t r i n g impl ) ;P rocessID [ ] i n i t ( S t r i n g [ ] a r g s ) ;P rocessID i d ( ) ;void f i n i s h ( ) ;Request i s e n d ( Object msg , PID dst , int tag ,int c n t x t ) ;Request i r e c v ( Object msg , PID src , int tag ,int c n txt , S t a t u s s ) ;void send ( Object msg , PID dst , int tag ,int c n t x t ) ;S t a t u s r e c v ( Object msg , PID src , int tag ,int c n t x t ) ;Request i s s e n d ( Object msg , PID dst , int tag ,int c n t x t ) ;void sse n d ( Object msg , PID src , int tag ,int c n t x t ) ;S t a t u s i p r o b e (PID src , int tag , int c n t x t ) ;S t a t u s probe (PID src , int tag , int c n t x t ) ;Request peek ( ) ;}Fig. 1.API pública <strong>de</strong> la clase xx<strong>de</strong>vIII. Mecanismos <strong>de</strong> Comunicación Eficientesen Re<strong>de</strong>s <strong>de</strong> Altas PrestacionesEsta sección presenta el diseño e implementación<strong>de</strong> los mecanismos <strong>de</strong> comunicación para las re<strong>de</strong>s<strong>de</strong> altas prestaciones soportadas eficientemente en F-MPJ.A. Myrinet/High Speed EthernetMyrinet es una red <strong>de</strong> interconexión <strong>de</strong> clusters <strong>de</strong>altas prestaciones <strong>de</strong>sarrollada por Myricom [7] queproporciona latencias reducidas, en torno a 3-8 µs yaltos anchos <strong>de</strong> banda, 2 Gbps en Myrinet 2000 y10 Gbps en Myri-10G. Myrinet Express (MX) [8] esla biblioteca <strong>de</strong> comunicación <strong>de</strong> bajo nivel y altasprestaciones que proporciona Myricom para su utilización,tratándonse <strong>de</strong> un API con una semánticaorientada al paso <strong>de</strong> mensajes. <strong>La</strong> presencia <strong>de</strong>Myrinet en el Top500 [9] se ha visto notablemente reducidaen los ultimos años, hasta el punto que Myricomha diseñado sus últimos productos (Myri-10G)para ser compatibles a nivel físico con 10 GigabitEthernet, y que gracias al protocolo MXoE (MX overEthernet) es totalmente compatible con Myrinet anivel <strong>de</strong> API utilizando MX.Open-MX [10] es una implementación open-source<strong>de</strong>l API MX para su utilización sobre re<strong>de</strong>s HighSpeed Ethernet, fundamentalmente 10/40 GigabitEthernet, que a<strong>de</strong>más proporciona compatibilidadcon el protocolo MXoE. Esto nos permite <strong>de</strong>sarrollarel dispositivo <strong>de</strong> comunicación siguiendo la especificación<strong>de</strong>l API MX, y po<strong>de</strong>r utilizarlo con unatarjeta <strong>de</strong> red Ethernet genérica, sin necesidad <strong>de</strong>lhardware especializado <strong>de</strong> Myricom. Su compatibilidada nivel <strong>de</strong> API permite su uso en re<strong>de</strong>s Myrinet oen re<strong>de</strong>s Ethernet utilizando los productos <strong>de</strong> Myricom.Como Open-MX está <strong>de</strong>sarrollado en lenguajeC es necesario el uso <strong>de</strong> la interfaz nativa <strong>de</strong> Java,JNI (Java Native Interface), para su soporte en Java.A.1 Dispositivo en Java sobre MX: omx<strong>de</strong>vEl código Java para el dispositivo <strong>de</strong> comunicacionespara Myrinet/High Speed Ethernet <strong>de</strong>be implementarla interfaz xx<strong>de</strong>v. Cada método <strong>de</strong> comunicación<strong>de</strong>lega en el método nativo correspondiente<strong>de</strong> la biblioteca MX a través <strong>de</strong> JNI, encargándose<strong>de</strong> la obtención <strong>de</strong> referencias así como <strong>de</strong>l manejo <strong>de</strong>los parámetros. Esto permite minimizar al máximoel código JNI, eliminando posibles problemas <strong>de</strong>rivados<strong>de</strong> su uso. Es necesario el uso <strong>de</strong> la función <strong>de</strong>JNI <strong>de</strong>nominada GetPrimitiveArrayCritical, la cualpermite obtener un puntero directo a los datos a enviarevitando así copias intermedias que <strong>de</strong>gra<strong>de</strong>n elrendimiento. De esta forma, cuando se hace un envío<strong>de</strong> tipos <strong>de</strong> datos primitivos se evita la serialización,que quedaría reservada al envío <strong>de</strong> los restantes objetosJava.B. InfiniBandInfiniBand es una tecnología <strong>de</strong> interconexión entrenodos <strong>de</strong> computación en clusters y dispositivos<strong>de</strong> E/S que permite formar una red <strong>de</strong> área <strong>de</strong> sistemao SAN (System Area Network), que <strong>de</strong>stacaen entornos HPC ya que es actualmente la red máspopular en las primeras 100 posiciones <strong>de</strong>l Top500.<strong>La</strong> arquitectura <strong>de</strong>finida por InfiniBand es in<strong>de</strong>pendiente<strong>de</strong>l sistema operativo y <strong>de</strong> la plataforma. Algunascaracterísticas <strong>de</strong>stacadas <strong>de</strong> InfiniBand sonel acceso directo a memoria remota, conocido comoRDMA (Remote Direct Memory Access), y tambiénel soporte <strong>de</strong> las clásicas operaciones Send/Receive,así como operaciones atómicas, soporte en hardware<strong>de</strong> operaciones multicast y QoS (Quality of Service).Al contrario que en otras especificaciones, la arquitectura<strong>de</strong> InfiniBand no estableció una API<strong>JP2011</strong>-434


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011estándar. En su lugar, <strong>de</strong>fine la funcionalidad quela tarjeta <strong>de</strong> red <strong>de</strong>be proporcionar al sistema operativoen términos <strong>de</strong> la interfaz verbs. Esta interfazespecifica la funcionalidad <strong>de</strong> la capa <strong>de</strong> transporte,siendo su implementación más extendida y utilizadala proporcionada por la OpenFabrics Alliance [11],<strong>de</strong>nominada InfiniBand Verbs API (IBV), un API<strong>de</strong> bajo nivel disponible sólo en C, lo cual fuerza <strong>de</strong>nuevo al uso <strong>de</strong> JNI para implementar un soportedirecto y eficiente <strong>de</strong>l API <strong>de</strong> IBV en Java.Al tratarse IBV <strong>de</strong> una capa inmediatamente porencima <strong>de</strong>l hardware, proporciona operaciones <strong>de</strong>bajo nivel sobre la tarjeta <strong>de</strong> red. <strong>La</strong> semánticarequerida por la API xx<strong>de</strong>v difiere mucho <strong>de</strong> lasemántica ofrecida por IBV, al contrario <strong>de</strong> lo quesucedía con la biblioteca MX. Es por ello que seha <strong>de</strong>sarrollado una biblioteca intermedia en C similara MX utilizando IBV, <strong>de</strong>nominada IBVX, conuna semántica orientada al paso <strong>de</strong> mensajes lo quepermitirá una implementación más fácil <strong>de</strong>s<strong>de</strong> Java,minimizando <strong>de</strong> esta forma el código JNI requerido.C. Biblioteca IBVXIBVX (IBV Express) es la biblioteca en C quehemos <strong>de</strong>sarrollado para comunicaciones eficientesen paso <strong>de</strong> mensajes sobre IBV. El API que ofreceIBVX, presentada en la Figura 2, ofrece primitivas <strong>de</strong>comunicación punto a punto tanto bloqueantes comono bloqueantes, así como comunicaciones síncronas oasíncronas. Así, es posible implementar el API xx<strong>de</strong>v<strong>de</strong> forma más sencilla <strong>de</strong>s<strong>de</strong> Java, que se limitará auna fina capa wrapper sobre IBVX.I B V I n i t ( char ∗∗pNames , int ∗ p orts , int nprocs ,int myRank ) ;I B V F i n a l i z e ( ) ;IBV Isend ( void ∗ buf , int s i z e , int dst , int tag ,int c n txt , Request ∗ r ) ;IBV Isse n d ( void ∗ buf , int s i z e , int dst , int tag ,int c n txt , Request ∗ r ) ;IBV Irecv ( void ∗ buf , int s i z e , int src , int tag ,int c n txt , Request ∗ r ) ;IBV Send ( void ∗ buf , int s i z e , int dst , int tag ,int c n t x t ) ;IBV Ssend ( void ∗ buf , int s i z e , int dst , int tag ,int c n t x t ) ;IBV Recv ( void ∗ buf , int s i z e , int src , int tag ,int c n txt , S t a t u s ∗ s ) ;IBV Wait ( Request ∗ r , S t a t u s ∗ s ) ;IBV Test ( Request ∗ r , S t a t u s ∗ s ) ;IBV Iprobe ( int src , int tag , int c n txt , S t a t u s ∗ s ) ;IBV Probe ( int src , int tag , int c n txt , S t a t u s ∗ s ) ;Request∗ IBV Peek ( ) ;Fig. 2.API <strong>de</strong> la biblioteca IBVXC.1 Protocolos <strong>de</strong> Comunicación en IBVXUsualmente las bibliotecas <strong>de</strong> paso <strong>de</strong> mensajesimplementan internamente dos protocolos <strong>de</strong> comunicación(véase Figura 3):• Eager: se trata <strong>de</strong> un protocolo <strong>de</strong> envío inmediato,<strong>de</strong> manera que el emisor hace el envíosin esperar a que el receptor haya invocadopreviamente su correspondiente recepción, asumiendoque tiene suficiente espacio para almacenarel mensaje, con lo cual no necesita unaautorización explícita <strong>de</strong> envío.• Ren<strong>de</strong>zvous: se trata <strong>de</strong> un protocolo <strong>de</strong> envíoacordado, ya que existe una negociación (handshaking)previa al envío en la que el receptorautoriza al emisor el envío <strong>de</strong>l mensaje, usandopara ello mensajes <strong>de</strong> control.Fig. 3.Protocolos <strong>de</strong> envío en paso <strong>de</strong> mensajesEl ligero sobrecoste <strong>de</strong>bido a la copia <strong>de</strong> los datoscon el protocolo eager es asumible en el caso <strong>de</strong> mensajes<strong>de</strong> pequeño tamaño a fin <strong>de</strong> obtener latenciaslo más reducidas posible. Dicho objetivo coinci<strong>de</strong>con las propieda<strong>de</strong>s <strong>de</strong> las operaciones Send/Receive<strong>de</strong> InfiniBand, utilizadas usualmente en mensajes <strong>de</strong>reducido tamaño. No obstante, el requisito en Infini-Band <strong>de</strong> que todos los bufers usados en las comunicacionesestén registrados, siendo el registro una operacióncostosa, supone una importante penalizaciónen el rendimiento <strong>de</strong> este protocolo que es atajadamediante el uso <strong>de</strong> un pool <strong>de</strong> bufers prerregistradospor proceso para las operaciones <strong>de</strong> envío, a<strong>de</strong>más<strong>de</strong> un pool <strong>de</strong> bufers prerregistrados para las recepcionespor cada proceso con el que se comunica, utilizadospara la copia <strong>de</strong> los datos a enviar/recibir.El protocolo ren<strong>de</strong>zvous es utilizado para el envío<strong>de</strong> mensajes largos, para los cuales es crítico evitarla copia <strong>de</strong> datos, lo que es posible mediante operacionesRemote Direct Memory Access (RDMA)para implementar un protocolo Zero-Copy don<strong>de</strong> seenvíen directamente los datos <strong>de</strong>l búfer origen albúfer <strong>de</strong>stino, sin copias intermedias a los bufers <strong>de</strong>lpool <strong>de</strong> envíos y recepciones. Como para el uso <strong>de</strong>las operaciones RDMA es necesario conocer tanto ladirección <strong>de</strong> memoria <strong>de</strong>stino como la clave remotaque nos permita el acceso a la misma, es necesarioque haya un intercambio <strong>de</strong> estos parámetros previoal envío <strong>de</strong> los datos. Es por ello que se pue<strong>de</strong>aprovechar el handshaking previo al envío <strong>de</strong>l mensajeque contiene los datos que existe en el protocoloren<strong>de</strong>zvous y mediante la operación RDMA Write seescribe el mensaje directamente en la memoria <strong>de</strong>lproceso <strong>de</strong>stino.C.2 Dispositivo en Java sobre IBV: ibv<strong>de</strong>vEl dispositivo Java que implementa la interfazxx<strong>de</strong>v para el soporte <strong>de</strong> InfiniBand se implementa<strong>de</strong> forma análoga al dispositivo omx<strong>de</strong>v. En efecto,la biblioteca IBVX se ha diseñado <strong>de</strong> tal modo quelos métodos <strong>de</strong> ibv<strong>de</strong>v <strong>de</strong>leguen directamente en suscorrespondientes métodos nativos (IBVX).<strong>JP2011</strong>-435


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA IDescripción <strong>de</strong> los clusters utilizados en la evaluación <strong>de</strong>l rendimientoClúster Ubicación Nodos Procesador Memoria RedPlutón Univ. A Coruña 16 2 Intel Xeon E5520 Quad-core 8GB InfiniBand DDR (16 Gbps)Plutón Univ. A Coruña 2 2 Intel Xeon E5440 Quad-core 16GB 10 Gigabit EthernetDAS-4 VU Amsterdam 74 2 Intel Xeon E5620 Quad-core 24 GB InfiniBand QDR (32 Gbps)Marenostrum BSC-CNS 2560 2 IBM PowerPC 970MP Dual-core 8GB Myrinet 2000 (2 Gbps)<strong>La</strong>tencia (µs)8580757065605550454035302520151050Punto a Punto (IB DDR − Plutón)Intel MPI − IBVF−MPJ (ibv<strong>de</strong>v) − IBVMPJE (nio<strong>de</strong>v) − IPoIB14 16 64 256 1K 4K 16K 64K 256K 1M 4M 0111098765432Ancho <strong>de</strong> Banda (Gbps)<strong>La</strong>tencia (µs)302826242220181614121086420Punto a Punto (10GbE − Plutón)Intel MPIF−MPJ (omx<strong>de</strong>v) − MXMPJE (mx<strong>de</strong>v) − MX14 16 64 256 1K 4K 16K 64K 256K 1M 4M 01098765432Ancho <strong>de</strong> Banda (Gbps)Tamaño <strong>de</strong>l Mensaje (bytes)Tamaño <strong>de</strong>l Mensaje (bytes)<strong>La</strong>tencia (µs)6560555045403530252015105Punto a Punto (IB QDR − DAS4)Intel MPI − IBVF−MPJ (ibv<strong>de</strong>v) − IBVMPJE (nio<strong>de</strong>v) − IPoIB204 16 64 256 1K 4K 16K 64K 256K 1M 4M 028262422201816141210864Ancho <strong>de</strong> Banda (Gbps)<strong>La</strong>tencia (µs)363432302826242220181614121086420Punto a Punto (Myrinet 2000 − Marenostrum)MPICH−MXF−MPJ (omx<strong>de</strong>v) − MXMPJE (mx<strong>de</strong>v) − MX0.24 16 64 256 1K 4K 16K 64K 256K 1M 4M 02.221.81.61.41.210.80.60.4Ancho <strong>de</strong> Banda (Gbps)Tamaño <strong>de</strong>l Mensaje (bytes)Tamaño <strong>de</strong>l Mensaje (bytes)Fig. 4.Rendimiento <strong>de</strong> las operaciones punto a punto <strong>de</strong> paso <strong>de</strong> mensajes en re<strong>de</strong>s <strong>de</strong> altas prestacionesIV. Evaluación <strong>de</strong>l RendimientoEl rendimiento <strong>de</strong> los mecanismos <strong>de</strong> comunicación<strong>de</strong>sarrollados ha sido evaluado en cuatro escenarioscon distintas re<strong>de</strong>s <strong>de</strong> interconexión cuyas característicasresumidas se presentan en la Tabla I. <strong>La</strong>sbibliotecas MPJ evaluadas han sido F-MPJ v0.1 yMPJ Express 0.38 en todos los sistemas, mientrasque las bibliotecas MPI utilizadas son Intel MPI version4 [12] en Plutón y DAS-4, y MPICH-MX [7] enel Marenostrum. Los benchmarks utilizados para laevaluación <strong>de</strong> su rendimiento en operaciones puntoa punto y colectivas son los Intel MPI Benchmarkspara MPI, y su versión equivalente para MPJ la cualhemos <strong>de</strong>sarrollado <strong>de</strong>bido a la inexistencia <strong>de</strong> benchmarksa<strong>de</strong>cuados para la evaluación en bibliotecasMPJ.A. Comunicaciones Punto a Punto<strong>La</strong> Figura 4 muestra los resultados <strong>de</strong>l rendimiento<strong>de</strong> las comunicaciones punto a punto en los cuatroescenarios evaluados. Tanto en InfiniBand (QDRy DDR) como en 10 Gigabit Ethernet, los resultadosobtenidos por F-MPJ son muy superiores alos obtenidos por MPJ Express, tanto en términos<strong>de</strong> latencia como en ancho <strong>de</strong> banda, obteniendorendimientos similares a Intel MPI. En Myrinet,F-MPJ sigue obteniendo resultados muy similaresa los <strong>de</strong> la biblioteca MPI, MPICH-MX, aunqueen este caso el margen <strong>de</strong> mejora con respecto aMPJ Express es inferior <strong>de</strong>bido al reducido ancho<strong>de</strong> banda que proporciona la red utilizada (2 Gbps),limitándose al beneficio obtenido a unos 0.5 Gbpsen términos <strong>de</strong> ancho <strong>de</strong> banda en mensajes largos,mientras que para mensajes cortos F-MPJ obtiene lamitad <strong>de</strong> latencia que MPJ Express.B. Comunicaciones Colectivas<strong>La</strong> Figura 5 presenta los resultados <strong>de</strong> rendimientopara las primitivas Broadcast y Allreduce en elclúster Plutón con 128 procesos (IB DDR), sobre elclúster DAS-4 con 512 procesos (IB QDR) y sobreel MareNostrum con 512 procesos (Myrinet 2000).Los datos transferidos son arrays <strong>de</strong> bytes, evitando<strong>de</strong> este modo la serialización ya que pue<strong>de</strong> penalizar<strong>de</strong> forma importante el rendimiento y el objetivo <strong>de</strong>esta evaluación es mostrar el rendimiento <strong>de</strong> las comunicacionescolectivas. <strong>La</strong> métrica utilizada es elancho <strong>de</strong> banda agregado que tiene en cuenta la cantidadtotal <strong>de</strong> información transferida por cada primitiva.Los resultados han sido obtenidos utilizandoel máximo número <strong>de</strong> núcleos disponibles por nodo,8 en el caso <strong>de</strong>l clúster Plutón y el DAS-4, y 4 enel caso <strong>de</strong>l MareNostrum. Los resultados <strong>de</strong> MPJExpress han sido obtenidos únicamente en el clústerPlutón <strong>de</strong>bido a que su runtime presenta problemascon los sistemas <strong>de</strong> colas <strong>de</strong>l DAS-4 y el MareNostrum.En las gráficas <strong>de</strong>l clúster Plutón se observa claramentecomo la mejora obtenida por F-MPJ para lascomunicaciones punto a punto, implementando en el<strong>JP2011</strong>-436


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Ancho <strong>de</strong> Banda Agregado (Gbps)600500400300200100Rendimiento Broadcast 128 Procesos (Plutón)Intel MPI − IBVF−MPJ (ibv<strong>de</strong>v) − IBVMPJE (nio<strong>de</strong>v) − IPoIB01K 4K 16K 64K 256K 1M 4MTamaño <strong>de</strong>l Mensaje (bytes)Ancho <strong>de</strong> Banda Agregado (Gbps)500400300200100Rendimiento Allreduce 128 Procesos (Plutón)Intel MPI − IBVF−MPJ (ibv<strong>de</strong>v) − IBVMPJE (nio<strong>de</strong>v) − IPoIB01K 4K 16K 64K 256K 1M 4MTamaño <strong>de</strong>l Mensaje (bytes)Ancho <strong>de</strong> Banda Agregado (Gbps)2000180016001400120010008006004002000Rendimiento Broadcast 512 Procesos (DAS−4)Intel MPI − IBVF−MPJ (ibv<strong>de</strong>v) − IBV1K 4K 16K 64K 256K 1M 4MTamaño <strong>de</strong>l Mensaje (bytes)Ancho <strong>de</strong> Banda Agregado (Gbps)1200110010009008007006005004003002001000Rendimiento Allreduce 512 Procesos (DAS−4)Intel MPI − IBVF−MPJ (ibv<strong>de</strong>v) − IBV1K 4K 16K 64K 256K 1M 4MTamaño <strong>de</strong>l Mensaje (bytes)Ancho <strong>de</strong> Banda Agregado (Gbps)400300200100Rendimiento Broadcast 512 Procesos (MareNostrum)MPICH−MXF−MPJ (omx<strong>de</strong>v) − MX01K 4K 16K 64K 256K 1M 4MTamaño <strong>de</strong>l Mensaje (bytes)Ancho <strong>de</strong> Banda Agregado (Gbps)500400300200100Rendimiento Allreduce 512 Procesos (MareNostrum)MPICH−MXF−MPJ (omx<strong>de</strong>v) − MX01K 4K 16K 64K 256K 1M 4MTamaño <strong>de</strong>l Mensaje (bytes)Fig. 5.Rendimiento <strong>de</strong> las operaciones colectivas en Plutón, DAS-4 y MareNostrumdispositivo ibv<strong>de</strong>v el soporte eficiente <strong>de</strong> InfiniBand,aumenta significativamente el rendimiento <strong>de</strong> las comunicacionescolectivas en relación a MPJ Express.No obstante, a pesar <strong>de</strong> que el rendimiento <strong>de</strong> lasoperaciones punto a punto <strong>de</strong> F-MPJ es muy similaral <strong>de</strong> Intel MPI, el rendimiento <strong>de</strong> las colectivas <strong>de</strong>MPI supera significativamente (en promedio dobla)el rendimiento <strong>de</strong> las colectivas <strong>de</strong> F-MPJ, a pesar <strong>de</strong>que estas últimas implementan algoritmos altamenteescalables [13]. <strong>La</strong> principal causa <strong>de</strong> esta reducción<strong>de</strong> rendimiento se halla en la mayor variabilidad <strong>de</strong>los tiempos (jitter) en Java, cuyo impacto se multiplicaen las operaciones colectivas implementadas envarios pasos, como por ejemplo en algoritmos basadosen árbol.C. NAS Parallel BenchmarksLos benchmarks NPB (NAS -NASA AdvancedSupercomputing- Parallel Benchmarks) son un conjunto<strong>de</strong> kernels computacionales y aplicaciones, querepresentan las partes con mayor carga computacional<strong>de</strong> simulaciones <strong>de</strong> dinámica <strong>de</strong> fluidos. Estoscódigos fueron utilizados por la NASA para la evaluación<strong>de</strong>l rendimiento en el ámbito <strong>de</strong> sus necesida<strong>de</strong>s<strong>de</strong> supercomputación. En el ámbito Java, seha <strong>de</strong>sarrollado una implementación para paso <strong>de</strong>mensajes en Java <strong>de</strong> los NPB <strong>de</strong>nominada NPB-MPJ [14].<strong>La</strong>s Figura 6 muestra los resultados obtenidos pordos kernels representativos <strong>de</strong> los NPB, CG (ConjugateGradient) y FT (Fourier Transform), parala Clase C en términos <strong>de</strong> MOPS (Millones <strong>de</strong> OperacionesPor Segundo) ejecutados sobre los clustersPlutón, DAS-4 y el MareNostrum. <strong>La</strong>s principalesconclusiones que se pue<strong>de</strong>n extraer <strong>de</strong> estos resultadosson que F-MPJ mejora significativamente elrendimiento <strong>de</strong> MPJ Express, llegando a obtener enPlutón en torno a un 50% <strong>de</strong> mejora para CG y un400% <strong>de</strong> beneficio para FT, gracias a la mayor escalabilidad<strong>de</strong> F-MPJ. Comparando el rendimiento<strong>de</strong> los NPB-MPJ con sus equivalentes en MPI po<strong>de</strong>mosapreciar que los resultados <strong>de</strong> CG son competitivosusando hasta 64 núcleos gracias a obtener resultadosmuy similares en un núcleo, sufriendo unamenor escalabilidad a partir <strong>de</strong> ese punto. En cambio,para FT el rendimiento <strong>de</strong> Java es muy inferioral <strong>de</strong>l código nativo (Fortran) ya que en un núcleoNPB-MPJ FT obtiene 705 MOPS frente a los 1388MOPS <strong>de</strong>l código nativo. Este factor condiciona elrendimiento <strong>de</strong> este benchmark ya que aunque F-MPJ presenta una escalabilidad similar a la <strong>de</strong> IntelMPI los resultados <strong>de</strong>l código Java están en torno ala mitad <strong>de</strong>l rendimiento <strong>de</strong>l FT MPI.V. ConclusionesEl rendimiento y la escalabilidad <strong>de</strong> las comunicacionesson aspectos <strong>de</strong> crucial importancia paralas arquitecturas clúster multi-core, especialmente enpresencia <strong>de</strong> re<strong>de</strong>s <strong>de</strong> baja latencia. Este artículo presentael diseño <strong>de</strong> los mecanismos <strong>de</strong> comunicaciónpara el soporte eficiente <strong>de</strong> re<strong>de</strong>s <strong>de</strong> baja latencia enJava, permitiendo mejorar el rendimiento <strong>de</strong> aplicacionesJava en computación <strong>de</strong> altas prestaciones, unámbito en el que todavía es una opción emergente.<strong>JP2011</strong>-437


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011MOPS20000180001600014000120001000080006000400020000CG Clase C (Plutón)Intel MPI − IBVF−MPJ (ibv<strong>de</strong>v) − IBVMPJE (nio<strong>de</strong>v) − IPoIB1 8 16 32 64 128Número <strong>de</strong> núcleosMOPS50000450004000035000300002500020000150001000050000FT Clase C (Plutón)Intel MPI − IBVF−MPJ (ibv<strong>de</strong>v) − IBVMPJE (nio<strong>de</strong>v) − IPoIB1 8 16 32 64 128Número <strong>de</strong> núcleosMOPS70000600005000040000300002000010000Intel MPI − IBVF−MPJ (ibv<strong>de</strong>v) − IBVCG Clase C (DAS−4)MOPS25000020000015000010000050000Intel MPI − IBVF−MPJ (ibv<strong>de</strong>v) − IBVFT Clase C (DAS−4)016 32 64 128 256 512Número <strong>de</strong> núcleos016 32 64 128 256 512Número <strong>de</strong> núcleos2500020000CG Clase C (MareNostrum)MPICH−MXF−MPJ (omx<strong>de</strong>v) − MX120000100000FT Clase C (MareNostrum)MPICH−MXF−MPJ (omx<strong>de</strong>v) − MXMOPS1500010000MOPS800006000040000500020000016 32 64 128 256 512Número <strong>de</strong> núcleos016 32 64 128 256 512Número <strong>de</strong> núcleosFig. 6.Rendimiento <strong>de</strong> los NPB para los kernels CG y FT en Plutón, DAS-4 y MareNostrumLos dispositivos <strong>de</strong> comunicación a bajo nivel parapaso <strong>de</strong> mensajes implementados son conformes alAPI xx<strong>de</strong>v, lo que ha permitido su integración <strong>de</strong>forma transparente en la biblioteca F-MPJ. <strong>La</strong> evaluaciónexperimental <strong>de</strong> su rendimiento, tanto <strong>de</strong> lascomunicationes punto a punto como <strong>de</strong> las colectivas,así como su impacto en aplicaciones a nivel <strong>de</strong> kernel/aplicaciónha mostrado aumentos significativos<strong>de</strong>l rendimiento. En efecto, se han obtenido mejoras<strong>de</strong> hasta dos ór<strong>de</strong>nes <strong>de</strong> magnitud en comparacióncon soluciones previamente existentes en paso <strong>de</strong>mensajes en Java, llegándose a obtener resultadoscompetitivos en comparación con MPI. Esta evaluaciónse llevó a cabo en escenarios representativos,evaluándose el rendimiento <strong>de</strong> F-MPJ en clusters conlas re<strong>de</strong>s <strong>de</strong> interconexión InfiniBand DDR y QDR,10 Gigabit Ethernet y Myrinet.Agra<strong>de</strong>cimientosEste trabajo ha sido financiado por el Ministerio<strong>de</strong> Ciencia e Innovación <strong>de</strong> España en el marco<strong>de</strong>l proyecto TIN2010-16735 y por el Programa <strong>de</strong>Consolidación y Estructuración <strong>de</strong> Unida<strong>de</strong>s <strong>de</strong> InvestigaciónCompetitivas <strong>de</strong> la Consellería <strong>de</strong> Educación<strong>de</strong> la Xunta <strong>de</strong> Galicia. Agra<strong>de</strong>cemos alBarcelona Supercomputing Center (BSC-CNS) el accesoal MareNostrum. We also gratefully thank AdvancedSchool for Computing and Imaging (ASCI) ofthe Vrije University Amsterdam for providing accessto the DAS-4 cluster.Referencias[1] G.L. Taboada, J. Touriño, and R. Doallo, “Java forHigh Performance Computing: Assessment of CurrentResearch and Practice,” in Proc. 7th Intl. Conf. onthe Principles and Practice of Programming in Java(PPPJ’09), Calgary, Alberta, Canada, 2009, pp. 30–39.[2] G.L. Taboada, J. Touriño, and R. Doallo, “F-MPJ: ScalableJava Message-passing Communications on ParallelSystems,” Journal of Supercomputing, 2011 (In press,http://dx.doi.org/10.1007/s11227-009-0270-0).[3] A. Shafi, B. Carpenter, and M. Baker, “Nested Parallelismfor Multi-core HPC Systems using Java,” Journalof Parallel and Distributed Computing, vol. 69, no. 6, pp.532–545, 2009.[4] “MPICH2,” http://www.mcs.anl.gov/research/projects/mpich2.[5] “Open Source High Performance MPI Library,” http://www.open-mpi.org.[6] M. Baker, B. Carpenter, and A. Shafi, “A Buffering <strong>La</strong>yerto Support Derived Types and Proprietary Networks forJava HPC,” Scalable Computing Practice and Experience,vol. 8, no. 4, pp. 343–358, 2007.[7] “Myricom Website,” http://www.myri.com.[8] “MX User’s Gui<strong>de</strong>,” http://www.myri.com/scs/MX/doc/mx.pdf.[9] “Top 500,” http://www.top500.org.[10] B. Goglin, “High-Performance Message Passing overGeneric Ethernet Hardware with Open-MX,” ParallelComputing, vol. 37, no. 2, pp. 85–100, 2011.[11] “OpenFabrics Alliance Website,” http://www.openfabrics.org.[12] “Intel R○ MPI Library,” http://www.intel.com/go/mpi.[13] G.L. Taboada, S. Ramos, J. Touriño, and R. Doallo,“Design of Efficient Java Message-passing Collectives onMulti-core Clusters,” Journal of Supercomputing, vol.55, no. 2, pp. 126–154, 2011.[14] D.A. Mallón, G.L. Taboada, J. Touriño, and R. Doallo,“NPB-MPJ: NAS Parallel Benchmarks Implementationfor Message-Passing in Java,” in Proc. 17th EuromicroIntl. Conf. on Parallel, Distributed, and Network-BasedProcessing (PDP’09), Weimar, Germany, 2009, pp. 181–190.<strong>JP2011</strong>-438


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Comunicaciones Escalables en MemoriaCompartida para Paso <strong>de</strong> Mensajes en JavaSabela Ramos, Guillermo L. Taboada, Juan Touriño, Ramón Doallo 1Resumen— Este artículo presenta el middleware <strong>de</strong>comunicaciones en memoria compartida smp<strong>de</strong>v, integradoen nuestra implementación <strong>de</strong> paso <strong>de</strong> mensajesen Java, Fast MPJ (F-MPJ). El continuo aumento<strong>de</strong>l número <strong>de</strong> núcleos por procesador pone <strong>de</strong> manifiestola necesidad <strong>de</strong> un soporte eficiente <strong>de</strong> comunicacionespara programación paralela no sólo a nivel<strong>de</strong> clúster, sino que optimice también las comunicacionesintra-nodo. Sin embargo, el aprovechamientoeficiente <strong>de</strong>l potencial <strong>de</strong> los procesadores multinúcleomediante el uso <strong>de</strong> threads en Java requiere un importanteesfuerzo por parte <strong>de</strong>l programador, mientrasque smp<strong>de</strong>v permite trabajar con un mayor nivel<strong>de</strong> abstracción utilizando un API <strong>de</strong> comunicacionesmediante paso <strong>de</strong> mensajes, simple, pero a la vez potente.A<strong>de</strong>más, el paso <strong>de</strong> mensajes no está limitado asistemas <strong>de</strong> memoria compartida, lo que permite explotarmás eficientemente los recursos hardware. Enefecto, smp<strong>de</strong>v permite sustituir el uso <strong>de</strong> procesos yprotocolos <strong>de</strong> comunicaciones en red por threads ytransferencias en memoria compartida. <strong>La</strong> evaluación<strong>de</strong>l rendimiento <strong>de</strong> smp<strong>de</strong>v muestra un incremento <strong>de</strong>prestaciones con respecto a soluciones similares enJava para paso <strong>de</strong> mensajes en memoria compartida,con un rendimiento próximo al obtenido con lenguajescompilados a código nativo (e.g., C o Fortran),llegando a superarlos en algunos casos.Palabras clave— Paso <strong>de</strong> Mensajes en Java (MPJ),Memoria Compartida, Arquitecturas Multinúcleo,Computación <strong>de</strong> Altas Prestaciones (HPC), Evaluación<strong>de</strong>l RendimientoI. IntroducciónJAVA es una alternativa emergente en Computación<strong>de</strong> Altas Prestaciones [1] (HPC) a pesar<strong>de</strong> que en sus inicios fue especialmente criticadopor su bajo rendimiento computacional [2]. Sin embargo,hoy en día, y gracias a los avances en la tecnología<strong>de</strong> la máquina virtual <strong>de</strong> Java (JVM) y a lacompilación Just-In-Time (JIT), capaces <strong>de</strong> generarcódigo nativo eficiente a partir <strong>de</strong>l byteco<strong>de</strong> in<strong>de</strong>pendiente<strong>de</strong> la plataforma, el rendimiento <strong>de</strong> Javaes tan solo un 30% inferior al <strong>de</strong> los lenguajes compiladosa código nativo (e.g., C o Fortran) [1] [3].A<strong>de</strong>más, Java proporciona algunas características interesantespara programación paralela como son uncompleto soporte multithread y <strong>de</strong> comunicacionesen red, manejo automático <strong>de</strong> memoria, in<strong>de</strong>pen<strong>de</strong>ncia<strong>de</strong> la plataforma, portabilidad, seguridad, orientacióna objetos, un API extenso y una amplia comunidad<strong>de</strong> <strong>de</strong>sarrolladores, siendo el lenguaje másusado en los ámbitos académico y empresarial<strong>La</strong> opción preferida a la hora <strong>de</strong> programar clusterses el paradigma <strong>de</strong> paso <strong>de</strong> mensajes <strong>de</strong>bido a suescalabilidad y relativo buen rendimiento. No obstante,en Java esta opción no suele aprovechar el1 Grupo <strong>de</strong> Arquitectura <strong>de</strong> Computadores, Dpto. <strong>de</strong>Electrónica y Sistemas, <strong>Universidad</strong>e <strong>de</strong> A Coruña, e-mail:{sramos, taboada, juan, doallo}@udc.esmultithreading para intercambiar mensajes mediantetransferencias en memoria compartida, evitando queprocesos <strong>de</strong>l mismo nodo utilicen protocolos <strong>de</strong> comunicaciónen red. Esta situación resulta crítica conel aumento <strong>de</strong>l número <strong>de</strong> núcleos por procesador,que hace crecer la <strong>de</strong>manda <strong>de</strong> soluciones escalables<strong>de</strong> programación paralela para memoria compartida.El multithreading <strong>de</strong> Java permite aprovechar elpotencial <strong>de</strong> las arquitecturas <strong>de</strong> memoria compartidaa costa <strong>de</strong> incrementar la complejidad <strong>de</strong> programación,ya que es el programador el que tieneque gestionar los threads, tareas y el acceso y mantenimiento<strong>de</strong> estructuras compartidas <strong>de</strong> datos. Eneste artículo presentamos un dispositivo <strong>de</strong> comunicacionesen memoria compartida que, <strong>de</strong> forma mássencilla y a más alto nivel, explota el multithreadingproporcionando una interfaz <strong>de</strong> paso <strong>de</strong> mensajes.A<strong>de</strong>más, se integra en una biblioteca <strong>de</strong> paso<strong>de</strong> mensajes <strong>de</strong> manera que el uso <strong>de</strong> un dispositivo<strong>de</strong> memoria compartida o distribuida es transparenteal usuario, aumentando así la portabilidad <strong>de</strong>l código<strong>de</strong>sarrollado.<strong>La</strong> estructura <strong>de</strong>l artículo es la siguiente: laSección II <strong>de</strong>scribe soluciones existentes para programaciónparalela en memoria compartida. <strong>La</strong>Sección III se centra en el diseño e implementación<strong>de</strong>l dispositivo smp<strong>de</strong>v. <strong>La</strong> Sección IV presenta unaevaluación <strong>de</strong>l rendimiento comparando smp<strong>de</strong>v conotro dispositivo <strong>de</strong> memoria compartida para paso<strong>de</strong> mensajes en Java, Java threads y con bibliotecasnativas MPI y OpenMP. Finalmente, la Sección V resumelas principales aportaciones y conclusiones <strong>de</strong>este trabajo.II. Proyectos RelacionadosEl paso <strong>de</strong> mensajes es el paradigma <strong>de</strong> programaciónparalela más ampliamente difundido. Enlenguajes nativos, como C y Fortran, existen distintasbibliotecas que implementan la interfaz estándarMPI y están mayoritariamente optimizadas para sistemas<strong>de</strong> memoria distribuida. No obstante, el aumento<strong>de</strong>l número <strong>de</strong> núcleos por procesador ha idofavoreciendo el <strong>de</strong>sarrollo <strong>de</strong> soluciones orientadas aaprovechar las arquitecturas <strong>de</strong> memoria compartidaempleando paso <strong>de</strong> mensajes. Destaca el proyectoMPICH2 [4] que incluye varios dispositivos <strong>de</strong> comunicaciónque explotan el uso <strong>de</strong> memoria compartidacomo ssm, shm o sshm. También incorpora un subsistema<strong>de</strong> comunicaciones, <strong>de</strong>nominado Nemesis [5],que optimiza los dispositivos orientados a memoriadistribuida para mejorar el rendimiento y la escalabilidad<strong>de</strong> los mismos en arquitecturas <strong>de</strong> memoriacompartida.<strong>JP2011</strong>-439


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Otra aproximación a la hora <strong>de</strong> sacar partido alos procesadores multinúcleo es utilizar OpenMP oPOSIX threads (pthreads), aunque su carencia <strong>de</strong>soporte para memoria distribuida limita las aplicacionesa sistemas <strong>de</strong> memoria compartida. Existen,no obstante, soluciones para ejecutar códigoOpenMP en sistemas <strong>de</strong> memoria distribuida peroque, o bien se basan en traductores que obtienencódigo MPI a partir <strong>de</strong> directivas OpenMP, o bien seejecutan en sistemas <strong>de</strong> Memoria Distribuida Compartidao DSM’s [6] [7].<strong>La</strong>s principales implementaciones en Java <strong>de</strong> interfacessimilares a OpenMP son JOMP [8] y JaMP [9].Ambos sistemas son 100% Java y están basados enthreads, con la diferencia <strong>de</strong> que el segundo empleautilida<strong>de</strong>s <strong>de</strong> concurrencia, superando ciertos problemas<strong>de</strong> eficiencia <strong>de</strong> JOMP. JaMP forma parte <strong>de</strong>Jackal [10], una máquina virtual <strong>de</strong> Java <strong>de</strong> memoriacompartida-distribuida (Java Distributed SharedMemory, DSM) y su principal problema es la falta<strong>de</strong> portabilidad.El soporte a comunicaciones en red y multithreading<strong>de</strong> Java lo convierten en una opción interesantepara la programación <strong>de</strong> arquitecturas <strong>de</strong> memoriacompartida. No obstante, el uso <strong>de</strong>l API <strong>de</strong> threads ylas herramientas <strong>de</strong> concurrencia exigen conocimientos<strong>de</strong> programación a bajo nivel y concurrencia, ylos códigos <strong>de</strong>sarrollados no sirven para ejecutarseen entornos <strong>de</strong> memoria distribuida. El proyectoParallel Java (PJ) [11] proporciona varias abstraccionessobre estas utilida<strong>de</strong>s <strong>de</strong> concurrencia, implementandotambién el paradigma <strong>de</strong> paso <strong>de</strong> mensajespara memoria distribuida proporcionando una interfazpropia.A. Paso <strong>de</strong> Mensajes en Java (MPJ)En cuanto al paso <strong>de</strong> mensajes en Java (MPJ) [1],los proyectos más relevantes en términos <strong>de</strong> adopciónpor parte <strong>de</strong> la comunidad HPC son mpiJava [12],MPJ Express [13]y F-MPJ [14].<strong>La</strong> biblioteca mpiJava [12] es un wrapper a MPIque proporciona comunicaciones eficientes sobre unabiblioteca nativa, por lo que podría utilizar optimizaciones<strong>de</strong> MPI para memoria compartida. Sin embargo,presenta problemas <strong>de</strong> inestabilidad <strong>de</strong>rivados<strong>de</strong>l wrapping y es incapaz <strong>de</strong> aprovechar los sistemasmultinúcleo a través <strong>de</strong> multithreading <strong>de</strong>bido a queno es thread-safe.MPJ Express [13] es una implementación MPJ100% Java. Este proyecto es actualmente el más activoen cuanto a adopción por la comunidad HPC,documentación disponible y presencia en entornosacadémicos y <strong>de</strong> producción. MPJ Express es threadsafey tiene un diseño modular, incluyendo una arquitecturaconfigurable <strong>de</strong> dispositivos <strong>de</strong> comunicaciónque permite combinar la portabilidad <strong>de</strong> los dispositivos100% Java (<strong>de</strong> memoria compartida y usando elpaquete New IO, Java NIO) con el alto rendimiento<strong>de</strong>l soporte a Myrinet (a través <strong>de</strong> la biblioteca nativa<strong>de</strong> comunicaciones Myrinet eXpress, MX). A<strong>de</strong>más,incluye un dispositivo multithread <strong>de</strong> memoria compartida[15].Nuestra implementación MPJ, Fast MPJ (F-MPJ) [14] proporciona soporte a re<strong>de</strong>s <strong>de</strong> altasprestaciones <strong>de</strong> forma directa. F-MPJ incluye unabiblioteca <strong>de</strong> colectivas MPJ escalables [16]. El middlewarepresentado en este artículo, smp<strong>de</strong>v se haintegrado en F-MPJ y las principales diferencias quepresenta con respecto a la implementación <strong>de</strong>l dispositivomultithread <strong>de</strong> memoria compartida <strong>de</strong> MPJExpress están el manejo <strong>de</strong> colas y el buffering.III. Dispositivo <strong>de</strong> Comunicación Eficienteen Memoria Compartida: smp<strong>de</strong>vA. Dispositivos <strong>de</strong> Comunicación en F-MPJEl uso <strong>de</strong> dispositivos configurables <strong>de</strong> comunicacionesa bajo nivel para soporte a re<strong>de</strong>s <strong>de</strong>altas prestaciones está ampliamente extendido enlas bibliotecas nativas <strong>de</strong> paso <strong>de</strong> mensajes comoMPICH2. Asimismo, MPJ Express y F-MPJtambién proporcionan diferentes dispositivos <strong>de</strong> comunicacionespara distintas tecnologías <strong>de</strong> intercomunicación.Los dispositivos <strong>de</strong> F-MPJ siguen el APIxx<strong>de</strong>v [14] (ver Figura 1), que evita el buffering<strong>de</strong> datos soportando envíos/recepciones directos <strong>de</strong>cualquier objeto serializable, al contrario que x<strong>de</strong>v,el API extendida por xx<strong>de</strong>v y adoptada por MPJExpress, que opera sobre una capa propia <strong>de</strong> buffering.El API xx<strong>de</strong>v está compuesto por operacionesbásicas como las comunicaciones punto a punto bloqueantes(send, recv) y no bloqueantes (isend, irecv),e incluye comunicaciones síncronas (ssend, issend).No maneja abstracciones <strong>de</strong> paso <strong>de</strong> mensajes <strong>de</strong> altonivel como grupos y comunicadores y, por ello, utilizaProcessID en lugar <strong>de</strong> rangos, pues el objetoProcessID i<strong>de</strong>ntifica unívocamente a un elemento<strong>de</strong>l dispositivo.public abstract class Device {static public Device newInstance(String <strong>de</strong>viceImpl);public int[] init(String[] args);public int id();public void finish();public Request isend(Object buf,int dst,int tag);public Request irecv(Object buf,int src,int tag,Status stts);public void send(Object buf,int dst,int tag);public Status recv(Object buf,int src,int tag);public Request issend(Object buf,int dst,int tag);public void ssend(Object buf,int dst,int tag);public Status iprobe(int src,int tag,int context);public Status probe(int src,int tag,int context);public Request peek();}Fig. 1.API of the xx<strong>de</strong>v.Device class<strong>La</strong> Figura 2 muestra los dispositivos <strong>de</strong> comunicacionesincluidos en F-MPJ. Actualmente, estosestán implementados sobre capas nativas <strong>de</strong> comunicacionesaccedidas mediante JNI, como Open-MX<strong>JP2011</strong>-440


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011(omx<strong>de</strong>v) e InfiniBand Verbs (IBV, ibv<strong>de</strong>v), y socketssobre la pila TCP/IP (io<strong>de</strong>v y nio<strong>de</strong>v), a<strong>de</strong>más<strong>de</strong>l que se presenta en este artículo, smp<strong>de</strong>v, implementadomediante threads Java.B. Implementación <strong>de</strong> smp<strong>de</strong>vEl dispositivo multithread <strong>de</strong> F-MPJ, smp<strong>de</strong>v, utilizathreads Java para ejecutar procesos MPJ, lo cualpermite aprovechar las transferencias <strong>de</strong> datos enmemoria compartida para llevar a cabo las comunicacionespunto a punto.B.1 Cargadores <strong>de</strong> ClaseEl uso <strong>de</strong> threads requiere el aislamiento <strong>de</strong>l espacio<strong>de</strong> nombres para cada thread en ejecución, <strong>de</strong>jantouna zona compartida en la que puedan llevara cabo el intercambio <strong>de</strong> mensajes. Este manejo sebasa en la implementación <strong>de</strong> un cargador <strong>de</strong> clase amedida tal y como se hace en MPJ Express [15].Po<strong>de</strong>mos establecer dos grupos <strong>de</strong> clases atendiendoa las necesida<strong>de</strong>s <strong>de</strong> aislamiento <strong>de</strong> las mismas.<strong>La</strong>s clases <strong>de</strong> la aplicación <strong>de</strong>l usuario y las clases<strong>de</strong> más alto nivel <strong>de</strong> la biblioteca, así como algunarelacionada con la gestión <strong>de</strong>l dispositivo, tienen queestar aisladas para proporcionar la abstracción <strong>de</strong>procesos MPJ sobre threads. <strong>La</strong>s variables estáticas<strong>de</strong> esas clases, por tanto, no <strong>de</strong>ben compartirse entrelos distintos threads. Sin embargo, es necesario ungrupo <strong>de</strong> clases compartidas que permitan la comunicaciónmediante transferencias en memoria compartida.Una máquina virtual <strong>de</strong> Java (JVM) i<strong>de</strong>ntificacada clase cargada por su nombre cualificado completoy su cargador <strong>de</strong> clase, haciendo, pues, que cadacargador <strong>de</strong>fina su propio espacio <strong>de</strong> nombres. Paraaislar a los threads, cada uno <strong>de</strong> ellos es creado pormedio <strong>de</strong> cargador <strong>de</strong> clase propio y a medida, elcual gestionará las clases no compartidas. <strong>La</strong> JVMhace uso <strong>de</strong> una jerarquía <strong>de</strong> cargadores en la que elprimero al que se recurre es el que existe por <strong>de</strong>fectoen el sistema, por lo que éste cargará todas las clasesque tenga a su alcance. Esto implica que <strong>de</strong>bemoslimitar su Classpath <strong>de</strong> forma que sólo tenga accesoa los paquetes compartidos. Así, cuando el cargador<strong>de</strong>l sistema no sea capaz <strong>de</strong> encontrar una clase, laJVM acudirá al cargador a medida <strong>de</strong> cada thread.B.2 Colas <strong>de</strong> Mensajes<strong>La</strong>s operaciones <strong>de</strong> comunicaciones punto a punto<strong>de</strong>legan en clases compartidas que manejan colas <strong>de</strong>mensajes pendientes para gestionar los envíos y lasrecepciones. A cada thread se le asignan dos colas,una para los mensajes recibidos y otra para los queespera recibir pero todavía no han llegado.El acceso a cada par <strong>de</strong> colas está sincronizadopara evitar inconsistencias. Cuando un thread envíaun mensaje chequea si hay alguna petición <strong>de</strong> recepciónen la cola <strong>de</strong>l thread <strong>de</strong>stino. Si encuentrauna coinci<strong>de</strong>ncia, copia el mensaje en su <strong>de</strong>stino y lapetición se marca como completada. Cuando no hayninguna coinci<strong>de</strong>ncia, inserta una petición en la cola<strong>de</strong> enviados. Dependiendo <strong>de</strong>l protocolo <strong>de</strong> envío, elemisor copiará o <strong>de</strong>jará una referencia a su propiomensaje. El proceso <strong>de</strong> recepción sigue este algoritmopero a la inversa. El receptor comprueba sucola y, si hay alguna petición <strong>de</strong> envío coinci<strong>de</strong>nte,completa la comunicación, si no, encola una petición<strong>de</strong> recepción.<strong>La</strong> Figura 3 muestra, <strong>de</strong> forma gráfica, un ejemplo<strong>de</strong> cómo se llevarían a cabo un par <strong>de</strong> comunicaciones.En la imagen superior, el Thread 0 envía elmensaje <strong>de</strong> forma previa a que el <strong>de</strong>stino haya solicitadola recepción por lo que <strong>de</strong>ja en la cola unapetición <strong>de</strong> envío. Es el receptor el que obtiene lapetición y copia el mensaje cuando recibe. En la inferior,el receptor inicia la comunicación y es el emisorel que encontrará la petición en la cola y completarála comunicación. Los números <strong>de</strong> secuencia indicanel or<strong>de</strong>n en el que se realiza cada acción. En todoslos casos, la i<strong>de</strong>ntificación <strong>de</strong>l mensaje se realiza através <strong>de</strong> la i<strong>de</strong>ntificación <strong>de</strong>l emisor, una etiqueta<strong>de</strong> usuario y un contexto que maneja el dispositivo.Send (data)Thread 0data1iddataSend (data)Thread 0dataUnexpectedRecvQueue4PostedRecvQueueUnexpectedRecvQueuePostedRecvQueueiddataUnexpectedRecvQueueiddata53PostedRecvQueueX2??PostedRecvQueue6UnexpectedRecvQueueX ? 13id6 52?4idid7Recv (data)Thread 1Recv (data)Thread 1Fig. 3. Shared memory queues for communications in smp<strong>de</strong>v.Todo envío <strong>de</strong> mensaje ha <strong>de</strong> recurrir a serializaciónexcepto cuando se trata <strong>de</strong> arrays <strong>de</strong> tiposprimitivos. Esto es <strong>de</strong>bido a que es Serializablees una interfaz más extensamente cumplida queCloneable y que presenta conflictos menores conla estructura <strong>de</strong> cargadores <strong>de</strong> clase. Así, el objetoa enviar es serializado utilizando el cargador<strong>de</strong> clase local <strong>de</strong>l emisor, pero si la <strong>de</strong>serializaciónse hace mediante la función ObjectInputStream<strong>de</strong>l JDK, que usa el cargador <strong>de</strong>l sistema por <strong>de</strong>fecto,la JVM consi<strong>de</strong>ra que el objeto <strong>de</strong>serializadoes una instancia <strong>de</strong> una clase diferente y lanza laexcepción ClassNotFoundException. Para superaresta limitación, se usa una clase <strong>de</strong>sarrollada a medidaque sobreescribe el método resolveClass() <strong>de</strong>ObjectInputStream [15], obteniendo el cargador localal thread y usándolo para cargar la clase mediante<strong>JP2011</strong>-441


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011MPJ ApplicationsF−MPJ Library<strong>de</strong>vice layeromx<strong>de</strong>vibv<strong>de</strong>vnio<strong>de</strong>v/io<strong>de</strong>vsmp<strong>de</strong>vJVMJNIJava SocketsJava Threadsnative commsOpen−MXIBVTCP/IPMyrinet/EthernetInfiniBandEthernetShared MemoryFig. 2.F-MPJ communication <strong>de</strong>vices on shared memory and cluster networksel método Class.forName(). Para que esta aproximaciónfuncione, es necesario tener en cuenta quela ejecución <strong>de</strong> la <strong>de</strong>serialización tiene que llevarsea cabo en el thread local, es <strong>de</strong>cir, en el receptor.Esto es relevante para las comunicaciones no bloqueantes,en las que cualquiera <strong>de</strong> los threads queestá esperando a que se complete pue<strong>de</strong> hacer la comunicaciónefectiva.IV. Evaluación <strong>de</strong>l RendimientoA. Configuración ExperimentalEn esta evaluación se han utilizado dos máquinas.<strong>La</strong> primera <strong>de</strong> ellas (“Nehalem”) cuenta con 2 procesadoresIntel Xeon E5520 quad-core Nehalem y 8Gbytes <strong>de</strong> RAM, con Sistema Operativo Linux CentOS5.3 y la JVM Sun JDK 1.6.0 23. <strong>La</strong> segunda(“Magny Cours”) es una máquina con 4 procesadoresAMD “Magny Cours”, cada uno con 12 núcleos (48núcleos en total) y 128 Gbytes <strong>de</strong> RAM. El SistemaOperativo es Linux CentOS 5.5, y la JVM Sun JDK1.6.0 05.<strong>La</strong>s implementaciones MPJ evaluadas son F-MPJ(release interna) y MPJ Express versión 0.38, a<strong>de</strong>más<strong>de</strong> las bibliotecas Intel MPI v.4.0.0.028 (usado enmáquina “Magny Cours”), OpenMPI v1.4.2 (en“Magny Cours”) y v1.3.3 (en “Nehalem”), y MVA-PICH2 r3510 (en “Nehalem”). Para OpenMP se hausado el compilador gcc v.4.3.4.B. Micro-benchmarking <strong>de</strong> Primitivas Punto aPuntoEl micro-benchmarking en Java se ha llevado acabo con nuestra propia suite, similar a los Intel MPIBenchmarks (IMB) utilizados para bibliotecas MPI,<strong>de</strong>bido a la falta <strong>de</strong> una suite <strong>de</strong> benchmarking a<strong>de</strong>cuadapara MPJ.<strong>La</strong> Figura 4 presenta el rendimiento <strong>de</strong> un benchmark<strong>de</strong> PingPong entre dos procesos/threads <strong>de</strong>ntro<strong>de</strong> un mismo nodo mostrando la latencia para mensajes<strong>de</strong> tamaño inferior a un Kbyte y el ancho <strong>de</strong>banda para mensajes mayores. Para la transferencia<strong>de</strong> datos se han utilizado arrays <strong>de</strong> bytes evitando elcoste <strong>de</strong> la serialización <strong>de</strong> objetos. <strong>La</strong>s opciones medidasson F-MPJ y MPJ Express con sus respectivosdispositivos smp<strong>de</strong>v y las distintas implementacionesMPI utilizando su soporte para memoria compartida.Tal y como se ve en las gráficas, la latencia <strong>de</strong>MPJ Express es bastante superior a la <strong>de</strong> las <strong>de</strong>másopciones, todas por <strong>de</strong>bajo <strong>de</strong> los 5 µs. En cuantoal ancho <strong>de</strong> banda, también se queda por <strong>de</strong>bajo,<strong>La</strong>tency (µs)Point-to-Point Java Communication Performance (Nehalem)8024F-MPJ (smp<strong>de</strong>v)MPJE (smp<strong>de</strong>v)7522MVAPICH27020OpenMPI6560185516501445124035103082562041510201 4 16 64 256 1K 4K 16K 64K 256K 1M 4M516M 0Message Size (Bytes)Point-to-point Java Communication Performance (Magny Cours)<strong>La</strong>tency (µs)4540F-MPJ (smp<strong>de</strong>v)MPJE (smp<strong>de</strong>v)IntelMPI 435242230201825162014121510810654204 16 64 256 1K 4K 16K 64K 256K 1M 4M 16M 0Message size (Bytes)Fig. 4. Message-passing point-to-point performance on sharedmemory.302826mientras que el dispositivo <strong>de</strong> memoria compartidapresentado en este artículo supera ampliamente elrendimiento <strong>de</strong> todas las <strong>de</strong>más. Esto es así porqueestá optimizado para que el intercambio <strong>de</strong> mensajesentre threads se realice mediante copias <strong>de</strong> arrays,aprovechando <strong>de</strong> este modo la arquitectura <strong>de</strong> memoriacompartida. <strong>La</strong> diferencia <strong>de</strong> ancho <strong>de</strong> banda entrediferentes procesadores se <strong>de</strong>be a la arquitectura<strong>de</strong>l procesador y a la asignación <strong>de</strong> threads a cores,ya que hay una probabilidad bastante elevada <strong>de</strong> quese ejecuten en núcleos <strong>de</strong> distintos procesadores <strong>de</strong>ntro<strong>de</strong>l mismo nodo. <strong>La</strong> pérdida <strong>de</strong> rendimiento apartir <strong>de</strong> 1 Mbyte con 8 núcleos, o <strong>de</strong> 256 Kbytescon 48, se pue<strong>de</strong> superar mediante la segmentación<strong>de</strong> mensajes lo cual permite incrementar la localidad<strong>de</strong> los datos.C. Micro-benchmarking <strong>de</strong> Primitivas Colectivas<strong>La</strong> Figura 5 presenta el ancho <strong>de</strong> banda agregado<strong>de</strong> una operación collectiva representativa (broadcast)utilizando todos los núcleos disponibles en “Nehalem”(8) y “Magny Cours” (48). <strong>La</strong> selección <strong>de</strong>lBandwidth (Gbps)Bandwidth (Gbps)<strong>JP2011</strong>-442


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011ancho <strong>de</strong> banda agregado como métrica es <strong>de</strong>bido aque tiene en cuenta la cantidad global <strong>de</strong> datos transferidos.No obstante, no hay resultados <strong>de</strong> MPI paratamaños superiores a 4 Mbytes <strong>de</strong>bido a limitaciones<strong>de</strong> la suite <strong>de</strong> benchmarking (IMB).Aggregated Bandwidth (Gbps)Aggregated Bandwidth (Gbps)Fig. 5.20018016014012010080604020F−MPJ (smp<strong>de</strong>v)MPJE (smp<strong>de</strong>v)MVAPICH2OpenMPIBroadcast on Nehalem (8 cores)01K 4K 16K 64K 256K 1M 4M 16MMessage Size (Bytes)8070605040302010Broadcast on Magny Cours (48 Cores)F−MPJ (smp<strong>de</strong>v)MPJE (smp<strong>de</strong>v)IntelMPI 401K 4K 16K 64K 256K 1M 4M 16MMessage Size (Bytes)Message-passing broadcast primitive performanceLos resultados <strong>de</strong> F-MPJ superan ampliamente alos obtenidos con MPJ Express, gracias a que se evitael uso <strong>de</strong> buffering y a la optimización <strong>de</strong> las operacionescolectivas mediante algoritmos específicos [16].En la comparación con MPI, el resultado es más irregular.En “Nehalem” la implementación <strong>de</strong>l broadcastutiliza copias directas <strong>de</strong>l mensaje a transmitir(“pull”), obteniendo elevados anchos <strong>de</strong> banda, llegandoa superar significativamente el rendimiento <strong>de</strong>MPI. En “Magny Cours” se utiliza otro tipo <strong>de</strong> algoritmobasado en árbol que elimina el cuello <strong>de</strong> botellaen el acceso al thread raíz (el que tiene el mensajea transmitir), balanceando <strong>de</strong> este modo la carga <strong>de</strong>comunicaciones. En este caso, se supera el ancho <strong>de</strong>banda <strong>de</strong> MPI con mensajes mayores <strong>de</strong> 4 Kbytes,siendo en general mayor el beneficio <strong>de</strong> F-MPJ conmensajes gran<strong>de</strong>s y el <strong>de</strong> MPI con tamaños <strong>de</strong> mensajepequeños.D. Impacto en el Rendimiento <strong>de</strong> KernelsEl impacto <strong>de</strong> smp<strong>de</strong>v en la escalabilidad <strong>de</strong> aplicacionesreales ha sido analizado con los NAS ParallelBenchmarks (NPB), seleccionados por ser losmás utilizados en la evaluación <strong>de</strong> lenguajes, bibliotecasy middleware para HPC. Existen implementacionespara MPI, OpenMP, códigos híbridosMPI/OpenMP y para MPJ (NPB-MPJ) [17]. Dentro<strong>de</strong> los NPB, se han seleccionado CG (ConjugateGradient), FT (Fourier Transform), IS (Integer Sort)y MG (Multi-Grid), y, a<strong>de</strong>más <strong>de</strong> las opciones presentadasen los otros apartados, se han recogido resultadospara OpenMP y Java threads. Los resultadosse han obtenido en el sistema “Magny Cours”utilizando hasta 32 núcleos (los benchmarks necesitanun número <strong>de</strong> threads/procesos que sea potencia<strong>de</strong> 2), y se muestran en términos <strong>de</strong> speedup en laFigura 6 con el objetivo <strong>de</strong> evaluar su escalabilidad.En la Tabla I se incluyen los resultados en millones<strong>de</strong> operaciones por segundo (MOPS) obtenido en unnúcleo para Java y C/Fortran, a efectos <strong>de</strong> compararsu rendimiento en términos absolutos. Con el dispositivo<strong>de</strong> memoria compartida <strong>de</strong> MPJ Express no sehan podido obtener datos para FT y MG <strong>de</strong>bido aque los tamaños <strong>de</strong> mensaje excedían lo permitidopor sus buffers.TABLA INPB performance (in MOPS) on one coreCG FT IS MGJava 224.069 461.850 42.826 530.351C/Fortran 201.31 711.38 58.61 847.59El principal problema <strong>de</strong> escalabilidad <strong>de</strong>l dispositivo<strong>de</strong>sarrollado se encuentra en MG, don<strong>de</strong> presentauna escalabilidad significativamente inferior ala <strong>de</strong> MPI. Sin embargo, en los restantes benchmarksse obtiene un resultado similar al <strong>de</strong> MPI, aunqueen FT se obtenga una escalabilidad algo menor enJava, y en IS con 32 núcleos. No obstante, tantoen términos <strong>de</strong> escalabilidad como <strong>de</strong> rendimientoen términos absolutos <strong>de</strong> MPI y F-MPJ son comparables,lo cual pone <strong>de</strong> manifiesto que el paso<strong>de</strong> mensajes en Java pue<strong>de</strong> conseguir resultados eficientesque ayu<strong>de</strong>n a superar la tradicional diferencia<strong>de</strong> rendimiento entre Java y los lenguajes nativos.OpenMP presenta una escalabilidad similar a MPIen CG y FT, quedándose por <strong>de</strong>bajo <strong>de</strong> F-MPJ enMG e IS (salvo en IS con 32 núcleos, en don<strong>de</strong> F-MPJ pier<strong>de</strong> escalabilidad). <strong>La</strong> implementación conthreads en Java presenta una escalabilidad reducida<strong>de</strong>bida a la pobre implementación <strong>de</strong> esta versión <strong>de</strong>los NPB, ya que F-MPJ, haciendo uso también <strong>de</strong>threads, es capaz <strong>de</strong> obtener mejores prestaciones.V. ConclusionesEste artículo presenta smp<strong>de</strong>v, un dispositivo<strong>de</strong> comunicación en memoria compartida que haceuso <strong>de</strong>l multithreading para aprovechar el paralelismoinherente a los procesadores multinúcleo.Este dispositivo, integrado en F-MPJ, permite alusuario abstraerse <strong>de</strong> la programación con threadsaprovechando <strong>de</strong> forma eficiente las arquitecturas <strong>de</strong>memoria compartida y, a la vez, disponer <strong>de</strong> códigosportables y ejecutables en sistemas <strong>de</strong> memoria distribuida.<strong>La</strong> evaluación <strong>de</strong>l rendimiento <strong>de</strong> smp<strong>de</strong>vmuestra que la solución <strong>de</strong> paso <strong>de</strong> mensajes enmemoria compartida propuesta alcanza resultadoscomparables a los obtenidos con bibliotecas nativasMPI, llegando a superarlas en ciertos casos. Estopone <strong>de</strong> manifiesto que Java es una alternativa <strong>de</strong>gran interés para HPC.<strong>JP2011</strong>-443


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Speedup16141210864F−MPJ (smp<strong>de</strong>v)Java ThreadsOpenMPIOpenMPCG Class C24 8 16 32Number of CoresSpeedup12111098765432F−MPJ (smp<strong>de</strong>v)Java ThreadsOpenMPIOpenMPFT Class C14 8 16 32Number of Cores1412F−MPJ (smp<strong>de</strong>v)Java ThreadsOpenMPIOpenMPIS Class C2520F−MPJ (smp<strong>de</strong>v)Java ThreadsOpenMPIOpenMPMG Class C10Speedup86Speedup151042504 8 16 32Number of Cores04 8 16 32Number of CoresFig. 6.NAS parallel benchmaks performance on quad-socket Magny Cours systemAgra<strong>de</strong>cimientosEste trabajo ha sido financiado por el Ministerio<strong>de</strong> Ciencia e Innovación <strong>de</strong> España en el marco <strong>de</strong>lproyecto TIN2010-16735 y una beca <strong>de</strong> Formación<strong>de</strong> Profesorado Universitario <strong>de</strong>l Ministerio <strong>de</strong> Educación(AP2009-2112). We gratefully thank the AdvancedSchool for Computing and Imaging (ASCI) ofthe Vrije University Amsterdam for providing accessto the “Magny Cours” system.Referencias[1] G. L. Taboada, J. Touriño, and R. Doallo, “Java forHigh Performance Computing: Assessment of CurrentResearch and Practice,” in Proc. 7th Intl. Conf. on Principlesand Practice of Programming in Java (PPPJ’09),Calgary, Alberta, Canada, 2009, pp. 30–39.[2] B. Blount and S. Chatterjee, “An Evaluation of Java forNumerical Computing,” Scientific Programming, vol. 7,no. 2, pp. 97–110, 1999.[3] A. Shafi, B. Carpenter, M. Baker, and A. Hussain, “AComparative Study of Java and C Performance in two<strong>La</strong>rge-scale Parallel Applications,” Concurrency andComputation: Practice and Experience, vol. 21, no. 15,pp. 1882–1906, 2009.[4] P. Ekman and P. Mucci, “Design Consi<strong>de</strong>rations forShared Memory MPI Implementations on Linux NUMASystems: An MPICH/MPICH2 Case Study,” AdvancedMicro Devices, July 2005.[5] D. Buntinas, G. Mercier, and W. Gropp, “Implementationand Evaluation of Shared-Memory Communicationand Synchronization Operations in MPICH2 using theNemesis Communication Subsystem,” Parallel Computing,vol. 33, no. 9, pp. 634–644, 2007.[6] A. Basumallik, S.-J. Min, and R. Eigenmann, “ProgrammingDistributed Memory Sytems Using OpenMP,”in Proc. 12th Intl. Workshop on High-Level ParallelProgramming Mo<strong>de</strong>ls and Supportive Environments(HIPS’07), Long Beach, CA, USA, 2007, pp. 1–8.[7] D. Millot, A. Muller, C. Parrot, and F. Silber-Chaussumier, “STEP: A Distributed OpenMP forCoarse-Grain Parallelism Tool,” in Proc. 4th Intl. Confon OpenMP in a new era of parallelism (IWOMP’08),West <strong>La</strong>fayette, IN, USA, 2008, pp. 83–99.[8] J. Bull, M. Westhead, and J. Obdržálek, “TowardsOpenMP for Java,” in Proc. 2nd European Workshopon OpenMP (EWOMP’00), Edinburgh, UK, 2000, pp.98–105.[9] M. Klemm, M. Bezold, R. Vel<strong>de</strong>ma, and M. Philippsen,“JaMP: an Implementation of OpenMP for a Java DSM,”Concurrency and Computation: Practice and Experience,vol. 19, no. 18, pp. 2333–2352, December 2007.[10] R. Vel<strong>de</strong>ma, R. F. H. Hofman, R. A. F. Bhoedjang, andH. E. Bal, “Run-time Optimizations for a Java DSM Implementation,”Concurrency and Computation: Practiceand Experience, vol. 15, no. 3-5, pp. 299–316, 2003.[11] A. Kaminsky, “Parallel Java: a Unified API for SharedMemory and Cluster Parallel Programming in 100%Java,” in Proc. 9th Intl. Workshop on Java and Componentsfor Parallelism, Distribution and Concurrency(IWJacPDC’07), Long Beach, CA, USA, 2007, pp. 1–8.[12] M. Baker, B. Carpenter, G. Fox, S.-H. Ko, and S. Lim, “mpiJava: an Object-Oriented Java Interface to MPI,”in Proc. 1st Intl. Workshop on Java for Parallel andDistributed Computing (IWJPDC’99), San Juan, PuertoRico, 1999, pp. 748–762.[13] A. Shafi, B. Carpenter, and M. Baker, “Nested Parallelismfor Multi-core HPC Systems using Java,” Journalof Parallel and Distributed Computing, vol. 69, no. 6, pp.532–545, 2009.[14] G.L. Taboada, J. Touriño, and R. Doallo, “F-MPJ: ScalableJava Message-passing Communications on ParallelSystems,” Journal of Supercomputing, , no. In press(DOI: 10.1007/s11227-009-0270-0), 2011.[15] A. Shafi, J. Manzoor, K. Hameed, B. Carpenter, andM. Baker, “Multicore-enabling the MPJ Express MessagingLibrary,” in Proc. 8th Intl. Conf. on Principlesand Practice of Programming in Java (PPPJ’10), Vienna,Austria, 2010, pp. 49–58.[16] G. L. Taboada, S. Ramos, J. Touriño, and R. Doallo,“Design of Efficient Java Message-Passing Collectives onMulti-core Clusters,” The Journal of Supercomputing,vol. 55, no. 2, pp. 126–154, 2011.[17] D.A. Mallón, G.L. Taboada, J. Touriño, and R. Doallo,“NPB-MPJ: NAS Parallel Benchmarks Implementationfor Message-Passing in Java,” in Proc. 17th EuromicroIntl. Conf. on Parallel, Distributed, and Network-BasedProcessing (PDP’09), Weimar, Germany, 2009, pp. 181–190.<strong>JP2011</strong>-444


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Aproximación distribuida <strong>de</strong> incendios forestalescon WSN usando la envolvente convexaM. Ángeles Serna 1 , Aurelio Bermú<strong>de</strong>z 1 , Rafael Casado 1 , Pawel Kulakowski 2Resumen—<strong>La</strong> monitorización <strong>de</strong> fenómenos físicos es uno <strong>de</strong>los campos <strong>de</strong> aplicación más prometedores <strong>de</strong> las re<strong>de</strong>sinalámbricas <strong>de</strong> sensores. Este trabajo se centra en obtener laforma <strong>de</strong> un incendio forestal. En este tipo <strong>de</strong> aplicaciones, lainformación captada por los nodos <strong>de</strong> la red normalmente setransmite a los extremos <strong>de</strong> la misma, don<strong>de</strong> finalmente seprocesa. Sin embargo, aquí supondremos que los nodos <strong>de</strong> lared son capaces <strong>de</strong> colaborar entre ellos con el fin <strong>de</strong> obteneruna aproximación <strong>de</strong>l incendio forestal <strong>de</strong> manera totalmentedistribuida. En este artículo se proponen y analizan dostécnicas para realizar esta aproximación. <strong>La</strong> primera hace unuso intensivo <strong>de</strong> recursos, mientras que la segunda incorporauna técnica <strong>de</strong> agregación, reduciendo sus requerimientos.Palabras clave— Wireless sensor networks, Environmentalmonitoring, Situation management, Forest fire mo<strong>de</strong>ling,Convex hull. I. INTRODUCCIÓNUNO <strong>de</strong> los usos más prometedores <strong>de</strong> las re<strong>de</strong>sinalámbricas <strong>de</strong> sensores (WSNs, wireless sensornetworks) [14] es su aplicación a lo que recientemente seestá <strong>de</strong>nominando como “gestión <strong>de</strong> situaciones” (situationmanagement) [12]. Se trata <strong>de</strong> escenarios dinámicos eimpre<strong>de</strong>cibles, don<strong>de</strong> un complejo sistema distribuido<strong>de</strong>splegado sobre un área extensa capta datos en tiemporeal <strong>de</strong> un gran número <strong>de</strong> fuentes <strong>de</strong> información <strong>de</strong>diversa naturaleza. El objetivo final <strong>de</strong>l sistema esproporcionar apoyo en la toma <strong>de</strong> <strong>de</strong>cisiones. Por logeneral, el papel <strong>de</strong> la WSN consiste en obtener unarepresentación o mo<strong>de</strong>lo <strong>de</strong> algún fenómeno físico.Un ejemplo <strong>de</strong> este tipo <strong>de</strong> aplicaciones es el sistemaEIDOS (Equipamiento Informático Destinado a laOrientación y Seguridad) [8], en el que una WSN <strong>de</strong> grantamaño es <strong>de</strong>splegada <strong>de</strong>s<strong>de</strong> el aire sobre el área afectadapor un incendio forestal, con el fin <strong>de</strong> recoger datosambientales y calcular un mapa <strong>de</strong>l incendio. Este mapa sesuministra directamente a los bomberos, que estánequipados con dispositivos móviles. El mo<strong>de</strong>lo <strong>de</strong> fuego esobtenido por los nodos <strong>de</strong> la red <strong>de</strong> una maneracompletamente distribuida y colaborativa, a partir <strong>de</strong> suslecturas y sin la participación <strong>de</strong> ninguna estación base.En el diseño actual <strong>de</strong> EIDOS, la primera tarea realizadapor cada nodo consiste en <strong>de</strong>terminar su localización. Ésta1 Instituto <strong>de</strong> Investigación en Informática <strong>de</strong> Albacete, Departamento <strong>de</strong>Sistemas Informáticos, <strong>Universidad</strong> <strong>de</strong> Castilla–<strong>La</strong> Mancha.{angeles.serna, aurelio.bermu<strong>de</strong>z, rafael.casado} @uclm.es.2 Department of Telecommunications, AGH University of Science andTechnology. kulakowski@kt.agh.edu.plpue<strong>de</strong> ser proporcionada por un receptor <strong>de</strong> GPS (GlobalPositioning System), o estimada por medio <strong>de</strong> un procesodistribuido <strong>de</strong> localización [7]. A partir <strong>de</strong> ese momento,cada vez que el fuego alcanza la posición <strong>de</strong> un nodo, sedispara un proceso <strong>de</strong> diseminación <strong>de</strong> dicha posición, <strong>de</strong>modo que cada nodo <strong>de</strong> la red recibe información sobre elevento. Con este fin, se han analizado diversas técnicas <strong>de</strong>difusión en [21].En este artículo se presentan y analizan dos formas <strong>de</strong>procesar la información recibida por cada nodo durante elproceso <strong>de</strong> difusión. <strong>La</strong> primera consiste en almacenartodos los datos recibidos. Como resultado, en cadamomento todos los nodos <strong>de</strong> la red conocen el conjunto <strong>de</strong>puntos alcanzados por el fuego. Obviamente, unarepresentación <strong>de</strong>l fuego obtenida a partir <strong>de</strong> estos datos esbastante exacta. El segundo método es nuestra principalcontribución. Consiste en aplicar una técnica distribuida <strong>de</strong>agregación <strong>de</strong> datos [4], con el fin <strong>de</strong> obtener un mo<strong>de</strong>lomás compacto <strong>de</strong> fuego. En particular, se propone utilizaruna representación <strong>de</strong>l incendio basada en la envolventeconvexa [20]. Como se verá en la sección <strong>de</strong> evaluación,este enfoque reduce el consumo <strong>de</strong> memoria en los propiosdispositivos <strong>de</strong> la red y la sobrecarga introducida en elmedio inalámbrico compartido, manteniendo al mismotiempo la fi<strong>de</strong>lidad en la representación <strong>de</strong>l fuego.El resto <strong>de</strong>l trabajo se organiza <strong>de</strong> la siguiente forma. Enprimer lugar, la Sección II presenta un estado <strong>de</strong>l arte sobremonitorización <strong>de</strong> fenómenos físicos con re<strong>de</strong>sinalámbricas <strong>de</strong> sensores. A continuación, en la Sección IIIse <strong>de</strong>scribe el funcionamiento <strong>de</strong> las técnicas consi<strong>de</strong>radasen este estudio para la aproximación <strong>de</strong> un incendioforestal. Posteriormente, la Sección IV presenta diversosresultados <strong>de</strong> simulación que nos permitirán realizar unanálisis comparativo <strong>de</strong> ambas técnicas. Finalmente, laSección V presenta las conclusiones <strong>de</strong> nuestrainvestigación y esboza el trabajo futuro.II. TRABAJOS RELACIONADOSEn la literatura existen muchas propuestas para estimar oaproximar el contorno (también el bor<strong>de</strong> o el límite) <strong>de</strong> unfenómeno físico mediante el uso <strong>de</strong> re<strong>de</strong>s <strong>de</strong> sensores.Algunos ejemplos son [1] [3] [11] [18] [22]. Sin embargo,aunque algunas <strong>de</strong> estas propuestas son en partedistribuidas (por lo general emplean clustering), todos estosmecanismos requieren la participación <strong>de</strong> una estación baseen algún momento <strong>de</strong>l proceso.<strong>JP2011</strong>-445


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>La</strong> técnica presentada recientemente en [15] también sebasa en un nodo raíz para obtener el contorno <strong>de</strong>lfenómeno. Sin embargo, es particularmente interesante<strong>de</strong>bido a que incorpora una estrategia para minimizar lasnecesida<strong>de</strong>s <strong>de</strong> comunicación. En esta propuesta, lossensores intercambian información solo cuando elfenómeno observado no se comporta como se esperaba. Noobstante requiere programar los nodos sensores con unmo<strong>de</strong>lo <strong>de</strong>l fenómeno (llamado tiny mo<strong>de</strong>l).A<strong>de</strong>más <strong>de</strong> la envolvente convexa, hay muchas otraspropuestas para representar <strong>de</strong> forma compacta la forma <strong>de</strong>un fenómeno físico a partir <strong>de</strong>l conjunto <strong>de</strong> posicionesdon<strong>de</strong> se ha <strong>de</strong>tectado su presencia. En [17], los autoresanalizan el uso <strong>de</strong> líneas y curvas <strong>de</strong> Bézier para laaproximación <strong>de</strong> un conjunto <strong>de</strong> puntos proporcionados poruna WSN. En [6] se utiliza un conjunto <strong>de</strong> polígonos pararepresentar el contorno <strong>de</strong>l fenómeno, siendo el número <strong>de</strong>vértices empleado un parámetro especificado por elusuario. Por último, existen otros mo<strong>de</strong>los analíticos máscomplejos, como los diagramas <strong>de</strong> Voronoi [11], kernellinear regression [10], y Gaussian kernel estimation [13],que también se han propuesto para mo<strong>de</strong>lar los datosobtenidos por los sensores.III. APROXIMACIONES PARA EL FUEGOEn esta sección se <strong>de</strong>tallan los mecanismos propuestos eneste trabajo para obtener el mapa <strong>de</strong> un incendio forestal.En primer lugar, se establecen algunas hipótesis generales.A continuación, se <strong>de</strong>scribe la técnica <strong>de</strong> difusión empleadapara transmitir la <strong>de</strong>tección <strong>de</strong>l incendio a toda la red.Sobre la capa <strong>de</strong> diseminación anterior se pue<strong>de</strong> <strong>de</strong>finir unacapa <strong>de</strong> representación <strong>de</strong>l fuego. En este trabajo, seanalizan dos aproximaciones distintas a este nivel: elmo<strong>de</strong>lo puntual y el mo<strong>de</strong>lo basado en envolvente convexa.A. SuposicionesSuponemos que la WSN se <strong>de</strong>spliega <strong>de</strong>s<strong>de</strong> el aire. Estoimplica que la topología <strong>de</strong> la red resultante será irregular y<strong>de</strong>sconocida.Supondremos que cada nodo conoce su ubicacióngeográfica una vez que cae al suelo. Ésta pue<strong>de</strong> serobtenida mediante un receptor <strong>de</strong> GPS integrado, o pormedio <strong>de</strong> la ejecución <strong>de</strong> un proceso <strong>de</strong> localización previo(fuera <strong>de</strong>l alcance <strong>de</strong> este trabajo). Dicha ubicación (p) serádifundida a toda la red en el momento en el que el sensor<strong>de</strong>tecte la llegada <strong>de</strong>l fuego. A<strong>de</strong>más, todos los nodos quereciban el mensaje <strong>de</strong> difusión (m p ) almacenarán en algunaestructura <strong>de</strong> datos interna la posición p <strong>de</strong>l iniciador, juntocon una referencia temporal (<strong>de</strong>scrito más a<strong>de</strong>lante).Los nodos no mantienen ninguna estructura jerárquica nidisponen <strong>de</strong> información sobre la topología <strong>de</strong> la red(incluyendo la cantidad <strong>de</strong> vecinos o su ubicación).Por último, en cuanto a la radio, suponemos el empleo <strong>de</strong>antenas omnidireccionales i<strong>de</strong>ales, que dan lugar a áreas <strong>de</strong>cobertura circulares. En todos los casos empleamos laFig. 1. Perímetro <strong>de</strong>l nodo J cubierto por un mensaje recibido <strong>de</strong> I.misma potencia <strong>de</strong> emisión, por tanto los círculos <strong>de</strong>cobertura serán <strong>de</strong>l mismo tamaño.B. Algoritmo <strong>de</strong> DiseminaciónComo mecanismo <strong>de</strong> difusión, hemos implementado elalgoritmo ABBA (Area-based Beaconless Algorithm) [19].Este mecanismo se basa en el concepto <strong>de</strong> perímetrocubierto por los mensajes recibidos. Por ejemplo, en la Fig.I1, el nodo J ha recibido un mensaje m p <strong>de</strong>l nodo I, enrelación a una <strong>de</strong>terminada posición p. <strong>La</strong> porción <strong>de</strong>perímetro cubierto por la transmisión (c p ) viene dada por laintersección <strong>de</strong> dos círculos, y se <strong>de</strong>nota por la diferenciaentre los ángulos inicial () y final (). A continuación, elnodo J pue<strong>de</strong> recibir nuevas copias (m K p , m L Ip ,...) <strong>de</strong> m p<strong>de</strong>s<strong>de</strong> vecinos diferentes (K, L,...). Estas copias generannuevos fragmentos cubiertos en su perímetro, que pue<strong>de</strong>nser total o parcialmente fusionados. Por otra parte, el hecho<strong>de</strong> utilizar círculos con el mismo radio garantiza que, comomucho, habrá dos segmentos por cubrir <strong>de</strong>ntro <strong>de</strong> dichoperímetro, lo cual reduce la cantidad <strong>de</strong> informaciónalmacenada en cada nodo. En este caso, c p representará lasuma <strong>de</strong> ambos segmentos.Cuando un nodo recibe un mensaje <strong>de</strong> difusión <strong>de</strong> unvecino, éste no se retransmite instantáneamente. El nodoestablece un retardo (d p ) tras el cual proce<strong>de</strong>rá aretransmitir el mensaje, según la expresión d p = (c p /360) xd max , don<strong>de</strong> c p es el ángulo (en grados) cubierto y d max es unlímite superior pre<strong>de</strong>finido para este retardo. Después,cuando el temporizador expira, se reenvía el mensaje. Sinembargo, la recepción <strong>de</strong> copias <strong>de</strong>l mismo mensaje antes<strong>de</strong> que d p termine modificará c p y d p , lo que retrasará latransmisión <strong>de</strong> nuevo. Por último, el reenvío <strong>de</strong>l mensaje secancela si c p = 360º, es <strong>de</strong>cir, si el perímetro ha sidocubierto completamente por las transmisiones <strong>de</strong> otrosvecinos.Obviamente, este algoritmo requiere que cada nodomantenga una lista don<strong>de</strong> almacenar los mensajespendientes <strong>de</strong> ser retransmitidos, junto con el perímetro nocubierto por otras copias. En a<strong>de</strong>lante, nos referiremos aesta estructura <strong>de</strong> datos como TL (Lista <strong>de</strong> Transmisiones).Nótese que, para que un nodo que recibe una informaciónpueda actualizar el perímetro cubierto por el emisor, esnecesario que el mensaje incluya explícitamente la posición<strong>de</strong>l emisor. Evi<strong>de</strong>ntemente, esto introduce una sobrecargaadicional en las comunicaciones.<strong>JP2011</strong>-446


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011C. Mo<strong>de</strong>lo PuntualEn esta propuesta, cada nodo almacena en una listainterna todas las posiciones <strong>de</strong> fuego recogidas por la red.Nos referiremos a esta estructura <strong>de</strong> datos como PL (Lista<strong>de</strong> Posiciones). Cuando se recibe un nuevo punto <strong>de</strong> fuego,se inserta en TL, y no se inserta en PL hasta que se elimina<strong>de</strong> TL. Esto ocurre cuando se ha transmitido correctamenteo cuando se cancela. <strong>La</strong> Fig. 2 (b) muestra el aspecto <strong>de</strong>lfuego (a) cuando se aproxima mediante este mo<strong>de</strong>lo.D. Mo<strong>de</strong>lo basado en Envolvente Convexa<strong>La</strong> principal diferencia entre este enfoque y el mo<strong>de</strong>lopuntual es que, en este caso, PL sólo contiene lasposiciones que forman la envolvente convexa.Cuando se recibe un nuevo punto <strong>de</strong> fuego, éste se insertaen TL y PL simultáneamente. Si el nuevo punto estáincluido en la envolvente convexa, se ignora. De locontrario, el punto está fuera <strong>de</strong> la envolvente, y suinclusión modifica su perímetro. A<strong>de</strong>más, la actualización<strong>de</strong>l perímetro pue<strong>de</strong> implicar la eliminación <strong>de</strong> otros nodosen el mismo. <strong>La</strong> Fig. 2 (c) muestra el aspecto <strong>de</strong>l fuego (a)cuando se aproxima usando este mo<strong>de</strong>lo.Este enfoque reduce los recursos en los nodos <strong>de</strong> red. Sila información recibida contribuye a su mo<strong>de</strong>lo actual <strong>de</strong>lincendio, los nodos almacenan y reenvían esta información.En otro caso, no es necesario ni transmitirla ni almacenarla.IV. EVALUACIÓNEn esta sección, se analizan las dos propuestas <strong>de</strong>scritasanteriormente. En primer lugar, se presenta el entorno <strong>de</strong># of correct cells100009000800070006000500040003000200010000-1000(a) Propagación <strong>de</strong>l fuego (b) Puntual (c) Envolvente convexaFig. 2. Aproximaciones <strong>de</strong>l fuego.FarsitePunctual R5Punctual R4Punctual R3Punctual R2Punctual R1simulación. A continuación, se establece un criterio paraevaluar la calidad <strong>de</strong> los mo<strong>de</strong>los obtenidos. Antes <strong>de</strong>comparar ambas propuestas, la aproximación puntual seajusta con el fin <strong>de</strong> obtener su mejor rendimiento. <strong>La</strong>comparativa se centra en la precisión, los recursosconsumidos, y la escalabilidad <strong>de</strong> los dos enfoques.A. Entorno <strong>de</strong> SimulaciónUsamos un entorno <strong>de</strong> simulación <strong>de</strong> área forestal [9]<strong>de</strong>sarrollado para el sistema EIDOS , que permite <strong>de</strong>splegaruna WSN, propagar un incendio forestal, situar a losbomberos en una localización concreta y ver la evolución<strong>de</strong> los frentes <strong>de</strong> llama que ellos perciben. Esta herramientase compone <strong>de</strong> varios módulos in<strong>de</strong>pendientes einterconectados, que comparten información a través <strong>de</strong>una base <strong>de</strong> datos global MySQL. En primer lugar se utilizaFarsite [5] para simular un incendio en un área forestalconcreta, usando datos geográficos, medioambientales y <strong>de</strong>vegetación reales. A continuación, la aplicación EIDOS seejecuta en cada nodo <strong>de</strong> la red en un simulador <strong>de</strong> WSN(<strong>de</strong>sarrollado en Python / TOSSIM [16]).Con el fin <strong>de</strong> obtener resultados realistas, el simuladorincorpora un mo<strong>de</strong>lo <strong>de</strong> interferencia, ruido y el mo<strong>de</strong>lo <strong>de</strong>Friis <strong>de</strong> propagación <strong>de</strong> la señal. Se ha mo<strong>de</strong>lado la radioque incorporan los motes Iris <strong>de</strong> Crossbow [2], con unapotencia <strong>de</strong> transmisión <strong>de</strong> 3 dBm y potencia mínima <strong>de</strong>recepción <strong>de</strong> -90 dBm, obteniendo un radio <strong>de</strong> coberturapróximo a los 87 metros. También se supone que todos losnodos <strong>de</strong> la red están equipados con un receptor <strong>de</strong> GPS.En cada simulación, se <strong>de</strong>spliega <strong>de</strong> forma aleatoria unared <strong>de</strong> sensores sobre un área <strong>de</strong> 1000×1000 metros. Se han0 1 2 3 40 1 2 3 4Time(h)Time(h)(a) Valores absolutos(b) Valores normalizadosFig. 3. Calidad <strong>de</strong> la aproximación (Farsite vs mo<strong>de</strong>lo puntual) (tamaño <strong>de</strong> red: 500 nodos).# of correct cells1,510,50-0,5-1-1,5FarsitePunctual R5Punctual R4Punctual R3Punctual R2Punctual R1<strong>JP2011</strong>-447


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011(a) Fuego real (d) Radio = 3 (e) Radio = 4Fig. 4. Aproximación <strong>de</strong>l mo<strong>de</strong>lo puntual a través <strong>de</strong> círculos.consi<strong>de</strong>rado tamaños <strong>de</strong> red <strong>de</strong> 200, 300, 400, 500, 600,700, 800, 900 y 1000 nodos, con un grado <strong>de</strong> conectividadasociado <strong>de</strong> 4.4, 6.5, 8.7, 11.06, 13.16, 15.37 17.58, 19.75 y22.07 respectivamente. Durante la ejecución <strong>de</strong> cadasimulación, el fuego alcanza a todos los nodos <strong>de</strong> la red(quemándolos progresivamente). Cada vez que un nodo<strong>de</strong>tecta la proximidad <strong>de</strong>l fuego (por medio <strong>de</strong> un aumentobrusco en la temperatura captada), proce<strong>de</strong> a difundir suposición a toda la red. Para la ejecución <strong>de</strong>l mecanismo <strong>de</strong>difusión el parámetro d max se ha fijado en 5 segundos.Finalmente, para incrementar la representatividad <strong>de</strong> losresultados, cada experimento se ha repetido varias vecespara cada tamaño <strong>de</strong> red y técnica <strong>de</strong> aproximación,presentándose aquí los valores medios obtenidos.B. MetodologíaEl simulador Farsite representa el área en que se haextendido el fuego "original" como un raster (o grid)llamado TOA (Time Of Arrival). El valor <strong>de</strong> cada celda <strong>de</strong>lraster proporciona la hora <strong>de</strong> llegada <strong>de</strong>l fuego a su centro,y se pue<strong>de</strong> <strong>de</strong>finir como t burning =TOA(celda), asumiendoque un valor infinito indica que el fuego nunca haalcanzado esa posición. <strong>La</strong> información <strong>de</strong>l TOA permiteanalizar cómo se propaga el fuego a lo largo <strong>de</strong>l tiempo. Enparticular, dado un tiempo t, una celda se quema cuandot≤TOA(celda). En la Fig. 3 (a), la serie "Farsite" muestra lacantidad <strong>de</strong> celdas quemadas a medida que avanza eltiempo. El eje horizontal representa el tiempo. Como elincendio forestal se extien<strong>de</strong> sobre un área <strong>de</strong> 1000×1000metros y el tamaño <strong>de</strong> la celda es <strong>de</strong> 10×10 metros, elnúmero máximo <strong>de</strong> celdas quemadas es igual a 10000.A efectos comparativos, cada aproximación <strong>de</strong>beríapresentar sus resultados utilizando la misma representación.Una vez que se tienen dos archivos TOA, TOA Farsite yTOA mo<strong>de</strong>l , se estima la calidad <strong>de</strong> la aproximación pormedio <strong>de</strong>l número <strong>de</strong> celdas con fuego correctamente<strong>de</strong>tectadas en cada instante.C. Resultados1) Ajuste <strong>de</strong>l Mo<strong>de</strong>lo PuntualEn el mo<strong>de</strong>lo puntual explicado en la Sección III, el fuegose representa como una colección <strong>de</strong> puntos <strong>de</strong> fuegorecopilados por la red. Este mo<strong>de</strong>lo supone que el fuegoestá activo en los alre<strong>de</strong>dores <strong>de</strong> cada una <strong>de</strong> estaslocalizaciones. En nuestro análisis, consi<strong>de</strong>raremos que lazona quemada viene dada por el conjunto <strong>de</strong> círculoscentrados en dichas localizaciones. <strong>La</strong> Fig. 4 muestra variasaproximaciones puntuales <strong>de</strong> un incendio, obtenidasmediante el uso <strong>de</strong> círculos con radios <strong>de</strong> 1 a 5 celdas. Acontinuación, se analiza la influencia <strong>de</strong>l tamaño <strong>de</strong> estoscírculos en la exactitud <strong>de</strong>l mo<strong>de</strong>lo resultante.A<strong>de</strong>más <strong>de</strong> la serie "Farsite", la Fig. 3 (a) muestra lacantidad <strong>de</strong> celdas quemadas aproximadas correctamentepor el mo<strong>de</strong>lo puntual, usando círculos con radios <strong>de</strong> 0 a 5celdas. <strong>La</strong> Fig. 3 (b) muestra los mismos resultados, peronormalizados a la cantidad real <strong>de</strong> celdas quemadas (segúnFarsite). Los valores negativos representan que la cantidad<strong>de</strong> celdas quemadas <strong>de</strong>tectadas incorrectamente supera lacantidad <strong>de</strong> las <strong>de</strong>tectadas correctamente. De ambasgráficas, se pue<strong>de</strong> concluir que los círculos pequeñosrepresentan el fuego mejor al inicio <strong>de</strong> la simulación. Porotra parte, <strong>de</strong>spués <strong>de</strong> dos horas, el fuego es lo bastanteamplio como para estar mejor representado con círculosmás gran<strong>de</strong>s. A<strong>de</strong>más, para el círculo R5 (el radio mayor),las mejoras obtenidas en incendios extensos no compensael error inicial, cuando se aproxima un conato <strong>de</strong> incendio.Por esta razón, se seleccionan los círculos R3 y R4(<strong>de</strong>scartando los círculos R0, R1, R2 y R5) como los mása<strong>de</strong>cuados para representar el fuego en el análisis siguiente.2) Precisión <strong>de</strong> la AproximaciónUna vez que la representación puntual se ha ajustado a R3y R4 con el fin <strong>de</strong> obtener resultados óptimos, se comparaesta aproximación con la basada en envolvente convexa. <strong>La</strong>Fig. 5 muestra los resultados <strong>de</strong> la misma forma que la Fig.3. Po<strong>de</strong>mos ver que la envolvente convexa muestra un buencomportamiento medio. Durante los primeros 30 minutos,# of correct cells100009000800070006000500040003000200010000-1000FarsitePunctual R4Convex HullPunctual R30 1 2Time(h)3 40 1 2 Time(h) 3 4(a) Valores absolutos(b) Valores normalizadosFig. 5. Calidad <strong>de</strong> la aproximación (Farsite vs mo<strong>de</strong>lo puntual y envolvente convexa) (tamaño <strong>de</strong> red: 500 nodos).# of correct cells1,210,80,60,40,20-0,2-0,4-0,6-0,8FarsitePunctual R4Convex HullPunctual R3<strong>JP2011</strong>-448


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Memory Required (PL items)400350300250200150100500PunctualConvex Hull0 1 2 3 4Time (h)Fig. 6. Consumo <strong>de</strong> memoria (tamaño <strong>de</strong> red: 500 nodos).es la mejor representación. Después <strong>de</strong> eso, se pue<strong>de</strong>observar una clara reducción en su exactitud (t = 1,2 horas).<strong>La</strong> razón es que la envolvente convexa no asimila bien loscambios repentinos en la dirección <strong>de</strong>l viento. Por último,cuando el fuego se extien<strong>de</strong> sobre el área, su precisiónaumenta <strong>de</strong> nuevo. Después <strong>de</strong> dos horas <strong>de</strong> simulación, laaproximación basada en envolvente convexa supera a R3 ymuestra un comportamiento similar a R4.3) Recursos Consumidos en la WSNEn el mo<strong>de</strong>lo puntual, cada nodo <strong>de</strong> la WSN almacenatodos los puntos recogidos en la lista PL (ver sección III.C).Por el contrario, para el mo<strong>de</strong>lo basado en envolventeconvexa sólo son relevantes los puntos situados en elperímetro <strong>de</strong>l incendio, mientras que los puntos interioresse <strong>de</strong>scartan.<strong>La</strong> Fig. 6 muestra la cantidad media <strong>de</strong> puntosalmacenados en PL a lo largo <strong>de</strong>l tiempo, para una red <strong>de</strong>500 nodos. Se <strong>de</strong>be tener en cuenta que los recursosconsumidos en la aproximación puntual son in<strong>de</strong>pendientes<strong>de</strong>l tamaño <strong>de</strong>l círculo utilizado, y que son proporcionalesal tamaño <strong>de</strong> la red. En la gráfica po<strong>de</strong>mos ver que, enmedia, sólo se han recibido 360 puntos (en lugar <strong>de</strong> 500puntos) <strong>de</strong>spués <strong>de</strong> 5 horas <strong>de</strong> simulación. Esto se <strong>de</strong>be ados razones. <strong>La</strong> primera es que el incendio forestal nocubre toda la zona <strong>de</strong> <strong>de</strong>spliegue y, en consecuencia, haynodos que no <strong>de</strong>tectan el fuego. <strong>La</strong> segunda razón es que amedida que el fuego avanza y los nodos se queman, la re<strong>de</strong>stá cada vez más <strong>de</strong>sconectada, lo que reduce la eficacia<strong>de</strong> las correspondientes difusiones.# of correct cells9000800070006000500040003000200010000FarsitePunctual R4Punctual R3ConvexHull0 5 10 15 20 25Connectivity DegreeFig. 7. Calidad <strong>de</strong> la representación para diferentes <strong>de</strong>nsida<strong>de</strong>s.Por otro lado, la figura muestra que la aproximaciónbasada en envolvente convexa requiere muy poca memoriaen los dispositivos. A<strong>de</strong>más, estos requisitos son constantesy no <strong>de</strong>pen<strong>de</strong>n <strong>de</strong>l tamaño <strong>de</strong> la red.4) Escalabilidad <strong>de</strong> las PropuestasA continuación, se analiza la escalabilidad <strong>de</strong> lasaproximaciones al modificar la cantidad <strong>de</strong> nodos<strong>de</strong>splegados en la misma zona y, en consecuencia, variandoel grado <strong>de</strong> la red. En la Fig. 5 (b) se observa que, <strong>de</strong>spués<strong>de</strong> 3 horas los resultados normalizados llegan a un estado<strong>de</strong> equilibrio. Por esta razón, los resultados siguientes sehan obtenido tras 3 horas <strong>de</strong> simulación.<strong>La</strong> Fig. 7 muestra la cantidad <strong>de</strong> celdas <strong>de</strong>l TOA<strong>de</strong>tectadas correctamente por las diferentes propuestas enfunción <strong>de</strong>l grado <strong>de</strong> la red. Como se esperaba, todos losalgoritmos obtienen mejores aproximaciones al aumentar la<strong>de</strong>nsidad <strong>de</strong> la red. Se pue<strong>de</strong> notar que las re<strong>de</strong>s <strong>de</strong>nsasproporcionan resultados muy similares, cercanos al óptimo.Por otra parte, el rendimiento <strong>de</strong> las aproximacionespuntuales se <strong>de</strong>grada significativamente cuando se ejecutansobre los <strong>de</strong>spliegues poco <strong>de</strong>nsos. Por el contrario, laaproximación basada en la envolvente convexa es menossensible a este hecho, obteniendo los mejores resultados.<strong>La</strong> Fig. 8 muestra la cantidad media <strong>de</strong> puntosalmacenados (elementos en PL) <strong>de</strong>spués <strong>de</strong> 3 horas, enfunción <strong>de</strong>l tamaño <strong>de</strong> la red. Po<strong>de</strong>mos ver que la memoriaconsumida por la aproximación puntual aumentalinealmente con el tamaño <strong>de</strong> la red. <strong>La</strong> razón es que lacantidad <strong>de</strong> puntos <strong>de</strong> fuego aumenta <strong>de</strong> manera lineal conel tamaño <strong>de</strong> la red, y en esta aproximación se almacenatoda la información recibida. Por otro lado, la aproximaciónbasada en envolvente convexa escala perfectamente,porque los recursos necesarios son constantes y no<strong>de</strong>pen<strong>de</strong>n <strong>de</strong>l tamaño <strong>de</strong> la red. <strong>La</strong> razón es que el conjunto<strong>de</strong> puntos involucrados en el perímetro se mantienerelativamente estable, mientras que la cantidad <strong>de</strong> puntos<strong>de</strong>scartados (<strong>de</strong>bido a que se encuentran contenidos en laenvolvente) aumenta linealmente con el tamaño <strong>de</strong> la red.Finalmente, la Fig. 9 muestra el efecto <strong>de</strong> los mecanismos<strong>de</strong> aproximación sobre el medio inalámbrico, a través <strong>de</strong> lacantidad <strong>de</strong> mensajes enviados (a), retransmisionespendientes (b), y colisiones (c) por nodo, en función <strong>de</strong>lgrado <strong>de</strong> la red. Como se mencionó anteriormente, laMemory Required (PL items)8007006005004003002001000PunctualConvexHull0 5 10 15 20 25Connectivity DegreeFig. 8. Consumo <strong>de</strong> memoria para diferentes <strong>de</strong>nsida<strong>de</strong>s.<strong>JP2011</strong>-449


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Sent messages per no<strong>de</strong>300250200150100500PunctualConvex Hull0 5 10 15 20 25Connectivity Degreeaproximación puntual retransmite todos los puntosrecopilados. Por lo tanto, en las gráficas, los mensajesenviados, retransmisiones pendientes, y colisiones <strong>de</strong>benmostrar el mismo comportamiento que el consumo <strong>de</strong>memoria analizado en la Fig. 8.Por otra parte, en el mo<strong>de</strong>lo basado en envolventeconvexa la cantidad <strong>de</strong> mensajes enviados no es sensible ala <strong>de</strong>nsidad <strong>de</strong> la red. Po<strong>de</strong>mos concluir que una gran parte<strong>de</strong> los puntos <strong>de</strong> fuego <strong>de</strong>scartados en la Fig. 8 fueroneliminados durante el proceso <strong>de</strong> inserción en la envolventeconvexa, antes <strong>de</strong> su retransmisión. Como consecuencia,tenemos una baja sobrecarga, <strong>de</strong>bida a los pocos puntos <strong>de</strong>lperímetro <strong>de</strong>l incendio. Obviamente, dado que este enfoquereduce la cantidad total <strong>de</strong> mensajes a transmitir, tambiénse reducen las retransmisiones pendientes y las colisiones.V. CONCLUSIONES Y TRABAJO FUTUROEn este trabajo se han propuesto y analizado dos métodosdistribuidos <strong>de</strong> aproximación <strong>de</strong> incendios forestalesusando re<strong>de</strong>s <strong>de</strong> sensores. En el mo<strong>de</strong>lo puntual, cada nodoalmacena y transmite toda la información que recibe <strong>de</strong> lared. A diferencia <strong>de</strong>l anterior, en el mo<strong>de</strong>lo basado enenvolvente convexa los nodos procesan la informaciónrecopilada, <strong>de</strong>scartando aquella que no es relevante. <strong>La</strong>evaluación <strong>de</strong> estas técnicas ha <strong>de</strong>mostrado que el uso <strong>de</strong> laenvolvente convexa consume menos recursos en los nodosy en el medio compartido, proporcionando a<strong>de</strong>más unabuena aproximación al fuego real.Como trabajo futuro, tenemos previsto mejorar la forma<strong>de</strong> representar el fuego. Por ejemplo, se pue<strong>de</strong> reducir lacantidad <strong>de</strong> puntos necesarios en re<strong>de</strong>s muy <strong>de</strong>nsas.A<strong>de</strong>más, nos planteamos emplear mejores aproximacionespara incendios no convexos. Aprovechar la informaciónsobre las posiciones a las que no ha llegado el fuegotodavía y enriquecer el mo<strong>de</strong>lo con información sobre elcomportamiento reciente <strong>de</strong>l incendio (velocidad,dirección, etc.) son otros trabajos futuros.VI. AGRADECIMIENTOSEste trabajo ha sido financiado conjuntamente por elMinisterio <strong>de</strong> Educación y Ciencia (MEC), el Ministerio <strong>de</strong>Ciencia e Innovación (MICINN) y el Fondo Europeo <strong>de</strong>Desarrollo Regional (FEDER) y el Programa UNITE FP7bajo los proyectos CSD2006-00046 y TIN2009-14475-Pending retransmissions per no<strong>de</strong>181614121086420PunctualConvex Hull0 5 10 15 20 25Connectivity DegreeCollisions per no<strong>de</strong>302520151050PunctualConvex Hull0 5 10 15 20 25Connectivity Degree(a) Mensajes (b) Retransmisiones pendientes (c) ColisionesFig. 9. Sobrecarga en el medio para distintas <strong>de</strong>nsida<strong>de</strong>s.C04; y por la Junta <strong>de</strong> Comunida<strong>de</strong>s <strong>de</strong> Castilla–<strong>La</strong>Mancha bajo el proyecto PII1C09-0101-9476.VII. REFERENCIAS[1] Chintalapudi, K.K. and Govindan, R. 2003. Localized edge <strong>de</strong>tection in sensorfields. Ad Hoc Networks (September 2003), 273–291.[2] Crossbow Technology, Inc. 2011. http://www.xbow.com/[3] Duttagupta, S., Ramamritham, K., and Ramanathan, P. 2006. Distributedboundary estimation using sensor network. In IEEE International Conf. onMobile Ad-hoc and Sensor Systems. 316–325.[4] Fasolo, E., Rossi, M., Widmer, J., Zorzi, M. In-network aggregationtechniques for wireless sensor networks: a survey. IEEE WirelessCommunications, 14, 2 (April 2007), 70–87.[5] Fire.org. 2011. http://fire.org/[6] Gandhi, S., Hershberger, J., and Suri, S. 2007. Approximate Isocontours andSpatial Summaries for Sensor Networks. In 6th International Conference onInformation Processing in Sensor Networks. IPSN’07. 400–409.[7] García, E. M., Bermú<strong>de</strong>z, A., and Casado, R. 2011. Range-Free Localizationfor Air-Dropped WSNs by Filtering Neighborhood Estimation Improvements.In Int. Conf. on Computer Science and Information Technology. 325–337.[8] García, E. M., Bermú<strong>de</strong>z, A., Casado, R., and Quiles, F. J. 2007. CollaborativeData Processing for Forest Fire Fighting. In adjunct poster/<strong>de</strong>mo proceedingsof the 4th European Conference on Wireless Sensor Networks. 3–4.[9] García, E. M., Serna, M. A., Bermú<strong>de</strong>z, A. and Casado, R. 2008. Simulating aWSN-based Wildfire Fighting Support System. In IEEE Int. Symposium onParallel and Distributed Processing with Applications. ISPA’08. 896–902.[10] Guestrin, C., Bodik, P., Thibaux, R., Paskin, M., and Mad<strong>de</strong>n, S. 2004.Distributed regression: an efficient framework for mo<strong>de</strong>ling sensor networkdata. In Int. Symposium on Information Processing in Sensor Networks. 1–10.[11] Ham, M. I. and Rodriguez, M. A. 2010. A Boundary ApproximationAlgorithm for Distributed Sensor Networks. International Journal of SensorNetworks, 8, 1 (2010), 41–46.[12] Jakobson, G., Buford, J. F., and Lewis, L. 2010. Guest Editorial: SituationManagement. IEEE Communications Magazine, 48, 3 (March 2010), 110–111.[13] Jin, G. and Nittel, S. 2008. Toward Spatial Window Queries over ContinuousPhenomena in Sensor Networks. IEEE Transactions on Parallel andDistributed Systems, 19, 4 (April 2008), 559–571.[14] Karl, H. and Willig, A. 2005. Protocols and Architectures for Wireless SensorNetworks. Wiley.[15] King, K. and Nittel, S. 2010. Efficient Data Collection and Event BoundaryDetection in Wireless Sensor Networks Using Tiny Mo<strong>de</strong>ls. In 6th Int. Conf.on Geographic Information Science. GIScience'10. 110–114.[16] Levis, P., Lee, N., Welsh, M. and Culler, D. TOSSIM: accurate and scalablesimulation of entire TinyOS applications. In 1st ACM Conf. on Embed<strong>de</strong>dNetworked Sensor Systems. SenSys 2003. 126–137.[17] Li, Y., Loke, S.W., and Ramakrishna, M.V. 2007. Performance Study of DataStream Approximation Algorithms in Wireless Sensor Networks. In Int. Conf.on Parallel and Distributed Systems. ICPADS 2007. 1–8.[18] Liao, P. K., Chang, M. K., and Jay Kuo, C.C. 2007. A Cross-<strong>La</strong>yer Approachto Contour No<strong>de</strong>s Inference with Data Fusion in Wireless Sensor Networks. InProc. of IEEE Wireless Communications and Networking Conf. 2773–2777.[19] Ovalle-Martínez, F. J., Nayak, A., Stojmenovic, I., Carle, J., and Simplot-Ryl,D. 2006. Area-based beaconless reliable broadcasting in sensor networks.International Journal on Sensor Networks, 1, 1/2 (January 2006), 20–33.[20] Preparata, F. P., Hong, S.J. Convex Hulls of Finite Sets of Points in Two andThree Dimensions. Communications of ACM, 20, 2 (February 1977), 87–93.[21] Serna, M. A., García, E. M., Bermú<strong>de</strong>z, A., and Casado, R. 2010. InformationDissemination in WSNs Applied to Physical Phenomena Tracking. Int. Conf.Mobile Ubiquitous Computing, Systems, Services and Technologies. 458–463.[22] Zhu, X., Sarkar, R., Gao, J., and Mitchell, J.S.B. 2008. Light-weight ContourTracking in Wireless Sensor Networks. In 27th IEEE Conf. on ComputerCommunications. INFOCOM 2008. 1175–1183.<strong>JP2011</strong>-450


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011A First Approach to King Topologies forOn-Chip NetworksE. Stafford 1 E. Stafford 2 J.L. Bosque 3 , C. Martínez 4 , F. Vallejo 5 , R. Beivi<strong>de</strong> 6 , C. Camarero 7Abstract— In this paper we propose two new topologiesfor on-chip networks that we have <strong>de</strong>noted as kingmesh and king torus. These are a higher <strong>de</strong>gree evolutionof the classical mesh and torus topologies. In aking network packets can traverse the networks usingorthogonal and diagonal movements like the king on achess board. First we present a topological study addressingdistance properties, bisection bandwidth andpath diversity as well as a folding scheme. Second weanalyze different routing mechanisms. Ranging fromminimal distance routings to missrouting techniqueswhich exploit the topological richness of these networks.Finally we make an exhaustive performanceevaluation comparing the new king topologies withtheir classical counterparts. The experimental resultsshow a performance improvement, that allow us topresent these new topologies as better alternative toclassical topologies.Keywords— Hoja <strong>de</strong> estilo, LATEX, Jornadas <strong>de</strong> Paralelismo.I. IntroductionALTHOUGH a lot of research on interconnectionnetworks has been conducted in the last<strong>de</strong>ca<strong>de</strong>s, constant technological changes <strong>de</strong>mand newinsights about this key component in mo<strong>de</strong>rn computers.Nowadays, networks are critical for managingboth off-chip and on-chip communications.Some recent and interesting papers advocate fornetworks with high-radix routers for large-scale supercomputers[1][2].The advent of economical opticallinks enables this kind of topologies that uselong global wires. Although the <strong>de</strong>sign scenario isvery different, on-chip networks with higher <strong>de</strong>greethan traditional 2D meshes or tori have also beenrecently explored[3]. Such networks entail the use oflong wires in which repeaters and channel pipeliningare nee<strong>de</strong>d. Nevertheless, with current VLSI technology,the planar substrate in which the network isgoing to be <strong>de</strong>ployed suggests the use of 2D meshliketopologies. This has been the case of Tilera[4]and the Intel’s Teraflop research chip[5], with 64 and80 cores arranged in a 2D mesh respectively. Forthcomingtechnologies such as on-chip high-speed signallingand optical communications could favor the1 Dpto. Electrónica y Computadores, Univ. Cantabria, e-mail: esteban.stafford@gestion.unican.es2 Dpto. Electrónica y Computadores, Univ. Cantabria, e-mail: esteban.stafford@gestion.unican.es3 Dpto. Electrónica y Computadores, Univ. Cantabria, e-mail: joseluis.bosque@unican.es4 Dpto. Electrónica y Computadores, Univ. Cantabria, e-mail: carmen.martinez@unican.es5 Dpto. Electrónica y Computadores, Univ. Cantabria, e-mail: fernando.vallejo@unican.es6 Dpto. Electrónica y Computadores, Univ. Cantabria, e-mail: ramon.beivi<strong>de</strong>@unican.es7 Dpto. Electrónica y Computadores, Univ. Cantabria, e-mail: cristobal.camarero@alumnos.unican.esuse of higher <strong>de</strong>gree on-chip networks.This paper proposes an intermediate solution. Weanalyze networks whose <strong>de</strong>grees double the radix ofa traditional 2D mesh while preserving an attractivelayout for planar VLSI <strong>de</strong>sign. We study <strong>de</strong>gree eightnetworks in which a packet at a given no<strong>de</strong> can travelin one hop to any of its eight neighbours just like theking on a chessboard. Thus, we <strong>de</strong>note them kingmeshes and king tori. In this way, we adopt a moreconservative evolution towards higher radix networkstrying to exploit the advantages while avoiding theuse of long wires. The simplicity and topologicalproperties of these networks offer tantalising featuresfor future on-chip architectures: higher throughput,smaller latency, trivial partitioning in smaller networks,good scalability and high fault-tolerance.The use of diagonal topologies has been consi<strong>de</strong>redin the past, in the fields of VLSI[6], FPGA[7] and interconnectionnetworks[8]. Also mesh and toroidaltopologies with ad<strong>de</strong>d diagonals have been consi<strong>de</strong>red,both with <strong>de</strong>gree six[9] and eight[10].The kinglattice has been previously studied in several papersof Information Theory[11].The goal is to explore the suitability of king topologiesto constitute the communication substrate offorthcoming on-chip parallel systems. With this i<strong>de</strong>ain mind, we present the foundations of king networksand a first attempt to unleash their potential. Themain contributions of our research are the following:i) An in-<strong>de</strong>pth analysis of the topological characteristicsof king tori and king meshes.ii) The introduction and evaluation of king tori,not consi<strong>de</strong>red previously in the literature.iii) A folding scheme ensuring king tori scalability.iv) An adaptive and <strong>de</strong>adlock-free routing algorithmfor king topologies.v) A first performance evaluation of king networksbased on synthetic traffic.The remain<strong>de</strong>r of this paper is organized as follows.Section II is <strong>de</strong>voted to <strong>de</strong>fine the network topologiesconsi<strong>de</strong>red in this paper. The most relevant distanceparameters and the bisection bandwidth arecomputed for each network and a folding methodis consi<strong>de</strong>red for networks with wrap-around links.Section III tackles the task of finding routing algorithmsto unlock the networks’ potential high performance,starting with simple minimum-distance algorithmsand evolving to more elaborate missroutingand load balancing techniques. Section IV presentsa first performance evaluation of these networks. Finally,Section V conclu<strong>de</strong>s the paper highlighting itsmost important findings.<strong>JP2011</strong>-451


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011II. Description of the TopologiesIn this Section we <strong>de</strong>fine and analyze distanceproperties of the network topologies consi<strong>de</strong>red inthis paper: square meshes, square king meshes,square tori and square king tori. Then, we obtain expressionsfor significant distance parameters as wellas the bisection bandwidth. Finally, we consi<strong>de</strong>rlay-out possibilities minimizing wire length for thosetopologies with wrap-around edges.As usual, networks are mo<strong>de</strong>led by graphs. Verticesrepresent processors and edges represent thecommunication links. In this paper we will only consi<strong>de</strong>rsquare networks, as sometimes networks withsi<strong>de</strong>s of different length result in an unbalanced use ofthe links in each dimension[12]. Therefore, in the followingwe will obviate the adjective “square”. Hence,for any of the networks consi<strong>de</strong>red here the numberof no<strong>de</strong>s will be n = s 2 , for any integer s > 1.By M s we will <strong>de</strong>note the usual mesh of si<strong>de</strong>s. This is a very well-known topology which hasbeen <strong>de</strong>eply studied. A mesh based network of <strong>de</strong>greeeight can be obtained by adding new links suchthat, any packet not only can travel in orthogonaldirections, but also can use diagonal movements.Will <strong>de</strong>note by KM s the king mesh network, whichis obtained by adding diagonal links (just for nonperipheralno<strong>de</strong>s) to M s .Note that both networks are neither regular norvertex-symmetric. The way to make this kind of networkregular and vertex-symmetric is to add wraparoundlinks so that every no<strong>de</strong> has the same numberof neighbors. We will <strong>de</strong>note as T s the usual torusnetwork of si<strong>de</strong> s. The torus is obviously the four<strong>de</strong>gree regular counterpart of the mesh. Then, KT swill <strong>de</strong>note the king torus network, that is, a kingmesh with new wrap-around links in or<strong>de</strong>r to obtainan eight <strong>de</strong>gree regular network. Another way to seethis network is as a torus with extra diagonal linksthat turn the four <strong>de</strong>gree torus into an eight <strong>de</strong>greenetwork. In Figure 1 an example of each is shown.In an i<strong>de</strong>al system, transmission <strong>de</strong>lays in the networkcan be inferred from its topological properties.The maximum packet <strong>de</strong>lay is given by the diameterof the graph. It is the maximum length over allminimum paths between any pair of no<strong>de</strong>s. The average<strong>de</strong>lay is proportional to the average distanceof every pair of no<strong>de</strong>s of the network. In Table I werecord these parameters of the four networks consi<strong>de</strong>red.The diameter and average distance of meshand torus are well-known values[13]. The distanceproperties of king torus were presented in [14].An specially important metric of interconnectionnetworks is the throughput, the maximum data ratethe network can <strong>de</strong>liver. In the case of uniform traffic,the throughput is boun<strong>de</strong>d by the bisection. Accordingto [13], in networks with homogeneous channelbandwidth, as the ones consi<strong>de</strong>red here, the bisectionbandwidth is proportional to the channel countacross the smallest cut that divi<strong>de</strong>s the network intotwo equal halves. This value represents an upperbound in the throughput un<strong>de</strong>r uniform traffic.Fig. 1. Examples of Mesh, King Mesh, Torus and King TorusNetworks.Network M s KM S T s KT sDiameter 2s s s ⌊ s 2 ⌋Average Distance ≈ 2 3 s ≈ 7 15 s ≈ s 2≈ s 3Bisection Bandwidth 2s 6s 4s 12sTABLE ITopological ParametersIn Table I, values for the bisection for mesh andtorus are shown, see [13]. The obtention of the bisectionbandwidth in king mesh and torus is straightforward.Note that a king network doubles the numberof links of its orthogonal counterpart but has threetimes the bisection bandwidth.In a more technological level, physical implementationof computer networks usually requires similar,if not constant, link lengths. In the contextof networks-on-chip, mesh implementation is fairlystraightforward. A regular mesh can be la<strong>de</strong> out witha single metal layer. Due to the crossing diagonallinks, the king mesh requires two metal layers.However tori have wrap-around links whose length<strong>de</strong>pend on the size of the network. To overcome thisproblem, a well known technique is graph folding. Astandard torus can be implemented with two metallayers. Our approach to folding king tori is basedon the former but because of the diagonal links fourmetal layers are required. As a consequence of thefolding, √ the length of the links is between two and8 in king tori. This seems to be the optimal solutionfor this kind of networks. Figure II shows a8 × 8 fol<strong>de</strong>d king torus. For the sake of clarity, thefol<strong>de</strong>d graph is shown with the orthogonal and diagonallinks separated.Now, if we compare king meshes with tori, we observethat the cost of doubling the number of links<strong>JP2011</strong>-452


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 2. Folding of King Torus Network. For the sake of clarity,the orthogonal and diagonal links are shown in separatesgraphs.gives great returns. Bisection bandwidth is 50%larger, average distance is almost 5% less and diameterremains the same. In addition, implementationof a king mesh on a network-on-chip is simpler, asit does not need to be fol<strong>de</strong>d and fits in two metallayers just like a fol<strong>de</strong>d torus.III. RoutingThis section explores different routing techniquestrying to take full advantage of the king networks.For simplicity it focuses on toroidal networks assumingthat meshes will have a similar behaviour. Our<strong>de</strong>velopment starts with the most simple minimumdistance routing continuing through to more elaborateload balancing schemes capable of giving highperformance in both benign and adverse traffic situations.Enabling packets to reach their <strong>de</strong>stination in directnetworks is traditionally done with source routing.This means that at the source no<strong>de</strong>, whenthe packet is injected, a routing record is calculatedbased on source and <strong>de</strong>stination using a routing function.This routing record is a vector whose integercomponents are the number of jumps the packetmust make in each dimension in or<strong>de</strong>r to reach its<strong>de</strong>stination.In 2D networks routing records have two components,∆ X and ∆ Y . These components could be usedto route packets in king networks, but the diagonallinks, that can be thought as shortcuts, would neverbe used. Then it is necessary to increase the numberof components in the routing record to accountfor the greater <strong>de</strong>gree of these new networks. Thuswe will broa<strong>de</strong>n the <strong>de</strong>finition of routing record as avector whose components are the number of jumpsa packet must make in each direction, not dimension.Thus, king networks will have four directions,namely X and Y as the horizontal and vertical, Z forthe diagonal y = x and T for the diagonal y = −x.A. Minimal RoutingTo efficiently route packets in a king network,we need a routing function that takes source and<strong>de</strong>stination no<strong>de</strong>s and gives a routing record thatmakes the packet reach its <strong>de</strong>stination in the minimumnumber of jumps. Starting with the 2D routingrecord, it is easy to <strong>de</strong>rive a naive king routingrecord that is minimal(Knaive). From the four componentsof the routing record, this routing functionwill not use two of them. Hence, routing records willhave, at most, two non-zero components, one is orthogonaland the other is diagonal. The algorithm issimple, consi<strong>de</strong>r (∆ X , ∆ Y ) where ∆ X > ∆ Y > 0.The corresponding king routing record would be(δ X , δ Y , δ Z , δ T ) = (∆ X − ∆ Y , 0, ∆ Y , 0). The rest ofthe cases are calculated in a similar fashion.In addition to being minimal, this algorithm balancesthe use of all directions un<strong>de</strong>r uniform traffic, akey aspect in or<strong>de</strong>r to achieve maximum throughput.The drawback, however, is that it does not exploitall the path diversity available in the network. Pathdiversity is <strong>de</strong>fined as the number of minimal pathsbetween a pair of no<strong>de</strong>s a, b of a network. For meshand tori will <strong>de</strong>note it as |R ab |.( )|∆x | + |∆ y ||R ab | =.|∆ x |Similarly, in king mesh and tori the path diversityis:( ) |∆x ||RK ab | =|∆ y |2( nn∑( )( )n 2n − 2jwhere = (−1)k)j j n − k − j2j=0Thus, the path diversity for king networks is overwhelminglyhigher than in meshes and tori. Take forexample ∆ x = 7, ∆ y = 1, this is the routing recordto go from the white box to the gray box in Figure1. In a mesh the path diversity would be R ab = 8while in a king mesh RK ab = 357.Now, the corresponding Knaive routing record is(δ X , δ Y , δ Z , δ T ) = (6, 0, 1, 0). This yields only 7 alternativepaths, so 350 path are ignored, this is evenless than the 2d torus. This is not a problem un<strong>de</strong>runiform and other benign traffic patterns but onadverse situations a diminished performance is observed.For instance, see the performance of 16 × 16torus with 1-phit packets in Figure 3. The throughputin uniform traffic of the Knaive algorithm is 2.4times higher than that of a standard torus, whichis a good gain for the cost of doubling network resources.However, in shuffle traffic, the throughputis only double and un<strong>de</strong>r other traffic patterns evenless.A way of improving this is increasing the path diversityby using routing records with three non-zerocomponents. This can be done by applying the notionthat two jumps in one orthogonal direction canbe replaced by a jump in Z plus one in T withoutaltering the path’s length. Based on our experimentswe have found that the best performance is obtainedwhen using transformations similar to the following.⌊δX(δ X , 0, δ Z , 0) → (3⌋ ⌊δX, 0, δ Z +3⌋ ⌊δX,3⌋)Being this an enhancement of the Knaive algorithmwe <strong>de</strong>note it EKnaive. It is important to note<strong>JP2011</strong>-453


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Throughput (phits/cycle/no<strong>de</strong>)16x16 king torus, uniform traffic1.210.80.60.40.200 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8Offered load (phits/cycle/no<strong>de</strong>)Throughput (phits/cycle/no<strong>de</strong>)1.210.80.60.40.216x16 king torus, shuffle trafficRouting2d torusKnaiveEKnaiveKmissKBugal00 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8Offered load (phits/cycle/no<strong>de</strong>)Fig. 3.Throughput comparison of the various routing algorithms in 16 × 16 toroidal networks.Routing Record Path(δ X , δ Y , δ Z , δ T ) Diversity(6,0,1,0) 7(4,0,2,1) 105(2,0,3,2) 210(0,0,4,3) 35theoretical 357TABLE IIAlternative routing records for (6,0,1,0) withcorresponding path diversitythat it is still minimum-distance and gives more pathdiversity but not all that is available. Continuingwith our example, this algorithm will give us 210 ofthe total 357 paths (See Table II).As can be seen in Figure 3, the EKnaive routingrecord improves the throughput in some adverse trafficpatterns due to its larger path diversity. Howeverthis comes at a cost. The inherent balance in thelink utilization of the Knaive algorithm is lost, thusgiving worse performance un<strong>de</strong>r uniform traffic.B. MisroutingIn the light of the previous experiences, we findthat direction balancing is key. But is it importantenough to relax the minimum distance requirement?In response to this question, we have <strong>de</strong>veloped anew routing function whose routing record may havefour non-zero components. Forcing packets to useall directions will cause missrouting as the minimumpaths will no longer be used. Thus we name thisapproach Kmiss.I<strong>de</strong>ally, to achieve direction balance, the four componentsshould be as close as possible. However thiswould cause path lengths to be very long. A compromisemust be reached between path length and componentsimilarity. With Kmiss, the routing recordis extracted from a table in<strong>de</strong>xed by the 2D routingrecord. The table is built so that the components ofthe routing records do not differ more than 3.The new function improves the load balance regardlessof the traffic pattern and provi<strong>de</strong>s packetswith more means to avoid local congestion. In additionit increases the path diversity.Experimental results as those shown in Section IVshow that this algorithm gives improved throughputin adverse traffic patterns but the misrouting diminishesits performance in benign situations. Figure 3shows that Kmiss is still poor in uniform traffic, butgives the highest throughput un<strong>de</strong>r shuffle.C. Routing CompositionIn essence, we have a collection of routing algorithms.Some are very good in benign traffic butperform badly un<strong>de</strong>r adverse traffic, while others arereasonably good in the latter but disappointing inthe former. I<strong>de</strong>ally, we would like to choose whichalgorithm to use <strong>de</strong>pending on the situation. Betteryet would be that the network switches from one toanother by its self. This is achieved to a certain extentin Universal Globally Adaptive Load-balancing(UGAL)[15]. In a nutshell what this algorithm doesis routing algorithm composition. Based on localtraffic information, each no<strong>de</strong> <strong>de</strong>ci<strong>de</strong>s whether apacket is sent using a minimal routing or the nonminimalValiant’s routing [16], composing a betteralgorithm that should have the benefits of both ofthe simple ones.As we show next, KBugal is an adaptation ofUGAL to king networks and bubble routing withtwo major improvements. On one hand, for the nonminimalrouting, instead of Valiant’s algorithm, weuse Kmiss routing. This approach takes advantageof the topology’s path diversity without significantlyincreasing latency and it has a simpler implementation.On the other hand, the philosophy behindUGAL resi<strong>de</strong>s in estimating the transmission time ofa packet at the source no<strong>de</strong> based on local information.Thus selecting the shortest output queue lengthamong all profitable channels both for the minimaland the non-minimal routings. In the best scenario,the performance of KBugal is the best out of the twoindividual algorithms, as can be seen in Figure 3.The use of bubble routing allows <strong>de</strong>adlock-free operationwith only two virtual channels per physicalchannel in contrast to the three used by originalUGAL. In or<strong>de</strong>r to get a better estimation, KBugaltakes into account the occupation of both virtual<strong>JP2011</strong>-454


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Throughput (phits/cycle/no<strong>de</strong>)8x8 networks, throughput2.521.510.500 0.5 1 1.5 2 2.5 3Offered load (phits/cycle/no<strong>de</strong>)<strong>La</strong>tency (cycles)302826248x8 networks, latency22Topology20king_meshking_torus18meshtorus160 0.2 0.4 0.6 0.8 1Offered load (phits/cycle/no<strong>de</strong>)Fig. 4.Throughput and latency of king topologies with Knaive compared to mesh and tori un<strong>de</strong>r uniform traffic.45uniform traffic 8x8 king torus45complement traffic 8x8 king torus45butterfly traffic 8x8 king torus404040<strong>La</strong>tency (cycles)353025<strong>La</strong>tency (cycles)353025<strong>La</strong>tency (cycles)353025202020150 0.2 0.4 0.6 0.8 1Offered load (phits/cycle/no<strong>de</strong>)150 0.2 0.4 0.6 0.8 1Offered load (phits/cycle/no<strong>de</strong>)150 0.2 0.4 0.6 0.8 1Offered load (phits/cycle/no<strong>de</strong>)Throughput (phits/cycle/no<strong>de</strong>)uniform traffic 8x8 king torus2.521.510.500 0.5 1 1.5 2 2.5 3 3.5 4Offered load (phits/cycle/no<strong>de</strong>)Throughput (phits/cycle/no<strong>de</strong>)complement traffic 8x8 king torus0.90.80.70.60.50.40.3ROUTINGKnaive0.2 Kmissugal0.1KBugal00 0.5 1 1.5 2 2.5 3 3.5 4Offered load (phits/cycle/no<strong>de</strong>)Throughput (phits/cycle/no<strong>de</strong>)butterfly traffic 8x8 king torus10.90.80.70.60.50.40.30.20.100 0.5 1 1.5 2 2.5 3 3.5 4Offered load (phits/cycle/no<strong>de</strong>)Fig. 5.Throughput and latency of routings on 8 × 8 king tori un<strong>de</strong>r different traffic patterns.channels together for each profitable physical channel.The reason behind this is fairly simple. Consi<strong>de</strong>ringthat all virtual channels share the same physicalchannel, the latency is <strong>de</strong>termined by the occupationof all virtual channels, not only the one it isinjected in.IV. EvaluationIn this section we present the experimental evaluationcarried out to verify the better performanceand scalability of the proposed networks. This isdone by comparing with other networks usually consi<strong>de</strong>redfor future network-on-chip architectures, asare the mesh and torus with size 8 × 8. The samestudy was ma<strong>de</strong> with 16 × 16 networks, but due totheir similarity to 8 × 8 and lack of space, these resultsare not shown.All the experiments have been done on a functionalsimulator called fsin[17]. The router mo<strong>de</strong>l is basedon the bubble adaptive router presented in [18] withtwo virtual channels. As we will be comparing networksof different <strong>de</strong>gree, a constant buffer space willbe assigned to each router and will be divi<strong>de</strong>d amongall individual buffers. Another important factor inthe evaluation of networks are the traffic patterns.The evaluation has been performed with syntheticworkload using typical traffic patterns. Accordingto the effect on load balance, traffic patterns can beclassified into benign and adverse. The former naturallybalances the use of network resources, like uni-<strong>JP2011</strong>-455


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011form or local, while the latter introduces contentionand hotspots that reduce performance, as in complementor butterfly. Due to space limitations, only theresults for three traffic patterns are shown as theycan represent the behaviour observed on the rest.These are uniform, bit-complement and butterfly.Figure 4 shows the throughput and latency of kingnetworks using Knaive compared to those of 2d toriand meshes. It proves that the increased <strong>de</strong>gree ofthe king networks outperforms their baseline counterpartsby more than a factor two. The averagelatency on zero load is reduced according to the averagedistance theoretical values. Packets are 16-phitlong, thus making the latency improvement less obviousin the graphs. Observe that king meshes havesignificantly better performance than 2d tori, bothin throughput and latency.Figure 5 presents an analysis of the different routingtechniques un<strong>de</strong>r the three traffic patterns andfor 8 × 8 king tori and meshes. Comparing the resultsof networks with different sizes highlights thatthe throughput per no<strong>de</strong> is halved. This is due to thewell known fact that the number of no<strong>de</strong>s in squarenetworks grows quadratically with the si<strong>de</strong> while thebisection bandwidth grows linearly.For benign traffic patterns, the best results aregiven by Knaive routing. However in adverse traffic,a sensible <strong>de</strong>crease in performance is observed,caused by the reduced path diversity. As mentionedin Section III this limitation is overcome by theKmiss routing. In fact this routing yields poor performanceun<strong>de</strong>r benign traffic pattern but very goodun<strong>de</strong>r the adverse ones.Our composite routing algorithm KBugal gives thebest average performance on all traffic patterns. Inthe benign situations the throughput is slightly lessthan Knaive. And un<strong>de</strong>r adverse traffic, performanceis similar to the Kmiss routing, being even better insome situations. The results show that KBugal givesbetter performance than its more generic pre<strong>de</strong>cessorUGAL. As can be seen, un<strong>de</strong>r benign traffic aimprovement of 15% is obtained and between 10%(complement) and 90% (butterfly).V. ConclusionIn this paper we have presented the foundations ofking networks. Their topological properties offer tantalisingpossibilities, positioning them as clear candidatesfor future network-on-chip systems. Noteworthyare king meshes, which have the implementationsimplicity and wire length of a mesh yet better performancethan 2d tori. In addition, we have presenteda series of routing techniques specific for kingnetworks, that are both adaptive and <strong>de</strong>adlock free,which allow to exploit their topological richness. Afirst performance evaluation of these algorithms un<strong>de</strong>rsynthetic traffic has been presented in which theirproperties are highlighted. Further study will be requiredto take full advantage of these novel topologiesthat promise higher throughput, smaller latency,trivial partitioning and high fault-tolerance.AcknowledgmentThis work has been fun<strong>de</strong>d by the Spanish Ministryof Education and Science (grant TIN2007-68023-C02-01, Consoli<strong>de</strong>r CSD2007-00050) and bythe HiPEAC European Network of Excellence.References[1] J. Kim, W.J. Dally, S. Scott, and D. Abts, “Technologydriven,highly-scalable dragonfly topology,” SIGARCHComput. Archit. News, vol. 36, no. 3, pp. 77–88, 2008.[2] S. Scott, D. Abts, J. Kim, and W.J. Dally, “The blackwidowhigh-radix clos network,” SIGARCH Comput. Archit.News, vol. 34, no. 2, pp. 16–28, 2006.[3] J. Kim, J. Balfour, and W. Dally, “Flattened butterflytopology for on-chip networks,” in MICRO 07: Proceedingsof the 40th Annual IEEE/ACM International Symposiumon Microarchitecture, Washington, DC, USA,2007, pp. 172–182, IEEE Computer Society.[4] D. Wentzlaff, P. Griffin, H. Hoffmann, L. Bao, B. Edwards,C. Ramey, M. Mattina, C.-C. Miao, J.F.B. III,and A. Agarwal, “On-chip interconnection architectureof the tile processor,” IEEE Micro, vol. 27, pp. 15–31,2007.[5] S.R. Vangal, J. Howard, G. Ruhl, S. Dighe, H. Wilson,J. Tschanz, D. Finan, A. Singh, T. Jacob, S. Jain,V. Erraguntla, C. Roberts, Y. Hoskote, N. Borkar, andS. Borkar, “An 80-tile sub-100-w teraflops processor in65-nm cmos,” Solid-State Circuits, IEEE Journal of, vol.43, no. 1, pp. 29–41, 2008.[6] M. Igarashi, T. Mitsuhashi, A. Le, S. Kazi, Y.T. Lin,A. Fujimura, and S. Teig, “A diagonal interconnect architectureand its application to risc core <strong>de</strong>sign,” IEICTechnical Report (Institute of Electronics, Informationand Communication Engineers), vol. 102, no. 72, pp. 19–23, 2002.[7] A. Marshall, T. Stansfield, I. Kostarnov, J. Vuillemin,and B. Hutchings, “A reconfigurable arithmetic array formultimedia applications,” in FPGA 99: Proceedings ofthe 1999 ACM/SIGDA seventh international symposiumon Field programmable gate arrays, New York, NY, USA,1999, pp. 135–143, Acm.[8] K.W. Tang and S.A. Padubidri, “Diagonal and toroidalmesh networks,” Computers, IEEE Transactions on, vol.43, no. 7, pp. 815–826, 1994.[9] K.G. Shin and G. Dykema, “A distributed i/o architecturefor harts,” in Computer Architecture, 1990. Proceedings.,17th Annual International Symposium on, 1990,pp. 332–342.[10] WH Hu, SE Lee, and N. Bagherza<strong>de</strong>h, “Dmesh: adiagonally-linked mesh network-on-chip architecture,”nocarc, 2008.[11] I.S. Honkala and T. <strong>La</strong>ihonen, “Co<strong>de</strong>s for i<strong>de</strong>ntificationin the king lattice,” Graphs and Combinatorics, vol. 19,no. 4, pp. 505–516, 2003.[12] J.M. Camara, M. Moreto, E. Vallejo, R. Beivi<strong>de</strong>,J. Miguel-Alonso, C. Martinez, and J. Navaridas,“Twisted torus topologies for enhanced interconnectionnetworks,” IEEE Transactions on Parallel and DistributedSystems, vol. 99, no. PrePrints, 2010.[13] W. Dally and B. Towles, Principles and Practices ofInterconnection Networks, Morgan Kaufmann PublishersInc., San Francisco, CA, USA, 2003.[14] C. Martinez, E. Stafford, R. Beivi<strong>de</strong>, C. Camarero,F. Vallejo, and E. Gabidulin, “Graph-based metrics overqam constellations,” Information Theory, 2008. ISIT2008. IEEE International Symposium on, pp. 2494–2498,2008.[15] A. Singh, Load-Balanced Routing in InterconnectionNetworks, Ph.D. thesis, 2005.[16] L.G. Valiant, “A scheme for fast parallel communication,”SIAM Journal on Computing, vol. 11, no. 2, pp.350–361, 1982.[17] FJ Ridruejo Perez and J. Miguel-Alonso, “Insee: Aninterconnection network simulation and evaluation environment,”2005.[18] V. Puente, C. Izu, R. Beivi<strong>de</strong>, JA Gregorio, F. Vallejo,and JM Prellezo, “The adaptive bubble router,” J. ParallelDistrib. Comput., vol. 61, no. 9, pp. 1180–1208, 2001.<strong>JP2011</strong>-456


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Sistemas Web e Internet<strong>JP2011</strong>-457


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-458


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Incorporación <strong>de</strong>l dinamismo <strong>de</strong>l usuario en unbenchmark <strong>de</strong> comercio electrónico 1Raúl Peña-Ortiz, José Antonio Gil, Julio Sahuquillo, Ana Pont 2Departament d’ Informàtica <strong>de</strong> Sistemes i Computadors (DISCA), Universitat Politècnica<strong>de</strong> València,Valencia, SpainResumen— En los últimos años venimos asistiendoa un aumento en la cantidad <strong>de</strong> servicios ofrecidos através <strong>de</strong> la World Wi<strong>de</strong> Web (Web). Estos servicioshan ido evolucionando paulatinamente, <strong>de</strong>s<strong>de</strong> losprimitivos servicios estáticos <strong>de</strong> primera generación,hasta las complejas y personalizadas aplicaciones webactuales, en las que el usuario es algo más que unmero espectador y se ha convertido en un creador<strong>de</strong> contenido dinámico. Esta evolución ha producidoa su vez una evolución en las pautas <strong>de</strong> comportamiento<strong>de</strong> estos usuarios, que resultan cada vez másdinámicas. Consecuencia directa <strong>de</strong> la evolución <strong>de</strong> laWeb es la necesidad <strong>de</strong> nuevas herramientas para unaevaluación <strong>de</strong> prestaciones más acor<strong>de</strong> con las característicasdinámicas <strong>de</strong> la misma; herramientas que<strong>de</strong>ben ser capaces <strong>de</strong> representar el comportamientodinámico <strong>de</strong>l usuario en la generación <strong>de</strong> la carga web.Este trabajo presenta un nuevo entorno <strong>de</strong> pruebacapaz <strong>de</strong> incorporar generación <strong>de</strong> carga dinámica enla evaluación <strong>de</strong> prestaciones <strong>de</strong> sistemas <strong>de</strong> comercioelectrónico basados en web. Con tal fin, se ha partido<strong>de</strong>l reconocido benchmark <strong>de</strong> comercio electrónicoTPC-W y se ha integrado la generación <strong>de</strong> cargadinámica proporcionada por el generador GUER-NICA, aprovechando sus cualida<strong>de</strong>s a la hora <strong>de</strong> caracterizary reproducir carga web basada en los patronesdinámicos <strong>de</strong>l comportamiento <strong>de</strong>l usuario.El nuevo entorno ha sido validado contra TPC-W,mostrando resultados similares cuando no se consi<strong>de</strong>radinamismo en la caracterización <strong>de</strong> la carga.Palabras clave— Evaluación <strong>de</strong> prestaciones web,generador <strong>de</strong> carga web, carga web dinámica, mo<strong>de</strong>lado<strong>de</strong>l comportamiento dinámico <strong>de</strong>l usuario.I. IntroducciónLos servicios ofertados a través <strong>de</strong> la World Wi<strong>de</strong>Web (Web) han sufrido una constante evolución enlos últimos años <strong>de</strong>bido a los incesantes cambios <strong>de</strong>la tecnología web, lo que ha propiciado la aparición<strong>de</strong> nuevos tipos <strong>de</strong> comportamiento en los usuarios<strong>de</strong> la Web [1].En los primitivos servicios estáticos <strong>de</strong> la primerageneración, la Web suponía un medio <strong>de</strong> bajo costepara compartir información <strong>de</strong> escasa o nula privacidad,y la información era principalmente <strong>de</strong> tipotexto, con un pequeño porcentaje <strong>de</strong> imágenes embebidas.El usuario tipo <strong>de</strong> esta Web era un meroespectador que se limitaba a consultar informacióny navegar <strong>de</strong> acuerdo a los enlaces que encontrabaen las páginas visitadas [2]. Posteriormente, los contenidosdinámicos alcanzaron gran auge, dando lugara la segunda generación <strong>de</strong> servicios basados en web.1 Este trabajo ha sido parcialmente financiado por el Ministerio<strong>de</strong> Ciencia e Innovación en el proyecto TIN2009-08201.2 Emails: rpenya@upvnet.upv.es, jagil@disca.upv.es,jsahuqui@disca.upv.es, apont@disca.upv.esEsta generación se caracterizó por fuertes cambiosen sus infraestructuras y arquitecturas (p.e., nuevossistemas <strong>de</strong> información basados en web, soportadospor servidores <strong>de</strong> aplicaciones y bases <strong>de</strong> datos) quepermitieron la generación, interrogación y almacenamientodinámicos <strong>de</strong> información; dinamismo quese extendió al comportamiento <strong>de</strong>l usuario [3], a suspautas <strong>de</strong> navegación (más dinámicas y personalizadas),y por lo tanto al tráfico generado por lasmismas [4]. En la actualidad, nos encontramos conuna nueva oferta servicios don<strong>de</strong> el usuario ha <strong>de</strong>jado<strong>de</strong> ser únicamente consumidor <strong>de</strong> información,para pasar a participar activamente en la creación<strong>de</strong> contenidos personalizados y en la difusión o recomendación<strong>de</strong> los mismos [2].Como todo sistema en continuo cambio, tanto ensus aplicaciones como en las infraestructuras que lassustentan, los estudios <strong>de</strong> evaluación <strong>de</strong> prestacionesson pieza clave para presentar propuestas apropiadascuando se diseñan nuevos sistemas web [5] (p.e., serviciosweb, servidores web, proxies o políticas <strong>de</strong> distribución<strong>de</strong> contenidos). Todo proceso <strong>de</strong> evaluación<strong>de</strong> prestaciones <strong>de</strong>be emplear mo<strong>de</strong>los <strong>de</strong> carga precisosy representativos para garantizar la vali<strong>de</strong>z <strong>de</strong>los resultados. En el caso <strong>de</strong> la Web, el dinamismoimplícito en el comportamiento <strong>de</strong> sus usuarios dificultael diseño <strong>de</strong> mo<strong>de</strong>los capaces <strong>de</strong> representar lasnavegaciones reales.En trabajos previos [6] introdujimos un nuevomo<strong>de</strong>lo para caracterizar carga web dinámica, <strong>de</strong>nominadoDweb. Este mo<strong>de</strong>lo está basado en el comportamientodinámico <strong>de</strong>l usuario y permite representarsu capacidad para cambiar su comportamientoa lo largo <strong>de</strong>l tiempo, adoptando dinámicamentediferentes roles (p.e., surfer, buscador o comprador)y por lo tanto navegando la Web <strong>de</strong> diferentes maneras.El generador <strong>de</strong> carga GUERNICA fue implementandotomando como base Dweb.En el presente trabajo proponemos un nuevobenchmark web con capacidad para generar cargadinámica. Este nuevo entorno toma como base elreconocido benchmark TPC-W en el que se ha integradoel proceso <strong>de</strong> generación <strong>de</strong> carga <strong>de</strong> GUER-NICA, con el fin <strong>de</strong> dotarle <strong>de</strong> la capacidad <strong>de</strong> caracterizary generar carga web dinámica a través <strong>de</strong>Dweb.El resto <strong>de</strong>l artículo se estructura como sigue. <strong>La</strong>sección II discute las razones que nos han llevadoa realizar esta nueva propuesta <strong>de</strong> benchmark web.<strong>La</strong>s secciones III y IV presentan y validan nuestra<strong>JP2011</strong>-459


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011propuesta, respectivamente. Finalmente, exponemosalgunas conclusiones finales y trabajo futuro en lasección V.II. Motivación y trabajo relacionado<strong>La</strong> necesidad <strong>de</strong> mo<strong>de</strong>los <strong>de</strong> carga basados en elcomportamiento <strong>de</strong>l usuario [7] aparece con la crecienteimportancia <strong>de</strong> las aplicaciones web. Estanecesidad es especialmente relevante en los entornos<strong>de</strong> comercio electrónico, don<strong>de</strong> la caracterización<strong>de</strong>l comportamiento <strong>de</strong>l usuario no es sólo objetivo<strong>de</strong> la evaluación <strong>de</strong> prestaciones web, sino quetambién juega un importante papel en términos <strong>de</strong>fi<strong>de</strong>lización <strong>de</strong> clientes. En este tipo <strong>de</strong> aplicacionesse pone <strong>de</strong> manifiesto, entre otras, las siguientes características:i) importancia <strong>de</strong> la información crítica;ii) elevado porcentaje <strong>de</strong> contenido dinámico y personalizado;iii) necesidad en la calidad <strong>de</strong>l servicioy calidad <strong>de</strong>l producto que se ofrece a los usuariosque son tratados como clientes potenciales; y iv) incorporación<strong>de</strong> tecnología <strong>de</strong> última generación. Enconsecuencia, la utilización <strong>de</strong> mo<strong>de</strong>los imprecisos enla evaluación <strong>de</strong> aplicaciones <strong>de</strong> comercio electrónicopue<strong>de</strong> <strong>de</strong>rivar en conclusiones incorrectas que suponganacciones inapropiadas sobre las prestaciones <strong>de</strong>lsistema y sobre el <strong>de</strong>sarrollo <strong>de</strong> negocio.Floyd et al. [8] <strong>de</strong>scriben los inconvenientes <strong>de</strong>evaluar las prestaciones web mediante mo<strong>de</strong>los <strong>de</strong>carga analíticos, <strong>de</strong>bido principalmente al componentedinámico <strong>de</strong> la carga y a la gran diversidad <strong>de</strong>parámetros que influyen en la caracterización <strong>de</strong> losmo<strong>de</strong>los analíticos (e.g., diferentes protocolos, tiposcaracterísticos <strong>de</strong> tráfico, patrones <strong>de</strong> navegación enlos usuarios, etc). En general, los retos actuales en lacaracterización <strong>de</strong> la carga web son: i) el mo<strong>de</strong>lado<strong>de</strong>l comportamiento dinámico <strong>de</strong>l usuario [7], ii) la<strong>de</strong>finición <strong>de</strong> los roles que el usuario juega cuandonavega la web [9] y iii) la representación <strong>de</strong> los continuoscambios <strong>de</strong> rol [10].Existen pocos aunque interesantes esfuerzos para<strong>de</strong>finir el comportamiento <strong>de</strong>l usuario con el fin <strong>de</strong>caracterizar carga web representativa <strong>de</strong> cierto tipo<strong>de</strong> aplicaciones. Menascé et al. [11] introdujeron elCustomer Behavior Mo<strong>de</strong>l Graph (CBMG) que <strong>de</strong>scribepatrones <strong>de</strong> comportamiento <strong>de</strong>l usuario en lacarga relativa a aplicaciones <strong>de</strong> comercio electrónico.Duarte et al. [12] aplicaron este mo<strong>de</strong>lo para <strong>de</strong>finirla carga <strong>de</strong> la blogsfera; Shams et al. [13] extendieronCBMG para reflejar las <strong>de</strong>pen<strong>de</strong>cias existentes entrelas peticiones HTTP <strong>de</strong> una navegación y entre losdatos relativos al contexto <strong>de</strong> la misma. Benevenutoet al. [14] introdujeron el mo<strong>de</strong>lo Clickstream paracaracterizar el comportamiento <strong>de</strong>l usuario en las re<strong>de</strong>ssociales. Sin embargo, estos mo<strong>de</strong>los sólo caracterizanla carga web en paradigmas o aplicaciones<strong>de</strong> propósito específico, y no abordan el segundo ytercero <strong>de</strong> los retos mencionados anteriormente. Estas<strong>de</strong>ficiencias nos motivaron a proponer un mo<strong>de</strong>lo<strong>de</strong> carga <strong>de</strong> propósito general <strong>de</strong>nominado Dweb[6], que nos permite consi<strong>de</strong>rar mo<strong>de</strong>los <strong>de</strong>l comportamientodinámico <strong>de</strong>l usuario en la caracterización<strong>de</strong> la carga. Dweb representa el dinamismo<strong>de</strong>l usuario <strong>de</strong> forma precisa teniendo en cuenta lostres retos mencionados.Los estudios <strong>de</strong> evaluación <strong>de</strong> prestaciones web sonsoportados por software <strong>de</strong>dicado, que tiene el objetivo<strong>de</strong> validar la calidad <strong>de</strong> servicio <strong>de</strong> un sistemabajo condiciones <strong>de</strong> carga específicas <strong>de</strong>finidas normalmentepor mo<strong>de</strong>los <strong>de</strong> carga. Existen varios tipos<strong>de</strong> software <strong>de</strong>dicado a la evaluación <strong>de</strong> prestaciones,<strong>de</strong> entre los cuales po<strong>de</strong>mos <strong>de</strong>stacar los benchmarksy los generadores <strong>de</strong> carga. Los primeros persiguenreproducir las condiciones <strong>de</strong> carga típicas <strong>de</strong>l entorno<strong>de</strong> trabajo habitual, con el fin <strong>de</strong> constatar siel sistema evaluado cumple con las pautas <strong>de</strong> calida<strong>de</strong>stablecidas. Los segundos buscan la generación <strong>de</strong>un número <strong>de</strong> peticiones HTTP lo suficientementeimportante como para conseguir una <strong>de</strong>gradaciónsignificativa <strong>de</strong> la calidad <strong>de</strong>l servicio, que podría llegara la <strong>de</strong>negación <strong>de</strong>l mismo. De entre todas lasherramientas software evaluadas en un trabajo previo[15], el benchmark TPC-W es el mejor entorno<strong>de</strong> pruebas representativo <strong>de</strong> un sistema <strong>de</strong> comercioelectrónico, mientras que GUERNICA es el únicogenerador que reproduce <strong>de</strong> forma precisa la cargaweb dinámica, a través <strong>de</strong>l uso que hace <strong>de</strong> Dweb.TPC-W reproduce múltiples sesiones concurrentes<strong>de</strong> clientes sobre una librería on-line, pero no generacarga dinámica precisa porque sólo incluye unarepresetación parcial <strong>de</strong>l comportamiento dinámico<strong>de</strong>l usuario basada en el uso <strong>de</strong>l mo<strong>de</strong>lo CBMG.En consecuencia, en el presente trabajo proponemosun nuevo benchmark para entornos <strong>de</strong> comercioelectrónico con capacidad para caracterizar ygenerar carga web dinámica. Este benchmark sediseña como una extensión <strong>de</strong> TPC-W en cuya arquitecturase introduce la generación <strong>de</strong> carga dinámicabasada en Dweb mediante la integración <strong>de</strong>l núcleo<strong>de</strong> GUERNICA.III. Integración TPC-W y GUERNICAEl <strong>de</strong>sarrollo <strong>de</strong>l benchmark i<strong>de</strong>ado se ha realizado<strong>de</strong> acuerdo a tres premisas. En primer lugar,el benchmark <strong>de</strong>be <strong>de</strong>finir y reproducir <strong>de</strong> formaapropiada y precisa la carga dinámica. En segundolugar, <strong>de</strong>bemos obtener un entorno que facilite lasmedidas <strong>de</strong> aquellas métricas <strong>de</strong> rendimiento, tantoen la parte cliente como en la parte servidor, imprescindiblesen los estudios <strong>de</strong> evaluación <strong>de</strong> prestacionescuando contemplamos diferentes cargas web.Finalmente, el benchmark <strong>de</strong>be proporcionar un entornorepresentativo <strong>de</strong> los sistemas web transaccionalesque se han establecido en los últimos años.De entre todas las alternativas <strong>de</strong> generación <strong>de</strong>carga web evaluadas en trabajos anteriores [15],TPC-W es el único benchmark que se ciñe a lamayoría <strong>de</strong> las premisas anteriores, pero aunque contemplael comportamiento dinámico <strong>de</strong>l usuario en lacaracterización <strong>de</strong> la carga, no lo hace <strong>de</strong> forma precisa.Consecuentemente, proponemos una extensión<strong>de</strong> TPC-W en la que se contempla el uso <strong>de</strong> GUER-NICA para generar carga web dinámica <strong>de</strong> forma<strong>JP2011</strong>-460


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011apropiada, lo que nos permite cumplir con las trespremisas.<strong>La</strong> sección III-A presenta las principales características<strong>de</strong> TPC-W y <strong>de</strong> la implementación seleccionadacomo base <strong>de</strong> nuestro <strong>de</strong>sarrollo. Posteriormente,presentamos las principales funcionalida<strong>de</strong>s<strong>de</strong> GUERNICA y su arquitectura básica en la secciónIII-B. Finalmente, la sección III-C introduce la arquitectura<strong>de</strong> integración entre TPC-W y GUER-NICA que nos habilita a contemplar <strong>de</strong> forma apropiaday precisa carga dinámica en los estudios en losque emplear el benchmark.A. TPC Benchmark TM WTPC Benchmark TM W (TPC-W) es un benchmark<strong>de</strong> web transaccional que simula las principalesactivida<strong>de</strong>s <strong>de</strong> un sitio web <strong>de</strong> comercioelectrónico, concretamente <strong>de</strong> una tienda <strong>de</strong> libroson-line [16]. El benchmark reproduce la carga generadapor múltiples sesiones concurrentes <strong>de</strong> clientessobre una aplicación web que se encarga <strong>de</strong> servirlos contenidos estáticos y dinámicos asociados a lasactivida<strong>de</strong>s <strong>de</strong> consulta y venta <strong>de</strong> la tienda.TPC-W proporciona un entorno estándar, in<strong>de</strong>pendiente<strong>de</strong> la tecnología <strong>de</strong> implementación, <strong>de</strong> laarquitectura y <strong>de</strong> la infraestructura, que ha sido altamentecontrastado y aceptado por la comunidadcientífico-técnica en numerosos estudios <strong>de</strong> evaluación<strong>de</strong> prestaciones web [17], [18], [19]. Comotodo benchmark <strong>de</strong> comercio electrónico, TPC-Wpresenta una arquitectura cliente-servidor, recogidaen la Figura 1. Los agentes software ubicados en laparte cliente (Remote Browser Emulators) son los encargados<strong>de</strong> generar carga sobre la aplicación <strong>de</strong> comercioelectrónico <strong>de</strong>l servidor (E-commerce server).Con el fin <strong>de</strong> reproducir una carga web representativa,los agentes simulan el comportamiento que <strong>de</strong>beríatener un usuario real al navegar por el sitioweb. El servidor alberga el sistema bajo prueba(Server Un<strong>de</strong>r Test), que se compone <strong>de</strong>: i) un servidorweb y su sistema <strong>de</strong> almacenamiento <strong>de</strong> objetosestáticos, y ii) un servidor <strong>de</strong> aplicaciones y una base<strong>de</strong> datos para la generación <strong>de</strong> contenido dinámico.<strong>La</strong> pasarela <strong>de</strong> pagos (Payment Gateway Emulator)representa la entidad encargada <strong>de</strong> autenticar a losusuarios y autorizar sus pagos. Los tres componentesprincipales <strong>de</strong> la arquitectura comunican entre sí através <strong>de</strong> una red <strong>de</strong> interconexión <strong>de</strong>dicada.Para nuestros propósitos, adoptamos una implementaciónJava <strong>de</strong> TPC-W realizada por el ComputerArchitecture Group <strong>de</strong> la UW-Madison [20].Como muestra la Figura 2, la parte cliente <strong>de</strong> suarquitectura está concebida como una aplicación <strong>de</strong>consola y proporciona dos interfaces relacionadas conel proceso <strong>de</strong> generación <strong>de</strong> carga: i) el agente softwareencargado <strong>de</strong> simular a los clientes (EB), y ii)la factoría <strong>de</strong> agentes (EBFactory), cuya función esla <strong>de</strong> crear y configurar los agentes proporcionados.Estas interfaces actúan como punto <strong>de</strong> extensión ypermiten personalizar la caracterización <strong>de</strong> la cargaweb. <strong>La</strong> parte <strong>de</strong>l servidor se ha <strong>de</strong>sarrollado comoFig. 1.Arquitectura TPC-WFig. 2. Componentes principales en la implementación Java<strong>de</strong> TPC-Wuna aplicación web compuesta por un cojunto <strong>de</strong>Servlets que se encargan <strong>de</strong> recoger las peticiones<strong>de</strong> los clientes y acce<strong>de</strong>r a la base <strong>de</strong> datos para po<strong>de</strong>rservirlas.B. GUERNICAGUERNICA (Universal Generator of DynamicWorkload un<strong>de</strong>r WWW Platforms) es un softwaregenerador <strong>de</strong> carga web resultado <strong>de</strong> la cooperación<strong>de</strong>l Grupo <strong>de</strong> Investigación en Arquitectura y Prestaciones<strong>de</strong> la Web <strong>de</strong> la Universitat Politècnica <strong>de</strong>València y la empresa Intelligent Software Components.<strong>La</strong> principal característica <strong>de</strong> GUERNICA es eluso que hace <strong>de</strong> los conceptos <strong>de</strong>l mo<strong>de</strong>lo Dweb (Dy-Fig. 3.Principales componentes en GUERNICA<strong>JP2011</strong>-461


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011namic web workload mo<strong>de</strong>l) [6] a la hora <strong>de</strong> <strong>de</strong>finirel comportamiento <strong>de</strong>l usuario, lo que le permite resolvercompletamente los tres retos planteados en lacaracterización <strong>de</strong> la carga dinámica. El concepto<strong>de</strong> navegación <strong>de</strong>fine el comportamiento <strong>de</strong>l usuariomientras interactúa con la web y facilita la caracterización<strong>de</strong>l dinamismo <strong>de</strong>l usuario en sus navegaciones.Por otro lado el concepto <strong>de</strong> test <strong>de</strong> cargase asocia a un conjunto <strong>de</strong> navegaciones que <strong>de</strong>finenlos posibles comportamientos <strong>de</strong> un usuario y proporcionaun mecanismo para mo<strong>de</strong>lar estos comportamientosy los posibles cambios contemplados.GUERNICA se presenta como un conjunto <strong>de</strong> tresaplicaciones principales: generador <strong>de</strong> carga (workloadgenerator client), evaluador <strong>de</strong> rendimiento(performance evaluator client) y planificador <strong>de</strong> lostest <strong>de</strong> prestaciones (performance tests planner),que permiten in<strong>de</strong>pendizar y distribuir en diferentesnodos las principales activida<strong>de</strong>s <strong>de</strong> los procesos<strong>de</strong> evaluación <strong>de</strong> prestaciones y evaluación funcional<strong>de</strong> una aplicación web. Estas tres aplicacionesse <strong>de</strong>finen <strong>de</strong>ntro <strong>de</strong> una arquitectura basadaen componentes, recogida en la Figura 3. El elementocentral <strong>de</strong> la arquitectura, GUERNICA.core,es el encargado <strong>de</strong> implementar el proceso <strong>de</strong> generación<strong>de</strong> carga basado en Dweb. Los conceptos<strong>de</strong> test <strong>de</strong> carga y navegación están representadosrespectivamente por las interfaces WorkloadTesty WorkloadNavigation. El componente encargado<strong>de</strong> simular el comportamiento <strong>de</strong> los usuariosrecibe el nombre <strong>de</strong> NavigationEngine; su configuraciónse expresa en términos <strong>de</strong> los conceptos<strong>de</strong> Dweb y se almacena en un repositorio <strong>de</strong> nombreWorkloadTestRespository. El acceso centralizadoa GUERNICA.core se lleva a cabo a través <strong>de</strong>lCoreManager.C. Arquitectura <strong>de</strong> integración<strong>La</strong> arquitectura <strong>de</strong> integración entre TPC-W yGUERNICA (TGI) se recoge en la Figura 4. Dichaarquitectura se organiza en tres capas. <strong>La</strong> capa superiorestá <strong>de</strong>finida por la parte cliente <strong>de</strong> TPC-W,que proporciona las dos interfaces principales <strong>de</strong>l proceso<strong>de</strong> generación <strong>de</strong> carga (EB y EBFactory), <strong>de</strong>talladasen secciones previas. <strong>La</strong> capa inferior estárelacionada con el proceso <strong>de</strong> generación <strong>de</strong> cargaen GUERNICA, introducido en la sección anterior.Finalmente, la capa intermedia <strong>de</strong>fine la integraciónentre TPC-W y GUERNICA, la cual es suministradacomo una librería Java in<strong>de</strong>pendiente <strong>de</strong> TPC-W y<strong>de</strong> nombre TGI. Esta librería implementa un nuevotipo <strong>de</strong> agente generador <strong>de</strong> carga (i.e., DwebEB)que usa el núcleo <strong>de</strong> GUERNICA para reproducir elcomportamiento dinámico <strong>de</strong> los usuarios en el proceso<strong>de</strong> generación <strong>de</strong> carga. A fin <strong>de</strong> simplificarla implementación <strong>de</strong> este agente, un nuevo motor<strong>de</strong> carga (i.e., DwebExecutorEngine) ha sido implementadopara llevar a cabo el proceso <strong>de</strong> generación.Adicionalmente, una nueva factoría <strong>de</strong> agentes (i.e.,DwebEBFactory) se ha <strong>de</strong>sarrollado para controlar laconfiguración, creación y gestión <strong>de</strong> las instancias <strong>de</strong>lnuevo agente en el entorno <strong>de</strong> TPC-W.Fig. 4.Arquitectura <strong>de</strong> TGIIV. Validación <strong>de</strong> TGIPara po<strong>de</strong>r explotar con garantías en trabajos futurosel nuevo benchmark, lo hemos validado contraTPC-W, consi<strong>de</strong>rando una configuración específica<strong>de</strong> entorno experimental para la cual se han medidosus principales métricas <strong>de</strong> rendimiento. <strong>La</strong>s SeccionesIV-A y IV-B <strong>de</strong>scriben el entorno experimentaly las métricas <strong>de</strong> rendimiento, respectivamente.<strong>La</strong> validación se <strong>de</strong>talla en la Sección IV-C.A. Entorno experimental<strong>La</strong> configuración utilizada en el entorno experimentalpara llevar a cabo la validación, sigue las pautas<strong>de</strong> una arquitectura tradicional cliente-servidor,que en nuestro caso consiste en un Servidor UbuntuLinux como back-end y un Cliente Ubuntu Linuxcomo capa <strong>de</strong> front-end. El back-end ejecuta la aplicaciónservidor <strong>de</strong> TPC-W, cuya base es una aplicaciónweb Java (TPC-W web app) que está <strong>de</strong>splegadaen el servidor <strong>de</strong> aplicaciones Tomcat. <strong>La</strong>s peticionesa contenido estático, es <strong>de</strong>cir las imágenes, sonservidas directamente por el servidor web Apache.<strong>La</strong>s peticiones a contenido dinámico son redirigidasa Tomcat. <strong>La</strong> aplicación web se encarga <strong>de</strong> servir estaspeticiones dinámicas accediendo a la informaciónalbergada en la base <strong>de</strong> datos MySQL. Por otro lado,en el front-end se ejecuta la aplicación <strong>de</strong>l benchmarkasociada a la generación <strong>de</strong> carga. Tanto laaplicación <strong>de</strong> back-end como la <strong>de</strong> front-end se ejecutansobre el entorno Java SUN 5.0 (JRE 5.0). <strong>La</strong>Figura 5 ilustra el entorno experimental y <strong>de</strong>talla elhardware y software empleados.Dada la arquitectura en capas <strong>de</strong>l entorno experimental,el ajuste <strong>de</strong> los diferentes parámetros <strong>de</strong>lsistema, tanto <strong>de</strong>l servidor como <strong>de</strong> los generadores<strong>de</strong> carga, ha supuesto un punto fundamental paragarantizar que los posibles cuellos <strong>de</strong> botella <strong>de</strong> la infraestructuraempleada no distorsionan la validación<strong>JP2011</strong>-462


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 5.Entorno experimentalrealizada. Se ha empleado una configuración <strong>de</strong>TPC-W que contempla gran cantidad <strong>de</strong> artículos yclientes potenciales, concretamente 100.000 artículosy hasta 100 clientes potenciales registrados al seguirlas reglas <strong>de</strong> escalabilidad <strong>de</strong>l benchmark. Estascondiciones experimentales nos han obligado a revisarel ajuste <strong>de</strong>l acceso a la base <strong>de</strong> datos (p.e., eltamaño <strong>de</strong>l pool <strong>de</strong> conexiones), <strong>de</strong>l servicio <strong>de</strong> contenidoestático por parte <strong>de</strong> Apache (p.e., el número<strong>de</strong> workers que sirven peticiones HTTP), o <strong>de</strong>l servicio<strong>de</strong> contenido dinámico por parte <strong>de</strong> Tomcat(p.e., el número <strong>de</strong> hilos para proporcionar contenidodinámico). En la validación <strong>de</strong>l entorno, para cadatipo <strong>de</strong> carga <strong>de</strong> trabajo hemos realizado medidas<strong>de</strong> las métricas <strong>de</strong> rendimiento durante varias repeticiones<strong>de</strong> los experimentos, con el fin <strong>de</strong> recopilarsus valores <strong>de</strong> una manera precisa y representativa.Cada una <strong>de</strong> estas ejecuciones se compone <strong>de</strong> unafase <strong>de</strong> calentamiento <strong>de</strong> 15 minutos seguida <strong>de</strong> unafase <strong>de</strong> medición <strong>de</strong> 30 minutos.B. Métricas <strong>de</strong> rendimiento<strong>La</strong> Tabla I resume aquellas métricas <strong>de</strong>rendimiento medidas en nuestro estudio. <strong>La</strong>sprincipales métricas consi<strong>de</strong>radas <strong>de</strong>s<strong>de</strong> el punto <strong>de</strong>vista <strong>de</strong>l cliente son el tiempo <strong>de</strong> respuesta (WIRT)y el total <strong>de</strong> peticiones por página. En el servidor,nuestro estudio recoge las estadísticas <strong>de</strong>l servidorque son requeridas por la especificación <strong>de</strong> TPC-W(p.e., utilización <strong>de</strong> la CPU, actividad <strong>de</strong> la E/S <strong>de</strong> labase <strong>de</strong> datos, actividad <strong>de</strong> la E/S <strong>de</strong>l sistema o lasestadísticas el servidor web) y a<strong>de</strong>más aña<strong>de</strong> otrasestadísticas opcionales. <strong>La</strong>s métricas recogidas seorganizan en dos grupos <strong>de</strong> acuerdo a su naturaleza:i) métricas <strong>de</strong> los principales recursos hardware<strong>de</strong>l sistema, y ii) <strong>de</strong>talles <strong>de</strong>l rendimiento <strong>de</strong> losprincipales componentes software <strong>de</strong>l back-end. Conel fin <strong>de</strong> estandarizar el proceso <strong>de</strong> evaluación <strong>de</strong>prestaciones empleamos un middleware llamadocollectd 1 que nos permite realizar una medidaperiódica.C. Resultados experimentales<strong>La</strong> validación <strong>de</strong>l benchmark, requerida previamentea su explotación con garantías en estudios<strong>de</strong> evaluación <strong>de</strong> prestaciones, se ha realizado con-1 http://collectd.org/tra TPC-W con el fin <strong>de</strong> contrastar las principalesfuncionalida<strong>de</strong>s y comportamiento <strong>de</strong> ambas implementaciones.Con este fin, i<strong>de</strong>ntificamos un sitio web<strong>de</strong> validación a partir <strong>de</strong>l mapa web <strong>de</strong> la librería onlineasociada a TPC-W.Según la especificación <strong>de</strong> TPC-W, el CBMG completopara la librería on-line se compone <strong>de</strong> 14páginas únicas y <strong>de</strong> la probabilidad <strong>de</strong> transición entreellas. Existen tres tipos <strong>de</strong> escenarios posibles:shopping, browsing, y or<strong>de</strong>ring. Para ilustrar el proceso<strong>de</strong> validación <strong>de</strong> nuestro benchmark, hemos seleccionadoel escenario browsing que se compone <strong>de</strong>una actividad <strong>de</strong> navegación muy significativa frentea la escasa actividad asociada a la compra <strong>de</strong> libros(or<strong>de</strong>ring). Basado en este escenario, el sitio web<strong>de</strong> validación se reduce a las páginas <strong>de</strong>l proceso <strong>de</strong>búsqueda (i.e., Home, Search request, Search resulty Product <strong>de</strong>tail page) y las transiciones entre ellas.<strong>La</strong> Figura 6 <strong>de</strong>talla el CBMG simplificado parael sitio web <strong>de</strong> validación, mostrando las diferentespáginas <strong>de</strong>l proceso <strong>de</strong> búsqueda (Home, Search request,Search result y Product <strong>de</strong>tail page) entre lasque pue<strong>de</strong>n transitar los usuarios, y las transicionespermitidas por los arcos <strong>de</strong>l grafo. Los números sobrelos arcos indican la probabilidad <strong>de</strong> transiciónentre las dos páginas conectadas. Así por ejemplo,la probabilidad <strong>de</strong> ir a la Product <strong>de</strong>tail page <strong>de</strong>s<strong>de</strong>la página Search results es <strong>de</strong>l 0.6195. El significado<strong>de</strong> esta probabilidad hace referencia a que <strong>de</strong>spués<strong>de</strong> una búsqueda, sin tener en cuenta si la misma ha<strong>de</strong>vuelto resultados o no, la Product <strong>de</strong>tail page esvisitada en el 61.95% <strong>de</strong> los casos. El libro a cuyo<strong>de</strong>talle se acce<strong>de</strong> será un resultado <strong>de</strong> la búsqueda ouno <strong>de</strong> los libros miembros <strong>de</strong>l banner <strong>de</strong> noveda<strong>de</strong>sincluido en la mayoría <strong>de</strong> páginas <strong>de</strong> la librería. Estasprobabilida<strong>de</strong>s han sido inferidas a partir <strong>de</strong> losumbrales <strong>de</strong>finidos por la especificación <strong>de</strong> TPC-Wpara el escenario browsing. Destacamos que hemosmo<strong>de</strong>lado el mismo tipo <strong>de</strong> carga usando únicamenteel concepto <strong>de</strong> navegación <strong>de</strong> Dweb y <strong>de</strong>sactivandoel resto <strong>de</strong> parámetros <strong>de</strong>l mo<strong>de</strong>lo que nos permitencaracterizar el dinamismo.En las pruebas <strong>de</strong> validación, hemos contrastadoestas dos aproximaciones <strong>de</strong> caracterización <strong>de</strong> carga.Únicamente se consi<strong>de</strong>ran 50 agentes en la generación<strong>de</strong> carga <strong>de</strong>bido a que la implementaciónJava <strong>de</strong> TPC-W adoptada presenta algunas limitacionesen el proceso <strong>de</strong> generación, que le impi<strong>de</strong>n<strong>JP2011</strong>-463


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA IMétricas <strong>de</strong> rendimientoRecurso Métrica DescripciónClienteWIRTReqpageW IRT W IRT =Web Interaction Response Time (WIRT) se <strong>de</strong>fine en TPC-W como t2 − t1, don<strong>de</strong>t1 es el tiempo medido en el agente generador <strong>de</strong> carga antes <strong>de</strong> enviar al servidorel primer byte <strong>de</strong> la primera petición HTTP en la interacción web, y t2 es eltiempo medido en el agente generador <strong>de</strong> carga <strong>de</strong>spués <strong>de</strong> recibir el último byte<strong>de</strong> la respuesta a la última petición HTTP que completa la interacción web con elservidor.Requests per Page (Reqpage) es el número total <strong>de</strong> peticiones por página que sonservidas con éxito.∑∑i∈P ages W IRT i ∗Req i.i∈P ages Req iServidor<strong>La</strong>s métricas para los principales recursos hardware incluyen la utilización paraHardware Memoria UmemoryCPU U CP UDiscoU disk , X disktodos ellos, y la productividad para el disco y la red <strong>de</strong> interconexión.Red InterconexiónU net , X netApache {X, CP U, MEM} apache Los <strong>de</strong>talles <strong>de</strong> rendimiento <strong>de</strong> los principales componentes software <strong>de</strong>l servidorSoftware Tomcat {X, CP U, MEM} tomcatincluyen: productividad, uso <strong>de</strong> la memoria y <strong>de</strong> la CPU por parte <strong>de</strong>l componente,procesos o hilos <strong>de</strong> ejecución <strong>de</strong>l componente, etc.MySQL{X, CP U, MEM} mysql1.0 Home1.0 Product <strong>de</strong>tail 1.00.36750.6195 Searchrequest0.013 SearchresultsFig. 6. Caracterización <strong>de</strong> la carga <strong>de</strong> trabajo en la validacióngenerar más carga <strong>de</strong> forma efectiva aunque consi<strong>de</strong>remosmás <strong>de</strong> 50 agentes. <strong>La</strong>s medidas han sido realizadasdurante 50 ejecuciones con el fin <strong>de</strong> obtenerresultados apropiados con un nivel <strong>de</strong> confianza <strong>de</strong>l99%.<strong>La</strong>s Figuras 7 y 8 muestran los resultados más significativos,<strong>de</strong> entre todas las métricas medidas en losexperimentos, para las cargas <strong>de</strong>finidas con CBMGy Dweb.Ambas cargas generan un número similar <strong>de</strong> peticionesa página, como muestra la Figura 7(a). Concretamente,la carga mo<strong>de</strong>lada por Dweb produce un1% menos <strong>de</strong> peticiones que la carga <strong>de</strong>finida porCBMG, pero esta diferencia no influye en el tiempo<strong>de</strong> respuesta, que es virtualmente el mismo en amboscasos, tal y como muestra la Figura 7(b).Por otro lado, el servidor se caracteriza por un pobrenivel <strong>de</strong> estrés, representado por una baja utilización<strong>de</strong> los principales recursos hardware. <strong>La</strong>Figura 8(a) <strong>de</strong>nota un bajo nivel <strong>de</strong> utilización <strong>de</strong>la CPU y la memoria en ambos casos. El tráficoentrante y saliente no provoca más <strong>de</strong> un 3% <strong>de</strong> utilización<strong>de</strong> la red para ambas cargas, como ilustra laFigura 8(b). Por otra parte, la utilización <strong>de</strong>l discoes <strong>de</strong>masiado pequeña (inferior al 0.5%) para ser representadagráficamente en ambos casos.Los resultados <strong>de</strong> las pruebas <strong>de</strong> validaciónnos permiten <strong>de</strong>mostrar que Dweb y GUERNICApue<strong>de</strong>n ser empleados en los estudios <strong>de</strong> evaluación<strong>de</strong> prestaciones como alternativa a los mo<strong>de</strong>los <strong>de</strong>carga tradicionales.1.0V. Conclusiones<strong>La</strong> evolución <strong>de</strong> la World Wi<strong>de</strong> Web, <strong>de</strong>s<strong>de</strong> losprimitivos servicios estáticos <strong>de</strong> la primera generaciónhasta las complejas y personalizadas aplicacionesweb actuales, es motivo <strong>de</strong> otra evolución,la <strong>de</strong> las pautas <strong>de</strong> comportamiento <strong>de</strong> sus usuarios.Usuarios que han <strong>de</strong>jado <strong>de</strong> comportarse comomeros cosumidores <strong>de</strong> información y han pasado aparticipar activamente en la creación y difusión <strong>de</strong>contenidos web dinámicos. Consecuentemente, losusuarios actuales se caracterizan por un comportamientomás dinámico que <strong>de</strong>be ser contempladoen los mo<strong>de</strong>los <strong>de</strong> caracterización <strong>de</strong> carga y en lasherramientas que los utilizan para la evaluación <strong>de</strong>prestaciones web.En trabajos previos [6] introducimos un nuevomo<strong>de</strong>lo, <strong>de</strong>nominado Dweb, para caracterizar cargaweb dinámica <strong>de</strong> una forma más precisa, e implementamosel generador <strong>de</strong> carga GUERNICA en base adicho mo<strong>de</strong>lo.El presente trabajo introduce un nuevo entorno<strong>de</strong> prueba capaz <strong>de</strong> incorporar generación <strong>de</strong> cargadinámica en la evaluación <strong>de</strong> prestaciones <strong>de</strong> sistemas<strong>de</strong> comercio electrónico basados en web. Con talfin, se ha partido <strong>de</strong>l reconocido benchmark <strong>de</strong> comercioelectrónico TPC-W y se ha integrado la generación<strong>de</strong> carga dinámica proporcionada por Dweby GUERNICA. El nuevo entorno ha sido validadocontra el propio TPC-W.Como trabajo futuro pensamos <strong>de</strong>mostrar quenuestro mo<strong>de</strong>lo <strong>de</strong> carga es una alternativa másvaliosa porque es capaz <strong>de</strong> reproducir el comportamientodinámico <strong>de</strong>l usuario en la caracterización<strong>de</strong> la carga web. Con tal fin, <strong>de</strong>bemos cuantificarel efecto <strong>de</strong> usar carga dinámica en los estudios <strong>de</strong>evaluación <strong>de</strong> prestaciones web.<strong>JP2011</strong>-464


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011(a) Peticiones a página <strong>de</strong> usuario(b) WIRTFig. 7.Métricas <strong>de</strong>s<strong>de</strong> el punto <strong>de</strong> vista <strong>de</strong>l cliente(a) Utilización <strong>de</strong> la CPU y la memoria(b) Utilización <strong>de</strong> la red <strong>de</strong> interconexiónFig. 8.Métricas <strong>de</strong>s<strong>de</strong> el punto <strong>de</strong> vista <strong>de</strong>l servidorReferencias[1] P. Rodriguez, “Web Infrastructure for the 21st Century”,WWW, 2009.[2] G. Cormo<strong>de</strong> and B. Krishnamurthy, “Key differences betweenWeb 1.0 and Web 2.0”, First Monday Journal, 2008.[3] T. O’Reilly, “What is Web 2.0. Design Patterns and BusinessMo<strong>de</strong>ls for the Next Generation of Software”, 2005.[4] G. Abdulla, Analysis and Mo<strong>de</strong>ling of World Wi<strong>de</strong> WebTraffic, Ph.D. thesis, May 1998.[5] P. Barford and M. Crovella, “Generating representative webworkloads for network and server performance evaluation”,SIGMETRICS, 1998.[6] R. Peña-Ortiz, J. Sahuquillo, A. Pont, and J.A. Gil Salinas,“Dweb mo<strong>de</strong>l: representing Web 2.0 dynamism”, ComputerCommunications Journal, 2009.[7] P. Barford, A. Bestavros, A. Bradley, and M. Crovella,“Changes in Web client access patterns: Characteristics andcaching implications”, WWW, 1999.[8] S. Floyd and V. Paxson, “Difficulties in simulating the Internet,”IEEE/ACM Transactions on Networking, 2001.[9] H. Weinreich, H. Obendorf, E. Her<strong>de</strong>r, and M. Mayer, “Offthe beaten tracks: exploring three aspects of web navigation”,WWW, 2006.[10] S. Goel, A. Bro<strong>de</strong>r, E. Gabrilovich, and B. Pang, “Anatomyof the long tail: ordinary people with extraordinary tastes”,SDM, 2010.[11] D.A. Menascé and V.A.F Almeida, Scaling for E-Business:Technologies, Mo<strong>de</strong>ls, Performance, and Capacity Planning,2000.[12] F. Duarte, B. Mattos, J. Almeida, V.A.F Almeida, M. Curiel,and A. Bestavros, “Hierarchical characterization and generationof blogosphere workloads”, Tech. Rep.,2008.[13] M. Shams, D. Krishnamurthy Ph.D, and B. Far, “A mo<strong>de</strong>lbasedapproach for testing the performance of web applications”,SOQUA, 2006.[14] F. Benevenuto, T.R <strong>de</strong> Magalhães, M. Cha, and V.A.FAlmeida, “Characterizing user behavior in online social networks”,IMC, 2009.[15] R. Peña-Ortiz, J. Sahuquillo, J.A. Gil Salinas, and A. Pont,“WEB WORKLOAD GENERATORS: A survey focusing onuser dynamism representationa”, WEBIST, 2011.[16] “TPC BENCHMARK(TM) W Specification. Version 1.8”,Tech. Rep., 2002.[17] R.C. Dodge Jr, D.A. Menascé, and D. Barbará, “Testinge-commerce site scalability with TPC-W”, CMG, 2001.[18] C. Amza, A. Chanda, and A. Cox, “Specification and implementationof dynamic web site benchmarks”, IISWC, 2002.[19] D.F. García and J. García, “TPC-W e-commerce benchmarkevaluation”, Computer Journal, 2003.[20] H.W Cain, R. Rajwar, M. Mar<strong>de</strong>n, and M.H Lipasti, “Anarchitectural evaluation of Java TPC-W”, HPCA, 2001.<strong>JP2011</strong>-465


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-466


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Servicios Web Semánticos. Una aproximación<strong>de</strong>s<strong>de</strong> las OntologíasIván López Rodríguez, 1 Esther González Rodríguez, 2 Elena Sánchez Nielsen 3Resumen— Debido al enorme crecimiento <strong>de</strong> contenidosque ha sufrido la Web en los últimos años,cada vez resulta más difícil encontrar una informaciónen concreto. Como solución ha surgido la WebSemántica, para permitir a las máquinas enten<strong>de</strong>rcómo se organiza la información contenida en la web.Idéntica ha sido la problemática <strong>de</strong>l <strong>de</strong>scubrimiento einvocación <strong>de</strong> los servicios web publicados. ¿Podríaaplicarse la semántica también al mundo <strong>de</strong> los serviciosweb? En este trabajo se hace un estudio <strong>de</strong> laviabilidad <strong>de</strong> este enfoque y cómo aplicarlo en un caso<strong>de</strong> estudio concreto: “Turismo en la isla <strong>de</strong> Tenerife”.Palabras clave— Servicios Web, Semántica, Ontologías,WSDL, RDF, SPARQL.I. IntroducciónEn los últimos años, la Web ha crecido <strong>de</strong>forma exponencial en dimensión y capacidad.Paradójicamente, esta imparable evolución es, <strong>de</strong>s<strong>de</strong>hace algún tiempo, uno <strong>de</strong> sus principales problemasa la hora <strong>de</strong> localizar una información concreta. Similarha sido la dinámica <strong>de</strong> los servicios web. Mientrasque las funcionalida<strong>de</strong>s que ofrece la Web se hanvisto mejoradas consi<strong>de</strong>rablemente con el nacimiento<strong>de</strong> esta tecnología, el gran número <strong>de</strong> servicios surgidosdio lugar a que su <strong>de</strong>scubrimiento, invocación ycomposición, no resultara un proceso óptimo.Los servicios y sus proveedores se catalogan enrepositorios <strong>de</strong> forma análoga a como se organiza lainformación telefónica <strong>de</strong> empresas y particulares enlas páginas blancas y amarillas. Se pue<strong>de</strong>n localizartodos los servicios <strong>de</strong> una compañía o buscar unoconcreto a partir <strong>de</strong> su nombre. Este sistema es muy<strong>de</strong>ficiente <strong>de</strong> cara al usuario final, pues implica conocerla empresa o el nombre <strong>de</strong>l servicio web, lo cualno es habitual, ya que el usuario busca por palabrasque <strong>de</strong>scriban la solución a su problema. Sin embargo,incluso conociendo dichos datos, los serviciosweb resultantes tras una búsqueda serían numerososy es el usuario quien <strong>de</strong>be <strong>de</strong>terminar el servicio <strong>de</strong>su interés.<strong>La</strong> semántica aporta la solución organizativanecesaria para mejorar <strong>de</strong> forma consi<strong>de</strong>rable lasbúsquedas, ya que permite la interoperabilidad entresistemas informáticos reduciendo la mediación <strong>de</strong>lusuario. Dentro <strong>de</strong>l campo <strong>de</strong> los servicios web, estetrabajo propone algunas mejoras semánticas a través<strong>de</strong>l uso <strong>de</strong> sinónimos y relaciones jerárquicas entreconceptos. El uso <strong>de</strong> sinónimos permite hallar unservicio usando diferentes palabras clave, ya que se1 D.E.I.O.C., <strong>Universidad</strong> <strong>de</strong> <strong>La</strong> <strong>La</strong>guna, e-mail:ilopezro@ull.es.2 D.E.I.O.C., <strong>Universidad</strong> <strong>de</strong> <strong>La</strong> <strong>La</strong>guna, e-mail:alu3179@etsii.ull.es.3 D.E.I.O.C., <strong>Universidad</strong> <strong>de</strong> <strong>La</strong> <strong>La</strong>guna, e-mail:enielsen@ull.es.pue<strong>de</strong> representar que el concepto “x”es equivalentea “y”(muy útil para incorporar soporte idiomático).Por otro lado, se pue<strong>de</strong>n relacionar conceptos comunesa un dominio <strong>de</strong> forma jerárquica, lo cual es<strong>de</strong> gran utilidad para <strong>de</strong>volver resultados apropiadoscuando la búsqueda <strong>de</strong>l usuario no proporcionaninguno o para ofrecer resultados alternativos. Asímismo, es posible alcanzar un nivel mayor <strong>de</strong> refinamientoen las búsquedas si se realizan uniones eintersecciones con los resultados <strong>de</strong> varios conceptos,ejecutando en una sola consulta sentencias complicadas.Esto evita que sea el usuario el que tenga quefiltrar <strong>de</strong> entre todos los resultados, aquellos que son<strong>de</strong> su interés.Como se pue<strong>de</strong> apreciar, la adición <strong>de</strong> semántica serevela como una po<strong>de</strong>rosa herramienta que permiteal usuario final hacer un mejor uso <strong>de</strong> los serviciosweb anotados semánticamente. A lo largo <strong>de</strong> las siguientessecciones se explicará en más <strong>de</strong>talle cómolograrlo.Fig. 1: Web tradicional.Tras la introducción, el resto <strong>de</strong>l trabajo se organizacomo sigue:1. Se hace un breve recorrido temporal relacionandola Web con los servicios web y explicandocomo, en ambos casos se ha optado porla semántica para continuar su <strong>de</strong>sarrollo.2. El núcleo <strong>de</strong>l trabajo compren<strong>de</strong> un casopráctico en el que se aborda la recopilación <strong>de</strong>un conjunto <strong>de</strong> servicios web relacionados conel sector servicios. Más concretamente, con elturismo en la isla <strong>de</strong> Tenerife.3. A continuación, se presentan las conclusionesque se pue<strong>de</strong>n inferir sobre la adición <strong>de</strong>semántica a un campo en constante explotacióncomo son los servicios web.4. Por último, se comentan las principales líneas<strong>de</strong> trabajo abiertas.II. Estado <strong>de</strong>l arteLos principales problemas actuales <strong>de</strong> la Web son:la sobrecarga <strong>de</strong> contenidos y la heterogeneidad <strong>de</strong><strong>JP2011</strong>-467


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011las fuentes <strong>de</strong> información con el consiguiente problema<strong>de</strong> interoperabilidad. <strong>La</strong> Web Semántica[5]ayuda a resolver todos estos problemas permitiendoa los usuarios <strong>de</strong>legar tareas en el software. Graciasa la semántica <strong>de</strong> la Web, el software es capaz <strong>de</strong>procesar su contenido, razonar con éste, combinarloy realizar <strong>de</strong>ducciones lógicas para resolver problemascotidianos <strong>de</strong> interoperabilidad. Para enten<strong>de</strong>rcómo se ha llegado hasta aquí, se hace un breve resumen<strong>de</strong> la situación actual <strong>de</strong> las partes implicadasen el presente trabajo:A. Servicios WebEn Internet, la arquitectura orientada a servicios,se concretó como servicios web. Éstos permiteninterconectar procesos, in<strong>de</strong>pendientemente<strong>de</strong>l lenguaje con el que fueron escritos o sobre laplataforma sobre la que se estén ejecutando.En general, estos servicios son accesibles a través<strong>de</strong> su <strong>de</strong>scripción sintáctica en WSDL (Web ServiceDescription <strong>La</strong>nguage), con la cual un usuario pue<strong>de</strong>conocer las funciones con las que cuenta el servicioweb; así como el número y tipo <strong>de</strong> parámetros, tanto<strong>de</strong> entrada como <strong>de</strong> salida. En concreto, se <strong>de</strong>finenlos tipos <strong>de</strong> los datos que se transmitirán en los mensajes(types), los propios mensajes (message), el or<strong>de</strong>n<strong>de</strong> intercambio <strong>de</strong> dichos mensajes (portType)y, por último, una <strong>de</strong>scripción más concreta <strong>de</strong> losportType (binding).Fig. 2: Web Semántica.Sin embargo, al igual que pasó con la Web, el crecientenúmero <strong>de</strong> servicios web que se publican dificultalas búsquedas óptimas. Por ello, se crearondirectorios UDDI (Universal Description Discoveryand Integration), estándares <strong>de</strong> información acerca<strong>de</strong> los servicios web para permitir su <strong>de</strong>scubrimiento,aunque resultan insuficientes.B. Web SemánticaHasta el momento, el concepto conocido <strong>de</strong> la Web,es el <strong>de</strong> un almacén ingente <strong>de</strong> información don<strong>de</strong> noexiste un formato común y sólo es inteligible paralas personas (ver figura 1). Es <strong>de</strong>bido a estas limitacionesque evolutivamente surgió la Web Semántica.Por ello, todos los trabajos para la mejora <strong>de</strong> la Webestán orientados a convertir esa información (sólo accesiblea través <strong>de</strong> búsquedas por palabras clave) enconocimiento. Esto quiere <strong>de</strong>cir que las aplicacionesy agentes software encontrarán el significado <strong>de</strong> losdatos gracias a la metainformación (ver figura 2).El concepto <strong>de</strong> Web Semántica se basa en quelas máquinas comprendan el significado <strong>de</strong> la informacióndisponible en ella. Puesto que es muydifícil dotar a las máquinas <strong>de</strong> inteligencia artificialcapaz <strong>de</strong> compren<strong>de</strong>r el lenguaje <strong>de</strong> las personas,se ha optado porque sean éstas quienes representenlos datos en un lenguaje formal que permitaa los agentes inteligentes usar dicha informaciónpara extraer inferencias lógicas. Estos lenguajes sontambién conocidos como lenguajes <strong>de</strong> representación<strong>de</strong>l conocimiento. Se expresan a través <strong>de</strong> las ontologías.C. OntologíasSon la herramienta que posibilita la representación<strong>de</strong>l conocimiento. Es <strong>de</strong>cir, permiten la <strong>de</strong>finición <strong>de</strong>conceptos comunes para los <strong>de</strong>sarrolladores que necesitancompartir información <strong>de</strong> un dominio específicoo área <strong>de</strong> conocimiento. Más concretamente, unaontología está compuesta por <strong>de</strong>finiciones <strong>de</strong> conceptosbásicos y las relaciones existentes entre ellos, expresadas<strong>de</strong> forma que sean interpretables por lasmáquinas. A<strong>de</strong>más, esto ofrece importantes ventajasa las personas, como son:• Compartir la forma <strong>de</strong> interpretar cierta informaciónentre personas y agentes software.• Reutilizar el conocimiento <strong>de</strong> un dominio.• Realizar inferencias a partir <strong>de</strong>l conocimiento existentepara obtener nueva información.• Separar el conocimiento <strong>de</strong>l dominio <strong>de</strong>lconocimiento operacional.Para la representación <strong>de</strong>l conocimiento, la WebSemántica utiliza RDF, SPARQL y OWL. Estosmecanismos ayudan a convertir la Web en una infraestructuraglobal en la que es posible compartir yreutilizar datos entre diferentes usuarios.• RDF (Resource Description Framework) proporcionainformación <strong>de</strong>scriptiva simple sobre losrecursos que se encuentran en la Web y se utiliza,por ejemplo, en catálogos <strong>de</strong> libros, directorios,colecciones personales <strong>de</strong> música, fotos,eventos, etcétera.• SPARQL (SPARQL Protocol and RDF Query<strong>La</strong>nguage) es un lenguaje <strong>de</strong> consulta sobreRDF, que permite hacer búsquedas sobre los recursos<strong>de</strong> la Web Semántica utilizando distintasfuentes datos. Tiene un comportamiento similara SQL pero, a la hora <strong>de</strong> trabajar con la información,lo hace a través <strong>de</strong> RDF. Por lo tanto,las consultas SPARQL acce<strong>de</strong>n a la informaciónen el formato <strong>de</strong> tripleta establecido en RDF: sujeto,propiedad, valor; a diferencia <strong>de</strong> SQL quelo hace con tablas y columnas.• OWL es un mecanismo que extien<strong>de</strong> a RDF-S (RDF Schema) y se utiliza para <strong>de</strong>sarrollartemas o vocabularios específicos en los que asociaresos recursos. Lo que hace OWL es proporcionarun lenguaje para <strong>de</strong>finir ontologías estructuradasque puedan ser utilizadas a través<strong>de</strong> diferentes sistemas. <strong>La</strong>s ontologías son uti-<strong>JP2011</strong>-468


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011lizadas por los usuarios, las bases <strong>de</strong> datos ylas aplicaciones que necesitan compartir informaciónespecífica perteneciente a un campo <strong>de</strong>terminado,como pue<strong>de</strong> ser el <strong>de</strong> las finanzas, lamedicina, el <strong>de</strong>porte, etcétera.D. Servicios Web SemánticosHasta ahora, los servicios web sólo se <strong>de</strong>finían <strong>de</strong>manera sintáctica gracias al lenguaje ampliamenteutilizado WSDL. Éste permite que se enumerenlas funciones que componen el servicio, el número<strong>de</strong> parámetros que recibe cada función y su tipo,pero resulta limitado ya que, la simple <strong>de</strong>finiciónsintáctica no almacena información sobre el significado<strong>de</strong> dichas funciones: ¿qué hacen?, ¿para quésirven?. Por esa misma razón, realizar búsquedas <strong>de</strong>servicios web es una tarea ardua y no es posible queagentes software puedan, <strong>de</strong> forma autónoma, usarestos servicios. Para solucionar todos estos problemasse <strong>de</strong>be añadir una <strong>de</strong>scripción <strong>de</strong> más alto nivelal servicio web, es <strong>de</strong>cir, una <strong>de</strong>scripción semántica.Existen dos alternativas para añadir metadatos alos servicios: los servicios que están expresadossemánticamente y los servicios que aña<strong>de</strong>n anotacionessemánticas a las sintácticas. En estetrabajo se ha optado por seguir la segunda aproximación,utilizando las ontologías para realizar las anotacionessemánticas sobre las sintácticas (<strong>de</strong>finición<strong>de</strong> los servicios web).Los servicios web enriquecidos con la semánticapermiten construir escenarios en los que se hace posible:• Descubrir servicios web automáticamente.• Invocar servicios web automáticamente.• Componer e interoperar con otros servicios webautomáticamente.• Monitorizar servicios web automáticamente.El trabajo <strong>de</strong>sarrollado se centra en el primerpunto y, para ilustrar las posibilida<strong>de</strong>s reales, se harealizado un caso práctico.III. Caso <strong>de</strong> Estudio: Provisión <strong>de</strong> ServiciosWeb Semánticos en el DominioTurísticoCon el fin <strong>de</strong> evaluar el rendimiento <strong>de</strong> las tecnologíassemánticas, se propone como caso <strong>de</strong> estudiocrear una herramienta para localizar serviciosturísticos localizados en el contexto geográfico <strong>de</strong> laisla <strong>de</strong> Tenerife (Tenerife e-Tourist MarketPlace). Enla figura 3 se pue<strong>de</strong> ver una representación <strong>de</strong>l problema.El objetivo final <strong>de</strong> este caso <strong>de</strong> estudio secentra en el proceso <strong>de</strong> catalogación y búsqueda <strong>de</strong>servicios web en el dominio propuesto. Con este fin,se evalúan y optimizan las búsquedas <strong>de</strong> serviciosmediante la incorporación <strong>de</strong> búsquedas semánticasen lugar <strong>de</strong> las tradicionales búsquedas por palabrasclaves.En el caso <strong>de</strong> estudio que se plantea, lametodología empleada para facilitar la búsqueda <strong>de</strong>servicios web relacionados con los servicios turísticos,Fig. 3: Mo<strong>de</strong>lo <strong>de</strong>l caso <strong>de</strong> estudio.se basa en catalogar cada uno <strong>de</strong> los servicios web enla ontología. Por lo tanto, el primer paso consiste encrear una ontología que mo<strong>de</strong>le el abanico <strong>de</strong> categoríasque <strong>de</strong>finen las posibles preferencias y opciones<strong>de</strong> un turista. En la figura 4 se pue<strong>de</strong>n ver algunas<strong>de</strong> las categorías creadas para ello. <strong>La</strong>s clases serelacionan jerárquicamente entre sí y, una vez mo<strong>de</strong>ladala ontología, es necesario anotar en la categoríacorrespondiente todos los servicios web ofrecidos alusuario final.<strong>La</strong> ontología <strong>de</strong>sarrollada durante este trabajadoha sido mo<strong>de</strong>lada haciendo uso <strong>de</strong>l software Protégé,un entorno <strong>de</strong> <strong>de</strong>sarrollo <strong>de</strong> ontologías, <strong>de</strong> códigoabierto y libre distribución que permite editar ontologíasy bases <strong>de</strong> conocimiento que pue<strong>de</strong>n ser exportadasa diferentes formatos, como son: OWL,RDF y XML Schema.Para realizar las búsquedas pertinentes en dichaontología, se pue<strong>de</strong> almacenar en un fichero tipoOWL (a<strong>de</strong>cuado para estructuras pequeñas). Sinembargo, es mucho más eficiente y robusto exportarlaa una base <strong>de</strong> datos con estructura tipo Jena.Jena es un framework creado para facilitar el <strong>de</strong>sarrollo<strong>de</strong> aplicaciones semánticas. Entre otras posibilida<strong>de</strong>spermite al programador interactuar con informaciónen formato RDF y realizar consultas enformato SPARQL como la que se presenta a continuación:String queryString = ”PREFIX tf: ”+ ”SELECT ?item ?name ” + ”WHERE ” + ”{ ”+ ”?item tf:Name ?name . ”+ ”FILTER regex(?name, ’” + wordIn + ”’, ’i’) . ”+ ”} ”;Listing 1: Consulta SPARQL.A. Algoritmo <strong>de</strong> búsqueda por nombreEl primer, y más simple, tipo <strong>de</strong> búsqueda consisteen introducir sólo palabras clave pero sin indicarninguna categoría <strong>de</strong> servicio. Se realiza entoncesuna búsqueda por nombres entre todos losítems almacenados en la base <strong>de</strong> datos. Es la opciónmás costosa computacionalmente. <strong>La</strong> relevancia <strong>de</strong>un servicio se calcula como el número <strong>de</strong> coinci<strong>de</strong>nciasocurridas entre el nombre <strong>de</strong> dicho servicio y las<strong>JP2011</strong>-469


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011palabras introducidas por el usuario.B. Algoritmo <strong>de</strong> búsqueda por claseEl segundo tipo <strong>de</strong> consulta es aquella en la queel usuario selecciona una o más clases pero no introduceninguna palabra clave. Por lo tanto, en el resultadoaparecerán todos los servicios que pertenezcana algunas <strong>de</strong> las clases seleccionadas. Sin embargo,hay que aclarar que las clases existentes relacionadascon las zonas geográficas (Norte, Sur, Metropolitanay todos sus <strong>de</strong>scendientes) son tratadas <strong>de</strong> formadistinta. Esto es así para ajustar correctamente elnúmero <strong>de</strong> resultados <strong>de</strong>vueltos tras una consulta,lo cual se ilustra con el siguiente ejemplo. Si elusuario introduce como términos <strong>de</strong> búsqueda “hotelesapartamentos”en los resultados <strong>de</strong>berían aparecertodos los servicios que pertenezcan a ambas clases.Es <strong>de</strong>cir, la unión <strong>de</strong> ambos conjuntos. Pero si elusuario introduce “hoteles orotava”y se muestra launión <strong>de</strong> ambos conjuntos en la búsqueda aparecerían,a<strong>de</strong>más <strong>de</strong> todos los hoteles en <strong>La</strong> Orotava(el objetivo buscado), todos los servicios ubicados en<strong>La</strong> Orotava: parques temáticos, gimnasios, museos...lo cual no sería el comportamiento esperado. Esto esasí porque, como existe una clase que hace referenciaa un <strong>de</strong>nominador geográfico como es Orotava, se<strong>de</strong>bería <strong>de</strong> mostrar la intersección <strong>de</strong> ambos conjuntos.Este es el motivo porque el que se <strong>de</strong>ben <strong>de</strong>tratar <strong>de</strong> diferente forma los nombres <strong>de</strong> lugares opuntos cardinales.C. Algoritmo <strong>de</strong> búsqueda por clases y nombreEs una opción <strong>de</strong> búsqueda en la que el usuariopue<strong>de</strong> marcar una o varias clases así como introduciruna o varias palabras claves. El sistema buscará,<strong>de</strong> entre todos los servicios ofrecidos en cada clase,aquellos que coincidan con las palabras claves.Para la implementación se ha creado un métodoque se encarga <strong>de</strong> lanzar las sucesivas búsquedas <strong>de</strong>las palabras claves por todas las clases marcadas porel usuario en la interfaz gráfica y restringiendo losresultados por cada zona seleccionada.D. Algoritmo <strong>de</strong> búsqueda inteligenteEn este caso se implementan búsquedas idénticasa las anteriores pero sin que el usuario tenga queintroducir manualmente qué palabras indican clasesy cuáles nombres.El primer paso es filtrar la entrada proveniente <strong>de</strong>lusuario eliminando palabras que no aportan informaciónsemántica, como los artículos, las preposiciones,las conjunciones, etc. Este procedimiento serealiza tanto para el idioma español como para elinglés.El siguiente problema a abordar es capturar elnombre <strong>de</strong> las clases a partir <strong>de</strong> la entrada <strong>de</strong>lusuario. <strong>La</strong> dificultad estriba en que se pue<strong>de</strong> <strong>de</strong>finirel concepto <strong>de</strong> muy distintas maneras. Para hacerreferencia a la clase Hotel se pue<strong>de</strong> escribir “Hotel”,“Hotels”o “Hoteles”. Todas estas palabras seleccionaránla clase “Hotels”en la búsqueda. Paralograr dicho efecto se almacena en la ontología unaserie <strong>de</strong> sinónimos (tanto en inglés como en español)para cada clase.Como ejemplo, si se introduce la búsqueda “palacehoteles en puerto”, el sistema sabrá que hay que buscarla palabra “palace”en los servicios que <strong>de</strong>sciendan<strong>de</strong> la clase “Hotels”y “Puerto <strong>de</strong> la Cruz”.Fig. 4: Ontología.Al trabajar con el buscador en el apartado <strong>de</strong>búsquedas sin asistencia, aparece un problema. Esimposible encontrar un servicio cuyo nombre ya existapara una clase. En caso <strong>de</strong> querer localizarun bar llamado “<strong>La</strong> Cruz”mediante la búsqueda “lacruz”el sistema eliminará la palabra “la”por superfluay cambiará “cruz”por la clase “Puerto <strong>de</strong> laCruz”. Para evitar este comportamiento que, aunque<strong>de</strong>seable en la mayoría <strong>de</strong> los casos, se pue<strong>de</strong> convertiren un impedimento, se ha introducido un carácterespecial:• El símbolo <strong>de</strong> cierre <strong>de</strong> exclamación (“!”) cuandoantece<strong>de</strong> a una palabra evita que ésta se transformeen una llamada <strong>de</strong> clase y que<strong>de</strong> comopalabra clave <strong>de</strong> búsqueda.Así, una búsqueda con el término “!cruz”arrojaráservicios cuyo nombre incluya esa palabra.Otro aspecto que se comprobó que se podía mejorarson los campos <strong>de</strong> búsqueda. Hasta ahora sebuscaba en el campo “Name”<strong>de</strong> los servicios. Estoes suficiente para la mayoría <strong>de</strong> las búsquedas. Perodado que en la ontología se pue<strong>de</strong> almacenar muchamás información, como el número <strong>de</strong> estrellas <strong>de</strong> loshoteles, el precio medio por noche en un alojamiento,la dirección <strong>de</strong>l archivo WSDL, etcétera, sería un errorno refinar las búsquedas usando estos campos.Para lograr búsquedas más eficientes se incluyóotro carácter especial: el signo <strong>de</strong> cierre <strong>de</strong> interrogación(“?”). De esta forma, el siguiente ejemplo<strong>de</strong> búsqueda introducida por un usuario “hotelpuerto ?category>=3 ?pricepernight


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011probando cada resultado buscando los hoteles quecumplieran con sus requerimientos (más <strong>de</strong> tres estrellasy menos <strong>de</strong> 60 euros).Otro ejemplo, haciendo uso <strong>de</strong>l campo WSDL seríael siguiente: “turquesa ?WSDL


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011una herramienta que proporciona una interacciónsencilla y cómoda con la <strong>de</strong>finición <strong>de</strong> la ontología.Al finalizar el trabajo, se dispone <strong>de</strong> una herramientaque permite localizar semánticamente serviciosweb relacionados con el turismo en Tenerife yque a<strong>de</strong>más, es fácilmente ampliable a cualquier zonageográfica o, incluso, a otras áeras <strong>de</strong>l conocimientoque no sean el turismo. Es importante resaltar queel código está diseñado para soportar, sin necesidad<strong>de</strong> modificaciones, una ampliación <strong>de</strong> la ontología.Los nombres <strong>de</strong> las clases y sus sinónimos no estánincrustados en el código sino que se leen en el momentoque se carga la ontología. A<strong>de</strong>más, se permiteal usuario introducir búsquedas tanto en inglés comoen español (incluidas palabras con acentos y ’ñ’).Otro <strong>de</strong> los puntos fuertes <strong>de</strong>l buscador son lascarácteres especiales como “!”y, especialmente “?”,que permiten buscar servicios por un atributo dado(no sólo por nombre). Esto contribuye a realizarbúsquedas más complejas y abre la posibilidad <strong>de</strong>añadir nuevas búsquedas (ampliando la ontología)sin modificar el código. Por ejemplo, si se aña<strong>de</strong>n losservicios que representan cines y uno <strong>de</strong> los atributoses si los recintos están adaptados a personasminusválidas o no, se podría realizar la siguientebúsqueda: “cines ?minusvalido=1”, que <strong>de</strong>volveríalos cines que están adaptados para minusválidos.Finalmente, se ofrecen una serie <strong>de</strong> búsquedas recomendadaspara cada perfil <strong>de</strong> usuario. Dependiendo<strong>de</strong> su rango <strong>de</strong> edad, <strong>de</strong> su liqui<strong>de</strong>z económica y<strong>de</strong> algunas otras características sobre el propio viaje(como duración o método <strong>de</strong> transporte preferido)se le ofrecerán unos servicios u otros. En el caso<strong>de</strong> no aportar información personal, se le asocia unperfil estándar llamado “None”, en el que se agrupanalgunos servicios <strong>de</strong> interés general o “serviciosrecomendados estándar”. A<strong>de</strong>más, en estasbúsquedas recomendadas, se extraen aquellas palabrasrelacionadas con zonas geográficas, en el caso<strong>de</strong> que existan, y se recalcula la relevancia para queaparezcan en los primeros puestos los servicios localizadosen esas cercanías. De esta forma se preten<strong>de</strong>ofrecer al usuario servicios que puedan serle <strong>de</strong> utilida<strong>de</strong>n la zona <strong>de</strong> su interés.Es importante resaltar que, basándose en la inmadurez<strong>de</strong> las herramientas y en el bajo número<strong>de</strong> estudios en este sentido, la semántica aplicada alos servicios web es un terreno relativamente nuevo yque necesita tiempo aún para implantarse con tantafuerza como los servicios web lo han hecho.V. Líneas <strong>de</strong> trabajo abiertas<strong>La</strong> semántica es un campo relativamente nuevoy en constante <strong>de</strong>sarrollo por lo que cuenta con unabanico enorme <strong>de</strong> líneas abiertas. En relación conla herramienta presentada en este trabajo, se pue<strong>de</strong>continuar la investigación por tres vías principales:• Razonador semántico: es posible implementarun razonador que tenga como entrada ellenguaje natural y que <strong>de</strong>vuelva como salidalas palabras clave y las clases en las que se<strong>de</strong>be realizar la búsqueda. Por ejemplo, anteuna entrada como “Tengo hambre”podría sugerirrealizar una búsqueda en la clase “Food”(enla que están englobadas las clases “Restaurants”y“Taverns”, así como sus correspondientessinónimos en todos los idiomas.• Búsquedas recomendadas: actualmente sehan establecido un conjunto <strong>de</strong> categorías recomendadassegún el perfil <strong>de</strong>l usuario y las características<strong>de</strong>l viaje, pero esto es sólo un ejemplo<strong>de</strong> uso <strong>de</strong> dichas búsquedas. Se podríanutilizar para intentar arrojar resultados a<strong>de</strong>cuadoscuando la búsqueda principal fracasa.Por ejemplo, si una búsqueda como “OrotavaMartiánez”no <strong>de</strong>vuelve ningún resultado sepodría cambiar por “North Martiánez”pues laclase “North”engloba todos los municipios <strong>de</strong>lnorte y es más probable encontrar algún resultado.• Inferencia <strong>de</strong>l perfil: obtener el perfil<strong>de</strong>l usuario (ver figura 6) automáticamente através <strong>de</strong> sus consultas. Los resultados <strong>de</strong>las búsquedas contienen información acerca <strong>de</strong>quiénes son sus clases padres. Si los resultadosse engloban, mayoritariamente, bajo la clase“Youth”se le pue<strong>de</strong> asignar ese perfil al usuarioen lugar <strong>de</strong>l perfil por <strong>de</strong>fecto (“None”). De estaforma se conseguirían unos resultados recomendadosmás en concordancia con los intereses <strong>de</strong>lusuario.Agra<strong>de</strong>cimientosEste trabajo ha sido parcialmente financiado porel Ministerio <strong>de</strong> Educación y Ciencia (Ref. TIN2008-06570-C04-C03) a través <strong>de</strong>l proyecto COPABIB.Agra<strong>de</strong>cer también la inestimable ayuda proporcionadapor la profesora D a . Elena Nielsen, directora<strong>de</strong>l presente trabajo.Referencias[1] S. Vinoski, Web Services Interactions Mo<strong>de</strong>ls, Part 1:Current Practice, IEEE Internet Computing, Vol 6, N o 3,pp. 89-91, 2002.[2] Tim Berners-Lee, What the Semantic Web can representhttp://www.w3.org/DesignIssues/RDFnot.html[3] Rudi Stu<strong>de</strong>r, Stephan Grimm, Andreas Abecker (Eds.),Semantic Web Services. Concepts, Technologies and Applications,Springer-Verlag, 2007.[4] M. Horridge, H. Knublauch, A. Rector, R. Stevens, C.Wroe, A Practical Gui<strong>de</strong> To Building OWL OntologiesUsing The Protégé-OWL Plugin and CO-ODE Tools Edition1.0 http://www.co-o<strong>de</strong>.org/resources/tutorials/ProtegeOWLTutorial.pdf[5] Karin Breitman, Marco Casanova, Walter Truszkowski,Semantic Web: Concepts, Technologies and Applications,Springer-Verlag, 2007.[6] Miguel Ángel Abián, El futuro <strong>de</strong> la web: XML,RDF/RDFS, ontologías y la Web semánticahttp://www.javahispano.org/contenidos/archivo/156/El_futuro_<strong>de</strong>_la_Web.zip[7] Asunción Gómez, Oscar Corcho, Ontology languages forthe Semantic Web, IEEE Intelligent Systems, vol17, issue1, pp. 54-60, 2002.<strong>JP2011</strong>-472


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Tecnología grid, cluster, cloud computing y plataformasdistribuidas<strong>JP2011</strong>-473


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-474


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Planificación <strong>de</strong> DAGS en entornosoportunísticosMaria <strong>de</strong>l Mar López, Elisa Heymann, Miquel Àngel Senar1Resumen—<strong>La</strong>s aplicaciones tipo workflow tienen granvolumen <strong>de</strong> cómputo y necesidad <strong>de</strong> transferencia <strong>de</strong>un importante volumen <strong>de</strong> datos con lo cual su tiempo<strong>de</strong> finalización es elevado. Para reducir este tiempo<strong>de</strong> finalización, es necesario ejecutarlas en diferentesmáquinas interconectadas entre sí a través <strong>de</strong> unared. Para obtener un buen tiempo <strong>de</strong> finalizacióno makespan <strong>de</strong>l DAG, es importante asignar correctamentesus tareas a las máquinas disponibles <strong>de</strong>l entorno<strong>de</strong> ejecución. El encargado <strong>de</strong> realizar la asignación<strong>de</strong> las tareas a las máquinas es el planificador.El principal problema <strong>de</strong> un planificador estático esque no tiene en cuenta los cambios que ocurren en elentorno <strong>de</strong> ejecución durante la ejecución <strong>de</strong>l DAG.Para solucionar este problema, se ha realizado unplanificador dinámico, el cual toma información sobreel comportamiento <strong>de</strong> las tareas que finalizan su ejecucióny el entorno <strong>de</strong> ejecución, y, reacciona ante loscambios <strong>de</strong>tectados auto-adaptando la planificación <strong>de</strong>lresto <strong>de</strong> tareas pendientes <strong>de</strong> ejecución. El objetivo<strong>de</strong> este trabajo es reducir la sobrecarga producida alrealizar excesivas auto-adaptaciones sin empeorar elmakespan. Para reducir la sobrecarga, el algoritmo seauto-adapta solo cuando se estima que habrá ganancia.<strong>La</strong>s políticas propuestas se han simulado y posteriormenteimplementado en un entorno real y engeneral se ha obtenido una reducción <strong>de</strong> la sobrecargasuperior a un 20%Palabras clave— Entornos oportunisticos, workflow,planificaciónI. IntroducciónEL trabajo se centra en aplicaciones don<strong>de</strong> se <strong>de</strong>finentareas y un flujo <strong>de</strong> datos entre ellas. Elflujo <strong>de</strong> datos implica que existe un or<strong>de</strong>n <strong>de</strong> ejecución<strong>de</strong> las tareas. A estas aplicaciones se las<strong>de</strong>nomina workflow. Los DAGS representan workflowsque no tienen circuitos. Actualmente existenmuchas aplicaciones workflow científicas con elevadotiempo <strong>de</strong> cómputo y elevadas transferencias <strong>de</strong>datos. [19], [20]Si se ejecutan estos workflows <strong>de</strong> forma secuencial(una tarea <strong>de</strong>trás <strong>de</strong> otra en la misma máquina) eltiempo <strong>de</strong> finalización es elevado (<strong>de</strong>l or<strong>de</strong>n <strong>de</strong> horas,días o semanas). Con el objetivo <strong>de</strong> reducir el tiempo<strong>de</strong> ejecución <strong>de</strong>l workflow, las tareas se ejecutan endiferentes máquinas <strong>de</strong> manera concurrente.Para po<strong>de</strong>r ejecutar las tareas <strong>de</strong>l workflow enparalelo se utilizan un conjunto <strong>de</strong> máquinas interconectadasa través <strong>de</strong> una red. A este conjunto <strong>de</strong>máquinas y red se la <strong>de</strong>nomina escenario en a<strong>de</strong>lante.<strong>La</strong> principal característica <strong>de</strong>l escenario es la heterogeneidad<strong>de</strong> sus máquinas.Para obtener un buen makespan es necesariorealizar planificación <strong>de</strong> las tareas <strong>de</strong>l DAG alas máquinas disponibles <strong>de</strong>l entorno <strong>de</strong> ejecución.1 Dpto. <strong>de</strong> Arquitectura <strong>de</strong> Computadores, Univ.Autónoma <strong>de</strong> Barcelona, e-mail: mmar@caos.uab.es.Elisa.Heymann,miquelangel.senar@uab.es.Antes <strong>de</strong> planificar las tareas se <strong>de</strong>be obtener información<strong>de</strong>l entorno <strong>de</strong> ejecución (características<strong>de</strong> las máquinas disponibles y <strong>de</strong> la red). Posteriormentese realiza la planificación. Esta planificaciónse <strong>de</strong>nomina estática, tiene en cuenta el entorno <strong>de</strong>ejecución antes <strong>de</strong> realizar la planificación sin consi<strong>de</strong>rarposibles alteraciones que en él se produzcan.Los entornos oportunísticos tienen un comportamientodinámico. Esto presenta un problema a laplanificación estática, pues el escenario pue<strong>de</strong> cambiardurante la ejecución <strong>de</strong>l DAG. Los cambios quese producen en el escenario son: <strong>de</strong>saparición <strong>de</strong>una máquina, aparición <strong>de</strong> una nueva máquina ymodificación <strong>de</strong> las características <strong>de</strong> una o variasmáquinas.Como consecuencia <strong>de</strong>l dinamismo <strong>de</strong> los escenariosoportunísticos se ha <strong>de</strong>sarrollado un algoritmo <strong>de</strong>planificación dinámica. Esta planificación dinámicase adapta a los cambios ocurridos en el escenario durantela ejecución <strong>de</strong>l DAG. Este proceso lo <strong>de</strong>nominamosauto-adaptación.El proceso <strong>de</strong> auto-adaptación a los cambios ocurridosen el escenario genera una sobrecarga enla política <strong>de</strong> planificación dinámica. Esta sobrecargase produce como consecuencia <strong>de</strong> recalcularlos parámetros utilizados por la política <strong>de</strong> planificacióndinámica en la asignación <strong>de</strong> las tareas a lasmáquinas y en ejecutar el algoritmo <strong>de</strong> planificación.Este trabajo tiene como principal objetivo el <strong>de</strong>alcanzar un buen makespan en la planificación <strong>de</strong>lDAG reduciendo la sobrecarga producido por lapolítica <strong>de</strong> planificación dinámica.<strong>La</strong> política dinámica planifica las tareas in<strong>de</strong>pendientes<strong>de</strong>l DAG. Se <strong>de</strong>nominan tareas in<strong>de</strong>pendientesaquellas que ya han satisfecho sus <strong>de</strong>pen<strong>de</strong>ncias<strong>de</strong> datos. Cuando una tarea finaliza su ejecuciónse comprueba si aparece alguna nueva tarea in<strong>de</strong>pendientepara planificarla. Se repite este procesohasta completar la planificación <strong>de</strong> todas las tareas<strong>de</strong>l DAG.Durante la ejecución <strong>de</strong> las tareas in<strong>de</strong>pendientes<strong>de</strong>l DAG se implementan tres pasos con el objetivo<strong>de</strong> reducir la sobrecarga producido por la autoadaptación<strong>de</strong>l algoritmo.1. <strong>La</strong> monitorización gestiona dos eventos in<strong>de</strong>pendientes:tiempo real <strong>de</strong> ejecución <strong>de</strong> las tareascríticas y largas <strong>de</strong>l DAG y, los cambios en el escenario.<strong>La</strong>s tareas largas son tareas no críticas, peroque tienen un peso elevado en el DAG. Monitorizarel escenario, <strong>de</strong>nominado captura en a<strong>de</strong>lante,consiste en obtener información <strong>de</strong> las máquinasdisponibles cada cierto periodo <strong>de</strong> tiempo. El pe-<strong>JP2011</strong>-475


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011riodo <strong>de</strong>finido entre dos capturas consecutivas <strong>de</strong> escenarioes dinámico, se adapta a los cambios observadosen capturas anteriores.2. <strong>La</strong> <strong>de</strong>tección se encarga <strong>de</strong> evaluar la informaciónobtenida en la monitorización. Si la informaciónproporcionara una mejora en el makespan setiene en cuenta en la planificación <strong>de</strong> las tareas pendientes<strong>de</strong> ejecución <strong>de</strong>l DAG.3. <strong>La</strong> reacción ocurre en caso que la <strong>de</strong>tecciónconsi<strong>de</strong>ra que es necesaria. <strong>La</strong> reacción implementalos siguientes pasos: capturar el nuevo escenario, calcularlos nuevos tiempos estimados <strong>de</strong> las tareas pendientes<strong>de</strong> ejecución <strong>de</strong>l DAG y obtener nuevas tareascríticas y largas <strong>de</strong> las tareas pendientes <strong>de</strong> ejecución<strong>de</strong>l DAG tras aplicar los cambios <strong>de</strong>tectados.Estos tres pasos (monitorización, reacción y <strong>de</strong>tección)se realizan durante la ejecución <strong>de</strong>l DAGy tras la finalización <strong>de</strong> ciertas tareas in<strong>de</strong>pendientes(esto se explica mas a<strong>de</strong>lante). Para planificarlas tareas in<strong>de</strong>pendientes <strong>de</strong>l DAG se ha creado unanueva política <strong>de</strong> planificación estática, <strong>de</strong>nominadaCLTHEF (Critical Long Task HEFT).Posteriormente, a la política <strong>de</strong> planificaciónestática CLTHEFT se le han añadido mejoras convirtiéndolaen dinámica. Para ello se han integradolos tres pasos (monitorización, <strong>de</strong>tección yreacción) explicados anteriormente <strong>de</strong>ntro <strong>de</strong>l algoritmoCLTHEFT. Esta política dinámica se <strong>de</strong>nominaSAHEFT (Self Adapting HEFT).Para evaluar la política <strong>de</strong> planificación dinámicaSAHEFT se ha <strong>de</strong>sarrollado un simulador. El simuladorha servido para realizar un estudio exhaustivo<strong>de</strong> los casos que proporcionan un buen makespan reduciendola sobrecarga.Posteriormente se han planificado y ejecutadoDAGS reales <strong>de</strong> forma estática (CLTHEFT) ydinámica (SAHEFT) en un entorno oportunísticoreal. El número <strong>de</strong> máquinas disponibles <strong>de</strong>l entorno<strong>de</strong> ejecución varía <strong>de</strong> 14 a 50 todas ellas interconectadasa través <strong>de</strong> una red. Estas máquinas estángestionadas por el gestor <strong>de</strong> colas Condor. <strong>La</strong>s aplicacionesreales ejecutadas son Montage [12], Blast[13] y Ligo [14].<strong>La</strong>s características <strong>de</strong> cada máquina <strong>de</strong>l entornose obtienen a través <strong>de</strong>l comando condor status [15]<strong>de</strong>l gestor <strong>de</strong> colas <strong>de</strong> Condor. Para medir el ancho<strong>de</strong> banda <strong>de</strong> la red se ha utilizado la herramientaNetwork Weather Service [16] la cual proporcionainformación <strong>de</strong> la red. Para ejecutar los DAGS realesse ha utilizado la herramienta Schedflow [17].El resto <strong>de</strong>l articulo se estructura <strong>de</strong> la siguientemanera: En la sección 2 se explica la política estática<strong>de</strong>sarrollada, la sección 3 explica nuestra políticadinámica, en la sección 4 se muestra la experimentaciónsimulada y real, en la sección 5 se hacereferencia a los trabajos relacionados, y finalmenteen la sección 6 se muestran las conclusiones.II. Política estática<strong>La</strong> política CLTHEFT obtiene las tareas críticas ylas tareas largas <strong>de</strong>l DAG. <strong>La</strong>s tareas críticas formanparte <strong>de</strong>l camino crítico <strong>de</strong>l DAG y son las tareas maspesadas <strong>de</strong>l DAG. El camino crítico hace referencia alcamino <strong>de</strong>l DAG que tardará mas en finalizar su ejecución(<strong>de</strong>s<strong>de</strong> alguna tarea inicial hasta alguna tareafinal <strong>de</strong>l DAG).<strong>La</strong>s tareas largas son tareas que no forman parte<strong>de</strong>l camino crítico, pero que tienen un elevado e importantepeso en el DAG. Pue<strong>de</strong> darse el caso queen un nivel <strong>de</strong> in<strong>de</strong>pen<strong>de</strong>ncia <strong>de</strong>l DAG existan mas<strong>de</strong> una tarea larga. En consecuencia, un DAG pue<strong>de</strong>tener mas <strong>de</strong> un camino largo. <strong>La</strong> figura 1 muestrael algoritmo implementado para la obtención <strong>de</strong> lastareas largas <strong>de</strong>l DAG.Fig. 1.Algoritmo para la obtención <strong>de</strong> tareas largasSe <strong>de</strong>staca que si el número <strong>de</strong> tareas críticas ylargas es superior al 50% respecto a las tareas totales<strong>de</strong>l DAG, los caminos largos no se tienen en cuenta.Para la obtención <strong>de</strong> tareas críticas, la políticaCLTHEFT se basa en la heurística CPOP [6]. <strong>La</strong>slíneas que no aparecen en negrita <strong>de</strong> la figura 2muestran el algoritmo CLTHEFT. En primer lugarse calcula el camino crítico y los caminos largos, seobtienen las características <strong>de</strong> las máquinas y se or<strong>de</strong>nan<strong>de</strong> mas rápidas a mas lentas. Seguidamente seobtienen las tareas in<strong>de</strong>pendientes <strong>de</strong>l DAG. Mientrasque<strong>de</strong>n tareas pendientes <strong>de</strong> planificación <strong>de</strong>lDAG, el algoritmo CLTHEFT planifica la tareacrítica in<strong>de</strong>pendiente en primer lugar a la máquinamás rápida disponible. Si tras la ejecución <strong>de</strong> la tareacrítica aparece una nueva tarea crítica in<strong>de</strong>pendientele asigna la mejor máquina disponible. Seguidamente,or<strong>de</strong>na las tareas largas según su peso y lasplanifica a las máquinas mas rápidas. Cuando noquedan tareas in<strong>de</strong>pendientes ni críticas ni largas, or<strong>de</strong>nael resto <strong>de</strong> tareas según su prioridad (basándoseen HEFT) y las planifica en función <strong>de</strong> una políticabase. <strong>La</strong>s políticas bases implementadas en el algoritmoCLTHEFT son: aleatoria, min-min, max-miny HEFT. Cada una <strong>de</strong> estas políticas base asignala tarea a una máquina <strong>de</strong>terminada, y la políticaCLTHEFT obtiene dicha asignación para planificar<strong>JP2011</strong>-476


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011las tareas no críticas ni largas.<strong>La</strong> política CLTHEFT necesita tres parámetros <strong>de</strong>entrada: el DAG que se planifica, los tiempos <strong>de</strong>cómputo y comunicación estimados <strong>de</strong> las tareas<strong>de</strong>l DAG y el escenario <strong>de</strong> ejecución. Los tiempos <strong>de</strong>cómputo estimados se calculan en función <strong>de</strong> tiemposobtenidos <strong>de</strong> ejecuciones reales en una única máquinay <strong>de</strong> las características <strong>de</strong> las máquinas. El escenario<strong>de</strong> ejecución se captura un instante antes <strong>de</strong> realizarla planificación.El tiempo <strong>de</strong> comunicación estimado se obtiene enfunción <strong>de</strong>l ancho <strong>de</strong> banda <strong>de</strong> la red y <strong>de</strong>l volumen<strong>de</strong> datos que se van a transferir <strong>de</strong> una máquina aotra <strong>de</strong>l escenario.III. Política dinámica<strong>La</strong> política dinámica, <strong>de</strong>nominada SAHEFT, planifica<strong>de</strong> forma estática las tareas in<strong>de</strong>pendientes <strong>de</strong>lDAG, monitoriza el escenario y el comportamiento<strong>de</strong> las tareas críticas y largas durante su ejecución,y según lo observado se auto-adapta a los cambios<strong>de</strong>tectados para planificar las siguientes tareas in<strong>de</strong>pendientes.El principal objetivo <strong>de</strong> la política dinámica es el<strong>de</strong> obtener un buen makespan <strong>de</strong>l DAG con una sobrecargabaja. El proceso <strong>de</strong> auto-adaptación generasobrecarga <strong>de</strong>bido a que se tienen que volver acalcular todos los parámetros <strong>de</strong> entrada <strong>de</strong>l planificador.Los parámetros <strong>de</strong> entrada son: tiempos <strong>de</strong>cómputo estimados, or<strong>de</strong>n <strong>de</strong> prioridad <strong>de</strong> las tareasno críticas ni largas, nuevos caminos críticos y largos,y la reor<strong>de</strong>nación <strong>de</strong> las máquinas (<strong>de</strong> mas rápida amas lenta).Este trabajo realiza un estudio sobre cuando esnecesario o no realizar auto-adaptación. Claramenteeste proceso <strong>de</strong> auto-adaptación se ha <strong>de</strong> realizar elmínimo número <strong>de</strong> veces, pero hay situaciones en lasque es indispensable para obtener una mejora significativaen el makespan <strong>de</strong>l DAG.El trabajo diferencia dos situaciones que aparecendurante la ejecución <strong>de</strong>l DAG, que son las siguientes:1. El tiempo <strong>de</strong> finalización real <strong>de</strong> una tarea nocorrespon<strong>de</strong> con el estimado.Únicamente se analiza el tiempo final real <strong>de</strong> ejecución<strong>de</strong> las tareas críticas y largas. Cuando ocurreesta situación, se consi<strong>de</strong>ran dos casos posibles. Elprimero es que el tiempo real <strong>de</strong> ejecución <strong>de</strong> latarea crítica o larga sea menor que el tiempo estimado.Cuando se da esta situación no se realizaauto-adaptación <strong>de</strong>bido a que la máquina que se estimabarápida se comporta mas rápido en la realidad.Tener en cuenta este cambio no modifica significativamentela planificación <strong>de</strong> las siguientes tareascríticas ni largas pendientes <strong>de</strong> ejecución, con lo queno se obtendrá una mejora importante <strong>de</strong>l makespan.El segundo caso se da cuando el tiempo real <strong>de</strong>ejecución <strong>de</strong> la tarea crítica o larga es mayor queel estimado. En este caso sí que se <strong>de</strong>be realizarauto-adaptación, pues significa que la estimación <strong>de</strong>la máquina adon<strong>de</strong> se envió la tarea crítica o largano era correcta. <strong>La</strong> máquina que se estimaba comorápida es lenta en la realidad, y este hecho se <strong>de</strong>beconsi<strong>de</strong>rar en la planificación <strong>de</strong>l resto <strong>de</strong> tareas pendientes<strong>de</strong> ejecución <strong>de</strong>l DAG. Al tener este dato encuenta se mejorará el makespan.2. Cambios en el entorno <strong>de</strong> ejecución (escenario).Se clasifican los cambios en el escenario en trestipos: <strong>de</strong>saparición <strong>de</strong> una máquina, aparición <strong>de</strong>una máquina y modificación <strong>de</strong> las características <strong>de</strong>una máquina (una máquina rápida pasa a lenta o alrevés). A continuación se explica como reacciona lapolítica SAHEFT tras monitorizar cada caso:a) Desaparece una máquinaAnte esta situación se reacciona siempre, pues evi<strong>de</strong>ntemente,nunca se <strong>de</strong>be enviar una tarea <strong>de</strong>l DAGa una máquina inexistente.b) Aparece una máquinaAnte esta situación se reacciona en función <strong>de</strong> lascaracterísticas <strong>de</strong> la máquina nueva que aparece. Sila nueva máquina es rápida y se prevé que será beneficiosapara la ejecución <strong>de</strong> las siguientes tareasin<strong>de</strong>pendientes, se la <strong>de</strong>be tener en cuenta. En casocontrario, la nueva máquina no se consi<strong>de</strong>ra.Para <strong>de</strong>cidir si es necesaria o no realizar autoadaptaciónse obtiene el máximo grado <strong>de</strong> paralelismo<strong>de</strong>l DAG, se or<strong>de</strong>nan las máquinas <strong>de</strong>l nuevoescenario <strong>de</strong> mas rápidas a mas lentas, y se obtienela posición que ocupa la nueva máquina en la lista <strong>de</strong>máquinas or<strong>de</strong>nadas. Si esta posición es mayor que elgrado máximo <strong>de</strong> paralelismo <strong>de</strong>l DAG, la máquinano se tiene en cuenta. En caso contrario si que se consi<strong>de</strong>rala nueva máquina y se realiza auto-adaptaciónc) Una máquina lenta pasa a rápida o al revés<strong>La</strong> <strong>de</strong>cisión <strong>de</strong> reaccionar cuando se <strong>de</strong>tecta algunamodificación en las características <strong>de</strong> una o variasmáquinas se realiza implementando el mismo algoritmo<strong>de</strong>l caso anterior (caso en el cual aparece unanueva máquina).<strong>La</strong> política SAHEFT no realiza capturas <strong>de</strong>l escenarioal finalizar algunas tareas <strong>de</strong>l DAG. <strong>La</strong>s capturasse realizan en periodos dinámicos. Estos periodosdinámicos se adaptan a los cambios <strong>de</strong>tectadosentre una captura <strong>de</strong> escenario y la siguiente. El periodomínimo entre dos capturas consecutivas no esinferior a 10 minutos, y el periodo máximo no exce<strong>de</strong>60 minutos.El periodo entre capturas se realiza mediante elsiguiente algoritmo: Inicialmente, se realizan capturas<strong>de</strong> escenario cada 10 minutos. Si se <strong>de</strong>tectancambios importantes entre una captura y la siguientese <strong>de</strong>crementa el periodo entre capturas en 5 minutos,sino se incrementa el periodo en 5 minutos. Loscambios entre dos capturas <strong>de</strong> escenario consecutivasse consi<strong>de</strong>ran importantes cuando conllevan a realizarauto-adaptación, estos casos son: se da una elevadavariación entre ambos escenarios (superior al5%), aparece una máquina rápida o <strong>de</strong>saparece algunamáquina<strong>La</strong> figura 2 muestra el algoritmo dinámicoSAHEFT. <strong>La</strong>s líneas <strong>de</strong> la figura 2 que no están ennegrita muestran el algoritmo estático CLTHEFT.<strong>La</strong>s líneas que aparecen en negrita en la figura 2<strong>JP2011</strong>-477


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011correspon<strong>de</strong>n a las modificaciones realizadas al algoritmoCLTHEFT para convertirlo en dinámico.A medida que finalizan las tareas planificadas, sealmacenan sus tiempos reales <strong>de</strong> ejecución en la listaTe. <strong>La</strong> variable Tc almacena las tareas críticas, lavariable Tl almacena las tareas largas, la variable Malmacena la lista or<strong>de</strong>nada <strong>de</strong> máquinas disponibles(<strong>de</strong> más rápidas a mas lentas), la variable Ti almacenalas tareas in<strong>de</strong>pendientes <strong>de</strong>l DAG, la variableTnc almacena las tareas que no son ni críticas nilargas. <strong>La</strong> variable periodo almacena el tiempo que<strong>de</strong>be transcurrir entre dos capturas consecutivas <strong>de</strong>escenario.<strong>La</strong> política SAHEFT monitoriza el escenario y laejecución <strong>de</strong> las tareas críticas y largas. En función<strong>de</strong> lo <strong>de</strong>tectado, <strong>de</strong>ci<strong>de</strong> si se <strong>de</strong>be realizar autoadaptación,y reacciona ante los cambios observados.la línea 7 el algoritmo comprueba si <strong>de</strong>be realizaruna nueva captura <strong>de</strong> escenario al transcurrir el periodo<strong>de</strong>finido. En caso afirmativo, la realiza. Enla línea 8 se comprueba si con el nuevo escenario seobtendrá una mejora en el makespan al realizar autoadaptación.Para saber esto se aplican los pasos explicadosen la sección correspondiente a cambios enel entorno <strong>de</strong> ejecución <strong>de</strong> este capítulo. En casoafirmativo, en la línea 10 indica que se <strong>de</strong>be realizarauto-adaptación. Posteriormente, <strong>de</strong>s<strong>de</strong> la línea 13hasta la 17 <strong>de</strong>termina cual será el nuevo periodo <strong>de</strong>captura para el siguiente escenario según los cambiosobservados.Fig. 3.Funcion monitorizacion y <strong>de</strong>teccionFig. 2.Algoritmo dinamico SAHEFT<strong>La</strong> figura 3 muestra el algoritmo que integra lamonitorización y la <strong>de</strong>tección. En primer lugar, talcomo indica la línea 3, el algoritmo comprueba si hafinalizado alguna tarea crítica o larga. En caso afirmativo,tal como muestra la linea 5, obtiene el porcentaje<strong>de</strong> error cometido en la estimación respectoa la realidad, y <strong>de</strong>ci<strong>de</strong> realizar auto-adaptación. EnIV. ExperimentaciónSe han realizado dos tipos <strong>de</strong> experimentación:simulada y real. <strong>La</strong> experimentación simulada haservido para estudiar los casos y las condiciones enlas que se reduce la sobrecarga <strong>de</strong> la política dinámicaobteniendo un buen makespan. <strong>La</strong> experimentaciónreal ha servido para validar la política dinámica <strong>de</strong>lsimulador en un escenario real. Seguidamente se explicanlas experimentaciones realizadas.1. Experimentación simuladaSe han simulado varios escenarios heterogéneos.En los escenarios simulados existen máquinas rápidasy lentas. Cada máquina <strong>de</strong>l escenario tiene asociadoun benchmark que es el que <strong>de</strong>termina la prestación<strong>de</strong> la máquina. El número <strong>de</strong> máquinas <strong>de</strong>l escenariosimulado se calcula <strong>de</strong> forma aleatoria, comprendidoentre 5 y 55 máquinas.El porcentaje <strong>de</strong> máquinas rápidas varía en cadaescenario, entre un 20% hasta un 50% respecto alnúmero total <strong>de</strong> máquinas <strong>de</strong>l escenario.Cada tarea <strong>de</strong>l DAG tiene asignado un tiempo <strong>de</strong>cómputo y <strong>de</strong> comunicación estimados. El tiempo<strong>de</strong> cómputo estimado se genera <strong>de</strong> forma aleatoriapara una máquina con unas características (benchmark)<strong>de</strong>terminadas. A esta máquina se la <strong>de</strong>nominamáquina <strong>de</strong> referencia. A partir <strong>de</strong> los tiempos<strong>de</strong> cómputo estimados <strong>de</strong> cada tarea <strong>de</strong>l DAG en<strong>JP2011</strong>-478


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011la máquina <strong>de</strong> referencia, se calculan los tiempos <strong>de</strong>cómputo estimados <strong>de</strong> todas las tareas <strong>de</strong>l DAG entodas las máquinas <strong>de</strong>l escenario. El cálculo <strong>de</strong> lostiempos <strong>de</strong> cómputo estimados en todas las máquinas<strong>de</strong>l escenario se realiza en función <strong>de</strong>l benchmark <strong>de</strong>cada una <strong>de</strong> ellas. El tiempo estimado <strong>de</strong> cada tareas<strong>de</strong>l DAG varía entre 100 a 1100 segundos.El tiempo <strong>de</strong> comunicación estimado <strong>de</strong> cada tarease obtiene en función <strong>de</strong>l volumen <strong>de</strong> datos que envíao recibe una tarea <strong>de</strong>l DAG y el ancho <strong>de</strong> banda <strong>de</strong>la red. El ancho <strong>de</strong> banda <strong>de</strong> la red se calcula <strong>de</strong>forma aleatoria entre 60 y 70 MBps. El volumen <strong>de</strong>datos que envían o reciben las tareas <strong>de</strong>l DAG sonvalores comprendidos entre 1 y 15 MBytes.El simulador genera diferentes escenarios cuandofinaliza el periodo <strong>de</strong>finido entre captura y captura.<strong>La</strong> probabilidad <strong>de</strong> realizar alguna modificación en elnuevo escenario es 1/2. Los escenarios nuevos simuladosimplementan los tres casos posibles:a) Modificación <strong>de</strong> las características (benchmark)<strong>de</strong> algunas máquinasEl número <strong>de</strong> máquinas que sufren variación noexce<strong>de</strong> <strong>de</strong>l 5%.b) Aparición <strong>de</strong> algunas máquinasSe selecciona <strong>de</strong> forma aleatoria una máquinacualquiera <strong>de</strong>l escenario (sin tener en cuenta si esrápida o lenta) y se le aplica una variación positivao negativa a su benchmark <strong>de</strong> un 10% a un 20%. Seasigna un nombre a esta nueva máquina y se la aña<strong>de</strong>al escenario.c) <strong>de</strong>saparición <strong>de</strong> algunas máquinasSe selecciona una máquina <strong>de</strong>l escenario aleatoriamente(sin consi<strong>de</strong>rar si es rápida o lenta) y se laelimina <strong>de</strong>l nuevo escenario.Para po<strong>de</strong>r evaluar los resultados <strong>de</strong>l simulador sehan utilizado tiempos sintéticos <strong>de</strong> ejecución paracada tarea <strong>de</strong>l DAG. Estos tiempos sintéticos <strong>de</strong>lsimulador equivalen a los tiempos que se obtienentras aplicar las políticas <strong>de</strong> planificación en escenariosreales. Estos tiempos sintéticos se han generadoaplicando variaciones positivas o negativas comprendidasentre un 0% a un 20% a los benchmarks <strong>de</strong> lasmáquinas <strong>de</strong>l escenario.<strong>La</strong> Tabla 1 muestra los resultados obtenidos <strong>de</strong>lsimulador tras aplicar la política SAHEFT a losDAGS Montage, Blast y Ligo. En el entorno <strong>de</strong>ejecución los tiempos estimados y sintéticos difierenentre un 10% a un 20%. Esto significa que hayun error comprendido entre un 10% a un 20% enlos tiempos estimados <strong>de</strong> ejecución <strong>de</strong> las tareas <strong>de</strong>lDAG. <strong>La</strong> variación entre escenarios consecutivos eselevada, motivo por el que el periodo entre capturases cada 600 segundos. En la primera fila<strong>de</strong> la tabla se muestra el makespan <strong>de</strong> la políticaestática HEFT, la segunda fila muestra el makespan<strong>de</strong> la política dinámica SAHEFT realizando autoadaptaciónsiempre, tras finalizar una tarea críticao larga en caso que se cometa un error superiora un 5% en la estimación y siempre que se capturaun nuevo escenario. <strong>La</strong> tercera fila muestra elmakespan resultante <strong>de</strong> la política SAHEFT al prevermejora. <strong>La</strong> cuarta fila muestra la sobrecarga producidaal realizar adaptación siempre. <strong>La</strong> sobrecargahace referencia al número <strong>de</strong> veces que la políticadinámica realiza adaptación. <strong>La</strong> quinta fila muestrala sobrecarga producida al realizar auto-adaptaciónúnicamente cuando se consi<strong>de</strong>ra imprescindible paramejorar el makespan <strong>de</strong>l DAG. <strong>La</strong> sexta fila muestrael porcentaje <strong>de</strong> ganancia en el makespan <strong>de</strong> nuestrapolítica dinámica SAHEFT respecto a la políticaestática HEFT. Finalmente, la séptima fila muestrael porcentaje <strong>de</strong> reducción <strong>de</strong> la sobrecarga al realizarauto-adaptación únicamente al prever mejoraen el makespan respecto a realizar auto-adaptaciónsiempre.TABLA IMakespan y sobrecarga en escenarios simuladosPolítica Montage Ligo BlastHEFT 4906 8715 6619Mak siempre 2772 5427 4006Mak necesario 2772 5427 4019Ov adaptación 5 12 10Ov necesario 3 7 5% ganancia mak 43,49 37,72 39,47% reducción ov 40 41,66 50Como se observa en la Tabla 1, al aplicar la políticaSAHEFT realizando siempre auto-adaptación oúnicamente al ser necesario, el makespan obtenido essimilar. El porcentaje <strong>de</strong> mejora <strong>de</strong>l makespan planificandocon SAHEFT respecto a HEFT es superiora 35% en los tres DAGS. Sin embargo, como muestranla cuarta y quinta fila <strong>de</strong> la tabla, la sobrecargadifiere en ambos casos. Al realizar auto-adaptaciónúnicamente al <strong>de</strong>tectar que se mejora el makespan<strong>de</strong>l DAG, la sobrecarga se reduce en mas <strong>de</strong> un 40%.Como se ha explicado, esta tabla simula un entornodon<strong>de</strong> se comete un error en la estimación comprendidoentre un 10% a un 20%. Se han simuladoentornos don<strong>de</strong> el error cometido en la estimación espequeño (comprendido entre 0% a 10%) y la variabilida<strong>de</strong>ntre escenarios consecutivos no exce<strong>de</strong> el 5%siendo las probabilida<strong>de</strong>s <strong>de</strong> aparición y <strong>de</strong>saparición<strong>de</strong> máquinas muy bajas, sobre 1/100. En estos entornos,el porcentaje <strong>de</strong> mejora <strong>de</strong>l makespan al realizarauto-adaptación es muy bajo, <strong>de</strong>l or<strong>de</strong>n <strong>de</strong> un5%. <strong>La</strong> reducción <strong>de</strong> la sobrecarga es significativa,<strong>de</strong>l or<strong>de</strong>n <strong>de</strong> 40%.2. Experimentación realSe dispone <strong>de</strong> máquinas heterogéneas interconectadasa través <strong>de</strong> una red. El número <strong>de</strong> máquinasdisponibles <strong>de</strong>l escenario no es constante, varía entre14 hasta 50 máquinas.Para obtener la información <strong>de</strong> las máquinasdisponibles <strong>de</strong>l escenario y sus características (benchmarken MFlops) se ha utilizado el comando condorstatus que proporciona el gestor <strong>de</strong> colas Condor.Para obtener la información <strong>de</strong>l ancho <strong>de</strong> banda<strong>de</strong> la red se ha utilizado la herramienta NWS.A través <strong>de</strong> NWS se ha <strong>de</strong>tectado que la red que<strong>JP2011</strong>-479


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011interconecta las máquinas es homogénea, el ancho<strong>de</strong> banda medido entre diferentes máquinas <strong>de</strong> la re<strong>de</strong>stá comprendido entre 65Mbps hasta 76Mbps. Espor este motivo que el trabajo está orientado más acómputo que a comunicación.Para ejecutar la política dinámica SAHEFT seha utilizado la herramienta SchedFlow. <strong>La</strong> políticaSAHEFT envía una planificación <strong>de</strong> las tareas in<strong>de</strong>pendientesa SchedFlow, y éste es el encargado<strong>de</strong> monitorizar si durante la ejecución <strong>de</strong> las tareas<strong>de</strong>l DAG ocurre algún problema. Si es así, avisa alplanificador <strong>de</strong> SchedFlow que ejecutará <strong>de</strong> nuevo lapolítica SAHEFT.Se ejecutaron las aplicaciones workflow Montage,Blast y Ligo. Tal como indicaba el simulador, se hacomprobado que la política SAHEFT ejecutada duranteel fin <strong>de</strong> semana o por la noche no presenta unaelevada mejora en el makespan respecto a HEFT (<strong>de</strong>lor<strong>de</strong>n <strong>de</strong>l 5%), <strong>de</strong>bido a que las máquinas no sufrenmodificación alguna. Sin embargo, cuando se ejecutanlos DAGS durante el día, la política SAHEFTmejora el makespan <strong>de</strong> la aplicación sobre un 15%,<strong>de</strong>pendiendo <strong>de</strong>l DAG que se ejecute, y <strong>de</strong> las modificacionesocurridas en el escenario.<strong>La</strong> Tabla 2 muestra uno <strong>de</strong> los resultados realesobtenidos con la planificación dinámica <strong>de</strong> los tresDAGS. En el entorno <strong>de</strong> ejecución las máquinasvarían durante la ejecución <strong>de</strong>l DAG, y hay un elevadoerror en los tiempos estimados <strong>de</strong> cómputo <strong>de</strong>las tareas <strong>de</strong> cada uno <strong>de</strong> los DAGS.Se han realizado pruebas en escenarios poco variablescon un porcentaje <strong>de</strong> error en el tiempo <strong>de</strong>cómputo estimado respecto al real menor <strong>de</strong>l 2%.En estos escenarios el makespan <strong>de</strong> los DAGS trasaplicar SAHEFT respecto al makespan obtenido mediantela política estática CLTHEFT es similar.TABLA IIMakespan y sobrecarga en escenarios realesPolítica Montage Ligo BlastHEFT 9784 8535 2220Mak siempre 8137 7952 2132Mak necesario 8052 8000 1845Ov adaptación 22 24 19Ov necesario 11 13 8% ganancia mak 17,7 6,36 16,9% reducción ov 50 45,83 57,9V. Trabajo relacionado<strong>La</strong>s políticas estáticas <strong>de</strong> planificación <strong>de</strong> workflowsse divi<strong>de</strong>n en dos categorías, las más simplesque planifican los DAGS por nivel <strong>de</strong> in<strong>de</strong>pen<strong>de</strong>ncia<strong>de</strong> sus tareas y las más complejas, que analizan todoel DAG antes <strong>de</strong> realizar la planificación.Del grupo <strong>de</strong> las políticas <strong>de</strong> planificación mas simplesse han estudiado las siguientes: random, minmin[1], max min [2] y sufferage [4]. Se han implementadoy evaluado con el simulador [18] y se haconcluido que, <strong>de</strong> todas ellas, la política sufferage esla que proporciona un mejor makespan <strong>de</strong>l DAG.Del grupo <strong>de</strong> las políticas estáticas <strong>de</strong> planificacióncomplejas, se han estudiado las siguientes: HEFT[3], BMCT [5] y CPOP. Normalmente la políticaHEFT es la que proporciona mejor resultado en elmakespan <strong>de</strong>l DAG [7], [8]. Es por este motivoque, para la experimentación <strong>de</strong> la política dinámicaen DAGS reales, se ha utilizado como política baseHEFT. Se ha adaptado la política HEFT para queplanifique las tareas in<strong>de</strong>pendientes. El hecho <strong>de</strong> utilizar<strong>de</strong> política base HEFT es el <strong>de</strong> garantizar uno<strong>de</strong> los mejores resultados en la planificación estática.Durante la realización <strong>de</strong> la política dinámicaSAHEFT, se han estudiado las políticas dinámicasAHEFT y ALSS que trabajan en entornos grid [9],[10], [11]. <strong>La</strong>s políticas AHEFT y ALSS replanificantodas las tareas pendientes <strong>de</strong> ejecución en caso quese consi<strong>de</strong>re necesario. El hecho <strong>de</strong> replanificar lastareas pendientes <strong>de</strong> ejecución genera sobrecarga enel sistema <strong>de</strong>bido a que se tiene que planificar comomínimo dos veces dichas tareas. Con el objetivo <strong>de</strong>reducir la sobrecarga generada al replanificar las tareas,nuestra política dinámica planifica una únicavez a cada tarea <strong>de</strong>l DAG.VI. ConclusionesEl objetivo principal <strong>de</strong> nuestro trabajo es el <strong>de</strong>proporcionar un buen makespan para cualquier DAGreduciendo la sobrecarga. Para ello se han estudiadodiferentes políticas <strong>de</strong> planificación estáticasy se han comparado entre ellas. Se han realizadopruebas <strong>de</strong> DAGS reales en entornos heterogéneosgestionados bajo Condor y se ha obtenido una mejorplanificación con la política estática HEFT. Durantela ejecución <strong>de</strong> las aplicaciones se ha observado unalto dinamismo en el entorno <strong>de</strong> ejecución y es poreste motivo que se ha visto la necesidad <strong>de</strong> implementaruna política dinámica que se adapte a loscambios que se producen en el escenario durante laejecución <strong>de</strong> un DAG.Para implementar la política dinámica se ha <strong>de</strong>sarrolladouna política estática <strong>de</strong> planificación llamadaCLTHEFT. <strong>La</strong> política estática CLTHEFTplanifica en primer lugar las tareas críticas <strong>de</strong>l DAGy posteriormente las tareas largas <strong>de</strong>l DAG a lasmejores máquinas disponibles <strong>de</strong>l entorno. Finalmente,las tareas no críticas ni largas se planificansegún una heurística base estática (min-min,maxmin,aleatoria, o HEFT).<strong>La</strong> política CLTHEFT proporciona un makespansimilar al <strong>de</strong> la política HEFT. Esto se ha verificadovía simulación y a través <strong>de</strong> ejecuciones <strong>de</strong> DAGSen un entorno real. Posteriormente, se han añadidomejoras a la política CLTHEFT hasta convertirla endinámica.<strong>La</strong> política dinámica, <strong>de</strong>nominada SAHEFT, tieneun inconveniente importante: al <strong>de</strong>tectar algún erroren la estimación <strong>de</strong>l planificador y reaccionar anteeste error, se genera sobrecarga. Consi<strong>de</strong>rando elerror <strong>de</strong>tectado, el planificador <strong>de</strong>be actualizar sus<strong>JP2011</strong>-480


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011parámetros <strong>de</strong> entrada y adaptarse al cambio producido.Es por este motivo que nuestro trabajotrata <strong>de</strong> reducir la sobrecarga <strong>de</strong> la política dinámicagarantizando un buen makespan <strong>de</strong>l DAG.A través <strong>de</strong>l simulador se realizó un estudio exhaustivo<strong>de</strong> cuales son los casos que proporcionanun mejor makespan tras finalizar un DAG y cualesno. Este estudio se ha integrado en el algoritmo que<strong>de</strong>ci<strong>de</strong> si se <strong>de</strong>be o no realizar auto-adaptación.Finalmente se han ejecutado DAGS reales con lapolítica SAHEFT en escenarios heterogéneos mediantela herramienta SchedFlow.De la experimentación real se concluye que, en casoque los escenarios sufran variaciones importantes yque el error que se cometa en la estimación seasuperior a un 5%, la política SAHEFT mejora elmakespan mas <strong>de</strong> un 15% respecto a HEFT. <strong>La</strong> reducción<strong>de</strong> sobrecarga que proporciona SAHEFT esimportante, <strong>de</strong>l or<strong>de</strong>n <strong>de</strong> 40% o superior respectoal hecho <strong>de</strong> reaccionar siempre ante la <strong>de</strong>tección <strong>de</strong>cualquier cambio.Agra<strong>de</strong>cimientosEste artículo ha sido financiado por el MEC-MICINN Spain mediante el proyecto TIN2007-64974tional Journal of Computer Science and Network Security,VOL.9 No.4, April 2009[14] D.A. Brown, P.R. Brady, A. Dietz, J. Cao, B. Johnsonand J. McNabb, A case study on the use of workflow technologiesfor scientific analysis: gravitational wave dataanalysis, Workflows for e-Science, Springer (2006).[15] Douglas Thain, Todd Tannenbaum, and Miron Livny,Distributed Computing in Practice: The Condor Experience,Concurrency and Computation: Practice and ExperienceVolume 17. Issue 2-4. pp: 323-356, 2005[16] Rich Wolski, Forecasting Network Performance to SupportDynamic Scheduling Using the Network Weather Service,High Performance Distributed Computing, 1997.Proceedings. The Sixth IEEE International Symposiumon, pp 316-325, 1997[17] Gustavo Martinez, Elisa Heymann, Miguel Angel Senar,Emilio Luque, Barton P. Miller Using SchedFlow for PerformanceEvaluation of Workflow Applications Workflowsin Support of <strong>La</strong>rge-Scale Science (WORKS), 5th Workshopon, pp. 1-8, 2010[18] Maria M. Lopez, Elisa Heymann, Miguel Angel Senar,Analysis of Dynamic Heuristics for Workflow Schedulingon Grid Systems, ispdc, pp.199-207, Proceedings ofThe Fifth International Symposium on Parallel and DistributedComputing (ISPDC’06), 2006[19] W.M.P. van <strong>de</strong>r Aalst, K.M. van Hee and G.J. Houben,Mo<strong>de</strong>lling and Analysing Workflow using a Petri-netBased Approach, 2nd Workshop on Computer-supportedCooperative Work, Petri Nets Related Formalisms, pp. 31-50,1994.[20] Jia Yu and Rajkumar Buyya A Taxonomy of WorkflowManagement Systems for Grid Computing, Journal ofGrid Computing Volume 3, Numbers 3-4, 171-200, 2005Referencias[1] Min-You Wu, Wei Shu, Hong Zhang. Segmented Min-Min:A Static Mapping Algorithm for Meta-Tasks on HeterogeneousComputing Systems., 9th Heterogeneous ComputingWorkshop, 2000, pp. 375-385, 2000.[2] Y.-K. Kwok, I. Ahmad, Static scheduling algorithms forallocating directed task graphs to multiprocessors., ACMComputing Surveys, 31(4), pp. 406-471, 1999.[3] H. Topcuoglu, S. Hariri, and M.Y. Wu. Performance-Effective and Low-Complexity Task Scheduling for HeterogeneousComputing., IEEE Trans. Parallel and DistributedSystems, Vol. 13, no. 3, pp. 260-274, 2002.[4] A. Mandal et al. Scheduling Strategies for MappingApplication Workflows onto the Grid. In 14th IEEESymposium on High Performance Distributed Computing(HPDC 2005). IEEE Computer Society Press, pp. 4, 2005.[5] R Sakellariou, H Zhao. A Hybrid Heuristic for DAG Schedulingon Heterogeneous Systems. Proc. Of the 13th HeterogeneousComputing Workshop (HCW 04), pp. 111,2004.[6] H Topcuoglu, S Hariri, Min-You Wu. Task SchedulingAlgorithms for Heterogeneous Processors. Eighth HeterogeneousComputing Workshop, hcw,pp.3-14, 1999.[7] Louis-Clau<strong>de</strong> Canon and Emmanuel Jeannot A Comparisonof Robustness Metrics for Scheduling DAGs on HeterogeneousSystems, IEEE International Conference onCluster Computing, pp.558-567, 2007[8] Louis-Clau<strong>de</strong> Canon and Emmanuel Jeannot, Rizos Sakellariouand Wei Zheng, Comparative evaluation ofthe robustness of DAG scheduling heuristics, GridComputing,pp.73-84, 2008,[9] R Sakellariou, H Zhao, A low-cost rescheduling policy forefficient mapping of workflows on grid systems. ScientificProgramming, 12 (4), pp. 253-262, Dec. 2004.[10] Zhifeng Yu and Weisong Shi, An Adaptive ReschedulingStrategy for Grid Workflow Applications, Proceedings ofthe 21st IPDPS 2007.[11] Sung Ho Chin,Taeweon Suh,Heon Chang Yu, Adaptiveservice scheduling for workflow applications in Service-Oriented Grid, The Journal of Supercomputing Volume52, Number 3, 253-283, 2009[12] Berriman, G. <strong>La</strong>ity, A. and et al, Montage: The Architectureand Scientific Applications of a National VirtualObservatory Service for Computing Astronomical ImageMosaics, In. Proc. of Earth Sciences Technology Conference,Maryland USA, 2006[13] Enis Afgant and Purushotham Bangaloret, DynamicBLAST a Grid Enabled BLAST, IJCSNS Interna-<strong>JP2011</strong>-481


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-482


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011QoS en Entornos Grid mediante un Sistema <strong>de</strong>Meta-planificación por A<strong>de</strong>lantado basado enSLAsJavier Conejero, Luis Tomás, Carmen Carrión, Blanca Caminero 1Resumen— El establecimiento <strong>de</strong> acuerdos entre losusuarios y las entida<strong>de</strong>s que gestionan los recursosGrid es todavía un reto. Se necesita una entidad encargada<strong>de</strong> la comunicación con los usuarios, con el objetivo<strong>de</strong> establecer los contratos <strong>de</strong> uso <strong>de</strong> los recursosy también <strong>de</strong> implementar técnicas <strong>de</strong> renegociación.Por otro lado, se <strong>de</strong>ben implementar mecanismos que<strong>de</strong>cidan si la calidad <strong>de</strong> servicio (QoS) solicitada pue<strong>de</strong>ser proporcionada y, en tal caso, asegurar que dichoacuerdo se cumple.Una forma <strong>de</strong> incrementar la probabilidad <strong>de</strong> logrardicha QoS es mediante la planificación <strong>de</strong> trabajos pora<strong>de</strong>lantado. Esto significa que los trabajos son planificadoscon un tiempo <strong>de</strong> antelación sobre su propiotiempo <strong>de</strong> ejecución. De esta forma, es mas fácil queel recurso apropiado este disponible para ejecutar lostrabajos cuando llegue su turno. Así pues, este artículopresenta un solución, implementada sobre Globusy el metaplanificador GridWay, para proveer QoS mediantedicho tipo <strong>de</strong> planificación. Aparte <strong>de</strong> esto,los mecanismos necesarios para gestionar la comunicaciónentre los usuarios y el sistema son presentadose implementados mediante contratos basados en la especificaciónWS-Agreement.Palabras clave—Meta-planificador, Grid, QoS, SLAs,WS-Agreement.I. IntroducciónEn sistemas altamente variables y heterogéneos,como es el caso <strong>de</strong> los entornos Grid, los recursospue<strong>de</strong>n estar distribuidos entre múltiples dominiosy bajo diferentes políticas <strong>de</strong> administración, loque hace extremadamente difícil proporcionar QoS alos usuarios. Por esto, la infraestructura Grid <strong>de</strong>beproporcionar los servicios necesarios para una planificación<strong>de</strong>l uso <strong>de</strong> los recursos automática, quese encargue <strong>de</strong> este proceso <strong>de</strong> manera transparentea los usuarios [1]. A este sistema se le llama“meta-planificador” [2]. Sin embargo, el proceso <strong>de</strong>planificación se complica <strong>de</strong>bido a que generalmenteel meta-planificador no tiene control, ni siquieracompleto conocimiento, <strong>de</strong> los recursos <strong>de</strong>l sistema,ni su red <strong>de</strong> interconexión. Esto significa que no siemprees posible realizar reservas <strong>de</strong> uso en esos recursospara ejecutar los trabajos, y por lo tanto, no esposible asegurar que dicho recurso va a finalizar laejecución <strong>de</strong> un <strong>de</strong>terminado trabajo a tiempo.Como las reservas no son siempre factibles, la i<strong>de</strong>aprincipal se basa en intentar asegurar que un recursoestará disponible cuando un trabajo lo necesite ypara ello se realiza una planificación por a<strong>de</strong>lantado<strong>de</strong>l uso <strong>de</strong> dichos recursos. Esta planificación pue<strong>de</strong>ser vista como el primer paso <strong>de</strong>l algoritmo <strong>de</strong> reservapor a<strong>de</strong>lantado, en el cual se seleccionan tanto el1 Instituto <strong>de</strong> Investigación en Informática <strong>de</strong> Albacete(I 3 A), <strong>Universidad</strong> <strong>de</strong> Castilla-<strong>La</strong> Mancha, e-mail:{FJavier.Conejero, Luis.Tomas, MariaBlanca.Caminero,Carmen.Carrion}@uclm.esrecurso como el periodo <strong>de</strong> tiempo en el que se ejecutaráel trabajo, pero sin llegar a hacer reserva físicaalguna <strong>de</strong>l recurso. De este modo, el sistema necesitaestimar el estado futuro <strong>de</strong> los recursos y cuantodurará la ejecución. Para ello, se han implementadoalgunas técnicas <strong>de</strong> predicción.Por otro lado, y teniendo en cuenta que elrendimiento <strong>de</strong>l sistema <strong>de</strong> meta-planificación será elque repercuta en la visión que el usuario tenga <strong>de</strong>lfuncionamiento <strong>de</strong>l sistema, es necesario <strong>de</strong>sarrollarmecanismos para gestionar la interacción entreambos. Para ello se usan contratos <strong>de</strong>l tipo ServiceLevel Agreements (SLAs [3]).Hoy en día, la economía actual está mostrando unaten<strong>de</strong>ncia hacia economías orientadas a servicios. Estaten<strong>de</strong>ncia requiere nuevos mecanismos para gestionary potenciar <strong>de</strong> forma eficiente el uso <strong>de</strong> recursoscomputacionales. Y está principalmente promovidopor motivos económicos y <strong>de</strong> negocios, don<strong>de</strong> sonnecesarios mecanismos para la negociación <strong>de</strong> acuerdoslegales [4]. Debido a este interés, muchos esfuerzosse han <strong>de</strong>dicado a tratar <strong>de</strong> resolver este problemaen entornos Grid; pero el trabajo más importante hasido la especificación WS-Agreement (Grid ResourceAllocation Agreement Protocol) para SLAs, consi<strong>de</strong>radaestándar <strong>de</strong> facto. Como resultado, muchosproyectos Grid actuales están interesados en la implantación<strong>de</strong> SLAs (p. ej. AssessGrid [5], Brein [6],y SLA@SOI [7] entre otros).Para nuestro propósito, los SLAs representan unaformalización <strong>de</strong>l proceso <strong>de</strong> emisión <strong>de</strong> trabajos paralos Grids. A<strong>de</strong>más, son el mecanismo fundamentalpara la representación formal <strong>de</strong> las restriccionestemporales asociadas a cada trabajo. Esta informaciónes necesaria en el proceso <strong>de</strong> meta-planificaciónpor a<strong>de</strong>lantado.En conclusión, la principal contribución presenteen el artículo es una solución construida sobre elmeta-planificador GridWay para proporcionar QoSmediante el <strong>de</strong>sarrollo <strong>de</strong> meta-planificaciones pora<strong>de</strong>lantado y con una interfaz <strong>de</strong> usuario basada enWS-Agreement. El uso <strong>de</strong> esta propuesta permiteque los trabajos finalicen su ejecución cumpliendocon sus <strong>de</strong>adlines gracias a algunas heurísticas queestiman el estado futuro <strong>de</strong> los recursos y cuanto duraránlas ejecuciones <strong>de</strong> los trabajos en ellos.Este artículo se organiza <strong>de</strong> la siguiente manera.Varios trabajos relacionados son presentados en laSección II. En la Sección III se <strong>de</strong>fine el sistema <strong>de</strong>meta-planificación por a<strong>de</strong>lantado basado en SLAs.Después se muestra la metodología usada para lle-<strong>JP2011</strong>-483


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011var a cabo el proceso <strong>de</strong> comunicación con los usuariosmediante contratos SLA en la Sección IV. Finalmente,las conclusiones obtenidas y las posibles lineas<strong>de</strong> trabajo futuro son <strong>de</strong>talladas en la Sección V.II. Trabajo RelacionadoProporcionar QoS en entornos Grid es todavía unproblema que está siendo ampliamente investigadopor una gran variedad <strong>de</strong> proyectos basados en reservaspor a<strong>de</strong>lantado: como GARA [8], Grid CapacityPlanning [9], o VIOLA [10], entre otros. Ésta técnicatiene un inconveniente: no todos los recursos pue<strong>de</strong>nser reservados. Debido a esta limitación, nuestro trabajopreten<strong>de</strong> explotar la planificación por a<strong>de</strong>lantadoen vez <strong>de</strong> la reserva <strong>de</strong> recursos por a<strong>de</strong>lantado.<strong>La</strong> meta-planificación por a<strong>de</strong>lantado requiere realizarpredicciones sobre el estado futuro <strong>de</strong> los recursosy sobre la duración <strong>de</strong> los trabajos en estosrecursos. Una visión global <strong>de</strong> algunas técnicas<strong>de</strong> predicción se pue<strong>de</strong> encontrar en [11]. Algunosejemplos aplican mo<strong>de</strong>los estadísticos a ejecucionespasadas [12] y heurísticas basadas en las características<strong>de</strong> los trabajos y recursos [13]. En [12], se muestraque aunque la carga exhibe propieda<strong>de</strong>s complejas,es pre<strong>de</strong>cible consistentemente a partir <strong>de</strong>l comportamientopasado. En [13], se evalúan varios mo<strong>de</strong>los<strong>de</strong> series lineales temporales para la predicción <strong>de</strong>carga <strong>de</strong> CPU. En nuestro trabajo, se utiliza unatécnica basada en datos históricos, dado que ha sido<strong>de</strong>mostrado que provee mejores resultados comparadoscon las funciones lineales [14].Este tipo <strong>de</strong> planificación necesita disponer <strong>de</strong> unaestructura <strong>de</strong> datos apropiada para gestionar todala información <strong>de</strong> forma eficiente. Hay varias estructuraspara la gestión <strong>de</strong> esta información, como GridAdvanced Reservation Queue [15] (GarQ). Pero eneste trabajo se utilizan los árboles rojo–negro dadoque proveen acceso eficiente a la información sobreel uso <strong>de</strong> recursos, como ha sido <strong>de</strong>mostrado en [16].Por otro lado, los SLAs son importantes hoy endía. Se han realizado muchos esfuerzos en camposcomo: su gestión [17], implicaciones con la QoS [18],explotación <strong>de</strong> la virtualización y semántica [19]y especialmente en su estandarización. El avancemás importante en el ámbito <strong>de</strong> los SLAs ha sidola especificación WS-Agreement [20], consi<strong>de</strong>radaestándar <strong>de</strong> facto, don<strong>de</strong> la estructura y mecanismospara <strong>de</strong>splegar los SLAs en un sistema, <strong>de</strong>s<strong>de</strong>un punto <strong>de</strong> vista global, son <strong>de</strong>finidos. Pero graciasa una reciente revisión <strong>de</strong> la especificación [21],ha sido <strong>de</strong>finido un nuevo protocolo <strong>de</strong> negociaciónque introduce el concepto <strong>de</strong> renegociación. Este conceptose <strong>de</strong>fine como una interacción múltiple entreel usuario y proveedor <strong>de</strong> servicios para conseguirmejores acuerdos. Pero WS-Agreement no es la únicaespecificación disponible; SLAng [22] y WSLA [23]son alternativas, pero <strong>de</strong>bido a su falta <strong>de</strong> soporteno son recomendables.Debido a la importancia <strong>de</strong> los SLAs, muchosproyectos están interesados en su implantación [24].<strong>La</strong> mayoría <strong>de</strong> ellos implementan WS-Agreement,como SLA@SOI [7], AssessGrid [5] y Brein [6]. Elprimero <strong>de</strong> ellos está orientado en la implantación<strong>de</strong> SLAs en infraestructuras orientadas a servicios(SOIs) <strong>de</strong>s<strong>de</strong> un punto <strong>de</strong> vista genérico. Assessgridy Brein tienen un propósito común, que es potenciarlos entornos computacionales Grid en entornos <strong>de</strong> negociosy sociedad. Sin embargo, Assessgrid se centraen la evaluación <strong>de</strong> riesgos, mientras que Brein secentra en la gestión eficiente <strong>de</strong> los Grids basándoseen técnicas <strong>de</strong> inteligencia artificial, web semántica ysistemas inteligentes. Otro proyecto importante <strong>de</strong>ntro<strong>de</strong> este ámbito es WSAG4J(WS-AGreement forJava [25]). Consiste en una implementación genérica<strong>de</strong> la especificación WS-Agreement. Está diseñadopara agilizar el <strong>de</strong>sarrollo y facilitar la <strong>de</strong>puración <strong>de</strong>servicios y aplicaciones basadas en WS-Agreement.No todos los proyectos implementan la especificaciónWS-Agreement para la gestión <strong>de</strong> SLAs. Unejemplo <strong>de</strong> esto es NextGrid [26].III. Meta-Planificación por A<strong>de</strong>lantadoEn un entorno Grid real muchos recursos nopue<strong>de</strong>n ser reservados <strong>de</strong>bido a que no todos losgestores locales lo permiten. También existen otrotipo <strong>de</strong> recursos, como el ancho <strong>de</strong> banda, que soncompartidos entre varios dominios administrativoshaciendo su reserva extremadamente complicada.Este es el principal argumento para llevar a cabouna planificación por a<strong>de</strong>lantado <strong>de</strong>l uso <strong>de</strong> los recursosen vez <strong>de</strong> reservas por a<strong>de</strong>lantado. Esto significaque el sistema necesita anotar las <strong>de</strong>cisionesprevias para po<strong>de</strong>r tomar <strong>de</strong>cisiones en el futuro sinque se produzcan solapamientos en las ejecuciones.Con todo esto, nuestro sistema <strong>de</strong> planificación siguelos siguientes pasos (ver Figura 1):1) El usuario envía una petición al meta-planificador<strong>de</strong> su dominio administrativo local a través <strong>de</strong> ungestor <strong>de</strong> SLAs (ver Sección IV). Cada SLA (petición<strong>de</strong> ejecución <strong>de</strong> un trabajo) <strong>de</strong>be proporcionaruna tupla con la información sobre la aplicación y losparámetros <strong>de</strong> QoS: (in file, app, t s, d). in file contienelos ficheros <strong>de</strong> entrada requeridos para ejecutarla aplicación app. En este estudio, los parámetros <strong>de</strong>QoS vienen especificados por el tiempo <strong>de</strong> inicio, t s(tiempo en el que el trabajo pue<strong>de</strong> empezar a ejecutarse),y el <strong>de</strong>adline, d (tiempo en el que el trabajo<strong>de</strong>be haberse ejecutado).2) El meta-planificador se comunica con el Gap Managementpara obtener el recurso y el intervalo <strong>de</strong>tiempo en el que ejecutar el trabajo. Los heurísticospresentados tienen en cuenta el estado predichopara el recurso (tanto recurso computacional comored), los trabajos que ya han sido planificados y losrequisitos <strong>de</strong> QoS <strong>de</strong>l trabajo.3) Si no es posible alojar el trabajo en los recursos<strong>de</strong>l propio dominio cumpliendo las QoS <strong>de</strong>seadas,empieza una comunicación con otros metaplanificadores<strong>de</strong> otros dominios. Para realizar estascomunicaciones eficientemente se pue<strong>de</strong>n usar técnicasbasadas en sistemas P2P (como se propusieronen [27], [28], entre otros).4) Si aún así no es posible ejecutar el trabajo con laQoS solicitada, un proceso <strong>de</strong> renegociación es ini-<strong>JP2011</strong>-484


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 1. Proceso <strong>de</strong> Meta-Planificación por A<strong>de</strong>lantadociado entre el usuario y el gestor <strong>de</strong> SLA para intentar<strong>de</strong>finir requisitos <strong>de</strong> QoS que puedan ser proporcionados.Recalcar que este proceso <strong>de</strong> renegociación,así como todo el proceso <strong>de</strong> interacción con los usuariosse lleva a cabo mediante SLAs (Sección IV <strong>de</strong>tallala implementación <strong>de</strong> los SLAs).Como muestra la Figura 1, pue<strong>de</strong> haber más <strong>de</strong> unmeta-planificador en cada dominio administrativo, sibien es cierto que tienen que comunicarse con el mismoGap Management, ya que tiene la información sobreel uso futuro <strong>de</strong> los recursos <strong>de</strong> ese dominio. Sinembargo, los recursos pue<strong>de</strong>n dividirse en subconjuntos,haciendo esta propuesta altamente escalable.Esto representa un escenario i<strong>de</strong>al, en el que todoslos trabajos son enviados a través <strong>de</strong>l Gap Management.Sin embargo, esta no es la regla en los entornosGrid, don<strong>de</strong> los recursos están compartidos entre losusuarios e incluso entre diferentes organizaciones virtuales(VOs). Por esta razón, con el fin <strong>de</strong> tener encuenta la carga que no es enviada a través <strong>de</strong>l metaplanificador,son necesarias estimaciones acerca <strong>de</strong>lestado futuro <strong>de</strong> los recursos.<strong>La</strong> funcionalidad <strong>de</strong>l meta-planificador por a<strong>de</strong>lantadoha sido implementada como una capa sobreel meta-planificador GridWay [2], llamada SA–layer(Scheduler in Advance <strong>La</strong>yer) [14] (ver Figura 2).Dicha capa usa las funcionalida<strong>de</strong>s proporcionadaspor GridWay para el <strong>de</strong>scubrimiento y monitorización<strong>de</strong> recursos, envío, ejecución y monitorización<strong>de</strong> los trabajos, etc. A<strong>de</strong>más, la información referentea previas ejecuciones <strong>de</strong> los trabajos, y al estado<strong>de</strong> la red y los recursos, se almacena en dos bases<strong>de</strong> datos, DB Executions y DB Resources, respectivamente.El uso <strong>de</strong> los recursos se divi<strong>de</strong> en intervalos <strong>de</strong>tiempo, llamados slots. Así, el sistema tiene que planificarel uso futuro <strong>de</strong> los recursos alojando los trabajosen un recurso en un tiempo específico (usandouno o más slots contiguos). De este modo, se necesitanestructuras <strong>de</strong> datos para mantener una traza<strong>de</strong> los slots usados (Data Structure en la Figura 2).En este trabajo se usan árboles rojo–negro [16] comoestructura <strong>de</strong> datos, con el objetivo <strong>de</strong> i<strong>de</strong>ntificareficientemente los slots a<strong>de</strong>cuados, sin tener que examinartodos los periodos libres. <strong>La</strong> razón <strong>de</strong> elegireste tipo <strong>de</strong> estructura es que el camino más largo <strong>de</strong>la raíz a las hojas no es más <strong>de</strong> dos veces el más corto.Así pues, el árbol se mantiene balanceado, y comoFig. 2. Capa <strong>de</strong> Planificación por A<strong>de</strong>lantado (SA–layer).resultado <strong>de</strong> ello, insertar, borrar o buscar en él tieneun peor caso proporcional a la altura <strong>de</strong>l árbol (O(logn)). <strong>La</strong> i<strong>de</strong>a <strong>de</strong> usar este tipo <strong>de</strong> árboles fue propuestaen [16]. Sin embargo, su propuesta no tiene en cuentala fluctuación en el rendimiento <strong>de</strong> los recursos.A<strong>de</strong>más, los autores asumen que los usuarios tienenun conocimiento previo sobre la duración <strong>de</strong> los trabajos,lo cual no es siempre cierto en un entorno Grid.Nuestro trabajo no hace esas suposiciones, por lo quenecesita un mecanismo para estimar la duración <strong>de</strong>los trabajos en los recursos (Predictor en Figura 2)y por lo tanto saber cuantos slots hacen falta para laejecución <strong>de</strong> un <strong>de</strong>terminado trabajo en un recurso.A. Predicción <strong>de</strong>l Tiempo <strong>de</strong> EjecuciónEl hecho <strong>de</strong> que los recursos presenten unrendimiento diferente hace muy difícil las tareas <strong>de</strong>predicción <strong>de</strong> duración <strong>de</strong> los trabajos en ellos. Ylo que es peor, las características <strong>de</strong> rendimientopue<strong>de</strong>n cambiar para las diferentes aplicaciones. Poresto, se necesita estimar el estado futuro <strong>de</strong> los recursosy teniendo esto en cuenta, estimar el tiempo necesariopara completar un trabajo en un recurso paraun intervalo <strong>de</strong> tiempo específico. Con el objetivo <strong>de</strong>hacer esas predicciones tan precisas como sea posible,los tiempo necesarios para la propia ejecución <strong>de</strong>ltrabajo y los tiempos necesarios para completar lastransferencias son calculados por separado. A<strong>de</strong>más,el sistema tiene en cuenta las características <strong>de</strong> lostrabajos, la potencia y uso <strong>de</strong> la CPU <strong>de</strong> los recursosy el estado <strong>de</strong> la red. Para ello, se implementa unatécnica basada en una función Exponential Smoothing[29] que calcula el estado futuro <strong>de</strong> las CPUs <strong>de</strong>los recursos y el estado futuro <strong>de</strong> los enlaces <strong>de</strong> red.Teniendo en cuenta esas informaciones sobre el estado<strong>de</strong>l Grid, una estimación para el tiempo <strong>de</strong> ejecuciónes calculado usando la información <strong>de</strong> ejecucionesprevias, como se muestra en el Algoritmo 1.Este algoritmo usa los tiempos <strong>de</strong> ejecuciones previas<strong>de</strong> la aplicación app en el recurso R i para calcular sutiempo <strong>de</strong> ejecución medio incluyendo los tiempos <strong>de</strong>encolado (línea 8). Después <strong>de</strong> esto, la predicción sobreel estado futuro <strong>de</strong> la CPU es calculado usandola función <strong>de</strong> Exponential Smoothing (línea 9). Condichas informaciones, la media <strong>de</strong>l tiempo <strong>de</strong> ejecuciónobtenida es pon<strong>de</strong>rada usando la informaciónpredicha para el estado <strong>de</strong> la CPU (línea 10). <strong>La</strong> forma<strong>de</strong> calcular los tiempos necesarios para completarlas transferencias es bastante similar. El ancho <strong>de</strong>banda medio predicho para el intervalo en el que eltrabajo tiene que ser ejecutado es otra vez calculadousando la función Exponential Smoothing. Con es-<strong>JP2011</strong>-485


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Algoritmo 1 Estimación <strong>de</strong>l tiempo <strong>de</strong> ejecución(ExecT Estimation)1: Sea R = conjunto <strong>de</strong> recursos conocidos por GridWay {R 1 ,R 2 ,. . . ,R n}2: Sea app el trabajo a ser ejecutado3: Sea initT el tiempo <strong>de</strong> inicio <strong>de</strong>l trabajo4: Sea d el <strong>de</strong>adline <strong>de</strong>l trabajo5: Sea ExecutionT ime(app, R i ) j el j tiempo <strong>de</strong> ejecuciónpara la aplicación app en el recurso R i6: Sea ES cpu(DB Resources Ri , initT, d) la función exponentialsmoothing que calcula el % <strong>de</strong> CPU libre en elrecurso R i entre el tiempo initT y d7: Sea CP U free(R i , initT, d) el % <strong>de</strong> CPU libre en el recursoR i <strong>de</strong>s<strong>de</strong> el tiempo ∑initT hasta dnj=18: ExecutionT ime =i) jn9: CP U free(R i , initT, d) = ES cpu(DB Resources Ri ,initT, d)10: ExecutionT ime = ExecutionT ime ∗ (2 −CP U free(R i , initT, d))11: <strong>de</strong>vuelve ExecutionT imeAlgoritmo 2 Estimación <strong>de</strong>l tiempo <strong>de</strong>l trabajo1: Sea R i = un recurso2: Sea app = el trabajo a ejecutar3: Sea initT = tiempo <strong>de</strong> inicio <strong>de</strong>l trabajo4: Sea d = <strong>de</strong>adline <strong>de</strong>l trabajo5: Sea size IN = el número <strong>de</strong> bytes <strong>de</strong> entrada a ser transferidos6: Sea size OUT = el número <strong>de</strong> bytes <strong>de</strong> salida a ser transferidos7: for cada R i que tenga un hueco do8: P rolog = T ransT Estimation(R i , initT, d, size IN )9: Epilog = T ransT Estimation(R i , initT, d, size OUT )10: ExecT = ExecT Estimation(R i , app)11: if RT (R i ) < 0 then12: ExecT = ExecT + |RT (R i )|13: end if14: JT Ri = P rolog + ExecT + Epilog15: end forta información junto con la cantidad total <strong>de</strong> bytes atransferir, se estima el tiempo necesario para completardichas transferencias.Finalmente, las predicciones obtenidas son pon<strong>de</strong>radasteniendo en cuenta la confianza en los recursosescogidos. Esta información sobre la confianza escalculada siguiendo el Algoritmo 2. Con la informaciónsobre las estimaciones <strong>de</strong> tiempos <strong>de</strong> ejecucióny transferencias, junto con la confianza en el recursoR i , <strong>de</strong>finido como RT (R i ), el tiempo <strong>de</strong> ejecución esajustado (línea 12) y la estimación para el tiempototal <strong>de</strong>l trabajo, JT Ri , es calculada (línea 14).<strong>La</strong> confianza en los recursos se obtiene usando laEcuación 1:∑ nj=(n−N)RT (R i ) =(Estimated (j,i) − Real (j,i) )N(1)siendo Estimated (j,i) el tiempo total estimado parala ejecución <strong>de</strong>l trabajo j en el recurso R i ; y Real (j,i)el tiempo total real para el trabajo j en el recurso R i .<strong>La</strong> salida <strong>de</strong> esta función es la media <strong>de</strong> los errorescometidos en las últimas N predicciones y es usadopara ajustar las predicciones <strong>de</strong> los trabajos que seejecuten en ese recurso. Como resultado, la confianzaen las estimaciones <strong>de</strong>pen<strong>de</strong> <strong>de</strong> como <strong>de</strong> confiablesea el comportamiento <strong>de</strong>l recurso. Los beneficios <strong>de</strong>este ajuste <strong>de</strong> las predicciones usando el factor <strong>de</strong>confianza fueron evaluadas en [14], dón<strong>de</strong> se puso<strong>de</strong> manifiesto la bondad <strong>de</strong> esta técnica. Así pues,ahora estamos mezclando las técnicas <strong>de</strong> estimaciónpresentadas en [14] y [29] con el fin <strong>de</strong> obtener unaspredicciones más precisas.Es importante <strong>de</strong>stacar que dichas prediccionessólo son calculadas en el caso <strong>de</strong> que un hueco seaencontrado en un recurso. De esta forma, no hayque calcular los tiempos para todos los recursos <strong>de</strong>lsistema, lo que sería muy ineficiente. Por otro lado,cuando un recurso abandona el sistema por cualquierrazón, los trabajos planificados para ser ejecutadosen él, son replanificados a otros recursos. Esta característicaes importante dada la dinamicidad <strong>de</strong> losGrids. Esta tarea es llevada a cabo por el móduloJob Rescheduler (ver Figura 2). Finalmente, <strong>de</strong>stacarque este trabajo esta centrado en trabajos simples,si bien es cierto que como trabajo futuro se quiereaumentar la funcionalidad para po<strong>de</strong>r manejar flujos<strong>de</strong> trabajos, así como pilot jobs.IV. Service Level Agreements (SLAs)Una vez que la ejecución <strong>de</strong> un trabajo pue<strong>de</strong> serasegurada con suficiente precisión, el siguiente pasoes establecer comunicación con el usuario para alcanzarun acuerdo sobre la ejecución. Este proceso serealiza mediante acuerdos <strong>de</strong> nivel <strong>de</strong> servicio (ServiceLevel Agreements (SLAs)). El concepto <strong>de</strong> SLAse <strong>de</strong>fine como un contrato entre usuario y proveedor<strong>de</strong> servicios, don<strong>de</strong> se <strong>de</strong>finen explícitamente lasexpectativas, obligaciones e implicaciones legales [3].Es <strong>de</strong>cir, en ellos se representa la QoS que el usuarioespera recibir. A<strong>de</strong>más, los SLAs son el principalmecanismo para mejorar la expansión comercial <strong>de</strong>los Grids, <strong>de</strong>bido fundamentalmente a su soportepara los mo<strong>de</strong>los pay–per–use y al hecho <strong>de</strong> representarun documento legal en la negociación [30].Formalmente, el uso <strong>de</strong> SLAs refuerza la relaciónentre usuario y proveedor <strong>de</strong> servicio <strong>de</strong> dos maneras:mediante un acuerdo legal que <strong>de</strong>be ser cumplido ycomo un acuerdo que pue<strong>de</strong> ser negociado. <strong>La</strong> negociaciónimplica que el proveedor <strong>de</strong> servicio tienela posibilidad <strong>de</strong> <strong>de</strong>cidir si los requisitos <strong>de</strong>l usuariopue<strong>de</strong>n ser satisfechos y, en la medida <strong>de</strong> lo posible,negociar con él para alcanzar un acuerdo mejor.Actualmente, el estándar más importante y ampliamenteutilizado en el ámbito <strong>de</strong> SLAs es WS-Agreement. <strong>La</strong> última versión <strong>de</strong> la especificación fuepublicada en Marzo <strong>de</strong> 2007 [20]. En ella se <strong>de</strong>finentodos los aspectos relacionados con la creación, estructuray gestión <strong>de</strong> los SLAs. WS-Agreement <strong>de</strong>fineun esquema básico para los acuerdos (ver Figura3). Cada acuerdo tiene un i<strong>de</strong>ntificador (Nombre)y un Contexto. En el Contexto se especifica todala información relativa al propio acuerdo, como: informaciónrelativa al proveedor <strong>de</strong> servicios, etc. Elbloque Términos está formado por dos subbloques:el primero <strong>de</strong> ellos, Términos <strong>de</strong> servicio, contiene lainformación relativa a los servicios/recursos que vana ser provistos (p. ej. número <strong>de</strong> máquinas, arquitectura<strong>de</strong> la CPU, etc.); y el segundo, Términos <strong>de</strong>garantía, contiene los niveles <strong>de</strong> servicio que <strong>de</strong>benser garantizados para cada servicio/recurso especifi-<strong>JP2011</strong>-486


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 3. Estructura <strong>de</strong> SLAcado en los Términos <strong>de</strong> servicio (ej. 2 (máquinas),x86 64 (arquitectura <strong>de</strong> la CPU), etc.). Finalmente,el bloque Restricciones <strong>de</strong> creación contiene las limitaciones<strong>de</strong> la negociación.En Enero <strong>de</strong> 2011, una revisión <strong>de</strong> la especificaciónWS-Agreement fue publicada [21], extendiendo elproceso <strong>de</strong> negociación. El protocolo <strong>de</strong> negociación<strong>de</strong>finido en la especificación básica contempla únicamenteun proceso <strong>de</strong> negociación simple, don<strong>de</strong> elusuario pi<strong>de</strong> una plantilla <strong>de</strong> negociación al proveedor<strong>de</strong> servicios, la rellena con la QoS que esperarecibir y la envía al proveedor <strong>de</strong> servicios; el cualacepta o rechaza el SLA. Pero con la reciente revisión(ver Figura 4), la renegociación es posible gracias aun bucle entre el usuario y el proveedor <strong>de</strong> serviciosprevia aceptación <strong>de</strong> una oferta. Esto permite alcanzarun acuerdo mejor para ambos participantes.<strong>La</strong> <strong>de</strong>finición <strong>de</strong> los Términos en cada SLA noestá <strong>de</strong>finido en la especificación WS-Agreement, porello, su <strong>de</strong>finición se <strong>de</strong>ja a cargo <strong>de</strong>l proveedor <strong>de</strong>servicios. Él es el encargado <strong>de</strong> especificar los términospara sus propias necesida<strong>de</strong>s (p. ej. hardware,restricciones temporales o restricciones relacionadascon el trabajo). Estos términos pue<strong>de</strong>n ser muy numerososy diferentes entre sí, pero hay varios <strong>de</strong> ellosque suelen aparecer: relacionados con el hardwarenecesario (como el número <strong>de</strong> máquinas o la cantidad<strong>de</strong> RAM entre otros), y más importantes, relacionadoscon restricciones temporales. Estas restriccionessuelen aparecer como start–time y duración (o<strong>de</strong>adline). Pero es posible <strong>de</strong>finir nuevos términospara mejorar el conocimiento sobre los trabajos yexplotarlos en el proceso <strong>de</strong> meta-planificación.Para este propósito, cada SLA emitido a esteframework <strong>de</strong>be seguir la especificación WS-Agreement (ver Figura 3). Por ello, los Términos<strong>de</strong> servicio especificados en cada SLA sonlos parámetros <strong>de</strong> ejecución para el proceso <strong>de</strong>meta-planificación. Estos términos son fundamentalmente:trabajo, (app, in file), start-time (t s) y<strong>de</strong>adline (d)). El bloque Nombre sólo especifica uni<strong>de</strong>ntificador <strong>de</strong> fácil reconocimiento para los humanos,mientras que el bloque Contexto contiene dosparámetros fundamentales: template-id, i<strong>de</strong>ntificador<strong>de</strong> la plantilla <strong>de</strong> negociación para i<strong>de</strong>ntificación internay proveedor <strong>de</strong> servicio para la i<strong>de</strong>ntificación<strong>de</strong>l proveedor <strong>de</strong> servicio. Esta estructura está abiertaa una futura extensión <strong>de</strong> los parámetros <strong>de</strong>finidos.Finalmente, no se prevee la utilización <strong>de</strong> las Restricciones<strong>de</strong> creación.Este framework implementa la especificación WS-Agreement y es posible interactuar con él a través <strong>de</strong>un portal web (ver Figura 5). Este portal ofrece loscampos a rellenar <strong>de</strong> una plantilla <strong>de</strong> negociación.Pulsando el botón “Submit”, la información <strong>de</strong> loscampos se transfiere a un SLA y es enviado al gestor<strong>de</strong> SLAs. El resultado <strong>de</strong> la petición se muestra alusuario a través <strong>de</strong>l mismo portal, y si la emisión <strong>de</strong>ltrabajo ha sido satisfactoria, <strong>de</strong>vuelve el EPR (End-Point Reference) <strong>de</strong>l acuerdo. <strong>La</strong> monitorización <strong>de</strong>los SLAs y la extensión <strong>de</strong>l proceso <strong>de</strong> negociaciónrepresenta el próximo hito <strong>de</strong> nuestro trabajo.Hay varias ventajas que se <strong>de</strong>spren<strong>de</strong>n <strong>de</strong>l uso <strong>de</strong>SLAs en nuestro sistema, y especialmente <strong>de</strong> la implantación<strong>de</strong> la especificación WS-Agreement. Principalmente,representa una formalización <strong>de</strong>l proceso<strong>de</strong> emisión <strong>de</strong> trabajos. A<strong>de</strong>más, son el mecanismopara una representación formal <strong>de</strong> las restriccionestemporales que el usuario requiere y que nuestro Gridtiene que respetar.Finalmente, los SLAs son mensajes XML (especificadoen WS-Agreement), por ello pue<strong>de</strong>n ser fácilmentemanejados en entornos web. A<strong>de</strong>más, tecnologíascomo Gridsphere [31] pue<strong>de</strong>n ser utilizadaspara el <strong>de</strong>sarrollo <strong>de</strong> nuevos entornos web. Para, <strong>de</strong>esta manera, ocultar la complejidad <strong>de</strong>l sistema alusuario, el cual tiene la posibilidad <strong>de</strong> interactuarcon el Grid a través <strong>de</strong> un portal web.V. Conclusiones y Trabajo FuturoVarias investigaciones intentan proveer QoS enGrids mediante reservas por a<strong>de</strong>lantado, aunque lareserva <strong>de</strong> recursos no siempre es posible en estos entornos.Por esto, este artículo propone un frameworkcon capacidad para negociar SLAs y planificar pora<strong>de</strong>lantado para mejorar la QoS <strong>de</strong> los servicios ofrecidos.Sin embargo, este tipo <strong>de</strong> planificación requiereestimar si una aplicación pue<strong>de</strong> ser ejecutada antes<strong>de</strong>l <strong>de</strong>adline especificado por el usuario. Por ello, esnecesario afrontar varios retos, como la predicción <strong>de</strong>ltiempo necesario para la ejecución <strong>de</strong> los trabajos enlos recursos.Por este motivo, el sistema se ocupa <strong>de</strong>l comportamientodinámico <strong>de</strong> los recursos asociados al Grid,su uso, y las características <strong>de</strong> los trabajos. A<strong>de</strong>más,este sistema tiene en cuenta la precisión en las últimaspredicciones para calcular su confianza en cadarecurso.A<strong>de</strong>más, implementa un gestor <strong>de</strong> SLAs para permitirla interacción con el usuario y ofrecer la capacidad<strong>de</strong> negociar SLAs entre usuario y proveedor <strong>de</strong>servicios. Este módulo se encarga <strong>de</strong> la comunicaciónentre el sistema, interactuando con el SA–<strong>La</strong>yer, y losusuarios; y hace posible proveer QoS a los usuarios <strong>de</strong>forma contractual (a través <strong>de</strong> los SLAs). Asimismo,cada SLA pue<strong>de</strong> especificar más información relativaal trabajo que pue<strong>de</strong> ser utilizada en el proceso <strong>de</strong>meta-planificación.Una interesante dirección a seguir en futuras investigacioneses el <strong>de</strong>sarrollo <strong>de</strong> técnicas para mejorarlas estimaciones <strong>de</strong> los tiempos <strong>de</strong> transferencia.<strong>JP2011</strong>-487


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 4. Protocolo <strong>de</strong> negociación<strong>de</strong>finido por WS-AgreementPor esta razón, es interesante intentar reservar ancho<strong>de</strong> banda <strong>de</strong> la red, cuando sea posible. A<strong>de</strong>más, el<strong>de</strong>sarrollo <strong>de</strong> algoritmos para planificar datos comosi <strong>de</strong> otro recurso se tratara es consi<strong>de</strong>rado trabajofuturo. Finalmente, otro punto sobre el que se planeatrabajar es la mejora <strong>de</strong>l gestor <strong>de</strong> SLAs para hacermás eficiente la planificación teniendo en cuenta loscostes asociados o la reducción <strong>de</strong> energía.Agra<strong>de</strong>cimientosEste trabajo ha sido apoyado conjuntamente por el MECy MICINN Español y la Comisión Europea (fondos FEDER)a través <strong>de</strong> los proyectos “Consoli<strong>de</strong>r Ingenio-2010 CSD2006-00046”, “TIN2009-14475-C04” y a través <strong>de</strong> una beca FPI asociadaal proyecto “TIN2009-14475-C04-03”. Conjuntamentecon la JCCM a través <strong>de</strong>l proyecto “PII1C09-0101-9476”.Referencias[1] U. Schwiegelshohn and et al. Perspectives on gridcomputing. Future Generation Computer Systems,26(8):1104–1115, 2010.[2] E. Huedo, R. S. Montero, and I. M. Llorente. A modularmeta-scheduling architecture for interfacing with pre-WSand WS Grid resource management services. Future GenerationComputing Systems, 23(2):252–261, 2007.[3] J. Padgett, K. Djemame, and P. Dew. Grid-Based SLAManagement. In Proc. of the European Grid Conference(EGC), Amsterdam, The Netherlands, 2005.[4] V. Stantchev and C. Schröpfer. Negotiating and EnforcingQoS and SLAs in Grid and Cloud Computing. InProc. of the 4th Intl. Conference on Advances in Gridand Pervasive Computing (GPC), Geneva, Switzerland,2009.[5] AssessGrid. Web page at http://www.assessgrid.eu,Accedido: 1 <strong>de</strong> Abril, 2011.[6] EU-Brein. Web page at http://www.eu-brein.com/, Accedido:1 <strong>de</strong> Abril, 2011.[7] SLA@SOI. Web page at http://sla-at-soi.eu/, Accedido:2 <strong>de</strong> Abril, 2011.[8] A. Roy and V. San<strong>de</strong>r. Grid Resource Management,chapter GARA: A Uniform Quality of Service Architecture,pages 377–394. Kluwer Aca<strong>de</strong>mic Publishers, 2003.[9] M. Siddiqui, A. Villazón, and T. Fahringer. Grid capacityplanning with negotiation-based advance reservationfor optimized QoS. In Proc. of the 2006 Conference onSupercomputing (SC), Tampa, USA, 2006.[10] O. Waldrich and et al. A meta-scheduling service for coallocatingarbitrary types of resources. In Proc. of the6th Intl. Conference on Parallel Processing and AppliedMathematics (PPAM), Poznan, Poland, 2005.[11] M. Dobber, R. van <strong>de</strong>r Mei, and G. Koole. A predictionmethod for job runtimes on shared processors: Survey,statistical analysis and new avenues. Performance Evaluation,64(7-8):755–781, 2007.[12] P. A. Dinda. The statistical properties of host load. ScientificProgramming, 7(3-4):211–229, 1999.[13] H. Jin, X. Shi, W. Qiang, and D. Zou. An adaptive meta-Fig. 5. Portal Webscheduler for data-intensive applications. Intl. Journal ofGrid and Utility Computing, 1(1):32–37, 2005.[14] L. Tomás, A. C. Caminero, C. Carrión, and B. Caminero.Network-aware meta-scheduling in advance with autonomousself-tuning system. Future Generation ComputerSystems, 27(5):486–497, 2011.[15] A. Sulistio, U. Cibej, S. K. Prasad, and R. Buyya. GarQ:An efficient scheduling data structure for advance reservationsof grid resources. Int. Journal of Parallel Emergentand Distributed Systems, 24(1):1–19, 2009.[16] C. Castillo, G. N. Rouskas, and K. Harfoush. On the<strong>de</strong>sign of online scheduling algorithms for advance reservationsand QoS in grids. In Proc. of the Intl. Paralleland Distributed Processing Symposium (IPDPS), LosAlamitos, USA, 2007.[17] W. Theilmann and L. Baresi. Multi-level SLAs for HarmonizedManagement in the Future Internet, chapter Towardsthe Future Internet, pages 193–202. IOS Press,2009.[18] I. Brandic and et al. Advanced QoS Methods forGrid Workflows Based on Meta-Negotiations and SLA-Mappings. In Proc. of the 3rd Workshop on Work owsin Support of <strong>La</strong>rge-Scale Science, Austin, USA, 2008.[19] J. Ejarque and et al. Exploiting semantics and virtualizationfor SLA-driven resource allocation in serviceprovi<strong>de</strong>rs. Concurrency and Computation: Practice andExperience, 22(5):541–572, 2010.[20] A. Andrieux and et al. Web Services Agreement Specification(WS-Agreement). Technical report, 2007.[21] O. Waeldrich and et al. WS-Agreement Negotiation Ver.1.0. Technical report, 2011.[22] D. Davi<strong>de</strong> <strong>La</strong>manna, J. Skene, and W. Emmerich. Slang:A language for <strong>de</strong>fining service level agreements. In Proc.of the Intl. Workshop of Future Trends of DistributedComputing Systems, Los Alamitos, USA, 2003.[23] WSLA. Web page at http://www.research.ibm.com/wsla/, Accedido: 14 <strong>de</strong> Abril, 2011.[24] M. Parkin, R. M. Badia, and J. Martrat. A comparisonof sla use in six of the european commissions fp6 projects.Technical Report TR-0129, 2008.[25] WSAG4J. Web page at http://packcs-e0.scai.fraunhofer.<strong>de</strong>/wsag4j/, Accedido: 1 <strong>de</strong> Abril, 2011.[26] NextGrid. Web page at http://www.nextgrid.org/, Accedido:2 <strong>de</strong> Abril, 2011.[27] A. Caminero, O. Rana, B. Caminero, and C. Carrión.Network-aware heuristics for inter-domain metaschedulingin grids. Journal of Computer and SystemSciences, 77(2):262 – 281, 2011.[28] A. Di Stefano and et al. A P2P strategy for QoS discoveryand SLA negotiation in Grid environment. FutureGeneration Computer Systems, 25(8):862–875, 2009.[29] L. Tomás, A. Caminero, C. Carrión, and B. Caminero.Exponential Smoothing for network-aware metaschedulerin advance in Grids. In Proc. of the 6th Intl.Workshop on Scheduling and Resource Managementon Parallel and Distributed Systems (SRMPDS), SanDiego,USA, 2010.[30] D. Armstrong and K. Djemame. Towards Quality of Servicein the Cloud. In Proc. of the 25th UK PerformanceEngineering Workshop, Leeds, UK., 2009.[31] Gridsphere. Web page at http://www.gridsphere.org/,Accedido: 15 <strong>de</strong> Abril, 2011.<strong>JP2011</strong>-488


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011RSA@Cloud: Sistema <strong>de</strong> Criptoanálisis sobreInfraestructuras CloudAlberto Megía Negrillo 1 , Antonio Molinera <strong>La</strong>mas 1 , José Antonio Rueda Sánchez 1 yJosé Luis Vázquez-Poletti 2Resumen—Este artículo <strong>de</strong>scribe un sistema queaprovecha las virtu<strong>de</strong>s <strong>de</strong> la computación Cloud y elparalelismo para la factorización <strong>de</strong> números gran<strong>de</strong>s, base<strong>de</strong> la seguridad <strong>de</strong>l criptosistema RSA. Se <strong>de</strong>muestra que,mediante el uso <strong>de</strong> diferentes algoritmos matemáticos <strong>de</strong>factorización <strong>de</strong> números consi<strong>de</strong>rablemente gran<strong>de</strong>s <strong>de</strong>forma paralela sobre varias máquinas en la infraestructura<strong>de</strong> Cloud público <strong>de</strong> Amazon, se pue<strong>de</strong> alcanzar unresultado óptimo en términos <strong>de</strong> tiempo, coste y unamétrica que relaciona a ambos.Palabras clave—Cloud, RSA, criptoanálisis, paralelismo,Amazon.LI. INTRODUCCIÓNA criptografía es el estudio <strong>de</strong> los principios y lastécnicas por las cuales la información pue<strong>de</strong>ocultarse en textos cifrados para <strong>de</strong>spués ser reveladapor usuarios autorizados empleando la clave privada,pero en el que es imposible o inviablecomputacionalmente para una persona que no estéautorizada para ello. Su objetivo principal, por tanto, esmantener en secreto un texto original, a salvo <strong>de</strong>personas no autorizadas que intentan obtener lainformación <strong>de</strong> dicho texto.Se <strong>de</strong>nomina criptoanálisis al conjunto <strong>de</strong> técnicas quese usan para recuperar los mensajes cifrados sinconocimiento <strong>de</strong> la clave. Los criptoanalistas tratan <strong>de</strong>comprometer la seguridad <strong>de</strong> un criptosistema.Un criptosistema [1] es una quíntupladon<strong>de</strong> „M‟ representa el conjunto <strong>de</strong> todos los mensajessin cifrar, ‘C’ representa el conjunto <strong>de</strong> todos losposibles mensajes cifrados, ‘K’ representa el conjunto <strong>de</strong>claves que se pue<strong>de</strong>n usar en el criptosistema, ‘E’ es lafamilia <strong>de</strong> funciones que se aplica a cada elemento <strong>de</strong>‘M’ para obtener un elemento <strong>de</strong> ‘C’. Análogamente,‘D’ es el conjunto <strong>de</strong> transformaciones <strong>de</strong> <strong>de</strong>scifrado, laoperación inversa a ‘E’. Todo criptosistema ha <strong>de</strong>cumplir la siguiente condición:don<strong>de</strong>‘m’ es un mensaje original.Denominamos criptosistemas simétricos o <strong>de</strong> claveprivada a aquellos que emplean la misma clave tantopara cifrar como para <strong>de</strong>scifrar textos. Loscriptosistemas asimétricos o <strong>de</strong> clave pública, por elcontrario, emplean una doble clave: una pública y otra1 Facultad <strong>de</strong> Informática, <strong>Universidad</strong> Complutense <strong>de</strong> Madrid,e-mail:[alberto.megia.negrillo|amlamas|jarueda]@estumail.ucm.es2 Dpto. <strong>de</strong> Arquitectura <strong>de</strong> Computadores, <strong>Universidad</strong> Complutense<strong>de</strong> Madrid, e-email: jlvazquez@fdi.ucm.esprivada, las cuales se usan para codificar y <strong>de</strong>codificarrespectivamente. En estos sistemas, el conocimiento <strong>de</strong>la clave pública no ha <strong>de</strong> permitir obtener la claveprivada.En la actualidad, el sistema RSA es el criptosistema <strong>de</strong>clave pública más extendido. Su seguridad estáestrechamente ligada al problema <strong>de</strong> la factorización <strong>de</strong>un número entero, esto es, la dificultad para factorizarun número compuesto gran<strong>de</strong> [2]. Hasta la fecha <strong>de</strong>lpresente documento no se conoce un algoritmo <strong>de</strong>factorización <strong>de</strong> números enteros eficiente, y en elloresi<strong>de</strong> la seguridad <strong>de</strong> RSA.<strong>La</strong> computación Cloud es un tipo <strong>de</strong> computaciónin<strong>de</strong>pendiente <strong>de</strong> la localización <strong>de</strong>l usuario, en la queservidores compartidos proveen recursos, software y/odatos en función <strong>de</strong> la <strong>de</strong>manda <strong>de</strong>seada en cadamomento (capacidad conocida como escalabilidad), sinque el usuario tenga la necesidad <strong>de</strong> tener conocimientosacerca <strong>de</strong> los servicios que le son proporcionados [3].Esta tecnología se presenta como la evolución natural <strong>de</strong>la creciente expansión <strong>de</strong>l empleo <strong>de</strong> la virtualización, lacomputación orientada a servicios y el concepto <strong>de</strong> éstacomo un servicio público más, como puedan ser el aguay la electricidad, entre otros.Este nuevo mo<strong>de</strong>lo significa la industrialización <strong>de</strong> lacomputación [4] y, por cuestiones económicas y <strong>de</strong>tiempo, es una clara alternativa a los centros <strong>de</strong> datos.Éstos últimos siempre han permitido añadir o liberarrecursos, pero nunca se ha podido hacer con tal grado <strong>de</strong>automatización y “a la carta” en función <strong>de</strong> lasnecesida<strong>de</strong>s y circunstancias <strong>de</strong> trabajo.El servicio <strong>de</strong> la tecnología <strong>de</strong> computación Cloudrequiere una combinación <strong>de</strong> hardware y softwareencaminada a suministrar un servicio a un númeroconsi<strong>de</strong>rable <strong>de</strong> usuarios. Dependiendo <strong>de</strong>l servicioproporcionado, algunos elementos constituyentes sonconfigurados por el proveedor <strong>de</strong>l servicio o se <strong>de</strong>jan adisposición <strong>de</strong> las necesida<strong>de</strong>s <strong>de</strong>l cliente: esta elecciónes <strong>de</strong>pendiente <strong>de</strong> las diferentes capas <strong>de</strong> servicio:infraestructura, plataforma y software (IaaS, PaaS ySaaS) [5].Se necesitan importantes recursos físicos para tenercapacidad <strong>de</strong> cómputo y almacenamiento así como unared que encamine la información que estas máquinasprocesan hacia las terminales <strong>de</strong> los usuarios, sinimportar dón<strong>de</strong> se encuentren. También hace falta unsistema operativo que gestione dichos recursos paradotar a cada cliente <strong>de</strong> su propia máquina remotaconfigurada a su elección. Para ello, a bajo nivel <strong>de</strong>behaber una capa que soporte las tareas <strong>de</strong> múltiplesusuarios in<strong>de</strong>pendientes que no son propietarios <strong>de</strong> la<strong>JP2011</strong>-489


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011máquina pero sí emplean una fracción <strong>de</strong> ella para sutrabajo: a este concepto se le llama virtualización [6].Este software simula la existencia <strong>de</strong> un conjunto <strong>de</strong>máquinas virtuales <strong>de</strong>ntro <strong>de</strong> una misma máquina físicay a la vez monitoriza su estado a través <strong>de</strong> un hipervisor,que asigna recursos y establece priorida<strong>de</strong>s a cada una<strong>de</strong> ellas.El objetivo <strong>de</strong>l sistema presentado en este artículoresi<strong>de</strong> en sentar las bases que permitan la ejecuciónparalela <strong>de</strong> cualquier implementación <strong>de</strong> un algoritmo <strong>de</strong>factorización <strong>de</strong> números en la nube. También sepreten<strong>de</strong> <strong>de</strong>mostrar el potencial <strong>de</strong> la computación ennube para <strong>de</strong>sarrollar trabajos <strong>de</strong> investigación científica[7] o <strong>de</strong> ámbito empresarial <strong>de</strong> gran<strong>de</strong>s dimensiones enun tiempo óptimo sin la necesidad <strong>de</strong> invertir sumasimportantes en la instalación <strong>de</strong> una infraestructurafísica <strong>de</strong> computación, implementando para ello unaherramienta que predice cuáles son los recursosnecesarios para <strong>de</strong>sempeñar cierta tarea <strong>de</strong> formaóptima.Para <strong>de</strong>scribir el proceso <strong>de</strong> la consecución <strong>de</strong> éstospropósitos, se dará un breve repaso sobre los aspectosmás relevantes <strong>de</strong> este estudio. En la sección II se<strong>de</strong>scriben los algoritmos implementados para laestructura principal. A continuación se <strong>de</strong>tallarán losdatos más significativos <strong>de</strong> la infraestructura Clou<strong>de</strong>mpleada para computar esta tarea (Amazon EC2) en lasección III, para luego profundizar en la arquitectura enla que se divi<strong>de</strong> el sistema implementado: „Engine‟ y„Forecaster‟ (sección IV). Por último, en las secciones Vy VI se dan a conocer tanto el análisis <strong>de</strong> los resultadosexperimentales como las conclusiones extraídas a partir<strong>de</strong> los mismos y el trabajo futuro.iteraciones, correspondientes a la cantidad <strong>de</strong> númerosque se comprueban.B. Criba cuadráticaEste algoritmo es más sofisticado que el anterior. Fuepublicado en 1981 por C. Pomerance [9], extendiendolos conceptos <strong>de</strong> „congruencia <strong>de</strong> cuadrados‟ [8] y la„Criba <strong>de</strong> Eratóstenes‟ [10].En él, buscamos números enteros ‘x’ e ‘y’ tales queperoPara encontrarestos resultados, jugamos con una función <strong>de</strong>finidacomo y tratamos <strong>de</strong>encontrar suficientes <strong>de</strong> forma que el producto <strong>de</strong> suscorrespondientes valores sea igual a un cuadrado.Por lo tanto(1)Conseguidos los dos cuadrados, sólo nos quedacalcular el máximo común divisor <strong>de</strong> la suma o la resta<strong>de</strong> ambos y <strong>de</strong>l número a factorizar, obteniendo con unaprobabilidad <strong>de</strong> un factor no trivial <strong>de</strong> „n‟.El algoritmo se divi<strong>de</strong> en cuatro fases:1. Configuración <strong>de</strong> parámetros.2. Proceso <strong>de</strong> criba.3. Construcción y reducción <strong>de</strong> la matriz.4. Solución.Para paralelizar este algoritmo se sigue la misma i<strong>de</strong>aque en la división por tentativa, creamos sub-intervalos<strong>de</strong> búsqueda sobre el intervalo <strong>de</strong> criba, con unas ligerasmodificaciones.(2)II. CRIPTOANÁLISIS: ALGORITMOSLos algoritmos implementados por el sistema son elalgoritmo <strong>de</strong> división por tentativa y la criba cuadrática.Se ha escogido el primero porque es altamenteparalelizable y, al ser eficiente únicamente paranúmeros pequeños , po<strong>de</strong>mos estudiar ladistribución <strong>de</strong> sus cálculos en la nube y exponer losbeneficios obtenidos sobre dicho algoritmo. <strong>La</strong> elección<strong>de</strong>l segundo se <strong>de</strong>be principalmente a que permitetrabajar con tamaños <strong>de</strong> clave aún más gran<strong>de</strong>s que en ladivisión por tentativa, y a<strong>de</strong>más se paraleliza <strong>de</strong> maneraanáloga a este.A. División por tentativaEs el algoritmo <strong>de</strong> factorización más fácil e intuitivo.<strong>La</strong> i<strong>de</strong>a es buscar el número primo más pequeño ‘p’ quedivi<strong>de</strong> a ‘n’, el número a factorizar, probando a dividireste último por todos los números primos <strong>de</strong>s<strong>de</strong> el „2‟hasta ‘n’ [8].En la práctica, la propiedad más interesante <strong>de</strong> estealgoritmo es su facilidad para dividir el trabajo enbúsquedas sobre sub-intervalos <strong>de</strong> forma totalmentein<strong>de</strong>pendientes, pudiendo asignar tareas <strong>de</strong> exploración adistintas máquinas, trabajando en paralelo.Para facilitar la paralelización, se comprueban todoslos números impares empezando <strong>de</strong>s<strong>de</strong> el siguiente a „2‟,éste inclusive. El algoritmo ejecutaIII. INFRAESTRUCTURA CLOUD EMPLEADAUn ejemplo <strong>de</strong> enfoque típico <strong>de</strong> infraestructura Clou<strong>de</strong>s Amazon EC2 3 , basada en una colección <strong>de</strong> servidores<strong>de</strong> propósito general conectados por red estándar <strong>de</strong> árealocal (LAN) mediante tecnologías <strong>de</strong> conmutación. Enla capa superior, el mo<strong>de</strong>lo <strong>de</strong> infraestructura comoservicio (IaaS) [5] se construye don<strong>de</strong> los usuariostienen acceso a los recursos <strong>de</strong>l sistema, mediante re<strong>de</strong>svirtuales y los anteriormente mencionados servidores.Por otra parte, la plataforma <strong>de</strong> software <strong>de</strong>virtualización [6] es ampliamente consi<strong>de</strong>rada como elfactor clave para IaaS, ya que <strong>de</strong>be proporcionar a losusuarios un entorno <strong>de</strong> software estándar sencillo <strong>de</strong>manejar, a<strong>de</strong>más <strong>de</strong> un control “multi-tenancy” (o <strong>de</strong>múltiples clientes) a los administradores <strong>de</strong>l servicio.<strong>La</strong> nube pública <strong>de</strong> Amazon EC2, ofrece sus servicios<strong>de</strong>s<strong>de</strong> cinco regiones diferentes, dos estadouni<strong>de</strong>nses,una europea y dos asiáticas. Amazon EC2 pone adisposición <strong>de</strong> sus usuarios una amplia gama <strong>de</strong>máquinas virtuales que pue<strong>de</strong>n ser instanciadas endistintas modalida<strong>de</strong>s. Dichas modalida<strong>de</strong>s o tipos <strong>de</strong>instancias <strong>de</strong>pen<strong>de</strong>rán <strong>de</strong> la memoria y <strong>de</strong>l número <strong>de</strong>núcleos por máquina virtual como se <strong>de</strong>talla en la TablaI. El usuario pue<strong>de</strong> escoger aquella que mejor se ajuste asus requisitos con respecto a la utilización <strong>de</strong> losrecursos. Cuando un usuario no precisa más <strong>de</strong> su uso,3 http://aws.amazon.com/es/ec2/<strong>JP2011</strong>-490


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011fácil integrarlo en ella mediante la elaboración <strong>de</strong>sólo tiene que apagar la máquina virtual contratada. Sin4 http://aws.amazon.com/es/ec2/pricing/7 http://www.shoup.net/ntl/embargo, el acceso a una infraestructura <strong>de</strong> módulos „envoltorio‟ que ejecuten los nuevoscomputación casi infinita no es gratuito. Cada instanciaproporciona una cantidad planificada <strong>de</strong> capacidad <strong>de</strong>cálculo <strong>de</strong>dicada, facturada por horas <strong>de</strong> uso.algoritmos.A<strong>de</strong>más, la arquitectura está diseñada <strong>de</strong> tal forma que,aparte <strong>de</strong> trabajar con máquinas instanciadas <strong>de</strong> AmazonEC2, se pue<strong>de</strong> hacer uso <strong>de</strong> cualquier otra máquinaTABLA ICARACTERÍSTICAS DE LAS DIFERENTES TIPOS DE MÁQUINASLinux a través <strong>de</strong> Internet.<strong>La</strong> arquitectura principal está <strong>de</strong>sarrollada paraOFRECIDAS POR AMAZON EC2. U.C DEFINE LA UNIDAD DE CÁLCULOplataformas tipo Linux. <strong>La</strong> estructura está implementadaen lenguaje Perl, el cual facilita el manejo <strong>de</strong> archivos, yDE EC2 POR NÚCLEO, EQUIVALENTE A 1,0-1,2 GHZ DE UNse apoya en otros lenguajes como C/C++ para el diseñoPROCESADOR 2007 OPTERON O 2007 XEON.<strong>de</strong> los algoritmos <strong>de</strong> factorización.Tipo Maquina Núcleos U.C Memoria Plataforma Precio/ Cabe <strong>de</strong>stacar la siguiente <strong>de</strong>pen<strong>de</strong>ncia en la máquinahora cliente:SSH-PASS 5 — Utilidad diseñada para ejecutar SSHSmall 1 1 1.7 GB 32 bit $ 0.085 <strong>de</strong> forma no interactiva, esto es, sin necesidad <strong>de</strong><strong>La</strong>rge 2 2 7.5 GB 64 bit $ 0.34introducir la autentificación cada vez que se realiza unaconexión entre dos máquinas. El módulo principalHigh CPUutiliza la versión „v1.04‟.2 2.5 1.7 GB 32 bit $ 0.17MediumLos algoritmos han sido implementados usando lassiguientes bibliotecas gratuitas:High CPU8 2.5 7 GB 64 bit $ 0.68 GMP 6 — Biblioteca para aritmética <strong>de</strong> precisiónExtra <strong>La</strong>rgearbitraria, operaciones entre números enteros con signo,números racionales y números en coma flotante,necesaria para trabajar con gran<strong>de</strong>s números. El tamaño<strong>La</strong> métrica utilizada para la elección <strong>de</strong>l tipo <strong>de</strong> límite lo impone la cantidad <strong>de</strong> memoria <strong>de</strong> la máquinamáquina que más se a<strong>de</strong>cúa a la ejecución <strong>de</strong> nuestros en la que se trabaja. I<strong>de</strong>al para aplicacionesalgoritmos se escoge en función <strong>de</strong>l tiempo, coste y criptográficas. El módulo principal utiliza la versiónrendimiento.„v5.0.1‟.Como veremos más a<strong>de</strong>lante, el tiempo <strong>de</strong> uso NTL 7 — Librería <strong>de</strong> alto rendimiento implementada<strong>de</strong>pen<strong>de</strong> <strong>de</strong>l número a factorizar y <strong>de</strong> la máquina virtual en C++ que provee estructuras <strong>de</strong> datos y algoritmos(número <strong>de</strong> núcleos, unida<strong>de</strong>s <strong>de</strong> cálculo, etc.). El coste para manipular enteros <strong>de</strong> longitud arbitraria y con<strong>de</strong> la utilización <strong>de</strong> las máquinas por hora difiere según signo, a<strong>de</strong>más <strong>de</strong> matrices, vectores, polinomios sobrela región escogida 4 . Para el <strong>de</strong>sarrollo <strong>de</strong> nuestros enteros y sobre campos finitos. Es perfectamentealgoritmos hemos escogido máquinas virtuales <strong>de</strong> la integrable con GMP para aprovechar las característicasregión <strong>de</strong> Virginia <strong>de</strong>l Norte, <strong>de</strong>bido a su precio más <strong>de</strong> rendimiento <strong>de</strong> este.económico. El rendimiento es el coste dividido por el El „Engine‟ se divi<strong>de</strong> en dos partes:tiempo, por tanto la elección <strong>de</strong> la máquina virtual más 1. Conexión. En la primera parte, se realiza laa<strong>de</strong>cuada será aquella que tenga mejor rendimientoconexión entre el cliente y los distintossegún la naturaleza <strong>de</strong> cada algoritmo.servidores. Inicialmente se establece unaconexión segura y no interactiva con todas ellosIV. ARQUITECTURA DEL SISTEMA<strong>La</strong> arquitectura <strong>de</strong>l sistema se divi<strong>de</strong> en dos módulosin<strong>de</strong>pendientes: „Engine‟ y „Forecaster‟.A. ‘Engine’mediante el intercambio <strong>de</strong> claves RSAgeneradas en el momento para <strong>de</strong>spués copiarel ejecutable <strong>de</strong>l algoritmo <strong>de</strong> factorización atratar y el envoltorio que lanza dichoejecutable.El módulo principal distribuye distintas tareas entretodas las máquinas disponibles, a las cuales se acce<strong>de</strong>mediante la lectura <strong>de</strong> un archivo que contiene su2. Tareas. En la segunda parte se distribuyen entrelos servidores <strong>de</strong> forma cíclica las distintastareas en las que se ha dividido el problemadirección IP y la dupla usuario/contraseña <strong>de</strong>l sistema.para su correspondiente algoritmo <strong>de</strong>Se basa en un mo<strong>de</strong>lo cliente-servidor, en el cual lamáquina en la que resi<strong>de</strong> la aplicación será <strong>de</strong>nominadacliente y el resto <strong>de</strong> máquinas que ejecutan el algoritmo<strong>de</strong> factorización tendrán el rol <strong>de</strong> servidores.factorización. Cada vez que una tarea escompletada por un servidor, éste envía unfichero <strong>de</strong> resultados al cliente. Cuando elfactor es encontrado, se <strong>de</strong>tiene la ejecución.Para mantener con carga <strong>de</strong> trabajo todos los núcleosB. ‘Forecaster’<strong>de</strong> la CPU <strong>de</strong> cada servidor, el sistema <strong>de</strong>sarrolla unaasignación dinámica <strong>de</strong> las tareas en el cual se verifica el Este módulo proporciona una herramienta muy útilestado (libre u ocupado) <strong>de</strong> cada núcleo que garantiza un para calcular una estimación <strong>de</strong> cuantas máquinas <strong>de</strong>máximo aprovechamiento <strong>de</strong> los recursos.Amazon EC2 se <strong>de</strong>ben contratar y/o durante cuántoSu diseño es modular, por lo que si se <strong>de</strong>sea tiempo para realizar una tarea <strong>de</strong> factorizaciónimplementar un algoritmo <strong>de</strong> factorización nuevo es5 http://sourceforge.net/projects/sshpass/6 http://gmplib.org/<strong>JP2011</strong>-491


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>de</strong>terminada en función <strong>de</strong> uno <strong>de</strong> los siguientesparámetros: tiempo, número <strong>de</strong> máquinas disponibles,presupuesto disponible, o la mejor relacióncoste/rendimiento.Tras configurar las preferencias, el programa nosmuestra un gráfico que <strong>de</strong>termina la relación entre laclave y el tiempo necesario para obtener sus factores yun informe con los resultados en función <strong>de</strong> los datos <strong>de</strong>entrada.Distinguimos cinco estrategias <strong>de</strong> predicción según elparámetro <strong>de</strong> estimación indicado. En todas ellas elusuario <strong>de</strong>berá indicar el tipo <strong>de</strong> máquina a utilizar, osolicitar el tipo <strong>de</strong> máquina con el que se consigue elresultado óptimo. <strong>La</strong>s estrategias son:Tiempo — El usuario introduce el tiempo máximo(en horas) que tendrá el algoritmo <strong>de</strong> factorizaciónindicado para procesar una clave elegida por élmismo. Como salida se muestra el número <strong>de</strong>máquinas virtuales mínimo y su coste asociadopara dicho límite temporal.Número <strong>de</strong> máquinas — En este caso se introduceel número <strong>de</strong> máquinas que se <strong>de</strong>sea utilizar en lafactorización y la clave a factorizar. Como salidaobtenemos el tiempo y precio necesarios para laclave dada con dicho número <strong>de</strong> máquinas.Coste — Como su propio nombre indica, estaestrategia estima el número <strong>de</strong> máquinas y eltiempo que necesita ese número <strong>de</strong> máquinas enfactorizar la clave con el coste límite elegido por elusuario.Óptima (C/R) — En esta modalidad se realiza unasimulación óptima. De entre todas lasconfiguraciones <strong>de</strong> tipo y número <strong>de</strong> máquinas,elige la que tiene la mejor relacióncoste/rendimiento. Este concepto se explicará en elsiguiente apartado.Manual — En esta estrategia se da total libertad alusuario para configurar los parámetros <strong>de</strong> lapredicción, incluido el tamaño <strong>de</strong> las subtareas enla que se divi<strong>de</strong> el trabajo total.V. RESULTADOS EXPERIMENTALESPara llevar a cabo los experimentos relacionados conla estimación <strong>de</strong>l tiempo y presupuesto que requierecierta tarea representativa, primero llevamos a cabo elestudio <strong>de</strong>l comportamiento <strong>de</strong>l algoritmo <strong>de</strong> la divisiónpor tentativa en cada tipo <strong>de</strong> máquina <strong>de</strong> Amazon. Paraello, se escogen distintos tamaños <strong>de</strong> clave y se ejecutael algoritmo, obteniendo la recta <strong>de</strong> regresión queexplica su comportamiento. Los resultados estánrecogidos en la Figura 1.Fig. 1. “Tiempos <strong>de</strong> ejecución <strong>de</strong>l algoritmo división por tentativa paradiferentes tamaños <strong>de</strong> clave en las máquinas instanciadas <strong>de</strong>Amazon. Éstas funciones expresan la relación entre el número <strong>de</strong>factores que se <strong>de</strong>ben probar para una clave <strong>de</strong>terminada y elnúmero <strong>de</strong> horas <strong>de</strong> ejecución”Una vez <strong>de</strong>finida la recta <strong>de</strong> regresión que <strong>de</strong>scribe elcomportamiento <strong>de</strong>l algoritmo en cada tipo <strong>de</strong> instanciapara tareas individuales, se pue<strong>de</strong> generalizar laecuación <strong>de</strong>l tiempo total T para el mo<strong>de</strong>lo <strong>de</strong>paralelización resultante <strong>de</strong> dividir el trabajo <strong>de</strong>factorizar cierta clave en un <strong>de</strong>terminado número <strong>de</strong>subtareas mediante la siguiente ecuación:Don<strong>de</strong> es la función resultante <strong>de</strong> lasregresiones obtenidas en la Figura 1, I e i son elintervalo total y el intervalo procesado en cada subtarearespectivamente, es el número <strong>de</strong> máquinasvirtuales instanciadas en el experimento y elnúmero <strong>de</strong> núcleos <strong>de</strong> cada instancia.El tiempo total <strong>de</strong> ejecución no es la única condición atener en cuenta a la hora <strong>de</strong> elegir una configuraciónóptima. Es necesario establecer una relación entre eltiempo T y su coste asociado, cuyo valor resultante es:Don<strong>de</strong> es el coste <strong>de</strong>l uso <strong>de</strong>l tipo <strong>de</strong> instanciaelegida por hora tal y como se <strong>de</strong>scribe en la Tabla 1. Ala variable T se le aplica la función techo <strong>de</strong>bido a quelos precios correspon<strong>de</strong>n a cada hora <strong>de</strong> uso <strong>de</strong> lamáquina solicitada.<strong>La</strong> configuración óptima está <strong>de</strong>terminada por labúsqueda <strong>de</strong> un compromiso entre el tiempo y el coste<strong>de</strong>nominado Coste/Rendimiento (C/R) [11]. Estarelación se obtiene al multiplicar ambos parámetros y laconfiguración más conveniente correspon<strong>de</strong> a su valormínimo:(3)(4)(5)Don<strong>de</strong> las variables correspon<strong>de</strong>n a las fórmulas 3 y 4y a la instancia seleccionada.El valor óptimo <strong>de</strong> C/R se alcanza cuando el número<strong>de</strong> instancias utilizado hace que el tiempo <strong>de</strong> uso <strong>de</strong> cadamáquina instanciada sea exactamente <strong>de</strong> una hora.<strong>JP2011</strong>-492


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Tras obtener el mejor C/R para cada máquina,po<strong>de</strong>mos evaluar cuál <strong>de</strong> ellas es mejor y averiguar elnúmero <strong>de</strong> máquinas virtuales necesarias para el trabajototal en el mejor caso con la expresión anterior. El valor<strong>de</strong> I está <strong>de</strong>terminado por el tamaño <strong>de</strong> la clave, cuyovalor es igual a. (6)Para estas estimaciones, el tamaño <strong>de</strong> cada tarea „i‟ hasido:(7)Los valores mínimos <strong>de</strong> C/R se alcanzan con diferentenúmero <strong>de</strong> máquinas según el tipo <strong>de</strong> instancia elegido.<strong>La</strong> Figura 3 muestra los valores <strong>de</strong> C/R y número <strong>de</strong>máquinas virtuales óptimos para el ejemplo consi<strong>de</strong>rado.Los valores <strong>de</strong>l coste son muy aproximados al valor <strong>de</strong>C/R obtenido ya que el tiempo está ajustado aaproximadamente una hora (0.95 horas = 57 minutos).Don<strong>de</strong> „k’ es el número <strong>de</strong> tareas asignadas a cadanúcleo <strong>de</strong> cada máquina. Tras consi<strong>de</strong>rar distintosvalores para ‘k’ llegamos a la conclusión que cuantomayor sea su valor, mejor será el rendimiento <strong>de</strong> lamáquina, ya que el tiempo <strong>de</strong> ejecución resultante T esmenor. Esto <strong>de</strong>riva en un menor valor <strong>de</strong> “i” y por tantomás subtareas y transferencias <strong>de</strong> archivos <strong>de</strong> lasmismas, por lo que se ha limitado el aumento <strong>de</strong>l valor<strong>de</strong> ‘k’ <strong>de</strong> tal manera que el producto(elnúmero <strong>de</strong> tareas por máquina) sea 120 para evitar unexceso <strong>de</strong> tráfico <strong>de</strong> archivos resultado entre lasmáquinas, <strong>de</strong> tal forma que no se superen un margen <strong>de</strong>3 minutos permitido en el caso <strong>de</strong> que cada transacciónimplique un valor aproximado <strong>de</strong> un segundo <strong>de</strong> retardo.Se establece una franja <strong>de</strong> seguridad <strong>de</strong> un minuto,<strong>de</strong>jando dos minutos para transferencias entre máquinas.Para valores <strong>de</strong> claves muy gran<strong>de</strong>s el número <strong>de</strong>instancias necesarias pue<strong>de</strong> ser muy elevado, lo cualimplica un problema: Amazon EC2 sólo permiteinstanciar un número máximo <strong>de</strong> 20 máquinas a la vez.Para la adquisición <strong>de</strong> más instancias ha <strong>de</strong> solicitarse aAmazon mediante un formulario justificando lanecesidad <strong>de</strong> las mínimas.En la Figura 2 se pue<strong>de</strong> ver un ejemplo <strong>de</strong> búsqueda<strong>de</strong>l tipo <strong>de</strong> instancia óptima para una clave. En ellaobservamos que al mayor uso <strong>de</strong> instancias mejor C/R.Pero a partir <strong>de</strong>l momento en que se alcanza el valoróptimo <strong>de</strong> C/R, éste empieza a crecer, haciendoineficiente el uso <strong>de</strong> más instancias.Fig. 2. “Comparación <strong>de</strong> C/R para todas las instancias <strong>de</strong> AmazonEC2, para una clave igual a 57695605808471080739826972481, ycon un valor k <strong>de</strong> 120. <strong>La</strong> gráfica <strong>de</strong>l interior ilustra los puntos <strong>de</strong>valor óptimo <strong>de</strong> C/R para los cuatro tipos <strong>de</strong> instanciasestudiadas.”Fig. 3. “Comparación <strong>de</strong> C/R óptimo fijando el tiempo <strong>de</strong> ejecución en57 minutos para todas las instancias <strong>de</strong> Amazon EC2, para losmismos valores <strong>de</strong> clave y k <strong>de</strong> la Figura 2.”Analizando las instancias <strong>de</strong> tipo „Small‟ y „<strong>La</strong>rge‟ seobtienen valores C/R similares, pero el número <strong>de</strong>instancias <strong>de</strong> tipo Small cuadruplica al número <strong>de</strong>máquinas <strong>de</strong> tipo „<strong>La</strong>rge‟, <strong>de</strong>bido a que el número <strong>de</strong>unida<strong>de</strong>s <strong>de</strong> cálculo EC2 en la instancia „<strong>La</strong>rge‟ es 4,mientras que la „Small‟ consta sólo <strong>de</strong> una unidad. Estarelación entre unida<strong>de</strong>s <strong>de</strong> cálculo pue<strong>de</strong> observarsetambién entre la familia <strong>de</strong> instancias „High CPU‟, conuna proporción <strong>de</strong> unida<strong>de</strong>s <strong>de</strong> cálculo <strong>de</strong> uno a cuatro,para la ‟Medium‟ respecto <strong>de</strong> la „Extra <strong>La</strong>rge‟.Elegir un tipo <strong>de</strong> instancia se traduce a elección <strong>de</strong>pagar más por la infraestructura o disminuir el nivel <strong>de</strong>paralelismo. Viendo la Figura 3, la instancia <strong>de</strong> tipo„Small‟ es la solución más cara pero con el mayornúmero <strong>de</strong> núcleos trabajando simultáneamente (6711).En la instancia tipo „<strong>La</strong>rge‟ el número <strong>de</strong> núcleos es lamitad (3374), pero con un coste similar. <strong>La</strong>s instancias<strong>de</strong> tipo „High CPU‟ realizan la misma tarea con unnúmero <strong>de</strong> núcleos similar a la instancia „Extra <strong>La</strong>rge‟,sin embargo el coste es mucho menor. En concreto elprecio para „High CPU Medium‟ es $267,42, y para„High CPU Extra <strong>La</strong>rge‟ es $287,65.Observando los resultados obtenidos, <strong>de</strong>terminamosque el tipo <strong>de</strong> instancia óptima es la „High CPUMedium‟, <strong>de</strong>bido al mayor aprovechamiento <strong>de</strong> lacapacidad <strong>de</strong> cálculo <strong>de</strong> sus núcleos. Con respecto a lasinstancias „<strong>La</strong>rge‟ y „High CPU Extra <strong>La</strong>rge‟ seconsigue realizar la tarea <strong>de</strong> factorización con un costemás económico empleando un número <strong>de</strong> núcleossimilar.VI. CONCLUSIONES Y TRABAJO FUTURO<strong>La</strong> computación Cloud es el paradigma <strong>de</strong> lacomputación distribuida que reúne las mejores virtu<strong>de</strong>s<strong>de</strong> las tecnologías <strong>de</strong>sarrolladas sobre este campo, talescomo los mo<strong>de</strong>los <strong>de</strong> clúster, Intranet Computing,Internet Computing, P2P y Grid [12]. Esta nuevatecnología, gracias al <strong>de</strong>sarrollo <strong>de</strong> la virtualización, laarquitectura <strong>de</strong> red orientada a servicios e Internet,<strong>JP2011</strong>-493


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011es que dispone <strong>de</strong> 33.5 unida<strong>de</strong>s <strong>de</strong> cálculo, muy porpermite un alto grado <strong>de</strong> rendimiento y disponibilidad,8 http://aws.amazon.com/hpc-applications/#HPCEC2balanceo <strong>de</strong> carga y escalabilidad así como elasticidad,lo que permite personalizar la cantidad <strong>de</strong> recursosdisponibles rápidamente, dando una sensación <strong>de</strong> accesopor <strong>de</strong>manda a recursos <strong>de</strong> computación infinitos. Unencima <strong>de</strong> todos los tipos vistos anteriormente. Suaplicación en el campo <strong>de</strong> la factorización reduciríaconsi<strong>de</strong>rablemente los tiempos <strong>de</strong> ejecución <strong>de</strong> cadatarea.rendimiento medio mayor, unido a la posible Por último, y motivado por la amplia oferta en elportabilidad <strong>de</strong> la información y el ahorro que supone noabordar gastos <strong>de</strong> mantenimiento y actualización sonotras cualida<strong>de</strong>s que posicionan esta tecnología a lavanguardia <strong>de</strong> la computación distribuida.En la actualidad, el criptoanálisis <strong>de</strong> un sistema RSAmercado <strong>de</strong> computación Cloud, se exten<strong>de</strong>rá lafuncionalidad <strong>de</strong>l „Forecaster‟ a otros proveedoresdistintos <strong>de</strong> Amazon, como pue<strong>de</strong>n ser Windows Azure(Microsoft), Salesforce, Netmagic y Google, entre otros,así como se adaptará la predicción al uso <strong>de</strong> distintossigue requiriendo enormes cantida<strong>de</strong>s <strong>de</strong> potencia tipos <strong>de</strong> máquinas a la vez, favoreciendo lacomputacional. <strong>La</strong> computación Cloud nos abre unanueva ventana hacia la factorización eficaz ofreciendoheterogeneidad <strong>de</strong> la infraestructura y obteniendomejores resultados para la métrica C/R.acceso a dicha capacidad <strong>de</strong> cálculo bajo <strong>de</strong>manda <strong>de</strong>lusuario, dándole la posibilidad <strong>de</strong> saber en cadaVII. AGRADECIMIENTOSmomento el precio <strong>de</strong> la potencia <strong>de</strong>mandada.Esta investigación ha sido financiada por los proyectosNuestro sistema pue<strong>de</strong> ser utilizado para evaluar laHPCcloud (TIN2009-07146) y MEDIANETseguridad <strong>de</strong> una clave RSA <strong>de</strong>terminando el coste(S2009/TIC-1468).necesario para comprometer su resistencia.El uso <strong>de</strong>l Cloud para la paralelización <strong>de</strong> tareas,VIII. REFERENCIASsupone gran<strong>de</strong>s ventajas y mejoras, sobre todo en[1] M.J. Lucena López, Criptografía y seguridad en computadores,función <strong>de</strong>l tiempo, ya que permite a cualquier usuarioversión 4-0.7.51. 11 <strong>de</strong> Junio <strong>de</strong> 2008. <strong>Universidad</strong> <strong>de</strong> Jaén.un mayor acceso <strong>de</strong> capacidad <strong>de</strong> computación. En [2] J. Buchmann, Introduction to Cryptography, Second Edition.nuestro sistema se pue<strong>de</strong> observar como la factorización ISBN: 978-0-387-21156-5.<strong>de</strong> números gran<strong>de</strong>s, en concreto <strong>de</strong> claves RSA, [3] Lutz Schubert ,The Future of Cloud Computing Opportunities forEuropean Cloud Computing Beyond 2010. Public Version 1.0,conlleva <strong>de</strong>masiado tiempo. Este tiempo se reduce <strong>de</strong>2010.forma consi<strong>de</strong>rable con el empleo <strong>de</strong> Cloud.[4] R. Buyya, C. Shin Yeo, S. Venugopal, J. Broberg & I. Brandic,Por otra parte, con vistas a continuar la investigación Cloud computing and energing IT plataforms: Vision, hype, and<strong>de</strong> algoritmos <strong>de</strong> factorización sobre infraestructuras reality for <strong>de</strong>livering computin as the 5th utility, FutureGenetarion Computer Systems vol. 25, Issue 6, Pag. 599-616,Cloud, el sistema <strong>de</strong>sarrollado dispone <strong>de</strong> un altoJune 2009.potencial en cuanto a posibilida<strong>de</strong>s <strong>de</strong> ampliación, [5] M. Armbrust, A. Fox, R. Griffith, A.D. Joseph, R. Katz, A.gracias a que el „Engine‟ está diseñado <strong>de</strong> forma Konwinski, G. Lee, D. Patterson, A. Rabkin, I. Stoica, & M.modular, lo cual permite la inclusión <strong>de</strong> diferentes Zaharia. A view of Cloud Computing, Communications of theACM, vol. 5 3 no. 4., April 2010programas ejecutables en el que se implementen otros[6] R. Figueiredo, P.A. Dinda, J. Fortes, Guest Editors' Introduction:algoritmos matemáticos <strong>de</strong>stinados a factorizar números Resource Virtualization Renaissance, Computer, vol.38, no.5,<strong>de</strong> aún mayor magnitud que la división por tentativa y la pp. 28- 31, May 2005.criba cuadrática, como por ejemplo el GNFS. <strong>La</strong> [7] G. Juve, E. Deelman, K. Vahi, G. Mehta, B. Berriman, B.P.Berman, P. Maechling, Scientific workflow applications oninclusión <strong>de</strong> uno o varios nuevos algoritmos a elegir enAmazon EC2, Workshop on Cloud-based Services an<strong>de</strong>l „Forecaster‟ supondría aún menos dificulta<strong>de</strong>s.Applications in Conjunction with 5th IEEE InternationalA<strong>de</strong>más, dado el carácter multiplataforma <strong>de</strong> los Conference on e-Science, e-Science‟09, 2009.lenguajes empleados (Perl, C, Java) para el <strong>de</strong>sarrollo <strong>de</strong> [8] Arjen K. Lenstra, Integer Factoring, Designs, Co<strong>de</strong>s andCryptography, 19, 101-128, 2000.los diferentes módulos <strong>de</strong> los que consta el sistema, sería[9] C. Pomerance, The Quadratic Sieve Factoring Algorithm,muy provechoso y relativamente sencillo adaptar el Departament of Mathematic, University of Georgia. Eurocript,sistema a un entorno in<strong>de</strong>pendiente <strong>de</strong> la plataforma y <strong>de</strong> 1981.la arquitectura en el cual el cliente y los servidores se [10] C. Pomerance, A Tale of Two Sieves, 1996.[11] J.L. Vazquez-Poletti, G. Bar<strong>de</strong>ras, I.M. Llorente, P. Romero. Acomunicasen entre sí sin importar el sistema operativoMo<strong>de</strong>l for Efficient Onboard Actualization of an Instrumental<strong>de</strong> las distintas máquinas (UNIX, Windows, Mac).Cyclogram for the Mars MetNet Mission on a Public CloudGracias a la modularidad <strong>de</strong> la plataforma, se Infrastructure. In Proc. PARA2010: State of the Art in Scientific<strong>de</strong>sarrollarán otros algoritmos <strong>de</strong> factorización capaces and Parallel Computing, Reykjavik (Iceland), June 2010, LectureNotes in Computer Science, Volume in press, 2011.<strong>de</strong> aprovechar los beneficios <strong>de</strong> la nube para la[12] I. Foster, Yong Zhao, I. Raicu, S. Lu, Cloud Computing and Gridparalelización <strong>de</strong> sus cálculos. Uno <strong>de</strong> los algoritmos Computing 360-Degree Compared, Grid Computingmás interesantes para esta tarea es GNFS („General Environments Workshop, 2008. GCE „08, vol., no., pp.1-10, 12-Number Field Sieve‟ / Criba General en el Campo <strong>de</strong> 16 Nov. 2008.Números), que es más rápido que la Criba Cuadráticapara tamaños <strong>de</strong> clave superiores a 110 dígitos.Amazon nos da la posibilidad <strong>de</strong> utilizar una nuevafamilia <strong>de</strong> instancias, lanzada en el año 2010 y<strong>de</strong>nominadas “Instancias <strong>de</strong> cálculo en clúster 8 ”,especialmente a<strong>de</strong>cuadas para aplicaciones <strong>de</strong> cálculo <strong>de</strong>alto rendimiento (HPC). Su característica más relevante<strong>JP2011</strong>-494


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Descripción <strong>de</strong> la Plataforma Formiga CloudFernando Gomez-Folgar 1 , Javier López Cacheiro 1 , Carlos Fernán<strong>de</strong>z Sánchez, 1 AntonioGarcia-Loureiro 2 , Raúl Valin 2 y Víctor Fernán<strong>de</strong>z-Albor 3Resumen— En la actualidad, diversos organismospúblicos, como universida<strong>de</strong>s, institutos y colegios,disponen <strong>de</strong> elevados recursos computacionales, principalmenteen sus aulas <strong>de</strong> informática, que acumulanuna gran potencia computacional. Su utilizaciónqueda restringida única y exclusivamente a sus respectivosusuarios, por lo que su aprovechamiento esrelativamente bajo, teniendo en cuenta su potencial<strong>de</strong> uso.<strong>La</strong> creación <strong>de</strong> una infraestructura común que permitaagregar los recursos computacionales <strong>de</strong> diversasorganizaciones, utilizando las tecnologías Cloud yGrid, posibilitaría su reutilización para efectuar tareas<strong>de</strong> cálculo <strong>de</strong> distintas áreas <strong>de</strong> investigación,y por otra su uso en los procesos <strong>de</strong> enseñanza yaprendizaje, por medio <strong>de</strong>l <strong>de</strong>spliegue <strong>de</strong> máquinasvirtuales creadas <strong>de</strong> forma específica por los profesoresque imparten diferentes cursos.En este trabajo se presenta la plataforma FormigaCloud que tiene por objetivo la agregación <strong>de</strong> los recursoscomputacionales <strong>de</strong> diversas organizaciones enuna infraestructura Cloud común accesible <strong>de</strong>s<strong>de</strong> unainterfaz Web única. Esta interfaz facilitará a los administradoresla gestión <strong>de</strong> la plataforma, y a los profesoresy alumnos la gestión <strong>de</strong> sus propios recursosvirtuales. <strong>La</strong> arquitectura <strong>de</strong> esta nueva infraestructurase presenta en este artículo.Palabras clave— Cloud computing, Grid, simulación,virtualización.I. IntroducciónCON el elevado incremento <strong>de</strong> la potencia <strong>de</strong> loscomputadores tanto organismos públicos comoempresas disponen <strong>de</strong> or<strong>de</strong>nadores que acumulan unagran potencia computacional. Sólo la <strong>Universidad</strong> <strong>de</strong>Santiago <strong>de</strong> Compostela (USC) dispone <strong>de</strong> 1800 or<strong>de</strong>nadoresen sus aulas <strong>de</strong> informática. Durante elproyecto Formiga se <strong>de</strong>sarrolló una plataforma gridvirtual que permite la reutilización <strong>de</strong> estos or<strong>de</strong>nadoresen tareas <strong>de</strong> cálculo científico [1], [2]. Estaplataforma fue implantada con éxito en las aulas <strong>de</strong>varias faculta<strong>de</strong>s <strong>de</strong> la <strong>Universidad</strong> <strong>de</strong> Santiago <strong>de</strong>Compostela, y fue puesta a disposición <strong>de</strong> los investigadorespara realizar, entre otras, simulaciones <strong>de</strong>tratamientos <strong>de</strong> radioterapia, nanodispositivos, asícomo cálculos <strong>de</strong> dinámica molecular.Hoy en día, las tecnologías Cloud están siendo objeto<strong>de</strong> interés tanto para las organizaciones públicascomo para las privadas [3], lo que ha permitido unrápido <strong>de</strong>sarrollo <strong>de</strong> las mismas. Debido al auge <strong>de</strong>estas tecnologías [4]-[9] es posible proporcionar funcionalida<strong>de</strong>sadicionales a la plataforma Formiga permitiendoofrecer la infraestructura como un servicio(IaaS). Formiga Cloud es una nueva plataforma que1 Dpto. <strong>de</strong> Sistemas, Centro <strong>de</strong> Supercomputación <strong>de</strong> Galicia(CESGA), e-mail: (fgfolgar, jlopez, carlosf)@cesga.es.2 Dpto. <strong>de</strong> Electrónica y Computación, <strong>Universidad</strong> <strong>de</strong> Santiago<strong>de</strong> Compostela, e-mail: (antonio.garcia.loureiro,raul.valin)@usc.es.3 Grupo <strong>de</strong> Física <strong>de</strong> Partículas, <strong>Universidad</strong> <strong>de</strong> Santiago <strong>de</strong>Compostela, e-mail: victormanuel.fernan<strong>de</strong>z@usc.es.permitirá agrupar recursos físicos <strong>de</strong> diferentes institucionesu organizaciones bajo una nueva infraestructuracomún compartida, accesible <strong>de</strong>s<strong>de</strong> una interfazWeb 2.0 única.<strong>La</strong> plataforma Formiga Cloud no sólo permitirá larealización <strong>de</strong> cálculos científicos, sino también cursosen los que los alumnos podrán <strong>de</strong>splegar unamáquina virtual previamente creada por el profesoro incluso crear una propia. A<strong>de</strong>más, permitiráque los alumnos situados en aulas que cuentan conequipos informáticos mo<strong>de</strong>stos realicen sus prácticasempleando, <strong>de</strong> forma sencilla, nodos <strong>de</strong> computaciónmás potentes que se encuentren en lugares remotos,sin la necesidad <strong>de</strong> cambiar físicamente <strong>de</strong> ubicación.De este modo, se fomenta la reutilización <strong>de</strong> los recursoscomputacionales disponibles.En este artículo se <strong>de</strong>scribe la plataforma FormigaCloud y su estructura es la siguiente: En la secciónII se <strong>de</strong>scribe el diseño <strong>de</strong> la plataforma. <strong>La</strong> secciónIII presenta el gestor CloudStack, empleado paraconstruir la plataforma Formiga Cloud. A continuación,en la sección IV se <strong>de</strong>scribe el portalDIRAC, que es el middleware que permite la unión<strong>de</strong> la plataforma Formiga Cloud con la infraestructuragrid. <strong>La</strong> sección V <strong>de</strong>scribe las re<strong>de</strong>s <strong>de</strong> interconexión<strong>de</strong> la plataforma y, finalmente, se presentanlas conclusiones en la sección VI.II. Diseño <strong>de</strong> la plataforma Formiga CloudFormiga Cloud es una plataforma que empleará lastecnologías Grid y Cloud y que permitirá a distintasorganizaciones unirse en una infraestructura común,<strong>de</strong> tal forma que el administrador <strong>de</strong> cada sitio podrágestionar sus recursos a través <strong>de</strong>l portal FormigaCloud. A<strong>de</strong>más, la plataforma Fomiga Cloud permitiráa los investigadores ejecutar cálculos científicos,y a los profesores y alumnos la realización <strong>de</strong> cursosmediante la utilización <strong>de</strong> Máquinas Virtuales (MVs)a medida.<strong>La</strong> plataforma Formiga Cloud presenta los siguientescasos <strong>de</strong> uso:Administradores: Los administradores <strong>de</strong> las aulaspodrán gestionar sus recursos en la plataformaFormiga Cloud. Para ello, dispondrán <strong>de</strong> una interfazsencilla.Profesores: Los profesores <strong>de</strong> los cursos que seimparten en las aulas <strong>de</strong> informática podrán gestionarsus máquinas virtuales y la distribución <strong>de</strong>éstas, es <strong>de</strong>cir, podrán efectuar el <strong>de</strong>spliegue <strong>de</strong> unnúmero <strong>de</strong> ellas a su elección, así como las plantillas<strong>de</strong> éstas. A<strong>de</strong>más, dispondrán <strong>de</strong> una interfazsencilla que les permitirá efectuar la gestión <strong>de</strong> susrecursos virtuales.Alumnos: Los alumnos podrán gestionar sus<strong>JP2011</strong>-495


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011máquinas virtuales; a<strong>de</strong>más, podrán controlar lasplantillas <strong>de</strong> éstas y dispondrán <strong>de</strong> una interfaz sencillaque les permitirá efectuar la gestión <strong>de</strong> estoselementos.Investigadores: Los investigadores podrán ejecutary gestionar sus propios trabajos <strong>de</strong> cálculocientífico, gracias a la interoperabilidad <strong>de</strong> laplataforma con la infraestructura grid.<strong>La</strong> arquitectura <strong>de</strong> la plataforma Formiga Cloud semuestra en la figura 1 y está formada principalmentepor tres componentes:• Gestor CloudStack• Portal grid DIRAC• Gestor <strong>de</strong> la red <strong>de</strong> interconexiónEn las siguientes secciones veremos en más <strong>de</strong>tallecada uno <strong>de</strong> ellos.Fig. 1.Arquitectura Formiga Cloud.III. Gestor CloudStackEn la actualidad, existen diversos gestores Cloud“open-source” que permiten crear Clouds privados,públicos e híbridos, como, por ejemplo, OpenNebula[10], Eucalyptus [11] y CloudStack [12]. Después<strong>de</strong> haber efectuado un estudio <strong>de</strong> evaluación y comparaciónentre los gestores Cloud [13] mencionadosanteriormente, se ha seleccionado CloudStack comogestor Cloud para la plataforma Formiga Cloud, pordisponer <strong>de</strong> una interfaz Web sencilla y completa, asícomo múltiples modos <strong>de</strong> configuración <strong>de</strong> la red <strong>de</strong>las MVs. Ambas funcionalida<strong>de</strong>s son fundamentalespara la plataforma Formiga Cloud.Hay que señalar que CloudStack es una plataforma“open-source” <strong>de</strong> Cloud <strong>de</strong>sarrollada por Cloud.com,que permite implementar cualquier tipo <strong>de</strong> Cloud:público, privado e híbrido.CloudStack gestionará los recursos físicos <strong>de</strong> laplataforma Formiga Cloud <strong>de</strong> forma elástica, incluyendola creación, el <strong>de</strong>spliegue y la configuración<strong>de</strong> las nuevas zonas pertenecientes a las organizacionesque se adherirán a la plataforma, así como lainstalación y gestión <strong>de</strong> las MVs que se ejecutaránen la nueva infraestructura común.A continuación, se efectúa una <strong>de</strong>scripción <strong>de</strong> laarquitectura <strong>de</strong> CloudStack y sus funcionalida<strong>de</strong>s.También se presenta un componente adicional queserá necesario <strong>de</strong>sarrollar <strong>de</strong>ntro <strong>de</strong>l proyecto ycuya función será la adaptación <strong>de</strong> CloudStack a laplataforma <strong>de</strong> aulas <strong>de</strong> informática.A. Arquitectura <strong>de</strong> CloudStackCloudStack está formado a su vez por cinco componentes,como se muestra en la figura 2: Nodos <strong>de</strong>Computación (NC), Clústeres, Pods, Zonas <strong>de</strong> disponibilidady el Servidor <strong>de</strong> Gestión.Los nodos <strong>de</strong> computación son los recursos computacionalesque tienen instalado alguno <strong>de</strong> los hipervisoressoportados por la plataforma y que permitenejecutar las Máquinas Virtuales (MV). Representanbloques básicos que permiten escalar la capacidad <strong>de</strong>lCloud. El administrador tiene la potestad <strong>de</strong> po<strong>de</strong>rañadirlos en cualquier momento para proporcionaruna mayor capacidad para albergar MVs. Los nodos<strong>de</strong> computación no son visibles para el usuariofinal (profesores y alumnos) y, por lo tanto, éste nopodrá <strong>de</strong>terminar en cuál <strong>de</strong> ellos se está ejecutandosu MV.Los clústeres representan el segundo nivel para elescalado físico. Un clúster es un grupo <strong>de</strong> nodos <strong>de</strong>computación que emplean el mismo hipervisor y que,a<strong>de</strong>más, comparten el mismo almacenamiento primario.Los Pods representan el tercer nivel para el escalado<strong>de</strong> los recursos. Un Pod es simplemente unacolección <strong>de</strong> clústeres.<strong>La</strong>s zonas <strong>de</strong> disponibilidad están formadas poruna colección <strong>de</strong> Pods e implican algún tipo <strong>de</strong> aislamientofísico y redundancia. Destacar que existela posibilidad <strong>de</strong> que los propios administradores <strong>de</strong>las aulas <strong>de</strong>n <strong>de</strong> alta sus propias zonas empleandoCloud Zone [12]. Ello les permitirá agregar sus recursoscomputacionales a la nueva plataforma y, a suvez, efectuar las tareas <strong>de</strong> administración. Hay queseñalar que las zonas <strong>de</strong> disponibilidad son visiblespara el usuario final.El servidor <strong>de</strong> gestión, mediante la interfaz Web,permite gestionar el Cloud por completo.B. Funcionalida<strong>de</strong>sEn este apartado vamos a analizar las funcionalida<strong>de</strong>s<strong>de</strong>s<strong>de</strong> el punto <strong>de</strong> vista <strong>de</strong> los usuarios, loshipervisores soportados, el almacenamiento, las re<strong>de</strong>s<strong>de</strong> las máquinas virtuales, las máquinas virtuales, lasinterfaces <strong>de</strong> gestión y los agentes <strong>de</strong> computación.Usuarios: CloudStack permite gestionar tres roles<strong>de</strong> usuario: administrador CloudStack <strong>de</strong>l dominioraíz, administrador CloudStack <strong>de</strong> dominio y usuariosno privilegiados.El administrador <strong>de</strong>l dominio raíz pue<strong>de</strong> efectuarlas tareas administrativas <strong>de</strong> todo el Cloud <strong>de</strong>Fomiga Cloud.<strong>JP2011</strong>-496


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 2.Arquitectura CloudStack.El administrador <strong>de</strong> dominio pue<strong>de</strong> efectuar las tareasadministrativas para los usuarios pertenecientesúnica y exclusivamente a su dominio.Los usuarios no privilegiados, en nuestro caso profesoresy alumnos, podrán gestionar sus propios recursosvirtuales, como, por ejemplo, sus máquinasvirtuales.Hipervisores soportados: CloudStack soporta loshipervisores KVM [15], Xenserver [14] y VMwarevSphere [16].Almacenamiento: CloudStack emplea dos tipos <strong>de</strong>almacenamiento: almacenamiento primario y almacenamientosecundario.El almacenamiento primario se emplea para almacenarel disco raíz <strong>de</strong> las máquinas virtuales, asícomo los volúmenes adicionales <strong>de</strong> datos. El almacenamientoprimario se registra con el clúster <strong>de</strong> losnodos <strong>de</strong> computación. Debe existir al menos uno<strong>de</strong> ellos para cada uno <strong>de</strong> los clústers. Los discosraíz <strong>de</strong> los volúmenes <strong>de</strong> las MVs se crean enél <strong>de</strong> forma automática cuando los usuarios inicianlas máquinas virtuales, y se eliminan, también <strong>de</strong>forma automática, cuando éstos las <strong>de</strong>struyen. Losvolúmenes <strong>de</strong> datos <strong>de</strong> las MVs se pue<strong>de</strong>n crear,conectar, <strong>de</strong>sconectar y eliminar <strong>de</strong> forma dinámicabajo <strong>de</strong>manda.El almacenamiento secundario se emplea para almacenarplantillas, snapshots <strong>de</strong> MVs, así comoimágenes ISO. Debe estar ubicado en la mismazona <strong>de</strong> disponibilidad que las MVs a las que sirve.A<strong>de</strong>más, <strong>de</strong>be haber exactamente uno por cada una<strong>de</strong> las zonas <strong>de</strong> disponibilidadRe<strong>de</strong>s <strong>de</strong> las MVs: CloudStack proporciona a lasMVs distintos modos <strong>de</strong> red entre los que se incluyeel modo <strong>de</strong> red directo y el modo <strong>de</strong> red virtual.En el modo <strong>de</strong> red directo, las MVs obtienen lasdirecciones IP <strong>de</strong> la subred local, <strong>de</strong> tal forma que severían <strong>de</strong> la misma manera que una máquina física<strong>de</strong> la infraestructura.En el modo <strong>de</strong> red virtual, CloudStack proporcionaun router virtual que actúa como puerta <strong>de</strong> enlacepara las MVs <strong>de</strong> cada una <strong>de</strong> las cuentas <strong>de</strong> usuario.El router virtual, a<strong>de</strong>más <strong>de</strong> efectuar NAT, proporcionalos servicios <strong>de</strong> DNS y DHCP a las MVs <strong>de</strong>lusuario. Hay que señalar que, en el modo <strong>de</strong> red virtual,el router virtual pue<strong>de</strong> configurarse para redireccionarel tráfico <strong>de</strong> Internet a las MVs a elección<strong>de</strong>l usuario. Por su parte, el tráfico <strong>de</strong> red <strong>de</strong> Internettambién pue<strong>de</strong> balancearse entre un conjunto <strong>de</strong>MVs configurable por el usuario.Máquinas virtuales: CloudStack permite efectuarla instalación <strong>de</strong> las MVs por medio <strong>de</strong> la interfazWeb empleando una imagen ISO <strong>de</strong> instalación <strong>de</strong>lsistema operativo. <strong>La</strong>s MVs emplean el formatoQCOW (Qemu Copy-On-Write). CloudStack proporcionala posibilidad <strong>de</strong> <strong>de</strong>finir MVs <strong>de</strong> alta disponibilidadque se mantendrán activas sin intervenciónalguna por parte <strong>de</strong>l administrador o <strong>de</strong>l usuario.A<strong>de</strong>más, hay que señalar que CloudStack permiteacce<strong>de</strong>r a la interfaz gráfica <strong>de</strong> las MVs empleandola interfaz Web.Interfaces <strong>de</strong> gestión: CloudStack dispone <strong>de</strong> unainterfaz Web completa y sencilla. Ésta proporcionaráel acceso completo al Cloud <strong>de</strong> la plataforma FormigaCloud a los administradores <strong>de</strong>l sistema, mientrasque para los profesores y los alumnos proporcionaráun acceso restringido que les permitirá, única y exclusivamente,gestionar sus respectivos recursos virtuales.CloudStack no dispone <strong>de</strong> interfaz <strong>de</strong> comandos,aunque proporciona una API REST que permiteacce<strong>de</strong>r a todas sus funcionalida<strong>de</strong>s.Agentes <strong>de</strong> computación: El agente <strong>de</strong> computaciónes un módulo que se instalará en cada uno<strong>de</strong> los or<strong>de</strong>nadores <strong>de</strong> las distintas aulas y que permitiráa CloudStack efectuar la gestión <strong>de</strong>l hipervisor<strong>de</strong>l nodo <strong>de</strong> computación. Por tanto, el agente <strong>de</strong>computación se encargará <strong>de</strong> gestionar las MVs quese encuentran bajo su supervisión y control.C. Planificador Formiga Cloud<strong>La</strong> adhesión en la plataforma Formiga Cloud <strong>de</strong> losrecursos computacionales pertenecientes a múltiplesorganizaciones, que emplean diferentes políticas <strong>de</strong>seguridad, <strong>de</strong> mantenimiento y <strong>de</strong> utilización <strong>de</strong> recursos,implica que no pueda garantizarse a priorisu disponibilidad para su utilización en la nueva infraestructuracomún.Los planificadores <strong>de</strong> <strong>de</strong>spliegue <strong>de</strong> los gestoresCloud no están diseñados para tener en cuenta las<strong>JP2011</strong>-497


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011particularida<strong>de</strong>s <strong>de</strong> este entorno multiorganizacional,como, por ejemplo, la disponibilidad <strong>de</strong> los nodos enfunción <strong>de</strong>l contexto <strong>de</strong> utilización <strong>de</strong> los mismos.El planificador FomigaCloud se integrará enCloudStack y se diseñó para adaptarse <strong>de</strong> forma automáticay trasparente a los entornos heterogéneos,y permitirá gestionar el <strong>de</strong>spliegue <strong>de</strong> las máquinasvirtuales en los nodos <strong>de</strong> computación <strong>de</strong> la nuevainfraestructura común. Para ello, empleará técnicasheurísticas que permitirán <strong>de</strong>terminar el nodo <strong>de</strong>computación más a<strong>de</strong>cuado en cada momento parala ejecución <strong>de</strong> las máquinas virtuales, teniendo encuenta el tiempo <strong>de</strong> disponibilidad <strong>de</strong> cada uno <strong>de</strong> losnodos <strong>de</strong> computación, esto es, el tiempo estimadodurante el cual se espera que el nodo <strong>de</strong> computaciónva a estar disponible para su utilización por parte <strong>de</strong>la nueva infraestructura común, así como el tiempo<strong>de</strong> utilización en el pasado <strong>de</strong> las distintas máquinasvirtuales.A la hora <strong>de</strong> seleccionar el nodo en el que se <strong>de</strong>splegarála máquina virtual, el planificador emplearálos datos <strong>de</strong> la utilización en el pasado <strong>de</strong> los distintosnodos <strong>de</strong> computación, lo que permitirá estimarel tiempo <strong>de</strong> disponibilidad esperado para cada uno<strong>de</strong> ellos. Análogamente, el planificador estimará eltiempo esperado que la máquina virtual permaneceráactiva, basándose en los datos históricos <strong>de</strong> su utilización,y seleccionará el nodo cuyo tiempo <strong>de</strong> disponibilida<strong>de</strong>sperado sea superior al tiempo requerido<strong>de</strong> utilización <strong>de</strong> la máquina virtual.Hay que señalar que uno <strong>de</strong> los usos principales <strong>de</strong>la plataforma será la realización <strong>de</strong> cursos medianteel <strong>de</strong>spliegue <strong>de</strong> máquinas virtuales. A<strong>de</strong>más, éstassuelen emplearse <strong>de</strong> forma periódica y se mantienenencendidas apenas unas pocas horas. Esta circunstanciapropicia que el planificador FormigaCloudpueda optimizar la utilización <strong>de</strong> aquellos nodos <strong>de</strong>computación cuyo nivel <strong>de</strong> disponibilidad es bajo, albergandoaquellas máquinas virtuales que se adaptena su disponibilidad estimada, reduciéndose, así, elnúmero <strong>de</strong> migraciones necesarias <strong>de</strong> las MVs entrelos distintos nodos para mantenerlas en su estadooperativo. El planificador Formiga Cloud permitiráobtener el mayor nivel <strong>de</strong> servicio en infraestructurasen las que la disponibilidad <strong>de</strong> los nodos <strong>de</strong> computaciónno está garantizada.IV. Portal DIRACDIRAC (Distributed Infrastructure with RemoteAgent Control) [17] es un middleware grid que permitela gestión y el envío <strong>de</strong> trabajos <strong>de</strong> computacióna infraestructuras grid basadas en gLite [18], o mediantela utilización <strong>de</strong> sus propios recursos. DIRACproporciona una solución grid completa [19] para lagestión <strong>de</strong> los trabajos, así como para el almacenamiento<strong>de</strong> los datos, y permite efectuar un usoconfiable <strong>de</strong> los recursos disponibles.En la plataforma Formiga Cloud, este portal seencargará <strong>de</strong> gestionar los trabajos <strong>de</strong> los investigadoresen la infraestructura grid virtual. Su integracióncon CloudStack hará posible la gestión bajo<strong>de</strong>manda <strong>de</strong> MVs configuradas como Worker No<strong>de</strong>s(WN) <strong>de</strong> Grid.DIRAC posee su propio framework para facilitar laintegración con distintos tipos <strong>de</strong> sistemas basados enSOA, así como su propio protocolo <strong>de</strong> comunicaciónsegura, <strong>de</strong>nominado DISET (DIRAC Secure Transport),que confiere una mayor seguridad al usuarioutilizando los mecanismos <strong>de</strong> autenticación <strong>de</strong> GSI(Grid Secure Infrastructure). Por otra parte, permitela configuración <strong>de</strong> reglas <strong>de</strong> autorización conla granularidad a<strong>de</strong>cuada tanto para usuarios comopara grupos. Hay que señalar que DIRAC dispone<strong>de</strong> un Servicio <strong>de</strong> Configuración (SC) que permitegestionar todos sus servicios y agentes. Éste se encuentraaccesible a través <strong>de</strong>l portal Web DIRAC, yposibilita que el administrador pueda efectuar la configuración<strong>de</strong> servicios y funcionalida<strong>de</strong>s <strong>de</strong> usuariospertenecientes a diferentes grupos.El WMS (Workload Management System) <strong>de</strong>DIRAC se ocupa <strong>de</strong> las tareas <strong>de</strong> la programaciónmediante la utilización <strong>de</strong> Genenic Pilot Jobs. Estemétodo <strong>de</strong> planificación, que soluciona muchos <strong>de</strong>los problemas causados por la utilización <strong>de</strong> recursoscomputacionales distribuidos inestables, consisteen la creación, con un certificado proxy <strong>de</strong> administrador,<strong>de</strong> un trabajo genérico <strong>de</strong>nominado PilotJob por medio <strong>de</strong>l cual se ejecutarán los trabajos <strong>de</strong>usuario.Algunos <strong>de</strong> los servicios más importantes <strong>de</strong>DIRAC, como son el sistema <strong>de</strong> gestión <strong>de</strong> datos,el servicio <strong>de</strong> monitorización, el central Job Monitoringy el Accounting Service, se <strong>de</strong>scribirán a continuación.El sistema <strong>de</strong> gestión <strong>de</strong> datos <strong>de</strong> DIRAC proporcionaa los usuarios un servicio <strong>de</strong> almacenamientoempleando el protocolo DISET, lo que le confiere segurida<strong>de</strong>n el almacenamiento <strong>de</strong> los datos. DIRACestá preparado para utilizar el <strong>de</strong>nominado LCGFile Catalog [20] (<strong>La</strong>rge Hadron Colli<strong>de</strong>r ComputingGrid File Catalog) que pue<strong>de</strong> ser accesible a travésmúltiples servidores <strong>de</strong> sólo lectura. A<strong>de</strong>más, poseesu propio File Catalog (FC) que se utiliza en el sistema<strong>de</strong> gestión <strong>de</strong> producción. El FC <strong>de</strong> DIRACdispone <strong>de</strong> la clase Replica Manager que permite encapsulartodas las operaciones relacionadas con lagestión y el manejo <strong>de</strong> archivos.El servicio <strong>de</strong> monitorización recopila los informes<strong>de</strong> actividad <strong>de</strong> todos los servicios <strong>de</strong> DIRAC y susagentes, y presenta los datos <strong>de</strong> múltiples formas,por ejemplo, gráficos históricos o informes agregados.Es interesante señalar que durante la ejecución <strong>de</strong>ltrabajo hay un agente local ejecutándose en paralelocon la aplicación <strong>de</strong>l usuario que tiene el cometido<strong>de</strong> enviar la información acerca <strong>de</strong>l progreso <strong>de</strong> lamisma al servicio central Job Monitoring.El servicio central Job Monitoring recopila informaciónacerca <strong>de</strong>l estado <strong>de</strong> los trabajos y la guardaen una base <strong>de</strong> datos en la que almacena todos losestados en los que se han encontrado aquellos.El Accounting Service efectúa la contabilidad <strong>de</strong>luso <strong>de</strong> los recursos a nivel <strong>de</strong> las cuentas <strong>de</strong> usuario.<strong>JP2011</strong>-498


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011El portal Web <strong>de</strong> DIRAC permite que el usuariopueda efectuar la monitorización <strong>de</strong> los trabajos yla <strong>de</strong>scarga <strong>de</strong> sus respectivos archivos <strong>de</strong> salida quehan sido procesados en los nodos <strong>de</strong> cálculo. Porotra parte, el portal Web proporciona una interfazamigable y segura para la administración <strong>de</strong> DIRAC,así como para la gestión <strong>de</strong> producciones y trabajos<strong>de</strong> usuario.<strong>La</strong> interfaz <strong>de</strong> usuario <strong>de</strong> DIRAC proporcionaráa los investigadores una serie <strong>de</strong> comandos y scriptspara el envío, la monitorización y la gestión <strong>de</strong> trabajosen el Grid virtual <strong>de</strong> las aulas. <strong>La</strong> Interfaz <strong>de</strong>Usuario (IU) permitirá el envío <strong>de</strong> los trabajos pormedio <strong>de</strong> un canal seguro, mediante la creación <strong>de</strong> uncertificado <strong>de</strong> proxy en la propia máquina a partir <strong>de</strong>lcertificado <strong>de</strong>l usuario.V. Gestor <strong>de</strong> red <strong>de</strong> interconexión<strong>La</strong> adhesión a la plataforma Formiga Cloud <strong>de</strong> losrecursos computacionales pertenecientes a diversasorganizaciones presenta dificulta<strong>de</strong>s <strong>de</strong>rivadas <strong>de</strong> lautilización <strong>de</strong> diferentes políticas <strong>de</strong> configuración ygestión <strong>de</strong> la red, como, por ejemplo, el empleo <strong>de</strong>direcciones IP privadas o públicas.El gestor CloudStack requiere que las conexionessean iniciadas <strong>de</strong>s<strong>de</strong> el servidor <strong>de</strong> gestión hacia losnodos <strong>de</strong> computación <strong>de</strong> las diferentes zonas <strong>de</strong> disponibilidad.En el caso <strong>de</strong> que los nodos <strong>de</strong> computaciónempleen direcciones IP públicas, el gestorCloudStack podría gestionarlos <strong>de</strong> forma directa sinmayores complicaciones, salvo las <strong>de</strong>rivadas <strong>de</strong> la implantación<strong>de</strong> las medidas <strong>de</strong> seguridad necesariaspara evitar que los nodos pudiesen verse comprometidos.Sin embargo, este modo <strong>de</strong> comunicación<strong>de</strong>l servidor <strong>de</strong> gestión <strong>de</strong> CloudStack imposibilitala conexión con los nodos <strong>de</strong> computación <strong>de</strong> aquellasinfraestructuras <strong>de</strong> red que emplean NAT comomedio <strong>de</strong> conexión a Internet. A<strong>de</strong>más, algunas organizacionespodrían hacer uso <strong>de</strong>l mismo rango <strong>de</strong>direcciones IP privadas entre las diferentes aulas, encuyo caso el uso <strong>de</strong> VPNs, como medio <strong>de</strong> interconexión<strong>de</strong> los nodos <strong>de</strong> computación con el servidor<strong>de</strong> gestión <strong>de</strong> CloudStack, no sería posible a causa<strong>de</strong> los rangos IP solapados. Por ejemplo, el servidor<strong>de</strong> gestión <strong>de</strong> CloudStack por medio <strong>de</strong> la VPNse estaría intentando conectar a un nodo cuya direcciónIP privada pudiera estar siendo utilizada pormúltiples nodos <strong>de</strong> computación al mismo tiempo.Para solventar estas limitaciones se evaluará el uso<strong>de</strong> Cloud Kit [21], que permite que sean los nodos<strong>de</strong> computación los que inicien la conexión con elservidor <strong>de</strong> gestión <strong>de</strong> CloudStack y no al revés. Deesta forma, no sería necesario efectuar modificaciónalguna en la infraestructura <strong>de</strong> red existente parapermitir que los nodos <strong>de</strong> computación <strong>de</strong> aquellasorganizaciones, cuyas re<strong>de</strong>s empleen NAT para alcanzarInternet, puedan establecer la conexión conel servidor <strong>de</strong> gestión Cloud.Existe una complicación adicional causada por lautilización <strong>de</strong> NAT por parte <strong>de</strong> las MVs para alcanzarInternet, ya que los usuarios <strong>de</strong> las mismas nopodrían conectarse a sus servicios, como, por ejemplo,ssh, <strong>de</strong>s<strong>de</strong> una red ajena a la infraestructura. Eneste caso, sería necesario proporcionar un mecanismoque les permitiese establecer la conexión y hacer uso<strong>de</strong> estos servicios <strong>de</strong>s<strong>de</strong> el exterior. Cabe <strong>de</strong>stacarque se está trabajando con los <strong>de</strong>sarrolladores <strong>de</strong>CloudStack para proporcionar la mejor solución enrelación a la conectividad <strong>de</strong>l usuario final con suMV.VI. Conclusiones<strong>La</strong> plataforma Formiga Cloud, empleando tecnologíasCloud y Grid, permitirá la agregación<strong>de</strong> los recursos computacionales <strong>de</strong> entornos heterogéneos,in<strong>de</strong>pendientemente <strong>de</strong>l modo <strong>de</strong> red utilizado(público o privado), en una infraestructuracomún accesible <strong>de</strong>s<strong>de</strong> una interfaz Web centralizadaque facultará a los administradores gestionarla plataforma, y a los profesores y alumnos gestionarsus propios recursos virtuales.<strong>La</strong> plataforma Formiga Cloud empleará Cloud-Stack como gestor Cloud y DIRAC para gestionarlos trabajos <strong>de</strong> los investigadores. Sin embargo, losplanificadores <strong>de</strong> <strong>de</strong>spliegue <strong>de</strong> los gestores Cloud noestán diseñados para tener en cuenta las particularida<strong>de</strong>s<strong>de</strong> este entorno multiorganizacional, como, porejemplo, la disponibilidad <strong>de</strong> los nodos en función <strong>de</strong>lcontexto <strong>de</strong> utilización <strong>de</strong> los mismos. Por este motivo,se <strong>de</strong>sarrollará el Planificador FormigaCloud,que empleará técnicas heurísticas que permitirán <strong>de</strong>terminarel nodo <strong>de</strong> computación más a<strong>de</strong>cuado, eneste entorno heterogéneo, para ejecutar las máquinasvirtuales. <strong>La</strong> integración <strong>de</strong> DIRAC con Cloud-Stack permitirá efectuar la gestión bajo <strong>de</strong>manda <strong>de</strong>máquinas virtuales configuradas como Worker No<strong>de</strong>s<strong>de</strong> Grid.<strong>La</strong> plataforma Formiga Cloud permitirá elaprovechamiento <strong>de</strong> recursos computacionales infrautilizadospara su uso en tareas <strong>de</strong> cálculo, asícomo en los procesos <strong>de</strong> enseñanza y aprendizaje. Elobjetivo final es po<strong>de</strong>r realizar un mejor uso <strong>de</strong> losrecursos computacionales disponibles por las organizaciones.Agra<strong>de</strong>cimientosEl presente trabajo ha sido financiado por la Xunta<strong>de</strong> Galicia mediante los proyectos 09TIC001CT eINCITE08PXIB206094PR, y por el Gobierno <strong>de</strong>España (MCYT) mediante el proyecto TEC2010-17320.Referencias[1] J. López et al., “FORMIGA/G-FLUXO: Adding computerlabs to the Grid”, 3rd Iberian Grid InfrastructureConference, Valencia, pp. 237-246, May 2009.[2] R. Valin et al., “Gridification of a nano<strong>de</strong>vice Monte Carlosimulator for the FORMIGA project”, 3rd Iberian GridInfrastructure Conference, Valencia, pp. 109-116, May2009.[3] K. Stanoevska-slabeva, T. Wozniak and S. Ristol, Gridand Cloud Computing: A Business Perspective on Technologyand Applications, Springer, Germany, 2010.[4] C. Babcock, Management Strategies For The Cloud Revolution,McGrawHill, USA, 2010.<strong>JP2011</strong>-499


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011[5] T. Mather, S. Kumaraswamy and S. <strong>La</strong>tif, Cloud Securityand Privacy, O’REILLY, Sebastopol, 2009.[6] B.J.S. Chee and C. Franklin, Cloud Computing. Technologiesand Strategies of the Ubiquitous Data Center, CRCPress, Boca Raton, 2010.[7] R.L. Krutz and R.D. Vines, Cloud Security, Wiley PublishingIndianapolis, 2010.[8] J.W. Rittinghouse and J.F. Ransome, Cloud Computing:Implementation, Management, and Security, CRC Press,Boca Raton, 2010.[9] A.T. Velte, T.J. Velte and R. Elsenpeter, Cloud Computing:A Practical Approach, McGrawHill, USA, 2010.[10] OpenNebula, http://opennebula.org[11] Eucalyptus, http://open.eucalyptus.com[12] CloudStack, http://www.cloud.com[13] F. Gomez-Folgar et al., “An Open-source Cloud ManagementPlatform Comparison”, 5th Open Cirrus Summit,Moscow, 2011. (Artículo aceptado).[14] D.E. Williams, Virtualization with Xen: Including XenEnterprise,XenServer, and XenExpress, Syngress, USA,2007.[15] KVM, http://www.linux-kvm.org[16] VMWare, http://www.vmware.com[17] A.Tsaregorodtsev et al, “DIRAC, The LHCb Data Productionand Distributed Analysis System”, Proceedings ofthe CHEP 2006 Conference.[18] gLite, http://glite.cern.ch[19] A.Tsaregorodtsev et al, “DIRAC: a community grid solution”,Journal of Physics: Conference Series, vol. 119-6,July 2008.[20] LCG FIle Catalog, https://svnweb.cern.ch/trac/lcgdm[21] RightScale, http://www.rightscale.com<strong>JP2011</strong>-500


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Planificación <strong>de</strong> trabajos MapReduce en clustersHadoop no-<strong>de</strong>dicadosAprigio Bezerra, Tharso Ferreira, Antonio Espinosa, Juan Carlos Moure y Porfídio Hernán<strong>de</strong>zResumen—A partir <strong>de</strong>l análisis realizado <strong>de</strong> lasaplicaciones bioinformáticas <strong>de</strong> tipo read-mapping (DataIntensive Computing), en clusters Hadoop no-<strong>de</strong>dicados;nuestro trabajo se centra en la propuesta <strong>de</strong> planificadores<strong>de</strong> trabajos para este tipo <strong>de</strong> entornos, que tengan encuenta las características <strong>de</strong> las aplicacionesbioinformáticas. Nuestra propuesta concreta <strong>de</strong>planificación, consiste en aprovechar: por parte <strong>de</strong> lasaplicaciones, la necesidad <strong>de</strong> compartición <strong>de</strong> los archivos(genomas <strong>de</strong> referencia por las aplicaciones <strong>de</strong> readmapping)y por parte <strong>de</strong>l entorno <strong>de</strong> planificación(framework Hadoop), la posibilidad <strong>de</strong> reutilización <strong>de</strong> lamáquina virtual Java, utilizada para la ejecución <strong>de</strong> lastareas MapReduce en los nodos <strong>de</strong> procesamiento. Todoello, sin comprometer el rendimiento <strong>de</strong> las aplicacioneslocales, ejecutadas en cada nodo.Nuestra propuesta muestra mejoras <strong>de</strong>l 17%, cuando sele compara con la política por <strong>de</strong>fecto <strong>de</strong>l frameworkHadoop.Palabras clave—Hadoop, MapReduce, Read-Mapping,cluster no-<strong>de</strong>dicado, planificación <strong>de</strong> trabajos.LI. INTRODUCCIÓNas mejoras recientes en el ancho <strong>de</strong> banda y latenciapara re<strong>de</strong>s LAN, la infrautilización <strong>de</strong> los entornos<strong>de</strong> estaciones <strong>de</strong> trabajo cuando se utilizanexclusivamente a tareas interactivas, y el bajo costo <strong>de</strong>los mismos, compitiendo en prestaciones con lossistemas masivamente paralelos (MPP); han hecho <strong>de</strong>los clusters <strong>de</strong> estaciones <strong>de</strong> trabajo, una arquitecturaatractiva para diversas cargas: secuenciales interactivasy paralelas.Por otro lado, los avances en los estudios genéticos estánproporcionando volúmenes <strong>de</strong> datos inmensamenteelevados, creándose repositorios <strong>de</strong> información queimplícitamente contemplan un conocimiento histórico <strong>de</strong>nuestra evolución. Estos datos necesitan ser procesadosy analizados; y se ha hecho evi<strong>de</strong>nte, que el únicoentorno para darle solución es la Computación <strong>de</strong> AltasPrestaciones. Este nuevo tipo <strong>de</strong> aplicaciones, intensivas<strong>de</strong> datos y cómputo; abre una nueva línea <strong>de</strong>investigación; en el diseño <strong>de</strong> sistemas más a<strong>de</strong>cuadospara su tratamiento, mo<strong>de</strong>los <strong>de</strong> programación ygestores <strong>de</strong> recursos.<strong>La</strong> i<strong>de</strong>a <strong>de</strong>l trabajo tiene como objetivo, diseñar uncluster <strong>de</strong> naturaleza no-<strong>de</strong>dicada, con capacidad para laejecución eficiente <strong>de</strong> aplicaciones paralelas DIC, <strong>de</strong>ltipo read-mapping; con prestaciones aceptables, sinperturbar en exceso la respuesta <strong>de</strong>l sistema a la cargalocal <strong>de</strong> los nodos <strong>de</strong>l cluster. Nuestra propuestaconcreta <strong>de</strong> planificación consiste en aprovechar: porparte <strong>de</strong> las aplicaciones; la necesidad <strong>de</strong> compartición<strong>de</strong> los archivos (genomas <strong>de</strong> referencia para lasDepartamento <strong>de</strong> Arquitectura <strong>de</strong> Computadores y Sistemas Operativos<strong>Universidad</strong> Autónoma <strong>de</strong> Barcelona, Edif. Q. Campus UAB. 08193Bellaterra. Barcelona. abezerra, tsouza,aespinosa@caos.uab.esaplicaciones <strong>de</strong> read-mapping) y por parte <strong>de</strong>l entorno<strong>de</strong> planificación (framework Hadoop); la posibilidad <strong>de</strong>reutilización <strong>de</strong> la máquina virtual Java, utilizada para laejecución <strong>de</strong> las tareas MapReduce en los nodos <strong>de</strong>procesamiento. <strong>La</strong> Figura 1 presenta un cluster Hadoopno-<strong>de</strong>dicado, con carga local y carga paralela inyectadaal cluster a través <strong>de</strong> una capa global <strong>de</strong> planificación <strong>de</strong>trabajos.<strong>La</strong>s siguientes secciones <strong>de</strong>scriben la propuestarealizada. <strong>La</strong> sección II presenta el paradigma <strong>de</strong>programación MapReduce [1]. <strong>La</strong> sección III <strong>de</strong>scribe elframework Hadoop [17][18], su sistema <strong>de</strong> archivosdistribuidos y como gestiona la ejecución <strong>de</strong> trabajos enun entorno paralelo. En la sección IV, se realiza una<strong>de</strong>scripción <strong>de</strong> aplicaciones <strong>de</strong> BioInformática <strong>de</strong>l tipoRead Mapping [19] <strong>de</strong>sarrolladas bajo el paradigma <strong>de</strong>programación Mapreduce, <strong>de</strong>sarrollada por nuestrogrupo <strong>de</strong> investigación. En la sección V, se presenta lapolítica <strong>de</strong> planificación <strong>de</strong> trabajos propuesta. En lasección VI, se <strong>de</strong>scriben los experimentos realizados ylos resultados obtenidos. En la sección VII se presentanlas conclusiones <strong>de</strong>l trabajo.Fig. 1. Entorno paralelo no-<strong>de</strong>dicado.II.MAPREDUCEMapReduce es un paradigma <strong>de</strong> programaciónorientado a datos, don<strong>de</strong> el programador especifica elflujo <strong>de</strong> tratamiento <strong>de</strong> los datos <strong>de</strong> entrada; esteprocesamiento, se especifica mediante la utilización <strong>de</strong>dos funciones: Map y Reduce que serán ejecutadas enparalelo.El paradigma MapReduce se expresa mediante laconstrucción <strong>de</strong> dos funciones: Map y Reduce, <strong>de</strong>finidasambas con respecto a datos estructurados en pares(clave, valor). En la función Map los datos <strong>de</strong> entradason procesados y es generada una lista <strong>de</strong> paresintermedios (clave, valor). A continuación la función<strong>JP2011</strong>-501


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Reduce se aplica sobre estas tuplas intermedias y hace laagrupación <strong>de</strong> los valores que tienen la misma clave.<strong>La</strong> Figura 2, representa un esquema <strong>de</strong>l flujo <strong>de</strong> datos,para la ejecución <strong>de</strong> una aplicación <strong>de</strong> contar palabras enun texto, utilizando el paradigma MapReduce.Fig.3 Framework Hadoop.Fig. 2. Esquema MapReduce para la aplicación WordCount en unCluster Hadoop.III.HADOOPHadoop es un framework altamente configurable<strong>de</strong>sarrollado en el proyecto Apache y que implementaMapReduce inspirado en la propuesta <strong>de</strong> Google [1] [3].Es un sistema <strong>de</strong> código abierto, e implementado enJava. Otras implementaciones <strong>de</strong>l paradigmaMapReduce, han aparecido en la literatura paradiferentes arquitecturas como Cell B.E [4], GPUs [5] yprocesadores multi-core [6].El framework Hadoop realiza <strong>de</strong> forma automática ladivisión y distribución <strong>de</strong> los archivos <strong>de</strong> entrada, laplanificación <strong>de</strong> los trabajos entre los nodos <strong>de</strong>l entornoparalelo, el control <strong>de</strong> fallos <strong>de</strong> los nodos y gestiona lanecesidad <strong>de</strong> comunicación entre los nodos <strong>de</strong>l cluster.Hadoop se ejecuta sobre un sistema <strong>de</strong> archivosdistribuidos, Hadoop Distributed File System – HDFS,que se soporta a su vez sobre el sistema <strong>de</strong> ficherosnativo, y don<strong>de</strong> la fiabilidad <strong>de</strong>l sistema es obtenida porla replicación <strong>de</strong> datos, y la posibilidad <strong>de</strong> po<strong>de</strong>r utilizarejecución especulativa <strong>de</strong> las tareas. Son utilizados dos<strong>de</strong>monios para hacer la gestión <strong>de</strong> los datos: nameno<strong>de</strong> ydatano<strong>de</strong>. <strong>La</strong> arquitectura <strong>de</strong> planificación <strong>de</strong> Hadoopobe<strong>de</strong>ce a un mo<strong>de</strong>lo master/worker: Job Tracker (en elnodo master) y Task Tracker (en los nodos Workers). Elplanificador <strong>de</strong> trabajos está diseñado en móduloscargables que permite la implementación <strong>de</strong> nuevaspolíticas <strong>de</strong> planificación <strong>de</strong> trabajos y la sustitución <strong>de</strong>estos módulos <strong>de</strong> planificación <strong>de</strong> manera sencilla. <strong>La</strong>Figura 3 muestra la distribución <strong>de</strong>l sistema en un nodo<strong>de</strong>l cluster.A. Hadoop Distributed File System – HDFSHDFS es el sistema <strong>de</strong> archivos distribuidosimplementado por Hadoop y se monta en el sistema <strong>de</strong>archivos <strong>de</strong> cada máquina <strong>de</strong>l cluster. Cuando se cargaun archivo en el sistema, HDFS hace la división <strong>de</strong>larchivo en bloques menores con tamaño <strong>de</strong>finido por elgestor <strong>de</strong>l sistema (por <strong>de</strong>fecto <strong>de</strong> 64 MB) bajo un factor<strong>de</strong> replicación, también <strong>de</strong>finido por el gestor <strong>de</strong>lsistema. Esta replicación <strong>de</strong> cada bloque <strong>de</strong> archivoa<strong>de</strong>más <strong>de</strong> permitir un mejor control <strong>de</strong> tolerancia afallos, aumenta la posibilidad <strong>de</strong> garantizar la localidad<strong>de</strong> datos, cuando Hadoop hace la distribución <strong>de</strong> tareasen el cluster. <strong>La</strong> Figura 4 presenta una distribución <strong>de</strong>bloques <strong>de</strong> un fichero <strong>de</strong> entrada, a lo largo <strong>de</strong> los nodos<strong>de</strong>l cluster.Fig. 4 Distribución <strong>de</strong> datos en HDFS.<strong>JP2011</strong>-502


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011B. Planificación <strong>de</strong> trabajos en Hadoop<strong>La</strong> planificación <strong>de</strong> las aplicaciones en Hadoop, serealiza <strong>de</strong> forma dinámica, siguiendo un mo<strong>de</strong>lomaster/worker para la distribución <strong>de</strong> tareas, a lo largo<strong>de</strong> los nodos <strong>de</strong>l cluster.<strong>La</strong> gestión <strong>de</strong> los trabajos en un cluster Hadoop serealiza por dos <strong>de</strong>monios: Job Tracker (en el nodomaster) y Task Tracker (en los nodos Workers). Lostrabajos MapReduce presentados al cluster soninyectados al sistema en una cola gestionada por el JobTracker. El or<strong>de</strong>n <strong>de</strong> ejecución <strong>de</strong> estos trabajos es<strong>de</strong>finido por la política <strong>de</strong> planificación <strong>de</strong> trabajos <strong>de</strong>Hadoop. Por <strong>de</strong>fecto esta política es basada en una cola<strong>de</strong>l tipo FIFO.Los trabajos encolados son divididos por Hadoop en unconjunto <strong>de</strong> tareas Map y Reduce. Para cada tarea se leasocia una partición <strong>de</strong> los datos <strong>de</strong> entrada, que mapeala ubicación <strong>de</strong>l bloque <strong>de</strong> archivo que se localiza enuno <strong>de</strong> los nodos <strong>de</strong>l cluster. El planificador Hadoopintenta asignar las tareas a los mismos nodos, don<strong>de</strong>están ubicados los bloques <strong>de</strong> datos.Cuando un nodo <strong>de</strong>l cluster está listo para empezar unatarea, envía un heartbeat al master (Job Tracker),informando <strong>de</strong> su estado. Posteriormente, Hadoop buscauna tarea que maneje un bloque <strong>de</strong> datos ubicado en elmismo nodo. Si no la encuentra, envía para el nodo laprimera tarea encolada. Si la encuentra, envía la tarea alnodo que hizo la solicitud. Para cada tarea recibida, el<strong>de</strong>monio local (Task Tracker) crea una máquina virtualJava para ejecutarla. Cuando un nodo local finaliza sutarea, el Task Tracker elimina la maquina virtual einforma, a través <strong>de</strong> un heartbeat, <strong>de</strong> su estado al JobTracker, que realiza la asignación <strong>de</strong> una nueva tarea. <strong>La</strong>Figura 5 presenta la planificación <strong>de</strong> trabajos en unentorno Hadoop.conteste al Job Tracker en un intervalo <strong>de</strong> tiempo<strong>de</strong>terminado, se marcará como en estado <strong>de</strong> fallo. Todaslas tareas Map que han sido iniciadas pero nofinalizadas, serán planificadas una vez más. <strong>La</strong>sversiones más recientes <strong>de</strong> Hadoop, también hacencheckpoints periódicos <strong>de</strong> las estructuras <strong>de</strong> datosexistentes en el Job Tracker. En caso <strong>de</strong> que ocurra unfallo en este, se pue<strong>de</strong> ejecutar un nuevo Job Tracker, apartir <strong>de</strong>l último checkpoint realizado.IV.APLICACIONES DE BIOINFORMÁTICA<strong>La</strong>s aplicaciones DIC, consi<strong>de</strong>radas en este trabajo, sebasan en la búsqueda <strong>de</strong> similitu<strong>de</strong>s entre secuenciasgenéticas localizadas en un archivo <strong>de</strong> referencia, y enun conjunto <strong>de</strong> archivos <strong>de</strong> consulta. <strong>La</strong>s aplicacionesread-mapping se caracterizan por manejar gran<strong>de</strong>svolúmenes <strong>de</strong> datos <strong>de</strong> entrada. El genoma humanocompleto consta <strong>de</strong> 3,7 Gigas <strong>de</strong> pares <strong>de</strong> bases, ya<strong>de</strong>más, las secuencias genéticas existentes en losarchivos <strong>de</strong> consulta pue<strong>de</strong>n ocupar centenas <strong>de</strong> Gigas oTerabytes en disco.Otra característica <strong>de</strong> las aplicaciones <strong>de</strong>l tipo read -mapping es el fuerte paralelismo <strong>de</strong> datos. Es común <strong>de</strong>estos programas, dividir el archivo <strong>de</strong> consulta enarchivos menores. Cada archivo <strong>de</strong> consulta constituyeun trabajo in<strong>de</strong>pendiente, aunque comparten el mismoarchivo <strong>de</strong> referencia, para realizar la búsqueda <strong>de</strong>similitu<strong>de</strong>s entre las secuencias genéticas.<strong>La</strong> Figura 6 presenta el flujo <strong>de</strong> datos para unaaplicación <strong>de</strong>l tipo read-mapping <strong>de</strong>sarrollada bajo elparadigma MapReduce, utilizando un archivo <strong>de</strong>referencia <strong>de</strong> 4 Gigabytes, y un archivo <strong>de</strong> consulta <strong>de</strong> 5Megabytes.Fig.6 Flujo <strong>de</strong> datos <strong>de</strong> una aplicación read-mapping.V. POLÍTICA PROPUESTASe propone, una política <strong>de</strong> planificación <strong>de</strong> trabajosMapReduce en clusters Hadoop no-<strong>de</strong>dicados. Estapolítica <strong>de</strong> planificación <strong>de</strong>berá gestionar con reserva <strong>de</strong>recursos, la mezcla eficiente <strong>de</strong> cargas localescontroladas que varían en el espacio y tiempo, y cargasparalelas <strong>de</strong> aplicaciones DIC.Fig.5 Planificación <strong>de</strong> trabajos en Hadoop.Hadoop proporciona un mecanismo <strong>de</strong> control <strong>de</strong>fallos. El Job Tracker, verifica periódicamente lafinalización <strong>de</strong> las tareas. En caso <strong>de</strong> que una tarea noNuestra propuesta concreta <strong>de</strong> planificación, consiste enaprovechar: por parte <strong>de</strong> las aplicaciones, la necesidad<strong>de</strong> compartición <strong>de</strong> los archivos (genomas <strong>de</strong> referenciapor las aplicaciones <strong>de</strong> read-mapping) y por parte <strong>de</strong>lentorno <strong>de</strong> planificación (framework Hadoop), laposibilidad <strong>de</strong> reutilización <strong>de</strong> la máquina virtual Java,utilizada para la ejecución <strong>de</strong> las tareas MapReduce enlos nodos <strong>de</strong> procesamiento.<strong>JP2011</strong>-503


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011A. Planificación <strong>de</strong> trabajos MapReduceLos trabajos paralelos se componen <strong>de</strong> aplicaciones <strong>de</strong>bioinformática <strong>de</strong>l tipo read-mapping <strong>de</strong>sarrolladas bajoel paradigma MapReduce. Los distintos trabajoscomparten el mismo archivo <strong>de</strong> referencia. <strong>La</strong> política<strong>de</strong> planificación propuesta intenta sacar provecho <strong>de</strong> estacaracterística utilizando afinidad entre tareas <strong>de</strong>diferentes trabajos. Cuando un nodo worker, envía unheartbeat al nodo master informando que está listo paraempezar una nueva tarea, Hadoop busca entre las tareas<strong>de</strong>l primer trabajo encolado, una tarea que aceda albloque <strong>de</strong> datos ubicado en este nodo. Si hay slots libresen el mismo nodo, la política propuesta evalúa lostrabajos encolados en busca <strong>de</strong> tareas que accedan almismo bloque <strong>de</strong>l archivo <strong>de</strong> referencia. Si se encuentrauna tarea <strong>de</strong> otro trabajo que acceda el mismo bloque <strong>de</strong>dados <strong>de</strong> entrada, esta tarea también es asignada al nodoworker.Otra característica <strong>de</strong> la política propuesta es reutilizarlas máquinas virtuales Java para tareas distintas. Cuandoel <strong>de</strong>monio local – Tasktraker – inicializa una maquinavirtual Java para ejecutar una tarea, la política propuestapermite que esta máquina virtual sea reutilizada, cuandola tarea es finalizada en el nodo. El propósito <strong>de</strong> estacaracterística, es el ahorro <strong>de</strong> tiempo <strong>de</strong> arranque yfinalización <strong>de</strong> las máquinas virtuales Java,especialmente cuando hay un gran número <strong>de</strong> tareas aejecutar. <strong>La</strong> Figura 7 presenta un esquema <strong>de</strong> la política<strong>de</strong> planificación propuesta.B. Reserva <strong>de</strong> RecursosGarantizar que las aplicaciones <strong>de</strong>l usuario local no seven afectadas en sus prestaciones, implica la necesidad<strong>de</strong> reservar los recursos necesarios para su ejecucióneficiente.<strong>La</strong> técnica propuesta por nuestra política <strong>de</strong>planificación, para permitir la mezcla <strong>de</strong> carga local ycarga paralela en el mismo nodo <strong>de</strong>l cluster no-<strong>de</strong>dicado,es la reserva <strong>de</strong> recursos mediante el uso <strong>de</strong> containers.<strong>La</strong> política presentada propone el uso <strong>de</strong> controlgroups– los cgroups para hacer reserva <strong>de</strong> recursos enlos nodos <strong>de</strong>l cluster. Linux implementa containers através <strong>de</strong> los cgropus. Los recursos <strong>de</strong> cada nodo sedivi<strong>de</strong>n en subsistemas y se crean una jerarquía <strong>de</strong>archivos – los cgroups. En cada cgroup se <strong>de</strong>finenporcentajes <strong>de</strong> uso <strong>de</strong> correspondientes subsistemas.Para cada cgroup se pue<strong>de</strong> asignar aplicaciones, usuarioso procesos, <strong>de</strong>finiendo <strong>de</strong> esta manera cómo será el usocompartido <strong>de</strong> los recursos <strong>de</strong>l cluster.Los clusters no-<strong>de</strong>dicados utilizados en laboratoriosinformáticos ejecutan carga local muy controlada. Estacarga varía en el tiempo (horas) y en el espacio. El reto<strong>de</strong> la política <strong>de</strong> planificación propuesta, es utilizardistintos cgroups, con diferentes configuraciones <strong>de</strong> uso<strong>de</strong> recursos, que serán utilizadas por cada nodo amedida que la carga local cambie.Fig.7 Esquema <strong>de</strong> la política <strong>de</strong> planificación <strong>de</strong> trabajos propuestaVI.EXPERIMENTOS Y RESULTADOSPara la ejecución <strong>de</strong> los experimentos fue utilizado uncluster no <strong>de</strong>dicado, compuesto por PC´s <strong>de</strong> sobremesa einterconectado mediante una red <strong>de</strong> interconexión a100Mbits/segundo.Este cluster está constituido por nueve máquinashomogéneas. Des<strong>de</strong> la perspectiva Hadoop, el sistemaestá formado por un nodo Master y 8 máquinasrealizando tareas <strong>de</strong> Worker. <strong>La</strong> planificación <strong>de</strong>trabajos, y la gestión <strong>de</strong>l sistema <strong>de</strong> archivos por HDFS -Hadoop Distributed File System, se centraliza en el nodomaster. Fue utilizado Hadoop en su versión 20.2, Javaen su versión jdk1.6.0_16 y como sistema operativoUbuntu en su versión 9.10.<strong>La</strong> Figura 8 presenta los tiempos <strong>de</strong> ejecución <strong>de</strong> unaaplicación MapReduce <strong>de</strong>l tipo read-mapping. Eltamaño <strong>de</strong> los datos <strong>de</strong> entrada ha sido <strong>de</strong> 4,5 Gigabytes.En cada nodo por <strong>de</strong>fecto, fueron <strong>de</strong>finidos dos slotspara tareas Map y dos slots para tareas Reduce. Eltrabajo ha sido dividido en 62 tareas Map y 16 tareasReduce en una primera ejecución. A continuación seejecutarán con 8, 4 y 2 tareas Reduce. <strong>La</strong> primeracolumna <strong>de</strong> la figura 8, presenta los tiempos <strong>de</strong>ejecución <strong>de</strong>l trabajo sin reutilizar la máquina virtualJava, y la segunda columna presenta los tiempos <strong>de</strong>ejecución reutilizando la máquina virtual Java. Losresultados muestran una ganancia <strong>de</strong> aproximadamenteel 5% en los tiempos <strong>de</strong> ejecución.<strong>La</strong> Figura 9 presenta los tiempos <strong>de</strong> finalización(makespan), cuando fueron ejecutados en paralelo ochotrabajos distintos <strong>de</strong>l tipo read-mapping. Cada trabajo<strong>JP2011</strong>-504


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011utiliza su propio archivo <strong>de</strong> consulta y los ocho trabajoscomparten entre ellos el mismo fichero <strong>de</strong> referencia.El tamaño <strong>de</strong> los datos <strong>de</strong> entrada también ha sido <strong>de</strong> 4,5Gigabytes. En cada nodo por <strong>de</strong>fecto, fueron <strong>de</strong>finidosdos slots para tareas Map y dos slots para tares Reduce.El trabajo ha sido dividido en 62 tareas Map y 8 tareasReduce.resultados <strong>de</strong> los primeros experimentos utilizando lapolítica propuesta, <strong>de</strong>muestran una disminución en eltiempo <strong>de</strong> makespan <strong>de</strong> trabajos MapReduce encoladosen el cluster Hadoop, comparados con los valores <strong>de</strong> lapolítica <strong>de</strong> planificación por <strong>de</strong>fecto. En una primeraaproximación, los resultados obtenidos, muestran laviabilidad <strong>de</strong> nuestras propuestas. No obstante, en esteapartado, se <strong>de</strong>berá completar la experimentación,incorporando más aplicaciones y casos <strong>de</strong> usoAGRADECIMIENTOSEl presente trabajo ha sido financiado por el MEC(Ministerio <strong>de</strong> Educación y Ciencia) mediante elproyecto con referencia TIN2007-64974.Fig.8 Política sin reutilización <strong>de</strong> JVM x Política con reutilización <strong>de</strong>JVM<strong>La</strong> primera columna <strong>de</strong> la figura 9, presenta lostiempos <strong>de</strong> ejecución <strong>de</strong>l trabajo <strong>de</strong> la política por<strong>de</strong>fecto <strong>de</strong>l framework Hadoop. <strong>La</strong> segunda columnamuestra los tiempos <strong>de</strong> ejecución, reutilizando lamáquina virtual Java. <strong>La</strong> tercera columna, presenta losresultados <strong>de</strong> la política <strong>de</strong> planificación propuesta. Losresultados muestran una ganancia <strong>de</strong> aproximadamente<strong>de</strong> 5% en el tiempo <strong>de</strong> makespan cuando se compara lareutilización <strong>de</strong> la maquina virtual Java con la políticapor <strong>de</strong>fecto <strong>de</strong> Hadoop. Y muestra una mejora <strong>de</strong>l 17%,cuando se compara la política <strong>de</strong> planificaciónpropuesta, con la política por <strong>de</strong>fecto <strong>de</strong>l frameworkHadoop.Fig.9 Comparativa <strong>de</strong> rendimiento al aplicar la política propuestaVII.CONCLUSIONES<strong>La</strong> política propuesta está basada en dos aspectos; laplanificación <strong>de</strong> trabajos paralelos MapReduce, y lareserva <strong>de</strong> recursos utilizando containers, para permitirla mezcla <strong>de</strong> cargas locales con cargas paralelas.Hasta ahora, ha sido implementado la planificación <strong>de</strong>trabajos paralelos MapReduce. Esta implentación estábasada en dos puntos: la afinidad <strong>de</strong> tareas <strong>de</strong> trabajosdistintos que compartan el mismo bloque <strong>de</strong> archivo <strong>de</strong>entrada y la reutilización <strong>de</strong> máquinas virtuales. LosREFERENCIAS[1] Dean, Jeffrey and Ghemawat, Sanjay MapReduce: simplifieddata processing on large clusters. ACM, 2008, Commun. ACM,Vol. 51, pp. 107-113.[2] Zaharia, M.; Konwinski, A.; Joseph, A.D.; Katz, R.; Stoica, I.Improving MapReduce Performance in HeterogeneousEnvironments. 2008, in 8th USENIX Symposium on OperatingSystems Design and Implementation, (OSDI'08).[3] Lämmel, Ralf. Google's MapReduce programming mo<strong>de</strong>l --Revisited. Elsevier North-Holland, Inc., 2008, Sci. Comput.Program., Vol. 70, pp. 1-30.[4] Kruijif, M.; Sankaralingam, K. MapReduce for the Cell B.E.Architecture. 2007, Technical Report, TR1625, The Universityof Wisconsin-Madison.[5] He, Bingsheng, et al. Mars: a MapReduce framework on graphicsprocessors. 2008, in Proceedings of the 17th internationalconference on Parallel architectures and compilation techniques.[6] Ranger, Colby, et al. Evaluating MapReduce for Multi-core andMultiprocessor Systems. 2007, in Proceedings of the IEEE 13thInternational Symposium on High Performance ComputerArchitecture.[7] Fischer, M.J.; Su, X.; Yin, Y. Assigning tasks for efficiency inHadoop: extend abstract. 2010, in ACM Sysmposium onParallelism in algorithms and architectures. (ACM-SPAA’10).[8] Ibrahim, S.; Jin, H.; Cheng, B.; Cao, H.; Wu, S; Qi, L.; Cloudlet:towards mapreduce implementation on virtual machines. 2009,ACM International Symposium onn High performancedistributed computing. (ACM-HPDC’09).[9] Isard, M.; Prabhakaran, V.; Currey, J.; Wie<strong>de</strong>r, U.; Talwar, K.;Goldberg, A. Quincy: fair scheduling for distributed computingclusters. 2009 , in Symposium on Operating systems principles(ACM -SOSP '09).[10] Kim, S.; Han, H.; Jung, H.; Eom, ,H.; Yeom, H. Harnessing inputredundancy in a MapReduce framework. 2010, in Symposium onApplied Computing. (ACM – SAC’10).[11] Luo, Y.; Guo, Z.; Sun, Y.; Qiu, J.; Li, W.W. A HierarchicalFramework for Cross-Domain MapReduce Execution. 2011, InHigh Performance Distributed Computing (ACM – HPDC’11).[12] Qin, A.; Tu, D.; Shu, C.; Gao, C. Xconveryer: guarantee hadoopThroughput via Lightweight OS-Level Virtualization. 2009,Eighth International Conference on Grid and CooperativeComputing. (IEEE-GCC’09).[13] Shafer, J.; Rixner, S.; Cox, A.L. The Hadoop distributedfilesystem: Balancing portability and performance. 2010, IEEEInternational Symposium on Performance Analysis of Systems &Software. (IEEE –ISPASS’10).[14] Stephen S.; Pötzl, H.; Fiuczynski, M. E.; Bavier, A.; Peterson, L.Container-based operating system virtualization: a scalable,high-performance alternative to hypervisors. SIGOPS Oper. Syst.Rev. 41, 3 (March 2007).[15] Xie, J.; Yin, S.; Ruan, X. Ding, Z.; Tian, Y.; Majors, J.;Manzanares, A.; Qin, X. Improving MapReduce performancethrough data placement in heterogeneous Hadoop clusters. 2010,IEEE International Symposium on Parallel & DistributedProcessing, Workshops and Phd Forum. (IEEE-IPDPSW’10).<strong>JP2011</strong>-505


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011[16] Zaharia, M.; Konwinski, A.; Joseph, A.D.; Katz, R.; Stoica, I.Improving MapReduce Performance in HeterogeneousEnvironments. 2008, 8th USENIX Symposium on OperatingSystems Design and Implementation. (OSDI'08).[17] Apache Hadoop. Retrived April 20, 2010, from ASF:http://hadoop.apache.org/core/.[18] Gunarathne, T,; Wu, T.; Qiu, J.; Fox, G. Cloud ComputingParadigms for Pleasingly Parallel Biomedical Applications.2010, in 19 th ACM International Symposium on HighPerformance Distributed Computing. (ACM – HPDC’10).[19] Schatz, M.C. Cloudburst: highly sensitive read mapping withMapReduce. Bioinformatics 2009 25(11):1363-1369<strong>JP2011</strong>-506


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Procesamiento <strong>de</strong> ví<strong>de</strong>os usando la nubeA. Morales 1 y F. Almeida 2Resumen— Este trabajo recoge el diseño <strong>de</strong>lframework Vi<strong>de</strong>oMante. Se trata <strong>de</strong> un frameworkgeneralista orientado al entendimiento <strong>de</strong> ví<strong>de</strong>o. Elproyecto se aborda como un proyecto interdisciplinaren el que se integran la computación en paraleloy distribuida, los algoritmos y las operaciones<strong>de</strong> análisis <strong>de</strong> imagen y visión y los lenguajes yherramientas orientadas a la programación y fusiónen ambos contextos. Como resultado preliminarse presenta como caso <strong>de</strong> uso un problema muyfrecuente en el ámbito <strong>de</strong> la visión por computadory el procesado <strong>de</strong> ví<strong>de</strong>os, que es la <strong>de</strong>tección <strong>de</strong>objetos en movimiento. Sin embargo, la metodologíapropuesta es extensible a otros casos <strong>de</strong> uso, comoel retocado <strong>de</strong> fotogramas o la realidad aumentada,sin mas que cambiar las funciones usadas. Semuestra, a<strong>de</strong>más, un análisis <strong>de</strong> rendimiento <strong>de</strong>las tecnologías seleccionadas y su versatilidad enentornos secuenciales y paralelos.Palabras clave— Computación paralela, análisis <strong>de</strong>ví<strong>de</strong>o, python, octave, OpenCV, OpenMP.I. IntroducciónLOS dispositivos <strong>de</strong> captación <strong>de</strong> imágenes yví<strong>de</strong>os han incrementado progresivamente lacantidad <strong>de</strong> datos que proporcionan. Cada vezse dispone <strong>de</strong> mayor resolución en fotografías yví<strong>de</strong>os, en términos <strong>de</strong>l número <strong>de</strong> píxeles o <strong>de</strong>lnúmero frames por segundo (FPS) que ofrecen.Los límites <strong>de</strong> la tecnología comercial rondanlos 7500 FPS a resolución 1000x1000 o millones<strong>de</strong> FPS a resoluciones <strong>de</strong> 100x100. Aunque sedispone <strong>de</strong> una amplia bibliografía orientada al<strong>de</strong>sarrollo <strong>de</strong> algoritmos y operaciones para eltratamiento <strong>de</strong> ví<strong>de</strong>o, a estas resoluciones se vuelvealtamente costosa su manipulación en términoscomputacionales, más aún cuando se requierensoluciones en tiempo real.Simultáneamente, la potencia <strong>de</strong> cómputo <strong>de</strong> lossistemas paralelos y distribuidos disponible, muy porencima <strong>de</strong> los sistemas embebidos y <strong>de</strong> escritorio,no parece que esté siendo aprovechada como unaforma generalizada y eficaz con la que abordartales operaciones e incrementar el alcance <strong>de</strong> losresultados.En este trabajo se presenta el proyecto, yresultados preliminares, para el <strong>de</strong>sarrollo <strong>de</strong>lframework generalista Vi<strong>de</strong>oMante orientadoa la manipulación y el entendimiento <strong>de</strong>ví<strong>de</strong>os. Vi<strong>de</strong>oMante aprovecharía los recursos<strong>de</strong> computación <strong>de</strong> altas prestaciones actualmentedisponibles y su acceso a través <strong>de</strong> re<strong>de</strong>s comoInternet. Nuestro esfuerzo trata, por tanto, <strong>de</strong>fusionar varios universos:• Imágenes <strong>de</strong> alta <strong>de</strong>finición1 Dpto. <strong>de</strong> Estadística e Investigación Operativa,<strong>Universidad</strong> <strong>de</strong> <strong>La</strong> <strong>La</strong>guna, e-mail: amorales@ull.es.2 Dpto. <strong>de</strong> Estadística e Investigación Operativa,<strong>Universidad</strong> <strong>de</strong> <strong>La</strong> <strong>La</strong>guna, e-mail: falmeida@ull.es.• Sistemas <strong>de</strong> cómputo paralelo y distribuido• Algoritmos eficientes en el área <strong>de</strong> visión cuyasalida se proporciona a procedimientos queextraen conclusiones <strong>de</strong> alto nivelEl objetivo principal es el <strong>de</strong> extraer <strong>de</strong>forma automática información contenida en elví<strong>de</strong>o que resulta difícil <strong>de</strong> obtener a través <strong>de</strong>métodos tradicionales. Por ejemplo: obtenerestadísticas <strong>de</strong>l tráfico en una rotonda, analizandoel comportamiento <strong>de</strong> cada individuo, a partir <strong>de</strong>lví<strong>de</strong>o proporcionado por una cámara <strong>de</strong> observación<strong>de</strong> tráfico.Hasta don<strong>de</strong> nosotros conocemos, no existeningún framework <strong>de</strong> caracter generalista orientadoal entendimiento <strong>de</strong> ví<strong>de</strong>os basado en Servicios Web yOpenCV. <strong>La</strong> mayoría <strong>de</strong> los trabajos y herramientashacen referencia a frameworks realizados ad-hoccon su propio juego <strong>de</strong> instrucciones, por ejemplo,basados en tecnologías GRID [8] o apoyándose enesqueletos [9] [10]. Nuestra propuesta preten<strong>de</strong> irun paso más allá y aprovechar tecnologías estándary ligeras ampliamente difundidas. Se propone, porejemplo, utilizar la librería OpenCV ampliamentevalidada, la baja barrera <strong>de</strong> entrada <strong>de</strong>l lenguajepython, así como las tecnologías que se apoyan enservicios web, más genéricas que las alternativasencontradas.<strong>La</strong> estructura <strong>de</strong>l trabajo es la que sigue: lasección II muestra el diseño <strong>de</strong> Vi<strong>de</strong>oMante comoun framework generalista, la sección III plantea uncaso <strong>de</strong> uso <strong>de</strong> Vi<strong>de</strong>oMante sobre el problema <strong>de</strong> la<strong>de</strong>tección <strong>de</strong> movimiento en ví<strong>de</strong>o, mostrando lastecnologías y las pruebas realizadas, se finalizarácon las secciones <strong>de</strong> resultados computacionales yconclusiones, secciones IV y V respectivamente.II. MetodologíaEl diseño propuesto para Vi<strong>de</strong>oMante pue<strong>de</strong> verseen la figura 1. Se observan un nodo maestro yun conjunto <strong>de</strong> N nodos esclavos con el mismoconjunto <strong>de</strong> software instalado. El nodo maestroes el encargado <strong>de</strong> orquestar el proceso según lascapacida<strong>de</strong>s <strong>de</strong> los nodos esclavos. Por lo generallos nodos esclavos serán principalmente <strong>de</strong> cómputo,pero si existe hardware <strong>de</strong> entrada (una cámara <strong>de</strong>ví<strong>de</strong>o) o <strong>de</strong> salida (una pantalla), en estos nodospriorizarán las funciones <strong>de</strong> captura o reproducción.De igual forma, se consi<strong>de</strong>rarían también entradao salida, la tarea <strong>de</strong> <strong>de</strong>scomponer un fichero <strong>de</strong>ví<strong>de</strong>o local en frames para su procesado, así comocomponerlo nuevamente a un ví<strong>de</strong>o o enviarlo a unservidor <strong>de</strong> streaming. Por último, se observa quelos nodos comparten un modulo <strong>de</strong> almacenamientoque actúa como repositorio <strong>de</strong> trabajos y resultados.Los paquetes <strong>de</strong> software instalados en los nodos<strong>JP2011</strong>-507


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Cámaraví<strong>de</strong>oFicheroví<strong>de</strong>oN xOpenCVSinglecoreNodo adquisición / cómputoOpenCFEsclavoC C++ Python Octave AlgoritmosFig. 1.OpenMPMulticoresotrasGPU PlataformaAlmacenamiento distribuidoLibreríasservicioswebEsquema <strong>de</strong>l frameworkNodo maestroOpenCFMaestroServidorstreamingFicheroví<strong>de</strong>oesclavos, con los que el usuario podrá elaborarlos algoritmos <strong>de</strong> visión o <strong>de</strong> codificado <strong>de</strong> ví<strong>de</strong>os,los po<strong>de</strong>mos clasificar en tres conjuntos diferentesatendiendo a su tecnología:• Lenguajes compilados, como C o C++, conlibrerías <strong>de</strong> visión como OpenCV [3], <strong>de</strong>procesado <strong>de</strong> ví<strong>de</strong>os como libffmpeg [4], olibrerías paralelas como OpenMP [5]. En estaprimera aproximación nos centramos en C,OpenCV y OpenMP.• Lenguajes interpretados generalistas, comopue<strong>de</strong>n ser python o perl, que algunos disponen<strong>de</strong> librerías para visión, o que pue<strong>de</strong>n servircomo lenguaje pegamento. En este caso se haescogido python por tener diferentes estilos <strong>de</strong>integración con C y OpenCV.• Lenguajes interpretados orientados a cálculonumérico, como pue<strong>de</strong>n ser octave o matlab, quedisponen <strong>de</strong> librerías para su uso en visión. Eneste caso se ha escogido Octave por su caráctergratuito.Como herramienta <strong>de</strong> comunicación entresistemas, se contempla OpenCF [1] , que permitiráservir y consumir algoritmos y funcionalida<strong>de</strong>sutilizando servicios web. Y por otro lado, parael paso <strong>de</strong> binarios (imágenes fuente e imágenesresultado) se preten<strong>de</strong> evaluar sistemas <strong>de</strong> archivosdistribuidos, como NFS u otros más adaptadosa la nube. No obstante no se evaluarán en estapublicación.Respecto a la arquitectura hardware subyacentese evalúa el uso <strong>de</strong> máquinas convencionales con unúnico núcleo y procesadores multinúcleo. En estaetapa no se evaluará el uso <strong>de</strong> GPUs pero es unobjetivo inmediato.<strong>La</strong> integración <strong>de</strong> este abanico <strong>de</strong> tecnologías,ligeras y escalables, permitiría resolver problemas<strong>de</strong> análisis <strong>de</strong> ví<strong>de</strong>o proporcionando soluciones entiempo real. El rendimiento y la latencia vendrándados por el problema concreto a resolver, el número<strong>de</strong> equipos y las condiciones <strong>de</strong> la red.Des<strong>de</strong> el punto <strong>de</strong> vista <strong>de</strong> la computación <strong>de</strong> altasprestaciones, los objetivos <strong>de</strong> Vi<strong>de</strong>oMante pue<strong>de</strong>nresumirse como:• Arquitectura distribuida: OpenCF en el nodomaestro y en los esclavos (comunicación usandoservicios web)• Arquitectura paralela, OpenMP en los nodos conmultinúcleo• Control centralizado <strong>de</strong> todas las ejecucionesy los parámetros <strong>de</strong>s<strong>de</strong> el nodo maestro(planificador)• Librerías compartidas: OpenCV (visión),libffmpeg (ví<strong>de</strong>os)• Código en diferentes lenguajes: C, C++, python,octave, etc• Imágenes y ví<strong>de</strong>os en almacenamientodistribuido transparenteDes<strong>de</strong> el punto <strong>de</strong> vista <strong>de</strong>l análisis <strong>de</strong> ví<strong>de</strong>o y <strong>de</strong>la visión por computador, el objetivo se concreta enla implementación <strong>de</strong> las siguientes funcionalida<strong>de</strong>s,acor<strong>de</strong> a unas interfaces preestablecidas que puedanreusarse:• Lectura <strong>de</strong> ví<strong>de</strong>o (tanto <strong>de</strong> fichero como <strong>de</strong>cámara)• Detección <strong>de</strong> fondo (varios métodos)• Detección <strong>de</strong> objetos (segmentacion)• Posición 2D <strong>de</strong> los objetos (p.ej: centroi<strong>de</strong>)• Posición 3D <strong>de</strong> los objetos (mapeo 2D-3D)• Composición <strong>de</strong> varios frames en uno• Sobreimpresión <strong>de</strong> resultados (p.ej: trazas, encentroi<strong>de</strong>)• Generación <strong>de</strong> ví<strong>de</strong>o (tanto a fichero como astreaming)Para que el usuario final <strong>de</strong> Vi<strong>de</strong>oMante obtengalas siguientes ventajas:• Programación modular con parámetrosconfigurables• Escalado <strong>de</strong>l problema agregando más nodos,más núcleos o más GPUs• Interfaz gráfica unificada (escritorio o web)Claramente las funcionalida<strong>de</strong>s propuestasconstituyen un conjunto básico <strong>de</strong> operacionesque podrá ser extendido con métodos <strong>de</strong> mayorcomplejidad.III. Caso <strong>de</strong> uso: <strong>de</strong>tección <strong>de</strong> objetos enmovimientoComo caso <strong>de</strong> uso para esta primera contribución,se ha elegido un problema muy frecuente en el ámbito<strong>de</strong> la visión por computador y el procesado <strong>de</strong> ví<strong>de</strong>os,como es la <strong>de</strong>tección <strong>de</strong> objetos en movimiento. Sinembargo, la metodología propuesta es extensible aotros casos <strong>de</strong> uso, como pue<strong>de</strong>n ser el retocado <strong>de</strong>fotogramas o la realidad aumentada, sin más quemodificar las funciones utilizadas.<strong>La</strong> manera habitual <strong>de</strong> <strong>de</strong>tectar el movimiento esutilizando un conjunto <strong>de</strong> fotogramas previos para<strong>de</strong>terminar el fondo, y sustraer dicho fondo <strong>de</strong>lfotograma para analizar qué se ha movido. Aunquela <strong>de</strong>tección <strong>de</strong> fondo es un campo maduro envisión, a día <strong>de</strong> hoy se siguen investigando nuevastécnicas. Se han elegido algunas <strong>de</strong> las tradicionales,y una implementación particular <strong>de</strong> una técnica másreciente:<strong>JP2011</strong>-508


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011• Media: El fondo se calcula como la media<strong>de</strong> un conjunto <strong>de</strong> fotogramas en el pasado,calculada haciendo la media pixel a pixel. Elnúmero <strong>de</strong> fotogramas elegidos, su disposición yla importancia (peso) <strong>de</strong> cada uno suelen venirdados por el problema.• Mediana: Este algoritmo es similar al anterior,pero realiza el cálculo <strong>de</strong> la mediana en vez <strong>de</strong>lcálculo <strong>de</strong> la media. En el caso anterior el objetoen movimiento forma parte <strong>de</strong>l valor <strong>de</strong> la media,aquí se <strong>de</strong>scarta siempre que el fondo se hayavisto en más <strong>de</strong>l 50% <strong>de</strong> los fotogramas.• RANSAC: El RANSAC (RANdom SAmpleConsensus) [6] es un algoritmo creado enlos años 80 para ajustar mo<strong>de</strong>los a datosexperimentales y ha sido aplicado a la <strong>de</strong>tección<strong>de</strong> fondo [7]. Mejora al algoritmo que aplica lamediana puesto que su concepto <strong>de</strong> similitu<strong>de</strong>s más flexible, y permite <strong>de</strong>tectar fondo queaparece en menos <strong>de</strong>l 50% <strong>de</strong> los fotogramas.Hemos mejorado la propuesta <strong>de</strong> este algoritmoy parametrizado el RANSAC <strong>de</strong> forma diferentepara conseguir un mejor comportamiento ymenor costo computacional.Comparación <strong>de</strong> lenguajes y técnicasEn un primer análisis, se ha implementado elmétodo <strong>de</strong> la mediana con diferentes combinacioneslenguajes y técnicas <strong>de</strong> programación. <strong>La</strong>s técnicasutilizadas han sido las siguientes:• octave-2d: Octave consi<strong>de</strong>ra a las imágenescomo matrices 2D. <strong>La</strong> forma trivial <strong>de</strong>tratamiento consiste en utilizar dos buclesanidados que recorren los diferentes elementos(x,y) <strong>de</strong> la matriz y hacer uso <strong>de</strong> la funciónmedian para calcular el valor correspondiente.• octave-3d: Se genera una matriz 3D que seconstruye apilando en el eje Z todas las imágenes2D, y se realiza la mediana sobre dicho eje Zutilizando la función median.• python-pyOpenCV: Se utilizan los bindingspyOpenCV para acce<strong>de</strong>r a las imágenesy se utilizan dos bucles para recorrer loselementos (x,y) aplicando la función medianaimplementada directamente en python.• python-ctypes: Se aplica igual que el casoanterior, pero utilizando en esta ocasión losbindings ctypes.• C-cvget2d: Se realizan dos bucles para recorrerlos diferentes elementos (x,y), utilizando lafunción cvGet2D para obtener el valor <strong>de</strong> lospixels, y la función qsort para obtener lamediana.• C-punteros: Se aplica igual que el caso anterior,pero utilizando aritmética <strong>de</strong> punteros paraobtener el valor <strong>de</strong> los pixels.• python-c-punteros-total: Se aplica el casoC-punteros, se ha compilado en una DLL yse ha usado <strong>de</strong>s<strong>de</strong> python con los bindings <strong>de</strong>ctypes.• python-c-punteros-neto: Se aplica el casopython-c-punteros-total, pero midiendosolamente el tiempo <strong>de</strong> ejecución, y omitiendoel tiempo carga <strong>de</strong>l intérprete.Ejecución secuencial/paralelaEjecutar cualquiera <strong>de</strong> los tests anteriores en unamáquina con una arquitectura <strong>de</strong> múltiples núcleos,a priori, no presenta ninguna mejora respecto <strong>de</strong>una arquitectura secuencial, puesto que ninguno <strong>de</strong>los lenguajes utilizados se adapta en función <strong>de</strong>lhardware subyacente.Octave presenta una librería multicore quepermite su ejecución en forma <strong>de</strong> múltiples hilos,pero su uso no es trivial.Python proporciona soporte para hilos en sulenguaje. Pero en su implementación actual, elinterprete CPython (el habitual usado en Linux,Windows o Mac) no está programado <strong>de</strong> formathread-safe y utiliza un semáforo global llamado GIL(Global Interpreter Lock) para evitar que dos hilospuedan modificar un mismo objeto. <strong>La</strong>s llamadas alibrerías en C no están afectadas <strong>de</strong>l uso <strong>de</strong>l GIL,siempre que no usen objetos <strong>de</strong>l espacio <strong>de</strong> python.De igual forma se pue<strong>de</strong>n usar procesos en vez <strong>de</strong>hilos, que no se ven afectados (usando la libreríamultiprocessing). Otros interpretes como Jython(java) no están afectados tampoco. <strong>La</strong> libreríaPyCuda también pue<strong>de</strong> ofrecer un amplio abanico<strong>de</strong> nuevas posibilida<strong>de</strong>s para la realización <strong>de</strong> códigoque po<strong>de</strong>r sumar a las funcionalida<strong>de</strong>s exportadas através <strong>de</strong> los servicios web.C ofrece soporte multinúcleo través <strong>de</strong> la libreríaOpenMP y sus directivas <strong>de</strong> compilación (#pragma).Esto presenta un handicap <strong>de</strong> cara al <strong>de</strong>sarrollo<strong>de</strong>l proyecto. Lenguajes como python resultancómodos como pegamento para invocar funciones <strong>de</strong>librerías en C, y también para realizar operaciones<strong>de</strong> alto nivel, como podría ser el módulo <strong>de</strong> serviciosweb. Sin embargo, son incapaces por sí mismos <strong>de</strong>ejecutarse con un paralelismo eficaz.Como solución se propone implementar lassecciones que se ejecutarán en la arquitecturamultinúcleo en C y el resto en python.#pragma omp p a r a l l e l#pragma omp f o r s c h e d u l e ( dynamic )f o r ( y = y i ; y < yf ; y++) {f o r ( x = x i ; x < xf ; x++) {// <strong>de</strong>ntro <strong>de</strong> e s t a f u n c i ó n se// r e c o r r e l a coor<strong>de</strong>nada zcalcula metodo ( imagenes , x , y ) ;}}Fig. 2.Código paralelizado <strong>de</strong> ejemploIV. Resultados ComputacionalesEn esta sección planteamos la experienciacomputacional realizada con el fin <strong>de</strong> validar<strong>JP2011</strong>-509


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011nuestras propuestas. En primer lugar analizamos elrendimiento <strong>de</strong> los distintos lenguajes y técnicas yposteriormente analizamos el rendimiento <strong>de</strong>l casoparalelo.Análisis <strong>de</strong> rendimiento <strong>de</strong> lenguajes y técnicasEntrada: 4 fotogramas (42, 53, 64 y 75) <strong>de</strong>1440x1080 pixels en color, correspondientes a <strong>de</strong> unví<strong>de</strong>o <strong>de</strong> 6 segundos a 25 FPS que muestra una escena<strong>de</strong> coches en movimiento (figura 3). Los fotogramasfueron escogidos con los objetos en movimientoen posiciones diferentes para que resultase sencillocalcular el fondo.Fig. 3.Fotogramas usados para el análisis <strong>de</strong> rendimientoCaracterísticas <strong>de</strong>l equipo:• Procesador: AMD64 Turion MK36 2.0GHz• Cache: 64+64KB L1 - 512KB L2• Memoria: 2GB DDR2 667MHzVersiones <strong>de</strong>l software: GCC 4.3.2, octave 3.0.1,OpenCV 1.0.0, python 2.5.2.En la tabla I se presentan como resultados lostiempos medios obtenidos para tres ejecucionesdiferentes <strong>de</strong>l algoritmo <strong>de</strong> la mediana. En todos loscasos se lanza previamente una primera ejecucióncon el fin <strong>de</strong> asegurar que tanto ejecutables, libreríase imágenes, se encuentran en la memoria cache <strong>de</strong>lsistema operativo.Se observa que los lenguajes interpretados por símismos resultan ineficientes en términos <strong>de</strong>l tiempo<strong>de</strong> ejecución para realizar cálculos. De ellos, el quemejores tiempos ha presentado es octave <strong>de</strong>bido aque posee una función específica para el cálculo <strong>de</strong>la mediana tridimensional. Obviando esa operación,el acceso a arrays <strong>de</strong> python ha resultado ser másrápido que el <strong>de</strong> octave. Por otro lado está laimplementación C, don<strong>de</strong>, si la programación serealiza con ciertos trucos se pue<strong>de</strong> conseguir explotarel rendimiento al máximo. Y por último se observaque el híbrido python-c aporta unos resultadoscomparables a la programación en C directamente,siempre que excluyamos los tiempos <strong>de</strong> carga <strong>de</strong>lintérprete <strong>de</strong> python, lo que lo convierte en unaalternativa viable dadas las facilida<strong>de</strong>s <strong>de</strong> <strong>de</strong>sarrolloque ofrece python.TABLA IResultados <strong>de</strong> comparación <strong>de</strong> lenguajes y técnicasC-punterospython-c-punterospython-c-punteros-totalC-cvget2doctave-3dpython-ctypespython-pyOpenCVoctave-2dAnálisis <strong>de</strong> rendimiento <strong>de</strong>l caso paralelo0.85 sg0.86 sg1.76 sg1.86 sg9.04 sg85.1 sg59.4 sg483 sgEntrada: 147 fotogramas <strong>de</strong> 1440x1080 pixels encolor correspondientes a un ví<strong>de</strong>o <strong>de</strong> 6 segundos a 25FPS que muestra una escena <strong>de</strong> un partido <strong>de</strong> tenis.Características <strong>de</strong>l equipo:• Procesador: Intel Core 2 Quad Q6600 2.4GHz.• Cache: 128+128KB L1 - 8MB L2• Memoria: 4GB DDR2 667MHz<strong>La</strong> tabla II muestra el tiempo <strong>de</strong> ejecución ensegundos invertido por los diferentes métodos enprocesar el ví<strong>de</strong>o <strong>de</strong> entrada y obtener el ví<strong>de</strong>o<strong>de</strong> salida. El procesado se hace íntegramente enmemoria, habiéndose excluido el tiempo <strong>de</strong> lecturay el <strong>de</strong> escritura.TABLA IIResultados <strong>de</strong> ejecución paralela con OpenMP. Tiempo<strong>de</strong> ejecución en segundosMétodo 1 núcleo 4 núcleos aceleraciónMedia 4.22 sg 1.34 sg 3.14Mediana 18.24 sg 4.67 sg 3.90RANSAC 148.83 sg 37.96 sg 3.92Como muestra <strong>de</strong> ejemplo, en la figura 4 se apreciaun fotograma <strong>de</strong>l ví<strong>de</strong>o <strong>de</strong> una composición don<strong>de</strong> semuestra el ví<strong>de</strong>o original y los tres ví<strong>de</strong>os resultados<strong>de</strong> la ejecución anterior.Se observa que con esta forma híbrida <strong>de</strong>proce<strong>de</strong>r, po<strong>de</strong>mos conseguir aceleraciones bastantebuenas. El método RANSAC y Mediana son máscomplicados computacionalmente que el <strong>de</strong> la Media,y observamos que las aceleraciones son mayores.Esto es así puesto que la proporción <strong>de</strong> códigoeficiente en C que se ejecuta es mayor. Aunqueel método RANSAC es computacionalmente máscostoso, presenta la ventaja <strong>de</strong> que los resultadosson mejores en general, y en especial cuando elfondo permanece poco tiempo visible.A la vista <strong>de</strong> los resultados y a modo <strong>de</strong> síntesisse propone la combinación python (cuanto menosposible) y C. Es importante seguir la máxima <strong>de</strong>que los cálculos sean implementados en C y <strong>de</strong>jaral lenguaje interpretado la labor <strong>de</strong> llamada. <strong>La</strong>saplicaciones presentan aceleraciones óptimas en elrango <strong>de</strong> procesadores consi<strong>de</strong>rados.<strong>JP2011</strong>-510


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 4. Diferentes métodos <strong>de</strong> <strong>de</strong>tección <strong>de</strong> fondo aplicados ypresentados en simultáneoOpenCV (Open Source Computer Vision)http://opencv.willowgarage.com/wiki/[4] Varios autores FFmpeg http://www.ffmpeg.org/[5] The OpenMP Architecture Review Board TheOpenMP API specification for parallel programminghttp://openmp.org/[6] M.A. Fischler and R.C. Bolles. Random sample consensus:A paradigm for mo<strong>de</strong>l fitting with applications to imageanalysis and automated cartography. Communications ofthe ACM, 24(6):381–395, 1981.[7] H. Wang and D. Suter. A novel robust statistical methodfor background initialization and visual surveillance.Computer Vision–ACCV 2006, pages 328–337, 2006.[8] F.J. Seinstra, J.M. Geusebroek, D. Koelma, C.G.M.Snoek, M. Worring, and A.W.M. Smeul<strong>de</strong>rs, “Highperformancedistributed vi<strong>de</strong>o content analysis withparallel-horus,” Multimedia, IEEE, vol. 14, no. 4, pp.64–75, 2007.[9] J. Sérot and D. Ginhac, “Skeletons for parallel imageprocessing: an overview of the skipper project,” Parallelcomputing, vol. 28, no. 12, pp. 1685–1708, 2002.[10] C. Nicolescu and P. Jonker, “A data and task parallelimage processing environment,” Parallel Computing, vol.28, no. 7-8, pp. 945–965, 2002.V. ConclusiónComo conclusión po<strong>de</strong>mos <strong>de</strong>cir que hemosrealizado el diseño <strong>de</strong>l framework Vi<strong>de</strong>oMante quepropone una estrategia genérica con la que abordarproblemas <strong>de</strong>l análisis <strong>de</strong> imagen y procesamiento<strong>de</strong> ví<strong>de</strong>o. El framework requiere <strong>de</strong> la integración <strong>de</strong>diversos lenguajes y herramientas <strong>de</strong> programación,<strong>de</strong> algoritmos y operaciones necesarias para abordarproblemas <strong>de</strong> visión y <strong>de</strong> la computación paralelay distribuida para conseguir tiempos <strong>de</strong> respuestafactibles. En estos momentos disponemos <strong>de</strong> unprimer prototipo funcional y esperamos en el futuropo<strong>de</strong>r cubrir las siguientes funcionalida<strong>de</strong>s:• Computacional– Paralelización usando OpenMP– Cliente y servidor OpenCF– Almacenamiento compartido– Planificador <strong>de</strong> tareas• Visión– Lectura y escritura <strong>de</strong> ví<strong>de</strong>os– Detección fondo (fijo y móvil)– Detección objeto y sus coor<strong>de</strong>nadas 2D– Múltiples frames con texto y dibujos• Calculos– Transformacion 2D-3D– Cálculo <strong>de</strong> velocidad y trayectoriasVI. Agra<strong>de</strong>cimientosEste proyecto ha sido parcialmente financiado confondos (FEDER) por los proyecto TIN2008-06570-C04-03 <strong>de</strong>l plan nacional I+D+I <strong>de</strong>l MEC y porel proyecto SolSubC200801000307 <strong>de</strong>l Gobierno <strong>de</strong>Canarias.Referencias[1] Francisco Almeida, Vicente Blanco Pérez, Carlos Delgado,Francisco <strong>de</strong> San<strong>de</strong>, and Adrián Santos, “I<strong>de</strong>wep: Webservice for astronomical parallel image <strong>de</strong>convolution,” J.Network and Computer Applications, vol. 32, no. 1, pp.293–313, 2009.[2] ULL Parallel Computing Group. Open computationalframework. http://opencf.pcg.ull.es/[3] Intel Corporation, Willow Garage, et all.<strong>JP2011</strong>-511


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-512


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011R en la nubeJuan Carlos Castillo, Francisco Almeida, Vicente Blanco, Adrián Santos 1Palabras clave Computación en paralelo, sistemasheterogéneos, servicios webs, cloud computing,lenguajes interpretados, RResumen Una <strong>de</strong> las principales metas <strong>de</strong> los entornosorientados a cloud computing es la <strong>de</strong> ofrecerel acceso a recursos distribuidos mediante interfaces ytecnologías basados en servicios web. OpenCF es unaherramienta que comparte estos objetivos y que pue<strong>de</strong>ser utilizada com plataforma <strong>de</strong> <strong>de</strong>sarrollo con la queofertar el hardware y software como servicio. En estetrabajo incorporamos las rutinas <strong>de</strong>l paquete estadísticoR a un portal <strong>de</strong> cómputo basado en OpenCF.Asismimo, contemplamos la opción <strong>de</strong> que el usuariopueda lanzar sus propios scripts <strong>de</strong> ejecución R através <strong>de</strong>l portal y a<strong>de</strong>más que estos scripts puedanser incorporados, por usuarios no expertos, al portal<strong>de</strong> cómputo como un servicio más. <strong>La</strong> propuesta quehacemos requiere la gestión <strong>de</strong> la automatización y <strong>de</strong>la incorporación dinámica <strong>de</strong> servicios.I. IntroducciónActualmente, los entornos basados en Cloud Computingpresentan las siguientes características [1]:dominios <strong>de</strong> administración múltiple, heterogeneidad,escalabilidad, y dinamicidad o adaptabilidad.Sistemas <strong>de</strong> gran escala aña<strong>de</strong>n la dicultad <strong>de</strong> gestionargran cantidad <strong>de</strong> recursos. Estándares enservicios web proveen un incremento en el nivel <strong>de</strong>usabilidad, extensibilidad e interoperabilidad entreparejas <strong>de</strong> servicios. <strong>La</strong> adopción <strong>de</strong> estas tecnologíasen el contexto <strong>de</strong> Grid y Cloud Computing ha mejoradoel uso eciente <strong>de</strong> los recursos computacionales.Proyectos como Globus [2] o OpenCF [3], [4], [5] hansido generados basados en tecnologías <strong>de</strong> serviciosweb para gestionar recursos computacionales: monitorización<strong>de</strong> sistemas o gestión y planicación <strong>de</strong>tareas entre otras.Open Computational Framework (OpenCF) facilitael acceso a recursos <strong>de</strong> computación <strong>de</strong> altasprestaciones para aquellos usuarios que lo <strong>de</strong>seen.<strong>La</strong> i<strong>de</strong>a principal es erradicar la barrrera tecnológicay <strong>de</strong> conocimiento a la que se enfrentanlos usuarios cuando intentan acce<strong>de</strong>r a los Sistemas<strong>de</strong> Computación <strong>de</strong> Altas Prestaciones (High PerformanceComputing Systems o HPCS). OpenCF haadoptado extensiblemente la tecnología <strong>de</strong> serviciosweb para su implementación. Monitorización <strong>de</strong>lrendimiento <strong>de</strong> sistemas o <strong>de</strong>scripción <strong>de</strong> recursoscomputacionales son ofertados a los usuarios comoservicios web. Propone <strong>de</strong>sacoplar en diferentes serviciosweb las tareas <strong>de</strong>sarrolladas por un planicador,<strong>de</strong>s<strong>de</strong> que estos servicios pue<strong>de</strong>n ser usadosen aplicaciones cliente <strong>de</strong> terceros. Su composiciónnos lleva a un meta-planicador distribuido basadoen una plataforma <strong>de</strong> servicios web que proporcionaun amplio rango <strong>de</strong> aplicaciones. Monitorización <strong>de</strong>1 Dept. <strong>de</strong> Estadística. I.O. y Computación. <strong>Universidad</strong> <strong>de</strong><strong>La</strong> <strong>La</strong>guna e-mail: falmeida@ull.esFig. 1OpenCF ofreciendo servicios <strong>de</strong> <strong>de</strong>scubrimiento,monitorización y planificación para systemas HPCsistemas, caraterización <strong>de</strong> la carga, <strong>de</strong>scripción <strong>de</strong>los HPC o políticas <strong>de</strong> planicación <strong>de</strong> tareas pue<strong>de</strong>ser implementadas como servicios web estándar.Uno <strong>de</strong> los principales problemas a los que seenfrentan los usuarios <strong>de</strong> los HPC es la portabilidad<strong>de</strong> sus aplicaciones o scripts. <strong>La</strong> compilación<strong>de</strong> código fuente o ejecución <strong>de</strong> archivos binariosestá fuertemente ligada a la plataforma don<strong>de</strong> sequiera operar, limitando la capacidad <strong>de</strong> pluralidad<strong>de</strong> las infraestructuras existentes. Los lenguajes interpretados(como Perl, Matlab, IDL, Mathematicao Python) son una alternativa bastante robusta parasortear este problema, puesto que el rendimiento enestos lenguajes ha ido aproximándose poco a poco al<strong>de</strong> los lenguajes compilados [6].En este trabajo presentamos las modicacionesen la arquitectura tenidas en cuenta para soportarejecución <strong>de</strong> tareas <strong>de</strong> lenguajes interpretados(poniendo como caso <strong>de</strong> uso el lenguaje R [7]). <strong>La</strong>solución propuesta permite la generación automática<strong>de</strong> servicios, así como la incorporación <strong>de</strong> nuevosservicios <strong>de</strong> forma dinámica. El usuario incorporaríanuevos servicios <strong>de</strong> cómputo que quedaríandisponibles para otros investigadores.Es trabajo se ha estructurado como sigue: lasección II introduce la infraestructura OpenCF,hablaremos brevemente <strong>de</strong> los lenguajes interpretadosen III, y el soporte <strong>de</strong> estos lenguajes (enel caso particular <strong>de</strong> R) en OpenCF será cubiertoen la sección IV. Finalmente concluimos el trabajocon algunas consi<strong>de</strong>raciones y comentarios acerca <strong>de</strong>lproyecto en IV-C.<strong>JP2011</strong>-513


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 2<strong>La</strong> arquitectura OpenCF.II. <strong>La</strong> arquitectura OpenCFEs importante conocer la arquitectura <strong>de</strong> OpenCF,pues es la plataforma sobre la que se ha trabajado.<strong>La</strong> arquitectura software <strong>de</strong> OpenCF se muestra enla gura 2. Tal y como se enuncia en [3], [4], [5]<strong>de</strong>staca por un diseño modular: módulo servidor ymódulo cliente. Los módulos pue<strong>de</strong>n ser extendidosin<strong>de</strong>pendientemente e incluso reemplazados paraproveer nuevas funcionalida<strong>de</strong>s sin alterar el resto<strong>de</strong> componentes <strong>de</strong>l sistema (como por ejemplo, elmódulo servidor <strong>de</strong> PyOpenCF adaptado al GAE??). El cliente y el servidor implementan las trescapas inferiores <strong>de</strong> la pila que <strong>de</strong>scriben los serviciosWeb: Descripción <strong>de</strong> Servicios, Mensajería XML yTransporte. El cuarto nivel, Descubrimiento <strong>de</strong> Servicios,no ha sido implementado por motivos <strong>de</strong> seguridad.Por tanto, los administradores <strong>de</strong> sistemasiguen controlando el acceso por parte <strong>de</strong> los clientesa las plataformas paralelas a través <strong>de</strong> técnicas tradicionales<strong>de</strong> autenticación.A. Módulo clienteEl módulo cliente es la interfaz entre el usuarional y el sistema. Los usuarios se registran en elsistema a través <strong>de</strong> un formulario. Alguno <strong>de</strong> loscampos requeridos son necesarios por motivos <strong>de</strong> seguridad,mientras que el resto son utilizados parala gestión <strong>de</strong> tareas. Esta información estará almacenadaen la base <strong>de</strong> datos asociada al módulo. Acontinuación se muestra la lista <strong>de</strong> submódulos <strong>de</strong>lcliente.• <strong>La</strong> Base <strong>de</strong> datos almacena la información <strong>de</strong>usuarios, servidores, tareas, cheros <strong>de</strong> entraday salida, etc. Se ha implementado una base <strong>de</strong>datos relacional MySQL a la que se acce<strong>de</strong> mediantescripts en PHP• El Procesador <strong>de</strong> Peticiones consiste en unainterfaz web a la que el usuario pue<strong>de</strong> acce<strong>de</strong>r yobtener la lista <strong>de</strong> aplicaciones disponibles comotareas en los distintos servidores que tiene acceso.Cada entrada en la lista muestra una pequeña<strong>de</strong>scripción <strong>de</strong> la rutina y los servidoresque la ofrecen. Cuando la ejecución <strong>de</strong> una tareaes solicitada, el servidor es seleccionado implícitamenteacor<strong>de</strong> a unas reglas <strong>de</strong> planicación.Los parámetros <strong>de</strong> entrada se insertan en unformulario XHTML generado dinámicamente apartir <strong>de</strong> la <strong>de</strong>scripción <strong>de</strong>l servicio.• El Recolector gestiona la salida <strong>de</strong> las tareasgenerada por el servidor. El servidor notica alusuario mediante un email cuando la tarea naliza.El estado <strong>de</strong> las tareas ejecutadas pue<strong>de</strong> serconsultado también en la interfaz web, así comoobtener los cheros <strong>de</strong> salida <strong>de</strong> la tarea una veznalizada ésta. A<strong>de</strong>más, se ofrece la posibilidad<strong>de</strong> cancelar tareas no nalizas o eliminar registro<strong>de</strong> las ya concluídas.B. El servidorEl servidor gestiona todo lo relacionado con tareas,ofertándolas como servicios web y controlandosu estado y ejecución. Requiere <strong>de</strong> un servidor web(normalmente Apache) para la gestión <strong>de</strong> consultas.Cuando una consulta es requerida por un cliente, elservidor web crea un hilo <strong>de</strong> ejecución in<strong>de</strong>pendientecon una nueva instancia <strong>de</strong>l módulo servidor.• El Procesador <strong>de</strong> Consultas consiste en unconjunto <strong>de</strong> scripts PHP responsables <strong>de</strong> distribuirlas tareas por los diferentes componentes.<strong>La</strong>s consultas direccionadas por el sistemacomputacional son enviadas a la interfaz<strong>de</strong> gestión <strong>de</strong> colas, y el resto <strong>de</strong> consultasson servidas por el procesador <strong>de</strong> consultas.El servicio web también es generado y ofertadopor este módulo. El documento <strong>de</strong> <strong>de</strong>scricpión<strong>de</strong> servicios (WSDL) es automáticamente generadoy actualizado por la clase NuSOAP <strong>de</strong> PHP.Esta clase también maneja la encapsulación <strong>de</strong>mensajes SOAP <strong>de</strong> los paquetes.• <strong>La</strong> Interfaz <strong>de</strong> Gestión <strong>de</strong> Colas controla lainteracción con el sistema <strong>de</strong> colas <strong>de</strong>l HPCS. Elservidor necesita conocer cómo una tarea pue<strong>de</strong>ser ejecutada y como consultar el estado <strong>de</strong> unatarea en ejecución en el sistema. Para ello, dosmétodos <strong>de</strong> la clase OpenCFJob <strong>de</strong> PHP han<strong>de</strong> ser reescritas y adaptadas para cada servidor.Estos métodos permiten la ejecución <strong>de</strong>una tarea bajo la cola <strong>de</strong>l sistema y la consulta<strong>de</strong> su estado. A<strong>de</strong>más, una <strong>de</strong>scripción XML <strong>de</strong>cada rutina es necesaria para <strong>de</strong>scribir la tarea.• El Generador <strong>de</strong> scrips produce los scriptsnecesarios para la ejecución <strong>de</strong> las tareas bajo<strong>JP2011</strong>-514


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011distintos sistemas <strong>de</strong> colas. Está compuestopor un conjunto <strong>de</strong> plantillas más un motor <strong>de</strong>procesamiento para generar el script. Diferentesplantillas son necesarias para cada una <strong>de</strong> losgestores <strong>de</strong> colas soportados. <strong>La</strong> plantilla esinstanciada en un script funcional por el motor<strong>de</strong> procesamiento mediante la sustitución <strong>de</strong>un conjunto <strong>de</strong> campos pre<strong>de</strong>terminados. Estoscampos son obtenidos <strong>de</strong> los datos <strong>de</strong> entrada<strong>de</strong>l servicio, <strong>de</strong>l documento <strong>de</strong> <strong>de</strong>scrpción<strong>de</strong> servicios XML y <strong>de</strong> la información <strong>de</strong> usuarioguardada en la base <strong>de</strong> datos <strong>de</strong>l cliente.• El <strong>La</strong>uncher es la interfaz entre OpenCF y el sistemaoperativo, lanza en segundo plano la tareaa ejecutar, obtiene su i<strong>de</strong>nticador y <strong>de</strong>sbloqueala consulta realizada por el cliente. <strong>La</strong> implementaciónestá basada en Perl para hacerla in<strong>de</strong>pendiente<strong>de</strong> cada arquitectura. En futurasversiones y relativo a gestión <strong>de</strong> usuarios y grupos,este módulo será el responsable <strong>de</strong> colectary reportar la información tanto <strong>de</strong> usuario como<strong>de</strong> grupo conforme a los recursos <strong>de</strong>l sistema.• El Recolector es la interfaz que <strong>de</strong>spacha los resultadosproducidos por las distintas ejecuciones<strong>de</strong> las tareas. Una vez una tarea es nalizada,la cola <strong>de</strong>l sistema automáticamente envía unemail al usuario y mueve los cheros <strong>de</strong> salidaa un directorio <strong>de</strong> <strong>de</strong>scargas para que pueda ser<strong>de</strong>scargado por el recolector <strong>de</strong>l cliente.III. Lenguajes interpretadosEl aumento <strong>de</strong> lenguajes interpretados comoPython, VisualBasic, MATLAB, IDL, Maple yMathematica para el <strong>de</strong>sarrollo <strong>de</strong> algoritmos, prototipos,análisis <strong>de</strong> datos e interfaces grácas <strong>de</strong>usuario (GUI) representa una ten<strong>de</strong>ncia importanteen la ingeniería <strong>de</strong> software. Sin embargo, utilizar loslenguajes interpretados en un HPCS actualmente esun reto en ámbitos académicos y cientícos. Des<strong>de</strong>el punto <strong>de</strong> vista <strong>de</strong>l ámbito cientíco, la mayoría<strong>de</strong> las soluciones proporcionadas a problemas abordadoscon lenguajes interpretados suelen solucionesparciales, como por ejemplo utilizar un lenguaje interpretadopara establecer un cálculo y luego interactuarcon un núcleo <strong>de</strong> cálculo escrito en un lenguajecompilado (por ejemplo, C, C++, Fortran) [8]. Sinembargo, esta ten<strong>de</strong>ncia ha ido cambiando en los últimosaños y po<strong>de</strong>mos encontrar soluciones integralesa problemas con alto grado <strong>de</strong> cómputo en lenguajesinterpretados, como por ejemplo SOLVCON [9], unentorno software en python para resolver ecuacionesdiferenciales parcialmente hiperbólicas. El paqueteestadístico R es un ejemplo <strong>de</strong> herramienta basadaen lenguajes interpretados que está ampliamente difundido,es usado por cientícos en general y pormatemáticos y estadísticos en particular. En función<strong>de</strong> los datos <strong>de</strong> entrada el cómputo a <strong>de</strong>sarrollarpue<strong>de</strong> requerir el uso <strong>de</strong> HPCS, este hecho justi-ca la aparición <strong>de</strong> una interfaz <strong>de</strong> R para MPI [10].Nos proponemos en este trabajo la incorporación <strong>de</strong>llenguaje R [7] en la plataforma OpenCF con distintasfuncionalida<strong>de</strong>s. Mediante estas funcionalida<strong>de</strong>s, elusuriario podrá lanzar sus scripts en una máquina <strong>de</strong>cálculo <strong>de</strong> una forma amigable que oculta los <strong>de</strong>talles<strong>de</strong> implementación inherentes a la dinámica <strong>de</strong> losHPCS. Con nuestra estrategia los códigos <strong>de</strong>sarrolladospor un usuario se incorporían dinámicamentea la plataforma para que puedan ser utilizados porotros usuarios.IV. R en la nube<strong>La</strong> mayoría <strong>de</strong> los entornos <strong>de</strong> <strong>de</strong>sarrollo basadosen servicios web ofrecen facilida<strong>de</strong>s para incluir serviciosa los que se pue<strong>de</strong> acce<strong>de</strong>r a través <strong>de</strong> unainterfaz web. Sin embargo, es cierto que estos entornosno proveen mecanismos automáticos generalespara añadir nuevos servicios web <strong>de</strong>s<strong>de</strong> códigos <strong>de</strong>usuarios. Típicamente, exportar un servicio implicareescribir o adaptar el servidor <strong>de</strong> servicios web y<strong>de</strong>scribir el servicio a través <strong>de</strong> una interfaz XML,implicando en la práctica una tarea laboriosa para<strong>de</strong>sarrollar por parte <strong>de</strong>l programador. Cuando elnúmero <strong>de</strong> servicios web es limitado es una tareaabordable; sin embargo, cuando el número <strong>de</strong> serviciosa gestionar supera un cierto tamaño (cientos omiles <strong>de</strong> servicios), se <strong>de</strong>be negociar con herramientasautomáticas para po<strong>de</strong>r gestionar dichos servicios.Unos <strong>de</strong> los problemas encontrados durante el diseño<strong>de</strong> OpenCF es el trabajo necesario para añadirnuevos servicios al mismo. Si el número <strong>de</strong> rutinasque queremos ofertar es limitado el trabajo <strong>de</strong>añadirlas es asumible, únicamente se ha <strong>de</strong> <strong>de</strong>nir la<strong>de</strong>scripción <strong>de</strong>l trabajo y comprobar que el códigocumple con los requisitos <strong>de</strong> OpenCF. Sin embargo,si <strong>de</strong>seamos trabajar con un número mayor <strong>de</strong> trabajos(cientos o incluso miles), tenemos que crearun mecanismo automatizado para llevar a cabo estatarea.<strong>La</strong> solución <strong>de</strong>sarrollada está basada en el análisis<strong>de</strong>l código fuente <strong>de</strong> las rutinas a exportar como trabajos.Se han analizado varias librerías que acometeneste trabajo. Generalmente, estas librerías trabajananalizando el código fuente y generando una<strong>de</strong>scripción XML. Esta manera <strong>de</strong> trabajar se ajustasin problemas a OpenCF ya que la <strong>de</strong>scripción <strong>de</strong> lostrabajos usadas también está basada en XML. A losumo lo único necesario sería realizar alguna transformaciónXSLT <strong>de</strong> la salida generada por la libreríapara ser traducida al esquema usado por OpenCF.El objectivo <strong>de</strong> adaptar OpenCF para po<strong>de</strong>r ejecutarlenguajes interpretados no fue sino el comienzo<strong>de</strong> un amplio camino por recorrer. Con R se consiguióuna plataforma <strong>de</strong> pruebas para la generacióndinámica <strong>de</strong> servicios webs, así como otras utilida<strong>de</strong>s(ejecución <strong>de</strong> código subido por el usuario y ofertaslas principales funciones <strong>de</strong> R como servicios web).Los principales problemas que se encontraron fueronlos siguientes:• I<strong>de</strong>nticar las rutinas que han <strong>de</strong> ser exportadascomo servicios. <strong>La</strong> lista <strong>de</strong> servicios a exportar<strong>de</strong>be ser conocida previamente.<strong>JP2011</strong>-515


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 3Lista <strong>de</strong> servicios agregadosFig. 4Ejecución <strong>de</strong> un nuevo servicio• I<strong>de</strong>nticar los tipos <strong>de</strong> datos asociados a los servicios.Los usuarios nales <strong>de</strong>berán introducirlos argumentos <strong>de</strong>l servicio a ejecutar a través<strong>de</strong> la interfaz web <strong>de</strong>l cliente. Una especicacióngenérica es necesaria para <strong>de</strong>sarrollar la interfaz<strong>de</strong> servicios, y lo sucientemente simple para serabordable en la práctica por un usuario normal.• Es muy dicil distinguir entre argumentos <strong>de</strong>salida y entrada a una rutina únicamente analizandola cabecera <strong>de</strong> la rutina. Podríamos<strong>de</strong>sarrollar una heurística basada en el uso <strong>de</strong>const, punteros, etc. pero se <strong>de</strong>bería ajustar acada tipo <strong>de</strong> código. Otra solución consiste enanotar los códigos, por ejemplo, haciendo uso <strong>de</strong>una sintaxis dada en los comentarios para <strong>de</strong>scribircada uno <strong>de</strong> los argumentos (por ejemplo<strong>JP2011</strong>-516


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 5Listado y ejecución <strong>de</strong>s<strong>de</strong> consolaFig. 6Agregar un nuevo servicio dinámicamente.basada en javadoc, etc.).• Generar la interfaz <strong>de</strong> servicios, la información<strong>de</strong> ayuda para el usuario y el código binario paraofrecer los nuevos servicios.A. Principales funciones <strong>de</strong> R como servicios webHaciendo uso <strong>de</strong>l script get.xml.py escrito enpython y haciendo uso <strong>de</strong> la librería rpy (que integrapython y R), se consiguió parsear la documentación<strong>de</strong> R y generar para cada función un chero XMLque <strong>de</strong>scribe dicha función como servicio web (es<strong>de</strong>cir, especicando sus argumentos <strong>de</strong> entrada, <strong>de</strong>salida, <strong>de</strong>scricpiones y nombre <strong>de</strong>l servicio). Comoejecutable se escribió un wrapper en perl para ejecutaruna llamada a la función seleccionada <strong>de</strong> R conlos argumentos pasados por el servicio web (wrapper.func.pl).Con esto se agregaron como servicioweb algunas <strong>de</strong> las funciones <strong>de</strong> R <strong>de</strong>l paquete basey <strong>de</strong>l paquete utils. Los pasos a seguir para agregaruna nueva función son:1. Ejecutar el script get.xml.py pasándole comoargumento en paquete <strong>de</strong> R don<strong>de</strong> se encuentrala función func.name.2. Copiar el chero func.name.xml al directorioxml <strong>de</strong>l servidor OpenCF.3. Ejecutar el binario bim/addjob.pl pasándolecomo argumento la ruta al xml anterior.<strong>JP2011</strong>-517


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20114. Como resultado se obtendrá un cherofunc.name.php en el directorio problems <strong>de</strong>lservidor. Asegurarse <strong>de</strong> que tiene permisos <strong>de</strong>ejecución.5. Realizar una llamada al nuevo servicio web<strong>de</strong>s<strong>de</strong> un cliente para comprobar el funcionamientocorrecto.No todas las funciones <strong>de</strong> R pue<strong>de</strong>n ser ofrecidascomo servicio web (por ejemplo, los operadores aritméticos).Para evitar servicios incorrectos, se guardaun listado <strong>de</strong> funciones no compatibles como serviciosweb para evitar la generación <strong>de</strong> cheros XMLincorrectos. Una lista <strong>de</strong> funciones añadida medianteeste procedimiento pue<strong>de</strong> ser consultada en lagura 3. Como ejemplo, pue<strong>de</strong> verse en la gura 4 elformulario generado para la función media.B. Ejecución <strong>de</strong> scripts <strong>de</strong> R en OpenCFUn objetivo fundamental <strong>de</strong>l proyecto es que elusuario pueda lanzar sus propios scritps a la máquina<strong>de</strong> cómputo. Con el script rwrapper.script.pl se consiguióejecutar scripts <strong>de</strong> R proporcionados por elusuario <strong>de</strong> forma aislada. Para ello, se ha creado unchero XML <strong>de</strong>scribiendo el servicio en cuestión, querequiere <strong>de</strong>l nombre <strong>de</strong>l script principal a ejecutar y<strong>de</strong>l chero R o un chero .zip con los scripts necesariospara la ejecución <strong>de</strong>l principal. <strong>La</strong> ejecución<strong>de</strong>l script R aportado como entrada podría generarvarios cheros <strong>de</strong> resultados. Es por ello que comoresultado <strong>de</strong>l servicio, el usuario <strong>de</strong>scarga un cherocomprimido que contiene los resultados y a<strong>de</strong>más lapropia entrada <strong>de</strong>l servicio. <strong>La</strong> gura 5 muestra lainterfaz en modo línea <strong>de</strong> comandos <strong>de</strong> OpenCF quepermite lanzar los trabajos <strong>de</strong> forma remota. Se observael servicio executerscript que permite lanzar suejecución. Los pasos a seguir para su uso son:1. Ejecutar el servicio web con los parámetrosnecesarios2. El wrapper prepara el entorno <strong>de</strong> ejecución yejecuta el script, generando los resultados oportunos.3. Descargar los resultados.C. Generación dinámica <strong>de</strong> servicios webEl objetivo <strong>de</strong> la generación dinámica <strong>de</strong> serviciosen OpenCF es dotar a los servidores <strong>de</strong> una mayoroferta <strong>de</strong> servicios <strong>de</strong> forma automática o semiautomática.Este servicio permite a un usuario <strong>de</strong>nirun nuevo servicio web que ejecuta un script R subidoal servidor por él. Para agregar un nuevo servicio, senecesita el script (o scripts) en R y un chero XMLque <strong>de</strong>scriba el trabajo, como muestra la imagen 6.<strong>La</strong> manera <strong>de</strong> elaborar un nuevo servicio web consta<strong>de</strong> tres pasos:1. Generar el script (o scripts) en R2. Hay que elaborar un chero XML que <strong>de</strong>scribael trabajo a servir.3. Ejecutar la tarea <strong>de</strong> agregar servicios dinámicamentecon los parámetros anteriores4. Comprobar que el servicio se agregó correctamente.Con esto conseguimos un nuevo servicio web presenteen el servidor don<strong>de</strong> se lanzó la ejecución listopara ser llamado por los clientes <strong>de</strong> OpenCF.V. ConclusiónTecnologías basadas en servicios web han emergidocomo alternativa tecnológica para los portales webcomputacionales. Facilitando el acceso a recursosdistribuidos a traves <strong>de</strong> interfaces web mientras quese asegura la seguridad simultáneamente es una <strong>de</strong>las principales metas en la mayoría <strong>de</strong> las herramientasy entornos <strong>de</strong> <strong>de</strong>sarrollo existentes. OpenCF,el entorno <strong>de</strong> <strong>de</strong>sarrollo computacional Open Sourceque hemos <strong>de</strong>sarrollado, comparte estos objetivos yaña<strong>de</strong> otros, como portabilidad, generidad, modularidady compatibilidad con un amplio rango <strong>de</strong> Sistemas<strong>de</strong> Computación <strong>de</strong> Alto Rendimiento. Con laincursión <strong>de</strong> los lenguajes interpretados hemos añadidoun valor extra a OpenCF ampliando consi<strong>de</strong>rablementelas posibilida<strong>de</strong>s para los usuarios nales,haciendo la plataforma aún más in<strong>de</strong>pendiente y exibleen cuanto se reere a la gestión <strong>de</strong> tareas porparte <strong>de</strong> los administradores y a la ejecución <strong>de</strong> lasmismas por parte <strong>de</strong> los usuarios. Con la posibilidad<strong>de</strong> agregar servicios web <strong>de</strong> forma dinámica se consigueun mayor grado <strong>de</strong> libertad y participación porparte <strong>de</strong> los usuarios, agilizando aún más el procesopara po<strong>de</strong>r ejecutar una tarea <strong>de</strong>s<strong>de</strong> 0 en los HPCS.AcknowlegementsEste trabajo ha sido parcialmente subvencionadopor la EC F(EDER) y la MICINN Española (PlanNacional <strong>de</strong> I+D+I, TIN2008-06570-C04-03).Referencias[1] Mark Baker, Rajkumar Buyya, and Domenico <strong>La</strong>forenza,Grids and grid technologies for wi<strong>de</strong>-area distributedcomputing, Softw., Pract. Exper., vol. 32, no. 15, pp.14371466, 2002.[2] Globus Toolkit: Open source software toolkit for buildingGrid systems,http://www.globus.org.[3] OpenCF project webpage, http://opencf.pcg.ull.es/.[4] A. Santos, F. Almeida, and V. Blanco, Lightweightweb services for high performace computing, in EuropeanConference on Software Architecture ECSA2007,Madrid, Spain, Sept. 2007, number 4758 in Lecture Notesin Computer Science, Springer-Verlag, Berlin, Hei<strong>de</strong>lberg.[5] Francisco Almeida, Vicente Blanco, Carlos Delgado,Francisco <strong>de</strong> San<strong>de</strong>, and Adrian Santos, IDEWEP: Webservice for astronomical parallel image <strong>de</strong>convolution,JNCA, vol. 32, pp. 293313, Jan. 2009.[6] Tia Newhall and Barton P. Miller, Performance measurementof interpreted programs, Lecture Notes inComputer Science, vol. 1470, pp. 146156, 1998.[7] R project, R is a free software environment for statisticalcomputing and graphics., .[8] Jeremy Kepner, Maya Gokhale, Ron Minnich, AaronMarks, and John DeGood, Interfacing interpreted andcompiled languages to support applications on a massivelyparallel network of workstations (mp-now), ClusterComputing, vol. 3, pp. 3544, January 2000.[9] Yung-Yu Chen, software framework for solving hyperbolicpartial dierential equations, 2011.[10] Mpi package for r, http://www.stats.uwo.ca/faculty/yu/Rmpi/.<strong>JP2011</strong>-518


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Comparativa y estudio <strong>de</strong> distribución <strong>de</strong> software<strong>de</strong> cálculo científico en entornos cloud con CVMFSVíctor Fernán<strong>de</strong>z-Albor 1 , Ricardo Graciani 2 , Javier López Cacheiro 3 , Fernando Gomez-Folgar 4 ,Antonio García-Loureiro 5 , Juan José Saborido 6Resumen 1 — En entornos <strong>de</strong> procesado <strong>de</strong> datos que usansistemas distribuidos cada grupo <strong>de</strong> investigación suelenecesitar un software específico para acce<strong>de</strong>r ytransformar los datos existentes. Ello necesita a menudoser <strong>de</strong>scargado e instalado en el propio sistema para po<strong>de</strong>rhacer frente a la correcta ejecución <strong>de</strong>l trabajo. Tiene, portanto, mucho interés el <strong>de</strong>spliegue <strong>de</strong> una infraestructuraque automatice la <strong>de</strong>scarga <strong>de</strong> software, que asegure supresencia en todos los nodos <strong>de</strong> ejecución con laposibilidad <strong>de</strong> ser gestionado externamente por unadministrador <strong>de</strong> versiones, que sea auto-actualizable yque se pueda aplicar también a entornos virtualizados.Todo ello permitiría acelerar la ejecución <strong>de</strong> trabajos,especialmente cuando éstos son cortos, y a<strong>de</strong>más reducir elconsumo <strong>de</strong> ancho <strong>de</strong> banda <strong>de</strong> la subred correspondiente.CVM File System (<strong>de</strong> aquí en a<strong>de</strong>lante CVMFS) es unsistema <strong>de</strong> archivos compatible con tales escenarios. Es unsoftware diseñado para recuperar fácilmente archivos<strong>de</strong>s<strong>de</strong> un servidor HTTP, y que ha sido diseñado por elCERN para dar acceso al software <strong>de</strong> los experimentos <strong>de</strong>LHC en máquinas virtuales. Posee la peculiaridad <strong>de</strong> quese pue<strong>de</strong> montar como un sistema <strong>de</strong> archivos normal através <strong>de</strong> archivos en espacio <strong>de</strong> usuario (FUSE). Debido aque los archivos se comparten a través <strong>de</strong> un servidor web,pue<strong>de</strong> hacer uso <strong>de</strong> servidores proxy Squid para reducir lalatencia <strong>de</strong>ntro <strong>de</strong> una misma subred y redistribuir lacarga <strong>de</strong>l servidor central. CVMFS posee una cachepropia que, añadida a la cache <strong>de</strong>l servidor proxy HTTP,completa un sistema flexible <strong>de</strong> <strong>de</strong>scarga <strong>de</strong> ficheros. Acontinuación se presenta la arquitectura, implementación ypruebas <strong>de</strong> esta solución basada en CVMFS.Palabras clave—Distribución <strong>de</strong> software, CVMFS,Cálculo en la nube, Cloud Computing, Grid, Cálculocientífico.I. INTRODUCCIÓNEn la actualidad existe un gran número <strong>de</strong> grupos <strong>de</strong>investigadores que para po<strong>de</strong>r ejecutar sus trabajos <strong>de</strong>cálculo, por medio <strong>de</strong> sistemas distribuidos, necesitanemplear software específico que normalmente no seencuentra instalado en los nodos <strong>de</strong> computación.1Grupo <strong>de</strong> Física <strong>de</strong> Partículas, <strong>Universidad</strong> <strong>de</strong> Santiago <strong>de</strong>Compostela (USC), e-mail: victormanuel.fernan<strong>de</strong>z@usc.es2 Dpto. <strong>de</strong> Estructura y Constituyentes <strong>de</strong> la Materia (UB),e-mail:graciani@ecm.ub.es3Dpto. <strong>de</strong> Sistemas, Centro <strong>de</strong> Supercomputación <strong>de</strong> Galicia(CESGA), e-mail: jlopez@cesga.es4Dpto. <strong>de</strong> Sistemas, Centro <strong>de</strong> Supercomputación <strong>de</strong> Galicia(CESGA), e-mail: fgfolgar@cesga.es5Dpto. Electrónica y Computación, <strong>Universidad</strong> <strong>de</strong> Santiago <strong>de</strong>Compostela, e-mail: antonio.garcia.loureiro@usc.es2Grupo <strong>de</strong> Física <strong>de</strong> Partículas, <strong>Universidad</strong> <strong>de</strong> Santiago <strong>de</strong>Compostela (USC), e-mail: Juan.Saborido@usc.esHabitualmente, es el propio usuario el encargado <strong>de</strong>efectuar la instalación y gestión <strong>de</strong> este softwareadicional, ya que es necesario para efectuar sussimulaciones, y ello repercute en el tiempo necesariopara ejecutar sus tareas <strong>de</strong> cálculo que vendrá dado porel máximo <strong>de</strong> los tiempos tanto <strong>de</strong> instalación <strong>de</strong>lsoftware en los nodos, como <strong>de</strong> ejecución en losmismos:maxi ∈ N Dmaxj ∈ S iT ij + t iN D = {1,2…,M}S i = {1,2…,N i }N i = Número máximo <strong>de</strong> trabajos en el nodo iT ij = Tiempo <strong>de</strong> ejecución <strong>de</strong>l trabajo j en el nodo it i = Tiempo <strong>de</strong> instalación <strong>de</strong>l software para ejecución<strong>de</strong> trabajos en el nodo iM = Número total <strong>de</strong> nodosi = Nodo en el que ha corrido un <strong>de</strong>terminado trabajoj = Número <strong>de</strong> trabajos en un nodoCon lo cual con el incremento <strong>de</strong>l tiempo <strong>de</strong>instalación <strong>de</strong>l software, va a incrementarse el tiempototal <strong>de</strong> finalización <strong>de</strong> trabajos <strong>de</strong> usuarios.A partir <strong>de</strong> la colaboración con el proyecto Formiga, enel que varios grupos <strong>de</strong> usuarios van a ejecutar sustrabajos en un entorno virtualizado haciendo uso <strong>de</strong>recursos ociosos <strong>de</strong> aulas <strong>de</strong> informática, nace lanecesidad <strong>de</strong> crear una infraestructura que permita queesos trabajos obtengan <strong>de</strong> forma dinámica y escalable elsoftware que necesitan. <strong>La</strong> solución se encuentra en laherramienta CVMFS, que emplea catálogos <strong>de</strong> ficherospara establecer un sistema <strong>de</strong> archivos <strong>de</strong> solo lectura através <strong>de</strong>l protocolo HTTP. Los archivos se transfierenen primer lugar a la caché local <strong>de</strong>l nodo. En CVMFS unvolumen específico se i<strong>de</strong>ntifica por su URL HTTP. Elmontaje <strong>de</strong> un volumen incluye la <strong>de</strong>scarga <strong>de</strong>l catalogo<strong>de</strong> archivos, que contiene la información global sobreque archivos son servidos a través <strong>de</strong> HTTP. <strong>La</strong>sversiones <strong>de</strong> software las mantiene inmutables, dándoselugar a nuevas versiones a partir <strong>de</strong> las actualizaciones yparches. Por otra parte, los archivos <strong>de</strong> catálogo <strong>de</strong>gran<strong>de</strong>s volúmenes son divididos en múltiplessubcatálogos creando así versiones más básicas.Actualmente, CVMFS provee el software a distintosgrupos <strong>de</strong> usuarios <strong>de</strong>l CERN, y está integrado en los<strong>JP2011</strong>-519


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011centros <strong>de</strong> procesos <strong>de</strong> datos <strong>de</strong>l TIER-0 y TIER-1. <strong>La</strong>forma en la que CVMFS trabaja, permite que se pueda<strong>de</strong>splegar en cualquier tipo <strong>de</strong> entorno. Por lo tanto, apriori parece la herramienta idónea para que distintosgrupos <strong>de</strong> usuarios, minimicen sus tiempos <strong>de</strong> ejecuciónpermitiéndoles emplear el software que necesitan, sin lanecesidad <strong>de</strong> <strong>de</strong>scargarlo directamente.En este artículo se preten<strong>de</strong> analizar y compararlos resultados obtenidos empleando CVMFS frente a la<strong>de</strong>scarga directa y la instalación <strong>de</strong>l software por parte<strong>de</strong>l usuario. El presente artículo está organizado <strong>de</strong> lasiguiente forma: la segunda sección <strong>de</strong>scribe el CVMFS;en la tercera, se <strong>de</strong>talla la infraestructura y el <strong>de</strong>spliegue<strong>de</strong> CVMFS; en la cuarta sección se <strong>de</strong>scriben laspruebas realizadas; en la quinta, los resultados;finalmente, las conclusiones se incluyen en la sextasección.II.DESCRIPCIÓN DEL CERNVM FILE SYSTEMEl sistema CVMFS ha sido optimizado para ladistribución <strong>de</strong>l software <strong>de</strong> los distintos grupos <strong>de</strong>trabajos <strong>de</strong>l CERN, y ha sido implementado como unsistema <strong>de</strong> archivos en espacio <strong>de</strong> usuario (FUSE).CVMFS ha sido diseñado para crear un árbol <strong>de</strong>directorios en un servidor web <strong>de</strong> solo lectura, <strong>de</strong> talforma que en el lado <strong>de</strong>l cliente solo se requeriráconectividad HTTP/HTTPS al servidor web. CVMFSrealiza un cacheado en distintos niveles, <strong>de</strong> tal formaque archivos y metadatos se almacenan en la caché <strong>de</strong>ldisco local así como en los servidores <strong>de</strong> respaldo HTTPintermedios, permitiendo que sea escalable hasta un grannúmero <strong>de</strong> clientes.El procedimiento <strong>de</strong> construir, instalar y validarlas versiones <strong>de</strong> software es responsabilidad <strong>de</strong> un gestor<strong>de</strong> versiones. Una vez realizadas estas tareas, se recrea elárbol <strong>de</strong> directorios <strong>de</strong>ntro <strong>de</strong>l repositorio <strong>de</strong> CVMFS.Este repositorio posee un formato particular cuyocontenido es un almacenamiento direccionable<strong>de</strong>nominado ―Shadow tree‖. <strong>La</strong> creación <strong>de</strong>l repositorioincluye la creación <strong>de</strong> los catálogos <strong>de</strong> archivo,compresión <strong>de</strong> archivos, y cálculo <strong>de</strong> los hashes. Porotra parte, los archivos se almacenan <strong>de</strong> forma local,<strong>de</strong>ntro <strong>de</strong> una caché en el servidor, como fragmentos <strong>de</strong>datos SHA1. Se hace esto con el fin <strong>de</strong> explotar laredundancia y utilizar el SHA1 como llave a la hora <strong>de</strong><strong>de</strong>scargar archivos. Esto permite evitar ciertasrestricciones firewall, como por ejemplo, lasprohibiciones <strong>de</strong> <strong>de</strong>scarga <strong>de</strong> archivos root.exe. Una vezrealizadas estas tareas, el nuevo software es publicado através <strong>de</strong>l servidor CVMFS.<strong>La</strong> publicación típica CVMFS sigue los siguientespasos:Crear los cambios necesarios en el ―shadow tree‖,añadir nuevos directorios, path <strong>de</strong> binarios, etc.Probar la instalación <strong>de</strong> software.Ejecutar la opción <strong>de</strong> sincronización con los nuevospaquetes añadidos.Publicar a través <strong>de</strong>l servidor web en el directoriopúblico.Fig. 1. Proceso para la publicación <strong>de</strong> una nueva versión <strong>de</strong>ntro <strong>de</strong>lrepositorio <strong>de</strong> software. Una vez finalizado el proceso <strong>de</strong>sincronización <strong>de</strong> CVMFS, está disponible a través <strong>de</strong> HTTP.III.INFRAESTRUCTURA Y DESPLIEGUE DELREPOSITORIO DE CVMFSPara poseer una infraestructura <strong>de</strong> pruebas lomás realista posible, en la que po<strong>de</strong>r comprobar tanto lasescalabilidad <strong>de</strong> la solución, como el montaje rápido ydinámico <strong>de</strong> las versiones <strong>de</strong> software científico, ypensando en po<strong>de</strong>r emplear la solución a un entorno <strong>de</strong>aulas virtualizado, hemos <strong>de</strong>splegado la infraestructurasobre un entorno heterogeneo <strong>de</strong> pruebas, don<strong>de</strong>, por unlado, se tiene un aula virtualizada en el Centro <strong>de</strong>Supercomputación <strong>de</strong> Galicia, por otro los nodos <strong>de</strong> uncluster local al repositorio en la <strong>Universidad</strong> <strong>de</strong>Santiago, y por último, nodos externos en la <strong>Universidad</strong><strong>de</strong> Barcelona.A. <strong>Universidad</strong> <strong>de</strong> Santiago <strong>de</strong> CompostelaPara po<strong>de</strong>r poner en contexto las pruebas,vamos a explicar un poco la infraestructura con la que secuenta. Por un lado, tenemos el repositorio CVMFS quees servido a través <strong>de</strong> Tomcat en una máquinaperteneciente al clúster <strong>de</strong>l TIER-2 <strong>de</strong> LHCb <strong>de</strong> la<strong>Universidad</strong> <strong>de</strong> Santiago <strong>de</strong> Compostela, <strong>de</strong>ntro <strong>de</strong>lmismo se <strong>de</strong>splegará un proxy HTTP Squid, con elobjetivo <strong>de</strong> minimizar los tiempos <strong>de</strong> respuesta, en caso<strong>de</strong> saturación <strong>de</strong>l servidor principal. Hay que tener encuenta que toda la infraestructura va a tener un sistemacacheado que va a intentar minimizar los tiempos <strong>de</strong><strong>de</strong>scarga y montaje <strong>de</strong> los sistemas <strong>de</strong> ficheros. Estesistema <strong>de</strong> cachés estará integrado <strong>de</strong>s<strong>de</strong> el propiorepositorio o servidor HTTP, que tendrá su cachéinterna, pasando por el proxy, hasta el propio nodo conla caché local en don<strong>de</strong> también existirá un tiemporesidual perteneciente, a la interacción con FUSE. <strong>La</strong>interconectividad <strong>de</strong> todos los nodos se realizará conSwichs <strong>de</strong> 100Mb/s.<strong>JP2011</strong>-520


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011B. Centro <strong>de</strong> Supercomputación <strong>de</strong> GaliciaPor otra parte, en el Centro <strong>de</strong>Supercomputación <strong>de</strong> Galicia, se tendrá un aula con unmáster <strong>de</strong>l gestor <strong>de</strong> CloudStack, que permitirá levantarun sistema virtualizado en los nodos a través <strong>de</strong> una red<strong>de</strong> 1Gb/s, <strong>de</strong>s<strong>de</strong> la cual, se habilita una <strong>de</strong> las máquinascon un servidor proxy para mejorar el escalado <strong>de</strong>ntro <strong>de</strong>la misma subred.C. <strong>Universidad</strong> <strong>de</strong> BarcelonaContaremos con nodos <strong>de</strong> cálculo normales,que nos van a permitir comprobar escalado en largasdistancias, don<strong>de</strong> la latencia <strong>de</strong> re<strong>de</strong>s <strong>de</strong> área extensa, esun factor importante a tener en cuenta.El tipo <strong>de</strong> nodos con los que se va a trabajarson, listados en función <strong>de</strong>l organismo al que pertenecenserán:1) <strong>Universidad</strong> <strong>de</strong> Santiago: servidoresDELL PowerEdge SC1425, con dos procesadoresPIV Xeon a 2.8 Ghz y 1 GB <strong>de</strong> RAM por procesador(Fig.2.).2) Centro <strong>de</strong> supercomputación: en el aulavirtualizada, las máquinas anfitriones serán <strong>de</strong>l tipoIntel(R) Core(TM)2 Duo E6750 @ 2.66GHz, siendolas máquinas virtuales <strong>de</strong> 2 Cores, con 1GB <strong>de</strong> RAMy 5GB <strong>de</strong> disco.3) <strong>Universidad</strong> <strong>de</strong> Barcelona: Dual Core AMDOpteron(tm) Processor 256 @ 1,7 GHz, 2 GB <strong>de</strong>RAM y 4 Cores.Fig. 2. Proceso para la publicación <strong>de</strong> una nueva versión <strong>de</strong>ntro <strong>de</strong>lrepositorio <strong>de</strong> software. Una vez finalizado el proceso <strong>de</strong>sincronización <strong>de</strong> CVMFS, está disponible a través <strong>de</strong> HTTP.El mo<strong>de</strong>lo anterior (Fig.2.) tiene todos loselementos necesarios para asegurar una escalabilidad,soportando miles <strong>de</strong> clientes CVMFS con la fiabilida<strong>de</strong>xigida por un sistema <strong>de</strong> archivos, y el rendimientosobre el tipo <strong>de</strong> red más común en re<strong>de</strong>s <strong>de</strong> área local,como las <strong>de</strong> las aulas <strong>de</strong> informática.IV.DESCRIPCIÓN PRUEBAS REALIZADAS<strong>La</strong>s siguientes pruebas tienen la intención <strong>de</strong>medir la sobrecarga <strong>de</strong> CVMFS bajo las cargas <strong>de</strong>trabajo típicas en cálculo científico.Para la realización <strong>de</strong> estas pruebas se hautilizado un programa <strong>de</strong> análisis <strong>de</strong> datos utilizado engrupos <strong>de</strong> Física <strong>de</strong> Altas energías <strong>de</strong>nominado ROOT(TablaI). ROOT, que está formado por librerías <strong>de</strong>software y un programa orientado a objetos <strong>de</strong>sarrolladopor el CERN, y fue <strong>de</strong>sarrollado para el análisis <strong>de</strong> física<strong>de</strong> partículas, conteniendo varias característicasespecíficas <strong>de</strong> este campo. Debido al amplio número <strong>de</strong>ficheros que utiliza ROOT, es la herramienta perfectapara utilizarla en las pruebas <strong>de</strong> software. El programaque se va a utilizar en ROOT ―rf202_exten<strong>de</strong>dmkfit.C‖es un software <strong>de</strong> pruebas que va a permitir generardatos a partir <strong>de</strong> un mo<strong>de</strong>lo numérico, mediante unafunción con una serie <strong>de</strong> parámetros, la cual variará paraajustarlos a otro mo<strong>de</strong>lo completamente distinto. Estonos permite modificar el número <strong>de</strong> eventos con el fin<strong>de</strong> ajustar mejor el mo<strong>de</strong>lo.<strong>La</strong> tabla I muestra algunas <strong>de</strong> las propieda<strong>de</strong>s<strong>de</strong> CVMFS o ROOT, don<strong>de</strong> po<strong>de</strong>mos ver, la cantidad <strong>de</strong>archivos con los que se va a trabajar o el tamaño <strong>de</strong>caché con el que vamos a contar.TABLA ICARACTERÍSTICAS DE LOS PROGRAMAS ROOT Y CVMFS EN CUANTOVersiónA TAMAÑO Y CANTIDAD DE ARCHIVOSTamañototalen MBROOT v.5.28 218(56 tar.gz)Número <strong>de</strong>archivosTamaño medio<strong>de</strong> los archivosen KB4630 2.5CachéCVMFS v.0.2.61 69 628 4.0En las pruebas que se realizarán, se hará lacomparativa <strong>de</strong> CVMFS contra la <strong>de</strong>scarga directa <strong>de</strong>lsoftware <strong>de</strong>s<strong>de</strong> el mismo servidor HTTP. El servidor <strong>de</strong>archivos que se ejecuta es Apache 2.2.3, mientras que elservidor proxy HTTP es Squid en su versión 2.6,teniendo el repositorio CVMFS almacenado en una zona<strong>de</strong> solo lectura <strong>de</strong> los nodos, y utilizando la versión <strong>de</strong>Scientific Linux 5.5. <strong>La</strong>s máquinas virtuales utilizanhipervisores KVM, y se cuenta con la pérdida constanteen la región <strong>de</strong>l 5%.Para compararlo a partir <strong>de</strong> un estado conocido y <strong>de</strong>manera reproducible, todas las cachés serán borradas encada una <strong>de</strong> las baterías <strong>de</strong> pruebas, obteniendo losresultados con la <strong>de</strong>nominada ―caché fría‖, y eligiendoel peor <strong>de</strong> los resultados en cada caso. Con esto lo quequeremos comprobar es la pérdida <strong>de</strong> rendimiento queexistiría en un posible caso real, en don<strong>de</strong> un usuario,nunca haya lanzado sus trabajos en uno o varios nodos,esta parece la simulación más realista ya que se pue<strong>de</strong>comparar a su vez con las pruebas <strong>de</strong> <strong>de</strong>scarga directa,<strong>JP2011</strong>-521


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011en don<strong>de</strong> el usuario tampoco va a poseer el softwarecacheado cuando efectúa la <strong>de</strong>scarga.Y para que las pruebas aún sean lo más realista posible,las primeras baterías <strong>de</strong> pruebas se realizarán lanzandoprimero un trabajo por nodo, mientras que las siguientessimulaciones se lanzará un trabajo por Core, para po<strong>de</strong>rver el incremento <strong>de</strong> carga en caso <strong>de</strong> ejecutar distintostrabajos diferentes sobre los nodos <strong>de</strong> cálculo. En todoslos casos, las ejecuciones empezarán <strong>de</strong> formasimultánea en todos los nodos, por cada batería <strong>de</strong>pruebas que se realice.El algoritmo <strong>de</strong> ejecución para las pruebas semuestra en las tablas II y III.V. RESULTADOSUna vez realizadas las pruebas anteriormente<strong>de</strong>scritas, proce<strong>de</strong>remos a dividirlas en 2 tipos distintos,<strong>de</strong>pendiendo <strong>de</strong> si se ejecuta ROOT como un procesoin<strong>de</strong>pendiente en cada uno <strong>de</strong> los nodos <strong>de</strong> cálculo, o sise ejecuta como un proceso por el número <strong>de</strong> Cores quetenga el nodo sobre el que se <strong>de</strong>sea ejecutar. Habrá quetener en consi<strong>de</strong>ración el impacto <strong>de</strong>l ancho <strong>de</strong> bandaen re<strong>de</strong>s <strong>de</strong> área amplia, don<strong>de</strong> la latencia será máselevada que en re<strong>de</strong>s <strong>de</strong> área local.TABLA IILÓGICA DEL PROGRAMA UTILIZADO PARA REALIZAR LAS PRUEBAS DEENVÍO DE SOFTWARE A TRAVÉS DE CVMFSTest 1: Uso CVMFSInput: no<strong>de</strong> listOutput: time resultsif multicore execution then;ejecutar una iteración en cada core <strong>de</strong> un nodotime A ← mount CVMFSset envtime B ← run rf202_exten<strong>de</strong>dmkfitelseejecutar una iteración en cada nodotime A ← mount CVMFSset envtime B ← run rf202_exten<strong>de</strong>dmkfitif no<strong>de</strong> execution finish thenget_results()umount CVMFSborrar caché Squid en cada Subnetborrar caché cvmfs en cada nodoreturn worst_result;TABLA IIILÓGICA DEL PROGRAMA UTILIZADO PARA REALIZAR LAS PRUEBAS DEENVÍO DE SOFTWARE DESCARGADO DE UN SERVIDOR HTTPTest 2: Descarga directaInput: no<strong>de</strong> listOutput: time resultsif multicore execution then;ejecutar una iteración en cada core <strong>de</strong> un nodotime A ← download rootset envtime B ← run rf202_exten<strong>de</strong>dmkfitelseejecutar una iteración en cada nodotime A ← download rootset envtime B ← run rf202_exten<strong>de</strong>dmkfitif no<strong>de</strong> execution finish thenborrar caché Squid en cada Subnetreturn worst_result;Cada una <strong>de</strong> las pruebas se realizará varias veces paracontrastar todos los resultados, y verificar que nohubiese ocurrido ningún tipo <strong>de</strong> error <strong>de</strong> saturación opicos <strong>de</strong> la red, que les pudiese haber afectado.Fig. 3. Comparativa <strong>de</strong>l tiempo <strong>de</strong> ejecución <strong>de</strong> un trabajo por nodo enuna red <strong>de</strong> área local, entre la <strong>de</strong>scarga directa <strong>de</strong>l software y elmontaje <strong>de</strong> CVMFS.El tiempo real <strong>de</strong> CVMFS (Fig. 3.) es un pocomás bajo en comparación con el tiempo <strong>de</strong> <strong>de</strong>scarga einstalación directa <strong>de</strong> un usuario, hay que tener encuenta que en este tipo <strong>de</strong> pruebas casi no se sufresobrecarga HTTP, ya que éstas se realizan íntegramenteen una red <strong>de</strong> baja latencia, <strong>de</strong>ntro todo <strong>de</strong> la mismasubred, siendo este un caso i<strong>de</strong>al <strong>de</strong> distribución <strong>de</strong>software. En un caso más realista, tanto la <strong>de</strong>scargadirecta, como el repositorio <strong>de</strong> software, necesitarán <strong>de</strong>servidores HTTP <strong>de</strong> respaldo para mejorar laescalabilidad.Fig. 4. Comparativa <strong>de</strong>l tiempo <strong>de</strong> ejecución <strong>de</strong> un trabajo por core enuna red <strong>de</strong> área local, entre la <strong>de</strong>scarga directa <strong>de</strong>l software y elmontaje <strong>de</strong> CVMFS.En la Figura 4 se observa claramente, como alincrementar el número <strong>de</strong> peticiones <strong>de</strong> software, lasaturación <strong>de</strong> la red aumenta, influyendo en el tiempo <strong>de</strong><strong>JP2011</strong>-522


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>de</strong>scarga, ya sea en CVMFS o en la <strong>de</strong>scargadirectamente <strong>de</strong>l paquete. Por tanto, el incremento <strong>de</strong>tiempo en la ejecución <strong>de</strong> programas <strong>de</strong> cálculocientífico, va a tener una relación directa con el número<strong>de</strong> envíos <strong>de</strong> trabajos simultáneos <strong>de</strong>ntro <strong>de</strong> una mismasubred. <strong>La</strong> escasa sobrecarga que se origina en CVMFS,al <strong>de</strong>scargar la aplicación necesaria para ejecutar eltrabajo <strong>de</strong>l usuario, podría verse reducida en unasituación realista. Si trabajos <strong>de</strong>l mismo tipo, corriesensobre el mismo nodo, ocasionaría que parte <strong>de</strong>l softwarenecesario ya estuviese cacheado localmente. EnCVMFS, se controla por otro lado la <strong>de</strong>scarga <strong>de</strong>múltiples copias <strong>de</strong>l mismo archivo mediante un controlseguro <strong>de</strong> su contenido (SHA1-Cache), evitando así larepetición <strong>de</strong> la <strong>de</strong>scarga, <strong>de</strong>bido a que los archivosduplicados se <strong>de</strong>tectan automáticamente, lo que resultaen menos espacio consumido por la caché local, ymenos tráfico <strong>de</strong> red. En estas pruebas, no se hacontemplado esa opción en CVMFS, ya que la caché seborra en cada una <strong>de</strong> las iteraciones <strong>de</strong> pruebas.En estos dos últimos casos no se contemplan ningún tipo<strong>de</strong> efectos externos sobre la latencia, ya que el entorno<strong>de</strong> pruebas está controlado y el repositorio <strong>de</strong>CERNVM, se encuentra <strong>de</strong>ntro <strong>de</strong> la red <strong>de</strong> área local,sobre la cual se efectúan.Fig. 6. Comparativa <strong>de</strong>l tiempo <strong>de</strong> ejecución <strong>de</strong> un trabajo por core enuna red <strong>de</strong> área local virtualizada, entre la <strong>de</strong>scarga directa <strong>de</strong>lsoftware y el montaje <strong>de</strong> CVMFS.En la Figura 6 se pue<strong>de</strong> comprobar lasaturación <strong>de</strong> <strong>de</strong>scarga directa <strong>de</strong> archivos, incrementadapor el número <strong>de</strong> nodos <strong>de</strong> la red, don<strong>de</strong> alcanza picos<strong>de</strong> 6 minutos en el peor <strong>de</strong> los casos, mientras que con elsistema <strong>de</strong> archivos CVMFS, el incremento es menospronunciado. <strong>La</strong> suma <strong>de</strong> tiempos <strong>de</strong> re<strong>de</strong>s <strong>de</strong> alta y bajalatencia, sumado a la limitación <strong>de</strong> la red <strong>de</strong> 100Mb <strong>de</strong>lrepositorio <strong>de</strong> software, hacen que la <strong>de</strong>scarga <strong>de</strong>lsoftware en los nodos virtuales sea un problema <strong>de</strong>escalado a la hora <strong>de</strong> ejecutar múltiples aplicaciones ennodos <strong>de</strong> cálculo científico.Fig. 5. Comparativa <strong>de</strong>l tiempo <strong>de</strong> ejecución <strong>de</strong> un trabajo por nodo enuna red <strong>de</strong> área local virtualizada, entre la <strong>de</strong>scarga directa <strong>de</strong>lsoftware y el montaje <strong>de</strong> CVMFS.Se pue<strong>de</strong> comprobar en la Figura 5 cómo lostiempos reales finales son sensiblemente mejores con eluso <strong>de</strong> CVMFS. El efecto <strong>de</strong>l servidor HTTP <strong>de</strong>respaldo Squid reduce el tiempo y la sobrecarga <strong>de</strong> red<strong>de</strong> alta latencia a través <strong>de</strong> la que se obtiene el software<strong>de</strong> CVMFS. Este es producido en su mayor parte por la<strong>de</strong>scarga <strong>de</strong> ficheros no cacheados en cada una <strong>de</strong> lasrepeticiones. En un entorno en el cual, la cachéestuviese llena, en el caso <strong>de</strong> aplicaciones que utilizasenel mismo software, el contorno <strong>de</strong> la línea <strong>de</strong> la gráfica<strong>de</strong> CVMFS <strong>de</strong>bería <strong>de</strong> ser más lineal, y no <strong>de</strong>notar unincremento tan pronunciado. Por otro lado, se ha podidocomprobar, que el tiempo <strong>de</strong> <strong>de</strong>scarga es sensiblementemayor a los primeros casos <strong>de</strong> pruebas expuestos, peroel resultado final, la suma <strong>de</strong> todos los tiempos, se vereducido <strong>de</strong>bido al tiempo <strong>de</strong> ejecución <strong>de</strong>l software enlos nodos virtuales.Fig. 7. Comparativa <strong>de</strong>l tiempo <strong>de</strong> ejecución <strong>de</strong> un trabajo por nodo enuna red <strong>de</strong> área local virtualizada y sin virtualizar, entre la <strong>de</strong>scargadirecta <strong>de</strong>l software y el montaje <strong>de</strong> CVMFS.En la Figura 7, se pue<strong>de</strong> comprobar que elescalado es in<strong>de</strong>pendiente <strong>de</strong> la mezcla <strong>de</strong> re<strong>de</strong>s connodos virtuales o nodos normales, habiéndose echo laspruebas aumentando en partes iguales el número <strong>de</strong>nodos a escalar, tanto virtuales como normales.<strong>JP2011</strong>-523


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 8. Comparativa <strong>de</strong>l tiempo <strong>de</strong> ejecución <strong>de</strong> un trabajo por core enuna red <strong>de</strong> área local virtualizada y sin virtualizar, entre la <strong>de</strong>scargadirecta <strong>de</strong>l software y el montaje <strong>de</strong> CVMFS.En la Figura 8, el incremento también vamarcado por latencia en estas pruebas. En la <strong>de</strong>scargadirecta <strong>de</strong> archivos, ésta se ve incrementada por elnúmero <strong>de</strong> nodos <strong>de</strong> la red, don<strong>de</strong> alcanza picos <strong>de</strong> 6minutos en el peor <strong>de</strong> los casos, mientras que con elsistema <strong>de</strong> archivos CVMFS, el incremento es menospronunciado, aunque existe un cierto repunte al final,originado por la saturación <strong>de</strong> la red, ya que el tiempo enla <strong>de</strong>scarga <strong>de</strong> archivos se ha visto incrementado.usuario que a través <strong>de</strong> un único punto en común van aser servidos <strong>de</strong> una forma fácil y dinámica, en don<strong>de</strong> elusuario, in<strong>de</strong>pendientemente <strong>de</strong>l grupo al quepertenezca, va a ver reducidos sus tiempos <strong>de</strong>finalización <strong>de</strong> trabajos, y tendrá la posibilidad <strong>de</strong> teneractualizado su software en todo momento. Al utilizar elprotocolo estándar HTTP para todas las comunicaciones,se pue<strong>de</strong> cachear eficientemente el software a distribuir,<strong>de</strong> tal forma que es indiferente la localización física <strong>de</strong>los nodos <strong>de</strong> cálculo, mostrando, así, una clara ventajacon respecto a la <strong>de</strong>scarga e instalación <strong>de</strong>l software porparte <strong>de</strong>l usuario. Este estudio <strong>de</strong>muestra una clarasuperioridad competitiva en cuanto a tiempos totales,para un usuario que necesita enviar múltiples trabajos,en entornos virtuales o nodos normales, que veráreducido su tiempo si lo utiliza, en vez <strong>de</strong> <strong>de</strong>scargarlodirectamente al nodo <strong>de</strong>s<strong>de</strong> el que se ejecute el trabajo.Con lo cual, la aplicación testeada favorece la mejora <strong>de</strong>tiempos para su utilización en entornos <strong>de</strong> aulasinformáticas virtualizadas, <strong>de</strong> varios grupos <strong>de</strong> usuarios,que emplean software <strong>de</strong> instalación distinto entre ellos.AGRADECIMIENTOSAl proyecto y a la gente <strong>de</strong> Formiga-Cloud, a través <strong>de</strong>lcual, se hizo necesario este estudio.Marcos A. Seco, por su colaboración en el <strong>de</strong>sarrollo <strong>de</strong>las pruebas.REFERENCIASFig. 9. Distintas pruebas <strong>de</strong>l tiempo <strong>de</strong> ejecución <strong>de</strong> un trabajo <strong>de</strong>s<strong>de</strong> la<strong>Universidad</strong> <strong>de</strong> Barcelona.En la Figura 9, la latencia <strong>de</strong> las re<strong>de</strong>s <strong>de</strong> áreaextensa vuelve a ser la causa <strong>de</strong>l incremento en eltiempo <strong>de</strong> finalización <strong>de</strong> un trabajo. En comparación eltiempo se reduce a casi la mitad indiferentemente <strong>de</strong>lnúmero <strong>de</strong> trabajos a ejecutar en un nodo.VI.CONCLUSIONES[1] Jakob Blomer, T Fuhrmann , ―A Fully Decentralized File SystemCache for the CernVM-FS‖, Proceedings of 19th InternationalConference on , vol., no., pp.1-6, 2-5 Aug. 2010, doi:10.1109/ICCCN.2010.5560054, 2010[2] B Segal et al., "LHC Cloud Computing with CernVM",Proceedings of the XIII. International Workshop on AdvancedComputing and Analysis Techniques in Physics Research(ACAT10), Jaipur, 2010[3] A Harutyunyan et al., ―Dynamic virtual AliEn Grid sites onNimbus with CernVM‖, J. Phys, 2010[4] P Buncic et al., ―CernVM – a virtual software appliance for LHCapplications‖, J. Phys. , 2010[5] P Buncic et al., "A practical approach to virtualization in HEP",The European Physical Journal Plus, 2011[6] Portable Analysis Environment using Virtualization Technology,Jakob Blomer,December 2010[7] An alternative mo<strong>de</strong>l to distribute VO specific software toWLCG sites: a prototype at PIC based on CernVM file system,Cern, GDB meeting, Elisa <strong>La</strong>nciotti, November 2010[8] Jeffrey Katcher, PostMark:File System Benchmark, 2008[9] Don Capps, Analyzing NFS Client Performance with IOzone,2009[10] CloudStack, http://www.cloud.com[11] IOzone Filesystem Benchmark, http://www.iozone.org[12] LHC Grid http://lcg.web.cern.ch/lcg/[13] CernVM http://cernvm.cern.ch/portal/En la ejecución <strong>de</strong> tareas <strong>de</strong> cálculo científicoes importante la conclusión <strong>de</strong> aquellas en el menortiempo posible, siendo la instalación <strong>de</strong>l propio softwarepara la ejecución por parte <strong>de</strong>l usuario, uno <strong>de</strong> losfactores que más pue<strong>de</strong>n incrementar este tiempo. ConCVMFS, se ha <strong>de</strong>mostrado tanto en entornosvitualizados como en nodos <strong>de</strong> cálculo reales, como sepue<strong>de</strong> crear una infraestructura para varios grupos <strong>de</strong><strong>JP2011</strong>-524


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Multi-Cluster Performance Impact on theMultiple-Job Co-Allocation SchedulingHéctor Blanco, Eloi Gabaldón, Fernando Guirado, Josep Lluís Lérida,1Abstract—Multi-cluster environments are composed of multipleclusters of computers that act collaboratively, andthus allow computational problems to be treated thatrequire more resources than those available in a singlecluster to be <strong>de</strong>alt with. However, the complexityof the scheduling process is greatly increased by theheterogeneity of resources and the co-allocation process,which distributes the tasks of parallel jobs acrosscluster boundaries. In a previous work, the authorspresented a new scheduling strategy ma<strong>de</strong> up of a jobselection function and a linear programming mo<strong>de</strong>lto find the best simultaneously allocation for multiplejobs from the system queue on a heterogeneous multicluster,by applying co-allocation when necessary.In this paper the effectiveness of our proposedscheduling strategy is evaluated un<strong>de</strong>r multiple configurationsfor the multi-cluster environment (computationheterogeneity and network availability) andcompared with other co-allocation strategies from theliterature. The results showed that co-allocation hasa negative effect on the response times when the networkavailability is low. On the other hand, the useof the multiple-job allocation contributes to maximizethe multi-cluster resources usage. By this, our strategywas able to adapt to different multi-cluster configurationsobtaining better scheduling <strong>de</strong>cisions thanthe other schedulers.Keywords—Job Scheduling, Multi-Cluster Heterogeneityand Performance, Co-Allocation, Mixed IntegerProgrammingI. IntroductionComputation problems that require more computationalresources than those offered by a single justcluster can be resolved by the use of multiple clustersin a collaborative manner. These environments,known as multi-clusters, are distinguished from gridsby their use of <strong>de</strong>dicated interconnection networkswith a known topology and more predictable performance[1].A critical aspect of exploiting the resources in amulti-cluster environment is the challenge of schedulingparallel jobs across different clusters [2]. This allocationstrategy, known as co-allocation, can maximizethe job throughput by reducing the queue waitingtimes, and thus, jobs that would otherwise waitin the queue for local resources can begin their executionearlier, improving system utilization and reducingaverage queue waiting time [2][3]. However,mapping jobs across the cluster boundaries can resultin rather poor overall performance when co-allocatedjobs contend for inter-cluster network bandwidth.Additionally, the heterogeneity of processing andcommunication resources increases the complexity ofthe scheduling problem [4][5].The scheduling strategies with co-allocation inmulti-cluster environments have generated great interestin recent years. The performance of differentscheduling strategies using co-allocation based on jobqueues was analyzed in [2]. This work conclu<strong>de</strong>dthat unrestricted co-allocation is not recommen<strong>de</strong>dand limiting the component sizes of the co-allocatedjobs improves performance. Some other studies <strong>de</strong>altwith co-allocation by <strong>de</strong>veloping load-balancing techniques[6][7], selecting the most powerful processors[8] or minimizing the inter-cluster links usage [4].These studies share the optimization of a single performancemetric, such as the computing capabilityor the communication links usage, without finding acompromise between these. In or<strong>de</strong>r to fill this gap, anew analytical mo<strong>de</strong>l was presented in [9] that measuresthe execution time of parallel applications byconsi<strong>de</strong>ring the resource availability of both processorsand communication resources.A common issue in those previous works is thatjobs are allocated individually, consi<strong>de</strong>ring all theavailable resources for them without taking otherjobs in the waiting queue into account. In or<strong>de</strong>rto solve this problem, in [3] we presented a newscheduling strategy, named PAS for Package AllocationStrategy. This strategy selects those jobs fromthe waiting queue that can be concurrently executedwith the available resources. Once the package ofjobs is selected, a Mixed-Integer Programming mo<strong>de</strong>l(MIP) is responsible for finding the best possible resourceallocation for them. The PAS strategy wasevaluated for a pre<strong>de</strong>termined multi-cluster environmentwith different kinds of workload. The resultsshow that applying the PAS strategy, the responsetimes were lower compared with the most commonscheduling strategies in the literature, making betteruse of the resources and preventing the saturation ofthe inter-cluster links.An important result observed in [3] is that the performanceof scheduling strategies is very sensitive tothe availability of resources. In a multi-cluster ma<strong>de</strong>up of different clusters with heterogeneous and non<strong>de</strong>dicatedresources, the availability of resources andtheir capabilities are <strong>de</strong>cisive for the performance ofthe scheduling strategies. Given this, it is necessaryto conduct a more <strong>de</strong>tailed analysis to <strong>de</strong>termine theeffect of the structure of the multi-cluster environmentand the availability of resources on the effectivenessof the previously-tested scheduling strategies.In the present paper, we evaluated thoroughly themulti-cluster configuration and resource availabilityon the effectiveness of different scheduling strategies.We assess the parallel application performance obtainedfor a fixed workload by varying the processorheterogeneity between clusters and the availablebandwidth on the communication links. We con-<strong>JP2011</strong>-525


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 1.Diagram of a multi-cluster topologyducted this evaluation using the Package AllocationStrategy (PAS) that we proposed in [3] and comparingthe results with those obtained for the schedulingstrategies presented by Jones [4] and Naik [8].The rest of the paper is organized as follows. InSection II, the multi-cluster and parallel applicationperformance mo<strong>de</strong>l used in this paper is presented.In Section III, we present our scheduling strategyfor multiple-job co-allocation in a multi-cluster environment.Section IV shows the experimentation resultsobtained from comparison with other schedulingstrategies in the literature by varying the heterogeneityand availability of the multi-cluster resources.Finally, the conclusions are presented inSection V.II. Multi-cluster Mo<strong>de</strong>lAdvances in computational and communicationtechnologies have ma<strong>de</strong> it economically feasible toconglomerate multiple clusters of heterogeneous networkedresources leading to the <strong>de</strong>velopment of largescaledistributed systems known as multi-cluster systems.Generally, multi-cluster systems can be classifiedinto super-clusters and cluster-of-clusters. Agood example of super-cluster systems is DAS-2 [10],which is characterized by a large number of homogeneousprocessors and heterogeneity in communicationnetworks. In contrast, cluster-of-clusters areconstructed by interconnecting multiple single clustersystems. Thus heterogeneity may be observed incommunication networks as well as processors. TheLLNL [11] multi-cluster system, which is built by interconnectingof four single clusters is an example ofcluster-of-clusters system.A commonly used mo<strong>de</strong>l for representing the generalstructure for multi-cluster systems is presentedin Figure 1. The system is ma<strong>de</strong> up of as a collectionof arbitrary sized clusters {C 1 ..C α }, each cluster i iscomposed of N i processors of type T i , i = 1, ..., C,where T i could be different for each cluster. Also,Clusters are connected to each other through single<strong>de</strong>dicatedlinks {L ∞ ..L α }, by means of a centralswitch.In the present work, we focus our discussion on thecluster-of-clusters system where heterogeneity maybe observed in both resources processors and communicationnetworks. Thus, we need a mo<strong>de</strong>l thatconsi<strong>de</strong>rs this feature to assess the performance ofparallel applications more accurately.A. Analytic Performance mo<strong>de</strong>lIn [9] we presented a new performance mo<strong>de</strong>l forparallel jobs that <strong>de</strong>fined the execution time by consi<strong>de</strong>ringboth the availability and heterogeneity ofthe processors and communication networks. Thismo<strong>de</strong>l <strong>de</strong>fines the execution time (T e ) of a paralleljob in a heterogeneous and non-<strong>de</strong>dicated environmentas its execution time in a <strong>de</strong>dicated environment(T e ) <strong>de</strong>layed by a slowdown factor (SD) producedby the heterogeneity and non-<strong>de</strong>dicated natureof the slowest allocated resources, and expressed byequation 1.T e = T e · SD (1)The slowdown of a parallel application <strong>de</strong>pendson the capacity and availability of both processingresources and communication network, and thus, wecan express SD based on its processing SP and communicationSC slowdowns by equation 2.SD = σ · SP + (1 − σ) · SC (2)where σ <strong>de</strong>notes the relevance of the processingtime with respect to the communication time of thecorresponding job. The <strong>de</strong>tails of the calculation ofthe SP and SC values are presented below.A.1 Processing CharacterizationWe assume that parallel job tasks are generallysimilar in size and executed separately, and thus,the job execution time is boun<strong>de</strong>d by the slowestallocated resource. Taking this into account, the jobprocessing slowdown (SP ) is obtained from the allocatedresource with maximum processing slowdown,expressed by equation 3.SP j = max{SP r |r ∈ P | } (3)where P | <strong>de</strong>notes the set of processing no<strong>de</strong>s allocatedto job j. In heterogeneous and non-<strong>de</strong>dicate<strong>de</strong>nvironments, the computing resources capabilitiescan be quite different. To measure these differences,we use the Effective Power metric (Γ r ) <strong>de</strong>fined in [9],which relates the computing power of each resourcewith its availability. Thus, Γ r = 1 when resource rhas full capacity to run tasks at full speed, otherwiseΓ r < 1. Assuming this, the processing slowdownof such resource SP r is inversely proportional to itsEffective Power weight, SP r = (Γ r ) −1 .A.2 Communication CharacterizationThe parallel job co-allocation consumes a certainamount of bandwidth across inter-cluster networklinks (BW j k). These are shown by equation 4.( )BW j k(t = j k · P NBW j) n j T·− tj kn j T − 1 , ∀ k ∈ 1..α(4)where n j Tis the total number of tasks of the job j,t j k<strong>de</strong>notes the total number of tasks allocated to clusterC k and P NBW j is the average per-no<strong>de</strong> bandwidthrequirement by job j from the jobs. The first<strong>JP2011</strong>-526


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011term in the equation is the total bandwidth requiredby all the no<strong>de</strong>s associated with job j in cluster C k .The second term represents the communication percentageof job j in other cluster no<strong>de</strong>s (not in C k )that will use the inter-cluster link k.The saturation <strong>de</strong>gree of inter-cluster links relatesthe available bandwidth of each link (ABW k ) withthe bandwidth requirements of the allocated parallelapplications, which is calculated by equation 5.BWk sat = ABW k∑j,k BW j k∀ k ∈ 1..α (5)When the required bandwidth is lower than theavailable, the link is not saturated and the communicationswill not suffer <strong>de</strong>lays. Otherwise, thenetwork link is saturated, drastically reducing theperformance of all the jobs sharing the link. Thus,the job communicating slowdown (SC) is obtainedfrom the slowest, most saturated, communicationlink used by the job, calculated as the inverse of thesaturation bandwidth with equation 6.SC j = max{(BW satk ) −1 |k ∈ 1..α} (6)The goodness of this analytic performance mo<strong>de</strong>lwas its ability to capture the performance for eachindividual application based on the characteristicsand load conditions of the multi-cluster environment.Thus, we can use this slowdown mo<strong>de</strong>l as a performancemetric from parallel application point ofview, allowing the scheduler to take best allocationresource<strong>de</strong>cisions according to stablished criteria.III. Multiple-Job Co-allocation StrategyA common feature of most on-line schedulingstrategies in cluster, multi-cluster and grid environmentsis the individual allocation of resources to applications.First, the scheduler selects the next job tobe executed according to a priority criterion. Whenthere are insufficient resources to run the selectedjob, the scheduler can wait for the release of enoughresources in or<strong>de</strong>r to follow a First Come First Served(FCFS) schema, or select a new job from the waitingqueue that can be executed with the availableresources by applying such a schema as Fit ProcessorsFirst Served (FPFS) or backfilling, etc. Oncea job is selected, it is individually allocated to themost appropriate resources according to the establishedcriteria.However, allocating the best available resources toa job without consi<strong>de</strong>ring the requirements of therest of the jobs in the waiting queue can impair theperformance of future allocations and therefore theoverall system performance. With the aim of overcomingthis drawback, in [3], we proposed a twophasescheduling strategy, named Package AllocationScheduling (PAS). Firstly, a Job Package Selectionfunction <strong>de</strong>termines those suitable jobs in the waitingqueue that will be allocated simultaneously. Secondly,a Mixed-Integer Programming (MIP) mo<strong>de</strong>lreturns the allocation that minimizes their globalslowdown while preventing the saturation of theinter-cluster links and applying co-allocation whenit is necessary.A. Job Package SelectionThe main aim of the selection function is to packagethe most suitable jobs from the waiting queueto be executed simultaneously, according to certaincriteria established in terms of <strong>de</strong>sired system performanceobjectives. The job package selection function(F) can be expressed as P CK = F(Q, R, C) whereQ is the set of jobs in the waiting queue, R the set ofmulti-cluster resources and C the criteria to be metby resources to allocate the job package.There is a wi<strong>de</strong> variety of criteria that can be appliedfrom the point of view of resource utilizationor the nature of the parallel applications. In thepresent work, in or<strong>de</strong>r to assess the effects of themulti-cluster configuration and resource availabilityon the scheduling strategies, we selected the mostcommonly used criterion which selects the set of jobsin the waiting queue that fits the free multi-clusterresources, and is expressed as∑∃ P CK ⊆ Q | τ | |R ′ ||∈PCKwhere P CK is the subset of jobs from the waitingqueue (Q) whose total number of tasks is less than,or equal to, the multi-cluster resources in R ′ , whichrepresents the subset of multi-cluster resources (R ′⊆R) that meet the criteria (C), which, in our case, arethose resources non-assigned to other parallel jobs.B. MIP Allocation Mo<strong>de</strong>lOnce a package of waiting jobs was selected, thePAS Strategy must allocate the most suitable resourcesaccording to established performance criteria.Using the slowdown mo<strong>de</strong>l expressed by equation2 as a parallel application performance metricand <strong>de</strong>fining the resource allocating problem as aMixed-Integer programming mo<strong>de</strong>l, as in [3], we obtainedan allocation mo<strong>de</strong>l that minimizes the globalresponse time for the target job package.The goodness of the PAS strategy was its abilityto obtain the best resources for each parallel job consi<strong>de</strong>ringthe other applications that can be executedconcurrently in the multi-cluster environment, andthus reducing the global response times while makingbetter use of the resources and also preventingthe saturation of the inter-cluster links.However, the effectiveness of the scheduling strategiesin these dynamic and heterogeneous environmentsis highly sensitive to the multi-cluster configurationand its availability. Therefore, it is necessaryto conduct a thorough analysis of the effect ofthese parameters on the effectiveness of the schedulingstrategies, allowing the scheduler to adjust accordingto the system characteristics and its status.In the next section, we assess the effects of the resourceheterogeneity and availability on the effectivenessof the scheduler <strong>de</strong>cisions.<strong>JP2011</strong>-527


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011IV. ExperimentationIn this section, we present an experimental evaluationof the impact of the multi-cluster performanceon the effectiveness of the co-allocation schedulingstrategies in heterogeneous multi-cluster environments.The main goal of this evaluation was to <strong>de</strong>terminethe scheduler ability to adapt its <strong>de</strong>cisionsto take advantage of the multi-cluster performancecharacteristics and then obtain the best performancefor the proposed workload. For this, we proposed apre<strong>de</strong>termined workload that was fixed for all theexperimentation process, and was scheduled on differentmulti-cluster configurations.The experimental study was carried out by modifyingtwo main parameters such as the BisectionBandwidth (BSBW ) and the <strong>de</strong>gree of heterogeneity(H). The first parameter BSBW , measured in Gigabytes/second(GB/s) [1], assessed the effect of thecommunication rate between two halves of the communicationsystem. It <strong>de</strong>termines the worst-case performanceon a particular network, since it is relatedto the cost of moving data from one si<strong>de</strong> of the systemto other. We chose values in the range of 0.1GB/sto 1.1GB/s, representing a low to high transmissioncost. This parameter would affect the schedulers toavoid jobs co-allocation when the network ad<strong>de</strong>d ahigh communication slowdown. The second parameter,the multi-cluster heterogeneity <strong>de</strong>gree H, meantthe percentage of difference of the effective power betweenthe individual clusters. Thus we <strong>de</strong>fined threedifferent configurations, H = 10% (low heterogeneity,near to a homogeneous multi-cluster), H = 50%(there were significant differences) and H = 90% (extremeheterogeneity). The effective power is an importantfactor for the schedulers because the use ofthe most powerful resources allows to reduce the jobexecution times, obtaining free resources as quicklyas possible and then reducing the overall waitingtimes. On the other hand, this parameter is in conflictwith the available bandwidth because for obtainingthe best computing resources in many cases it isnecessary to apply co-allocation.The experimentation was done with our strategyPackage Allocation Scheduling (PAS) as a basis,and the results were compared with two other coallocationstrategies from the literature. The first,presented by Jones in [4], named CBS for ChunkBig Small, tries to co-allocate a “large chunk” (75%of the job tasks) to a single cluster in an attemptto avoid inter-cluster link saturation. The second,presented by Naik in [8], named JPR for Job Preferenceson Resources, allocates parallel jobs selectingthe most powerful resources, co-allocating themwhen is nee<strong>de</strong>d. Both of these use a FCFS (FirstCome First Served) scheduling policy, the same thatwe used in our selection function to compare the differentallocation strategies properly. For an accuratecomparison, both techniques were implemented byusing a MIP mo<strong>de</strong>l using the CPLEX solver package.The multi-cluster environment was ma<strong>de</strong> up of4 clusters composed of 24, 16, 16 and 8 no<strong>de</strong>s, inter-Number of jobs100 jobsAvg. exec. time170 time unitsInterarrival time (Li’04) weibull (λ = 82.6 , k = 0.6)Job sizes (Lublin’03) gamma (α = 4.04, β = 0.77),”power of two” prevalenceJob actual runtime(Li’04) weibull (λ = 200 , k = 1)Comm.requ. P NBW( j =(Jones’05)4(njTBSBW)(n j T )2TABLA IWorkload parametersconnected by a Gigabit network.A. Workload characterizationA <strong>de</strong>tailed characterization of a super-cluster waspresented in [12], where different distribution functionswere obtained from the characterization ofthe behavior of different real cluster environments.Based on the results of this study and also takinginto account the consi<strong>de</strong>rations ma<strong>de</strong> by Lublin [13]and Jones [4] about the size of the jobs and the characterizationof the communications requirements respectively,we have <strong>de</strong>fined the most representativeworkload for a cluster-of-clusters according to theliterature. As can be seen in Table 1, the <strong>de</strong>finedworkload is ma<strong>de</strong> up of 100 jobs with an interarrivaltime <strong>de</strong>fined by a weibull distribution with parametersλ = 82.6 and k = 0.6, the job runtime was characterizedby a weibull distribution with parametersλ = 200 and k = 1, and an average execution timeof 170 seconds. The jobs sizes were characterized bya gamma distribution with parameters α = 4.04 andβ = 0.77 and adjusted to fit the prevalence of ”powerof two” job sizes as is observed by Lublin in [13]. Finally,the communication requirements (PNBW ) ofthe jobs were <strong>de</strong>fined as proposed by Jones in [4].Figure 2 <strong>de</strong>picts the distribution functions used to<strong>de</strong>fine the workload used in this experimentation.B. Experimental resultsIn or<strong>de</strong>r to <strong>de</strong>termine the effectiveness of the coallocationscheduling strategies, we firstly evaluatedthe average response time for the pre<strong>de</strong>fined workload.The results obtained are shown in Figure3 for the three H configurations and for each onevarying the BSBW parameter. For the H = 10%case study, where the multi-cluster is approximatelyhomogeneous, two different ten<strong>de</strong>ncies can be observed.When the BSBW is lower than 0.6, therewas enough bandwidth for all job communications,and thus, all schedulers obtained similar results.However, when the BSBW increased, JPR couldnot obtain an a<strong>de</strong>quate allocation because its maingoal was to obtain the most powerful computationresources without taking the communication overheadinto account. PAS and CBS obtained similarresults as they tried to reduce the network usage.However, PAS also selected the best computationresources from the multi-cluster, and this allowed itto slightly reduce the average response time.For the H = 50% and H = 90% case studies,the impact of the different effective power capabil-<strong>JP2011</strong>-528


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 2.Workload characteristicsFig. 3.Response Time.ities among the clusters became an important factor.When the BSBW was lower than 0.6, PASand JPR were able to take advantage of the heterogeneouscomputation resources, obtaining lowerresponse times. The worst results were obtained byCBS because its main goal was to reduce the networkusage by forcing jobs to be allocated on individualclusters, without consi<strong>de</strong>ring the computingcapabilites. When the BSBW increased, as inthe previous case JPR became worse. CBS continuedavoiding the use of the network communicationswhile PAS was also able to select the computationresources that allowed the job execution times to bereduced.From this results we conclu<strong>de</strong> that the most sensitiveparameter for the job response time is the networkavailability. When the network is available (below0.6), for each H case study, the network availabilityhas no effect on the response time. However,when it is less available (over 0.6), the use ofinter-cluster links reduces even more the availablebandwidth. Then, in or<strong>de</strong>r to get better responsetimes, the schedulers should provi<strong>de</strong> allocations thatreduce as much as possible the inter-cluster communications.Next, with the aim to <strong>de</strong>termine how the schedulerstreated the availability of the network, we evaluatedhow many jobs were co-allocated by each one.It is important to take into account that the coallocatedjobs are those that could be more affectedby the low network availability. In Figure 4, thenumber of co-allocated jobs for each case of studyis presented. As can be observed, the JPR wasthe scheduler with the higher <strong>de</strong>gree of co-allocation,60% of the total jobs present in the workload. Thiswas due to its need to obtain the best computationresources, irrespectively of the network availability.The opposite case was CBS with an overall 14% ofco-allocated jobs, as it tried to allocate at least the75% of the job tasks to the same cluster. The PASstrategy took both, heterogeneity and network availability,into account in or<strong>de</strong>r to reduce the job responsetime. In this case, the number of co-allocatedjobs was adapted to the multi-cluster characteristics.When the BSBW was low, it was able to co-allocatemore jobs. However, when BSBW increased, andthe communication slowdown penalized the responsetime, the <strong>de</strong>gree of co-allocation was reduced forcingthe jobs to be maintained insi<strong>de</strong> the individual clusterswhen its size (number of tasks) allowed this.The obtained results <strong>de</strong>monstrated that the coallocationhas an important performance impact onthe response times when network availability <strong>de</strong>creases.By this, the schedulers should take this effectin their allocation <strong>de</strong>cisions into account in or<strong>de</strong>rto improve the parallel applications performance.Finally we studied the effect of the multiple-joballocation done by PAS, (both JPR and CBS, arenot capable of doing multiple allocation). By usingmultiple-job allocation, PAS tries to maximize themulti-cluster resource usage and minimize the jobpackage execution time.The total number of jobs that were selected by theJob Package Selection is shown in Figure 5. As canbe seen, <strong>de</strong>spite there could be enough free computationno<strong>de</strong>s among the multi-cluster, the numberof jobs treated together <strong>de</strong>creased when the BSBWincreased. This was because PAS tried to avoid asmuch as possible the saturation of the network andthis implies the use of the co-allocation just onlywhen it is profitable.Finally, these experimental results corroborate<strong>JP2011</strong>-529


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 4.Co-Allocation jobs.that the most important multi-cluster parameter isthe network availability. The more available it is,the lower effect it has on the response time. Otherwise,when the network is low available, the benefitsof having high effective power on the computationno<strong>de</strong>s are less noticeable. By this, the bestperformance results were obtained when the schedulerstried to avoid as much as possible the interclustercommunication links. On this situation, PASobtained the best results adapting the multiple-jobco-allocation to the resources availability.Fig. 5.Number of jobs treated in a multiple allocation.V. ConclusionsIn or<strong>de</strong>r to obtain the best performance, the schedulersneed to be able of taking the dynamic availabilityon the multi-cluster resources into account. Tocorroborate this hypothesis, we evaluated the impactof the network availability and computation heterogeneityon the effectiveness of the scheduling process.We compared our strategy, Package AllocationScheduling (PAS), with two other co-allocationstrategies from the literature,CBS for Chunk BigSmall and JPR for Job Preferences on Resources.The results <strong>de</strong>monstrated that co-allocation has anegative effect on the response times when the networkavailability is low, and it must be used just onlywhen it is profitable. On the other hand, the use ofthe multiple-job allocation contributes to maximizethe multi-cluster resources usage while reducing theworkload response times. By this, our Package AllocationStrategy, which is composed of both a JobPackage Selection and Multiple-Job Allocation, wasable to adapt to the different multi-cluster configurationsand thus obtaining better scheduling <strong>de</strong>cisionsthan the compared schedulers.Finally, we consi<strong>de</strong>r that the multi-cluster schedulersneed to take care not only of the current availablebandwidth, but also to estimate how muchbandwidth will be available after their scheduling<strong>de</strong>cisions in or<strong>de</strong>r to obtain better results for the responsetimes.Acknowledgements This work was supported by theMEC-Spain un<strong>de</strong>r contract TIN2008-05913 and the CUR ofDIUE of GENCAT and the European Social Fund.References[1] B. Javadi, M.K. Akbari, J.H. Abawajy, A performanceMo<strong>de</strong>l for Analysis of Heterogeneous Multi-Cluster Systems,Parallel Computing,vol.32(11-12), pp.831–851,2006.[2] A.I.D. Bucur, D.H.J. Epema, Schedulling Policies forProcessor Coallocation in Multicluster Systems, IEEETPDS, vol.18(7), pp.958–972, 2007.[3] H. Blanco, A. Montañola, F. Guirado, J. Lérida FairnessScheduling for Multi-Cluster Systems Based on LinearProgramming., 10th International Conference Computationaland Mathematical Methods in Science and Engineering(CMMSE’10), vol.1, pp.227-239, June 2010[4] W. Jones, W. Ligon, L. Pang, D. Stanzione, Characterizationof Bandwidth-Aware Meta-Schedulers for Co-Allocating Jobs Across Multiple Clusters, Journal of Supercomputing,vol.34(2), pp.135–163, 2005.[5] J.Abawajy, S.Dandamudi, Parallel Job Scheduling onMulticluster Computing Systems, IEEE Int. Conf.CLUSTER’03,pp.11–18, 2003.[6] E.M.Heien, N.Fujimoto, K.Hagihara, Static Load Distributionfor Communicative Intensive Parallel Computingin Multiclusters, IEEE PDP’08,pp.321-328, 2008.[7] C. Yang, H. Tung, K. Chou, W. Chu Well-Balanced AllocationStrategy for Multiple-Cluster Computing, IEEEInt. Conf. FTDCS’08, pp.178–184, 2008.[8] V.K. Naik, C.Liu, L.Yang, J.Wagner, Online ResourceMatching for Heterogeneous Grid Environments,IEEE/ACM Int. Conf. CCGRID’05,vol.2,pp.607–614,2005.[9] J.L. Lérida, F. Solsona, F. Giné, J.R. García, P.Hernán<strong>de</strong>z, Resource Matching in Non-<strong>de</strong>dicated MulticlusterEnvironments, In VECPAR’08, pp.160–173,2008.[10] The DAS-2 Supercomputer. Available from:http://www.cs.vu.nl/das2[11] The Livermore National <strong>La</strong>boratoryMulti-cluster system., Available from:https://computing.llnl.gov/tutorials[12] H. Li, D. Groep, L. Wolters. Workload Characteristicsof a Multi-cluster Supercomputer, Job Scheduling Strategiesfor Parallel Proc., JSSPP’04, pp.176-193, 2005.[13] U.Lublin, D.G. Feitelson. The workload on parallel supercomputers:mo<strong>de</strong>ling the characteristics of rigid jobs.,J.Parallel Distr.Comp., vol.63(11),pp.1105-1122, 2003.<strong>JP2011</strong>-530


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Mr-Cirrus: Implementación <strong>de</strong> Map-Reduce bajo MPI para la ejecuciónparalela <strong>de</strong> programas secuencialesDaniel Ramet 1 , Juan <strong>La</strong>go 2 , Johan Karlsson 1 , Juan Falgueras 3 y Oswaldo Trelles 1Resumen—Este documento presenta la aplicaciónMr-Cirrus (Map-Reduce High Level Clouds) quepermite la ejecución <strong>de</strong> programas secuenciales, sinninguna modificación interna, trabajando encolaboración para producir un resultadocoordinado en entornos <strong>de</strong> red, computación ennube (cloud computing) y multiprocesadores. Elmarco <strong>de</strong> <strong>de</strong>sarrollo se basa en el paradigma Map-Reduce y ha sido implementada bajo MPI. De estaforma, muchas aplicaciones bioinformáticas (sobrelas 200 actualmente incluyendo Dotplots,comparación <strong>de</strong> secuencias, PAML, Muscle,MAFFT, MrBayes y BLAST) pue<strong>de</strong>n escalarse através <strong>de</strong> su ejecución paralela, sin necesidad <strong>de</strong>instalaciones específicas o <strong>de</strong> alto coste, ni necesidad<strong>de</strong> conocimientos <strong>de</strong> programación en entornosmultiprocesador. Se han realizado pruebasintensivas en diferentes tipos <strong>de</strong> procesos condiferentes cargas computaciones y patronescomputacionales, con resultados satisfactorios.Palabras clave— MapReduce, Cloud Computing,MPI, bioinformática, escalabilidad.encargadas <strong>de</strong> procesar los datos moleculares sonestrictamente regulares, pero cuyo problema actual esel manejo <strong>de</strong> los nuevos volúmenes <strong>de</strong> datos y que porlo tanto se adaptan perfectamente a una ejecuciónparalela. Así, por ejemplo, la ejecución <strong>de</strong> unabúsqueda por semejanza entre una secuencia problemay una colección <strong>de</strong> secuencias escala linealmente con elnúmero <strong>de</strong> secuencias en la base <strong>de</strong> datos, sin ninguna<strong>de</strong>pen<strong>de</strong>ncia <strong>de</strong> datos con respecto al or<strong>de</strong>n <strong>de</strong>comparación ni a la completitud <strong>de</strong> los datos acomparar en el caso <strong>de</strong> repartir el proceso en variossubprocesos que produzcan resultados parciales.<strong>La</strong> tercera razón viene motivada por el éxito <strong>de</strong>lparadigma Map-Reduce [10] en entornos <strong>de</strong>computación <strong>de</strong> alto rendimiento. Su facilidad <strong>de</strong> usomatiza <strong>de</strong> forma efectiva la falta <strong>de</strong> programadoresespecializados en construir software <strong>de</strong> altorendimiento. Se estima que menos <strong>de</strong>l 1% <strong>de</strong> los<strong>de</strong>sarrolladores <strong>de</strong> software a nivel mundial estánentrenados en computación paralela, y dar el salto a ellano es en absoluto trivial.LI. INTRODUCCIÓNA computación en la nube o “cloud computing” [1]ha reinventado el tradicional Centro <strong>de</strong> Datos (datacenter) para la prestación <strong>de</strong> servicios computacionales,con una rápida introducción y aceptación en distintossectores y ámbitos <strong>de</strong> actividad [2]. Esto es así en granmedida porque la computación en la Cloud promete, yen muchas situaciones lo consigue, recortes en loscostes operativos y <strong>de</strong> capital en la gestión <strong>de</strong> losrecursos computacionales <strong>de</strong> las instituciones por elahorro en la adquisición <strong>de</strong> la infraestructura a cambio<strong>de</strong> alquilar un recurso <strong>de</strong> pago-a-<strong>de</strong>manda segúnconsumo <strong>de</strong> los recursos (computación,almacenamiento, ancho <strong>de</strong> banda, etc) y evitando lagestión <strong>de</strong> las tareas <strong>de</strong> mantenimiento y puesta a punto<strong>de</strong>l centro <strong>de</strong> datos. Hay proveedores <strong>de</strong> servicios enCloud (como por ejemplo Google App Engine [3],Microsoft Azure [4], IBM Smart Cloud [5] y AmazonEC2 [6]) que ofrecen cantida<strong>de</strong>s importantes <strong>de</strong> CPU yalmacenamiento bajo un software <strong>de</strong> gestión robusto ysobre cuyas plataformas es relativamente simpleinstalar una infraestructura en cuestión <strong>de</strong> minutos [7].Por otra parte, el espectacular incremento en laproducción <strong>de</strong> datos moleculares (<strong>de</strong>l or<strong>de</strong>n <strong>de</strong> los Teray Petabytes) [8,9] y la necesidad <strong>de</strong> analizar múltipleshipótesis bajo diversos escenarios hace que el análisis<strong>de</strong> datos genómicos en la biología actual requiera <strong>de</strong>una potencia computacional que <strong>de</strong>be ser buscada en lacomputación paralela. También <strong>de</strong>bemos tener presenteque una buena parte <strong>de</strong> las aplicaciones bioinformáticas1. Dpto. <strong>de</strong> Arquitectura <strong>de</strong> Computadores, <strong>Universidad</strong> <strong>de</strong> Málaga. dramet, tjkarlsson, ortrelles@uma.es2. Dpto. <strong>de</strong> Innovación y Tecnología, Fundación IAVANTE. juan.lago@iavante.es3. Dpto. <strong>de</strong> Lenguajes y Ciencias <strong>de</strong> la Computación, <strong>Universidad</strong> <strong>de</strong> Málaga. juanfc@uma.es<strong>JP2011</strong>-531En este contexto, el objetivo principal <strong>de</strong> este trabajoes proporcionar un marco <strong>de</strong> ejecución <strong>de</strong> aplicacionessecuenciales, con la premisa <strong>de</strong> no modificarlas enabsoluto, en varias instancias paralelas. El esquema sebasa en un gestor <strong>de</strong> la ejecución que hace a la vez <strong>de</strong>lanzador <strong>de</strong> instancias, y dos programas externos paraasignar la carga sobre las instancias (map); y pararecolectar los resultados parciales y producir unresultado integrado final (reduce). En ambos casos setrata <strong>de</strong> programas relativamente simples y que no<strong>de</strong>mandan habilida<strong>de</strong>s <strong>de</strong> programación paralela.Para validar y evaluar el sistema se han elegido dosaplicaciones representativas en el área <strong>de</strong> labioinformática; una con un gran número <strong>de</strong> tareasin<strong>de</strong>pendientes <strong>de</strong> pequeños volúmenes <strong>de</strong> datos(búsquedas por semejanza) y la otra con una sola tareapero un gran volumen <strong>de</strong> datos (matrices <strong>de</strong> puntos).Estas aplicaciones presentan muchas <strong>de</strong> lascaracterísticas <strong>de</strong> los procesos actuales en genómica;elevada E-S, gran consumo <strong>de</strong> memoria y <strong>de</strong>manda <strong>de</strong>CPU. Su evaluación nos proporciona informaciónimportante para portar al entorno un gran conjunto <strong>de</strong>aplicaciones con estructura computacional similar.II. MÉTODOS Y SISTEMASA. El gestor <strong>de</strong> instanciasEl diseño <strong>de</strong>l esquema <strong>de</strong> gestión <strong>de</strong> la ejecuciónparalela <strong>de</strong> programas secuenciales se ha representadoen la figura 1. Un proceso maestro es el encargado <strong>de</strong>la creación <strong>de</strong> las instancias (servidores) que a su vez


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011invocan al proceso secuencial <strong>de</strong> acuerdo a lasespecificación que el maestro ha leído <strong>de</strong>l fichero <strong>de</strong>mapeo. Los procesos secuenciales ejecutan trabajosparciales e informan <strong>de</strong> su finalización al servidorquien maneja sus comunicaciones con el maestro, yquien a la finalización <strong>de</strong> todos los procesos servidoresinvoca el proceso <strong>de</strong> reducción o recolección <strong>de</strong>resultados parciales.Una secuencia genómica S n es una ca<strong>de</strong>na <strong>de</strong>símbolos {x 1 , x 2 , ..., x n } que pertenecen al alfabeto <strong>de</strong>lADN (x i ⊂ A {A, C, G, T}). <strong>La</strong> matriz <strong>de</strong> puntos es uno<strong>de</strong> los métodos más antiguos <strong>de</strong> comparación <strong>de</strong>secuencias moleculares [11]. En términos simples, setrata <strong>de</strong> una representación visual <strong>de</strong>l parecido entredos secuencias. Una se dispone en horizontal y la otraen vertical y la matriz <strong>de</strong> puntos se construyecomparando cada símbolo <strong>de</strong> ambas secuencias,ubicando un punto en la celda <strong>de</strong> intersección <strong>de</strong>coor<strong>de</strong>nadas cuando los elementos son iguales. De estaforma, las regiones <strong>de</strong> las secuencias que comparten unparecido sustancial aparecerán como fragmentosdiagonales en la matriz. El método estándar parareducir el ruido <strong>de</strong> los parecidos aleatorios <strong>de</strong> pequeñosfragmentos utiliza una ventana <strong>de</strong>slizante <strong>de</strong> un<strong>de</strong>terminado tamaño, <strong>de</strong> forma que solo resulte en unpunto los fragmentos en la ventana cuyo parecidosupere un umbral prefijado.Hay muchas y antiguas extensiones a estametodología básica, que incluyen la fijación interactiva<strong>de</strong>l umbral [12], [13], filtros estadísticos y el uso <strong>de</strong>diversos símbolos para discriminar las señales [14], eluso <strong>de</strong> colores para representar la información [15], yse ha extendido la capacidad interactiva [16, 17],incluyendo aplicaciones Web [11], con las típicascapacida<strong>de</strong>s <strong>de</strong> navegación.Fig. 1. En la parte superior se esquematiza el proceso <strong>de</strong>asignación o distribución <strong>de</strong> la carga (map) y la generación <strong>de</strong>los scripts <strong>de</strong> ejecución. Un proceso maestro con los respectivosservidores, en el centro, se encargan <strong>de</strong> realizar las tareasparciales; para finalmente en un proceso <strong>de</strong> reducción producirel resultado integrado final (reduce).Tanto los procesos <strong>de</strong> distribución <strong>de</strong> recursos comolos <strong>de</strong> colección <strong>de</strong> resultados se especifican a través <strong>de</strong>ficheros que pue<strong>de</strong>n ser producidos automáticamentepor pequeños y simples programas <strong>de</strong> distribucióncolección<strong>de</strong> la carga. Estos son los únicos programasque necesitan ser escritos para completar el sistema ymuchas veces correspon<strong>de</strong>n a conjuntos o lotes <strong>de</strong>comandos <strong>de</strong>l sistema operativo.El proceso maestro está preparado para ser tolerante alos fallos <strong>de</strong> procesos, redistribuyendo la carga noresuelta y para lanzar la totalidad <strong>de</strong> las instancias porpartes o etapas <strong>de</strong> acuerdo a los recursos disponibles.Ello permite el diseño con distribuciones <strong>de</strong> carga <strong>de</strong>tamaño variable a fin <strong>de</strong> reducir el coste <strong>de</strong>planificación, y mejorar la sincronización final <strong>de</strong> losprocesos para tareas <strong>de</strong> baja regularidad.B. <strong>La</strong>s aplicaciones a implementar1) <strong>La</strong>s matrices <strong>de</strong> puntosEstas referencias nos permiten analizar algunosaspectos computacionales. Estrictamente hablando, lapropuesta inicial que realiza la comparación a nivel <strong>de</strong>símbolo, no requiere las secuencias ni la matriz <strong>de</strong>puntos en memoria. Bastaría con tener una <strong>de</strong> lassecuencias o parte <strong>de</strong> ella en memoria e ir trabajandoun símbolo a la vez <strong>de</strong> la segunda secuencia, paramostrar en una pantalla un punto o no. Sin embargo, yael uso <strong>de</strong> la ventana <strong>de</strong>slizante requiere al menos parte<strong>de</strong> la segunda secuencia en memoria. Finalmente, lainteractividad sobre la matriz <strong>de</strong> resultados requiereque las aplicaciones gestionen la matriz <strong>de</strong> puntos enmemoria. Esto era posible porque se trabajaba sobre lassecuencias relativamente pequeñas que se disponían(genes o genomas <strong>de</strong> pequeños virus <strong>de</strong> algunos pocosKB).Sin embargo, hoy en día se dispone <strong>de</strong> información<strong>de</strong> genomas completos <strong>de</strong> organismos superiores, entreellos el humano, con algunos GB <strong>de</strong> símbolos (elgenoma humano sobrepasa los 3 GB y sus cromosomasson <strong>de</strong> algunos cientos <strong>de</strong> MB). Aún por separado,tanto el cálculo como la visualización <strong>de</strong> la matriz <strong>de</strong>puntos representan gran<strong>de</strong>s retos computacionales. Porejemplo, la comparación <strong>de</strong> dos genomas medios <strong>de</strong>bacterias <strong>de</strong> 3 Mb, en un equipo capaz <strong>de</strong> comparar 100MB, usando una ventana <strong>de</strong> un solo símbolo necesitaríaalre<strong>de</strong>dor <strong>de</strong> 25 horas, [16]. Cada incremento <strong>de</strong> unaunidad en el tamaño <strong>de</strong> la ventana representaría un díamás <strong>de</strong> tiempo <strong>de</strong> computación. Por otra parte, lasaplicaciones <strong>de</strong> análisis interactivo requieren la matrizen memoria. En [18] propusimos gestionar la matriz adistintos niveles <strong>de</strong> resolución llegando a manejarmatrices con algunos, notables para su momento,cientos <strong>de</strong> KB <strong>de</strong> longitud. Más a<strong>de</strong>lante, en [15] se<strong>JP2011</strong>-532


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011presenta una aplicación para visualizar gran<strong>de</strong>salineamientos y en [19], se hizo en Web.2) Comparación <strong>de</strong> secuencias biológicas<strong>La</strong> comparación <strong>de</strong> secuencias biológicas esposiblemente la aplicación <strong>de</strong> mayor uso enbioinformática. En esencia, dada una secuenciaproblema y una colección <strong>de</strong> secuencias conocidas, setrata <strong>de</strong> i<strong>de</strong>ntificar aquellas secuencias en la colecciónque más se parezcan a la secuencia problema. De estasrelaciones se pue<strong>de</strong>n inferir relaciones evolutivas,estructurales o funcionales entre las secuencias. Entérminos más formales, dada una secuencia S Q y unconjunto <strong>de</strong> secuencias D = {S 1 , S 2 , ..., S n } se <strong>de</strong>becomparar S Q contra cada una <strong>de</strong> las secuencias <strong>de</strong>lconjunto D a fin <strong>de</strong> i<strong>de</strong>ntificar aquellas S i , i ∈ {1…n}.III. RESULTADOSA. Los procesos <strong>de</strong> distribución y reducciónLos procesos <strong>de</strong> asignación <strong>de</strong> carga a procesos(Map) y colección <strong>de</strong> resultados (Reduce) se handiseñado para que puedan ser preparados <strong>de</strong> formaexterna tanto a la aplicación secuencial como al gestor<strong>de</strong> la ejecución.En el primer caso <strong>de</strong> estudio, la matriz <strong>de</strong> puntos seconstruye para dos secuencias S x y S y , por lo que ladistribución <strong>de</strong> carga más simple es la <strong>de</strong> repartir elespacio computacional L x × L y , don<strong>de</strong> L x y L y son laslongitu<strong>de</strong>s <strong>de</strong> las secuencias respectivas. Para ello, separte cada una <strong>de</strong> las secuencias en N x y N y trozos paraluego invocar el programa para cada combinación S i yS j ∀ i=1... N x ; y j=1...N y ), lo que producirá resultadosparciales RES(i,j) que serán unidos por un proceso <strong>de</strong>Reducción para producir la super-matriz final. Esinteresante indicar que este proceso genera a<strong>de</strong>más losscripts que permiten lanzar directamente las instancias(incluso en una máquina monoprocesadora).que las tareas que involucren a las secuencias largasgobernarán la eficiencia <strong>de</strong>l sistema.Por ello, la distribución <strong>de</strong> la base <strong>de</strong> datos (conjuntoconocido <strong>de</strong> secuencias) no solo es importante, sinoque <strong>de</strong>be realizarse <strong>de</strong> forma que minimice la latencia<strong>de</strong> inicio (con mínimo <strong>de</strong> lanzamiento <strong>de</strong> instancias) yfacilite la sincronización <strong>de</strong> finalización mediante, enambos casos, <strong>de</strong> las tareas livianas al inicio y final <strong>de</strong>lprocesamiento en paralelo.El coste <strong>de</strong> planificación está asociado al número <strong>de</strong>tareas a distribuir (en nuestro caso especialmente por lalatencia <strong>de</strong> lanzar una nueva instancia) y al “tamaño”<strong>de</strong> las últimas tareas a distribuir. <strong>La</strong> planificaciónguiada (Gui<strong>de</strong>d Self Scheduling) se planteó esteproblema. Dado un número n <strong>de</strong> instancias a crear enparalelo, la mejor solución en la que permite a todas lasinstancias finalizar con una diferencia máxima <strong>de</strong> Bunida<strong>de</strong>s <strong>de</strong> tiempo, siendo B el tiempo necesario pararealizar un bloque básico <strong>de</strong> tareas. El razonamiento esel <strong>de</strong> asignar en la i-ésima distribución x i bloques,<strong>de</strong>jando suficientes bloques para distribuir a los n-1instancias. Para conseguirlo, sea N el número <strong>de</strong>bloques <strong>de</strong> tareas, entonces x i queda <strong>de</strong>finido por:x i = | R i / n |R i+1 = R i - x i don<strong>de</strong> R 1 = NNosotros propusimos una modificación <strong>de</strong> estadistribución bajo la observación <strong>de</strong> que las tareasgran<strong>de</strong>s que se generan en las primera iteraciones (vertabla 1) produce una gran latencia tanto por ellanzamiento <strong>de</strong> la instancia pero especialmente por lallegada <strong>de</strong> los datos, llegando a producir inclusoTABLA 1TAMAÑOS DE LOS BLOQUES A DISTRIBUIR USANDO GSS YNUESTRO GSS MODIFICADO (GSS-MOD) PARA N=100 Y 4PROCESADORES.El segundo caso, búsquedas <strong>de</strong> secuencias porsemejanza, presenta dos variantes. Una primera sepresenta cuando se dispone <strong>de</strong> varias secuencias S Q(Q=1...N) y por tanto la primera distribución es la <strong>de</strong>repartir cada una <strong>de</strong> las secuencias a cada proceso. Enel segundo caso se trata <strong>de</strong> procesar una sola secuenciaS Q que se compara contra todas las secuencias <strong>de</strong>lconjunto, por lo que en este caso lo natural es distribuirla colección <strong>de</strong> secuencias.Se <strong>de</strong>be observar que ambas soluciones pue<strong>de</strong>n a suvez combinarse para formar una tercera opción queconsistiría en separar secuencias y distribuir también elconjunto <strong>de</strong> secuencias conocidas.Es importante <strong>de</strong>stacar que la primera variante pue<strong>de</strong>presentar serios problemas <strong>de</strong> eficiencia cuando elnúmero <strong>de</strong> secuencias problema (S Q ) es muy pequeño,y cuando las diferencias <strong>de</strong> longitud <strong>de</strong> las secuenciasen dicho conjunto sean significativas, lo que supone<strong>JP2011</strong>-533


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011inanición en las últimas instancias (este hecho fueconfirmado en los experimentos <strong>de</strong>l trabajo <strong>de</strong> Google[10]). Estas modificaciones se traducen en los siguientecálculos:x i = | R i / n |x -i+1 = x iR i+1 = R i - x i siendo R 1 = N / 2B. EvaluaciónPara evaluar la solución propuesta hemos utilizado elcluster <strong>de</strong> la Red Española <strong>de</strong> Supercomputación,ubicado en el Centro <strong>de</strong> Bioinnovación <strong>de</strong> la<strong>Universidad</strong> <strong>de</strong> Málaga. Este cluster <strong>de</strong> memoriadistribuida <strong>de</strong> la marca IBM está compuesto por 256nodos JS20-IBM, cada nodo con 2 CPU IBM PowerPCsingle-core 970FX <strong>de</strong> 64bits a 2GHz, y 1 TB <strong>de</strong>memoria distribuida. <strong>La</strong> programación se ha realizadoen C, usando la librería <strong>de</strong> paso <strong>de</strong> mensajes MPI.Para las primeras pruebas realizadas sobre laaplicación <strong>de</strong> matrices <strong>de</strong> puntos, se han usado dossecuencias <strong>de</strong> aproximadamente 1 MB <strong>de</strong> longitud, <strong>de</strong>las cepas APS y BPS <strong>de</strong> la bacteria Buchneraaphidicola (el primer genoma eucariota secuenciado enEspaña); y también variaciones en tamaño <strong>de</strong> estassecuencias para observar el comportamiento conreferencia al espacio computacional a distribuir. Para lasegunda aplicación se ha seleccionado un conjunto <strong>de</strong>secuencias <strong>de</strong> la base <strong>de</strong> datos swissprot (80 milsecuencias) y se han seleccionado <strong>de</strong> ella 100secuencias que serán usadas como conjunto problema(estas secuencias fueron a su vez eliminadas <strong>de</strong>lconjunto conocido <strong>de</strong> secuencias). En cada una <strong>de</strong> laspruebas se han utilizado diferente número <strong>de</strong> instancias<strong>de</strong> los procesos a fin <strong>de</strong> evaluar la escalabilidad. <strong>La</strong>tabla 2 muestra los resultados <strong>de</strong> las pruebas don<strong>de</strong> sepue<strong>de</strong> apreciar que se han utilizado distintos tamañospara validar la eficacia <strong>de</strong> la propuesta ante diferentestamaños <strong>de</strong> carga.Fig. 2. Composición <strong>de</strong> los resultados parciales <strong>de</strong>l proceso <strong>de</strong> lamatriz <strong>de</strong> puntos, utilizando para ello dos secuencias <strong>de</strong> 2 y 3KB<strong>de</strong> longitud con diferente particionado.matrices parciales que conforman la matriz <strong>de</strong> punto <strong>de</strong>dos secuencias, obtenidas por seis procesos diferentes.Finalmente en la figura 3 se muestran los tiempos y lagráfica <strong>de</strong> aceleración correspondientes para los testsrealizados. Para la aplicación <strong>de</strong> las Matrices <strong>de</strong> Puntos,se han usado los genomas <strong>de</strong> las bacterias BuchneraTABLA 2DETALLES DE LOS CONJUNTOS DE PRUEBA. TAMAÑO DE LASSECUENCIAS EN LOS DOTPLOTS Y DE LOS CONJUNTOS PROBLEMAEN LAS BÚSQUEDAS POR SEMEJANZA.ACELERACIÓN2 PE 4 PE 8 PE 16 PE 32 PE 64 PEÓptima 2,00 4,00 8,00 16,00 32,00 64,00Dotplot Buchnera 2,00 3,87 7,58 14,17 25,13 53,06Frag. E.Coli y B.Subtilis 1,96 3,80 7,84 15,84 31,04 61,44Fragmentos Buchnera 1,95 3,78 8,00 16,00 31,68 59,58Blast 161.000 singletons 1,98 3,96 7,88 15,74 30,86 56,66Los programas se han comprobado a fin <strong>de</strong> confirmarque reproducen los resultados originales como semuestra en la figura 2, en la que se muestran las seisFig.3. Resultados <strong>de</strong> aceleración en las implementacionespropuestas, en las que se observa un comportamiento cercano ali<strong>de</strong>al tanto para el proceso <strong>de</strong> la matriz <strong>de</strong> puntos, para la obtención<strong>de</strong> todos los fragmentos mayores que una longitud mínima (a partir<strong>de</strong> ahora, Fragmentos), y para el Blast en ejecuciones <strong>de</strong> casosreales. Para el caso <strong>de</strong> los Dotplots y Fragmentos, estos resultadoscorrespon<strong>de</strong>n a las secuencias Buchnera APS y BPS (600 KB),mientras que para Blast se han utilizado un conjunto <strong>de</strong> 120.000contigs y 161.000 singletons que hacen las veces <strong>de</strong> secuenciasproblema. Para conjuntos <strong>de</strong> datos mayores, los resultados sonincluso mejores, <strong>de</strong>mostrando la escalabilidad <strong>de</strong> la solución, tal ycomo se pue<strong>de</strong> ver en la ejecución <strong>de</strong> Fragmentos para las bacteriasE. Coli (4,5 MB) y B. Subtilis (4,1 MB). Para datos <strong>de</strong> tiempos, verla tabla 3.<strong>JP2011</strong>-534


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA 3DETALLES DE LOS DATOS DE TIEMPO ASOCIADOS A LAS IMPLEMENTACIONES PROPUESTAS (CONTINUACIÓN FIGURA 3).Dotplot BuchneraTIEMPO2 PE 4 PE 8 PE 16 PE 32 PE 64 PEÓptimo 03:21:48 01:40:54 00:50:27 00:25:14 00:12:37 00:06:19Map-Reduce 03:19:47 01:44:17 00:53:07 00:30:00 00:15:20 00:07:24Fragmentos E. Coli y B. Óptimo 50:40:00 25:20:00 12:40:00 06:20:00 03:10:00 01:35:00Subtilis Map-Reduce 51:40:00 26:40:00 12:49:25 06:21:40 03:14:50 01:38:00Fragmentos BuchneraBlast 161.000 singletonsÓptimo 01:05:00 00:32:30 00:16:15 00:08:08 00:04:04 00:02:02Map-Reduce 01:06:37 00:34:17 00:16:15 00:08:08 00:04:06 00:02:10Óptimo 00:58:10 00:29:05 00:14:33 00:07:17 00:03:39 00:01:50Map-Reduce 00:58:37 00:29:21 00:14:46 00:07:24 00:03:47 00:02:02APS y BPS <strong>de</strong> algo más <strong>de</strong> 600 KB <strong>de</strong> longitud;mientras que en las Comparaciones por Semejanza, sehan utilizado 161.000 secuencias (singletonsproce<strong>de</strong>ntes <strong>de</strong> un proceso <strong>de</strong> ensamblaje) que soncontrastadas contra 120.000 grupos (contigs) <strong>de</strong>secuencias. También se han realizado pruebas con unacarga <strong>de</strong> datos mayor como son las bacterias E. Coli yB. Subtilis <strong>de</strong> más <strong>de</strong> 4 MB <strong>de</strong> longitud mediante lacomparación por semejanza. Los resultados indican queestas implementaciones escalan linealmente con elnúmero <strong>de</strong> procesadores con aceleraciones cercanas ala máxima. Se ha probado el rendimiento paravolúmenes <strong>de</strong> datos o carga computacional menor, ycomo cabría esperar, cuando el número <strong>de</strong> procesadorescrece, la carga por proceso no es suficiente paracompensar la latencia <strong>de</strong> inicio <strong>de</strong> los procesos y, portanto, el número <strong>de</strong> procesadores <strong>de</strong>be fijarse enfunción <strong>de</strong> la carga para alcanzar buenos rendimientos.IV. CONCLUSIONES<strong>La</strong> computación en la Cloud abre nuevasoportunida<strong>de</strong>s para acercar la computación <strong>de</strong> altorendimiento a laboratorios que requieren procesargran<strong>de</strong>s cantida<strong>de</strong>s <strong>de</strong> datos pero que no disponen <strong>de</strong>infraestructura computacional a<strong>de</strong>cuada. Por otra parte,la bioinformática ha <strong>de</strong>spegado como una línea <strong>de</strong>investigación en la que el <strong>de</strong>sarrollo <strong>de</strong> software tieneque lidiar con el problema <strong>de</strong> los gran<strong>de</strong>s conjuntos <strong>de</strong>datos. Existe una gran diversidad <strong>de</strong> aplicaciones eneste campo, pero en su práctica totalidad estánpreparadas para una ejecución secuencial y unascondiciones que ya han <strong>de</strong>jado <strong>de</strong> estar presentes.Este documento se centra en el <strong>de</strong>sarrollo <strong>de</strong> unmarco <strong>de</strong> trabajo que permita la reutilización <strong>de</strong> estasaplicaciones en entornos paralelos, exigiendo que no setoque el código secuencial ya que muchas <strong>de</strong> ellas sonaplicaciones bastante antiguas aunque válidas (legacyapplications). El <strong>de</strong>sarrollo es en i<strong>de</strong>a sencillo, aunquerequiere una programación eficiente y cuidadosa paramanejar situaciones <strong>de</strong> conflicto, como es el fallo <strong>de</strong>procesos, su sincronización, y el balanceo <strong>de</strong> la carga.Los mayores problemas encontrados, como era <strong>de</strong>esperar, han sido en el ámbito <strong>de</strong> la E-S. Para el caso <strong>de</strong>re<strong>de</strong>s <strong>de</strong> or<strong>de</strong>nadores, siempre es posible utilizar losdiscos locales para evitar el cuello <strong>de</strong> botella en elsistema <strong>de</strong> almacenamiento al concurrir a él cientos ypotencialmente miles <strong>de</strong> procesos. Cuando no sedispone <strong>de</strong> este sistema distribuido <strong>de</strong> almacenamiento,el cuello <strong>de</strong> botella impi<strong>de</strong> escalar bien a la aplicación.Por ello en algunos casos es necesario abordar tanto lareformulación como el diseño <strong>de</strong> nuevo software.También es cierto que el sistema es válido paraaplicaciones que <strong>de</strong>ben llevar a<strong>de</strong>lante una serie <strong>de</strong>tareas más o menos homogéneas y que procesos <strong>de</strong> unasola tarea y con gran<strong>de</strong>s <strong>de</strong>pen<strong>de</strong>ncias <strong>de</strong> datos, son enprincipio difíciles <strong>de</strong> a<strong>de</strong>cuar a este entorno. Sinembargo, una estimación realizada en nuestro grupo,calcula que no más <strong>de</strong>l 20% <strong>de</strong> los programasbioinformáticos tienen este diseño, por lo que laaproximación sigue siendo válida para el granporcentaje <strong>de</strong> aplicaciones bioinformáticas.Aunque las aplicaciones presentadas en estedocumento tienen un patrón <strong>de</strong> cálculo bastante regular(en el caso <strong>de</strong> los dotplots se ha usado un código <strong>de</strong>fuerza bruta) la introducción <strong>de</strong> heterogeneidad en lastareas (que no la <strong>de</strong> inter<strong>de</strong>pen<strong>de</strong>ncias) es aúnmanejable vía el uso <strong>de</strong> una distribución <strong>de</strong> carga másinteligente (guiada, por ejemplo) con resultadossatisfactorios. Por tanto, no hay <strong>de</strong>pen<strong>de</strong>ncia con laoptimización <strong>de</strong> los cálculos que puedan introducirnuevas versiones <strong>de</strong> los algoritmos.Finalmente, el <strong>de</strong>sarrollo <strong>de</strong> este entorno <strong>de</strong> trabajopermitirá llevar a una ejecución paralela a cientos <strong>de</strong>programas en el ámbito bioinformático, abriendonuevas oportunida<strong>de</strong>s para el análisis <strong>de</strong> datos y para laciencia en general.AGRADECIMIENTOSEste trabajo ha sido parcialmente financiado por elInstituto Nacional <strong>de</strong> Bioinformática, plataforma <strong>de</strong>lInstituto <strong>de</strong> Salud Carlos III; la Acción Integrada <strong>de</strong>lPrograma Nacional <strong>de</strong> Internacionalización <strong>de</strong> la I+D;Subprograma: Acciones Integradas 2009; Ministerio <strong>de</strong>Ciencia e Innovación. Referencia AT2009-0025 y elprograma Virtual Multidisciplinary EnviroNmentsUSing Cloud Infrastructures, FP7-VENUS-C(www.venus-c.eu).REFERENCIAS[1] Armbrust M, Fox , et al. Above the Clouds: A Berkeley View ofCloud Computing. Technical report<strong>JP2011</strong>-535


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-536


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011AbFS: Sistema <strong>de</strong> Ficheros AbiertoAntonio F. Díaz 1 , Mancia Anguita 1 , Hugo E. Camacho 1 , Erik Nieto 1 , Julio Ortega 1Resumen—AbFS es un sistema <strong>de</strong> ficheros distribuidoque permite que se compartan los dispositivos <strong>de</strong>almacenamiento local <strong>de</strong> bajo coste que tienen loscomputadores <strong>de</strong> un cluster. Se ha implementado en elnúcleo <strong>de</strong> sistema operativo. <strong>La</strong> implementación <strong>de</strong> lagestión <strong>de</strong> metadatos <strong>de</strong> AbFS mezcla en la mismaestructura el espacio <strong>de</strong> nombres y los atributos, y combinahash, tablas, estructuras jerárquicas y caches. Con estaúltima combinación evita los problemas que presentan lasimplementaciones basadas en hash y las basadas en tablas.AbFS usa caches <strong>de</strong> metadatos y <strong>de</strong> datos en los clientes.<strong>La</strong>s caches comparten el mismo protocolo <strong>de</strong>mantenimiento <strong>de</strong> coherencia y aprovechan las estructuras<strong>de</strong> cache <strong>de</strong> Linux reduciendo, <strong>de</strong> esta forma, lacomplejidad añadida. En este trabajo se presenta, a<strong>de</strong>más<strong>de</strong> una breve <strong>de</strong>scripción <strong>de</strong> la implementación <strong>de</strong> lagestión <strong>de</strong> metadatos y <strong>de</strong> las caches en el cliente, algunosresultados experimentales. Estos resultados muestran lasbuenas prestaciones <strong>de</strong> las implementaciones propuestas.Palabras clave—Sistemas <strong>de</strong> ficheros distribuidos,metadatos, cache <strong>de</strong> datos, cache <strong>de</strong> metadatos.AI. INTRODUCCIÓNctualmente resulta asequible disponer <strong>de</strong> unconjunto <strong>de</strong> PC o servidores conectados a través <strong>de</strong>una red. El almacenamiento local <strong>de</strong> estoscomputadores se pue<strong>de</strong> compartir por las aplicacionesque ejecutan usando sistemas <strong>de</strong> ficheros distribuidoscomo PVFS [1], Lustre [2] o Ceph [3]. Al igual queestos sistemas <strong>de</strong> ficheros, AbFS permite que todos loscomputadores <strong>de</strong> un cluster puedan compartir losdispositivos <strong>de</strong> almacenamiento que tienen directamenteconectados.Un sistema <strong>de</strong> ficheros distribuido como AbFS,teniendo en cuenta que aprovecha el almacenamiento <strong>de</strong>bajo coste disponible en los nodos <strong>de</strong> cómputo y que sepue<strong>de</strong>n conectar estos nodos con re<strong>de</strong>s <strong>de</strong> prestacionessimilares a las re<strong>de</strong>s <strong>de</strong> área <strong>de</strong> almacenamiento o SAN(Store Area Networks), pue<strong>de</strong> potencialmente ofrecer unalmacenamiento <strong>de</strong> bajo coste que compita enprestaciones con los almacenamientos sistemas <strong>de</strong>ficheros basados en SAN, como IBM GPFS [4], RedHatGFS [5], SGI CXFS, Oracle OCFS o PolyServe.Para po<strong>de</strong>r alcanzar unas altas prestaciones yescalabilidad, el sistema <strong>de</strong> ficheros tiene que conseguir,a<strong>de</strong>más <strong>de</strong> unas altas prestaciones en el acceso a losdatos, también en los accesos a metadatos. Hay quetener en cuenta que las peticiones <strong>de</strong> acceso a metadatospue<strong>de</strong>n suponer más <strong>de</strong>l 50% <strong>de</strong> todas las peticionesgeneradas [6],[7],[8]; por tanto, las prestaciones <strong>de</strong> losaccesos a metadatos son importantes y para que escalen,especialmente en sistemas gran<strong>de</strong>s, se <strong>de</strong>berían distribuirentre múltiples servidores <strong>de</strong> metadatos.<strong>La</strong> gestión <strong>de</strong> metadatos no sólo incluye el acceso alespacio <strong>de</strong> nombres, a los atributos <strong>de</strong> los ficheros y alas direcciones <strong>de</strong> los bloques, también sincronizaactualizaciones concurrentes, controla los accesos ymantiene consistencia entre los datos <strong>de</strong> usuario y losmetadatos <strong>de</strong> los ficheros.AbFS utiliza cache en los clientes y servidores paramejorar las prestaciones en la lectura y escritura <strong>de</strong>metadatos y <strong>de</strong> datos. No todas las aplicaciones sebenefician <strong>de</strong>l uso <strong>de</strong> cache <strong>de</strong> datos; el sistema <strong>de</strong>ficheros Google File System [9], por ejemplo, no usacache <strong>de</strong> datos en los clientes porque no resulta rentablepara la mayor parte <strong>de</strong> su carga <strong>de</strong> trabajo. Pero hayaplicaciones que se benefician <strong>de</strong> esta cache porquepresentan proximidad espacial y temporal en los accesoso porque constan <strong>de</strong> varios programas que se comunicana través <strong>de</strong> ficheros.En este trabajo se presenta la implementación y lasprestaciones <strong>de</strong> la gestión <strong>de</strong> metadatos y <strong>de</strong> la cache <strong>de</strong>datos en los clientes <strong>de</strong> AbFS. <strong>La</strong>s implementaciones sehan realizado en el kernel. Los resultadosexperimentales se han obtenido con un prototipo <strong>de</strong>lsistema <strong>de</strong> ficheros <strong>de</strong> 64 bits completo que usa extentpara la gestión <strong>de</strong> bloques.El resto <strong>de</strong> este trabajo se ha organizado en variassecciones. <strong>La</strong> Sección II presenta la implementación <strong>de</strong>la gestión <strong>de</strong> metadatos y sus prestaciones evaluadas enel prototipo <strong>de</strong> AbFS implementado. <strong>La</strong> Sección IIIresume la implementación <strong>de</strong> la cache en los clientes ymuestra las prestaciones <strong>de</strong> la cache <strong>de</strong> datos en elprototipo. Por último, la Sección IV resume lasconclusiones <strong>de</strong>l trabajo presentado y el trabajo futuro.II. GESTIÓN DE METADATOSA. Implementación <strong>de</strong> la gestión <strong>de</strong> metadatosAbFS es un sistema <strong>de</strong> ficheros simétrico; es <strong>de</strong>cir, loscomputadores en una plataforma con AbFS pue<strong>de</strong>n ser ala vez clientes, servidores <strong>de</strong> datos y servidores <strong>de</strong>metadatos. No obstante, podría configurarse para quealgunos nodos no compartan sus dispositivos <strong>de</strong>almacenamiento (Fig. 1), podrían ser sólo clientes.Igualmente pue<strong>de</strong> haber nodos que actúen sólo comoservidores.AbFSImagen única <strong>de</strong>l almacenamientoRedAbFSAbFS1 Dpto. Arquitectura y Tecnología <strong>de</strong> Computadores, <strong>Universidad</strong> <strong>de</strong>Granada, e-mail: {afdiaz,manguita,hcamacho,enieto,jortega}@atc.ugr.esFig. 1. Sistema AbFS<strong>JP2011</strong>-537


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Todos los componentes <strong>de</strong> AbFS (inodos, ficheros, etc.)están compuestos <strong>de</strong> bloques lógicos <strong>de</strong> 4KB. Eli<strong>de</strong>ntificador <strong>de</strong> un bloque lógico consta <strong>de</strong> 64 bits, 12<strong>de</strong> esos bits i<strong>de</strong>ntifican el volumen don<strong>de</strong> se encuentraalmacenado y los 52 bits restantes el bloque <strong>de</strong>ntro <strong>de</strong>lvolumen. El volumen es una partición en un disco.AbFS utiliza tres estructuras para gestionar losmetadatos: una tabla <strong>de</strong> volúmenes, una tabla <strong>de</strong><strong>de</strong>legación y una estructura inodos. <strong>La</strong> estructura <strong>de</strong>inodos realmente está fundida con la estructura <strong>de</strong>directorio; están ambas, por tanto, almacenadas juntas endisco. Se ha hecho así para ahorrar tiempo porque unapetición <strong>de</strong> acceso a la estructura <strong>de</strong> directorios suelevenir seguida <strong>de</strong> una petición <strong>de</strong> acceso a los atributos<strong>de</strong>l fichero al que se acce<strong>de</strong>. <strong>La</strong>s tablas <strong>de</strong> <strong>de</strong>legación yla <strong>de</strong> volúmenes están replicadas en todos los nodos.Un servidor <strong>de</strong> datos y metadatos pue<strong>de</strong> contenervarios volúmenes como refleja la Fig. 1. <strong>La</strong> tabla <strong>de</strong>volúmenes relaciona cada volumen con el servidordon<strong>de</strong> se encuentra.En la Fig. 2 se pue<strong>de</strong> ver un ejemplo <strong>de</strong> tabla <strong>de</strong><strong>de</strong>legación, en este caso con 32.768 entradas. En lafigura también aparecen las sub-tablas <strong>de</strong> la estructura<strong>de</strong> inodos. Cada inodo en una estructura <strong>de</strong> inodos ocupa512 bytes.El <strong>de</strong>scriptor interno <strong>de</strong> un fichero o <strong>de</strong> un directorio esel i<strong>de</strong>ntificador <strong>de</strong>l inodo don<strong>de</strong> se encuentran susmetadatos. Usando una función hash (Fig. 2) se obtieneel <strong>de</strong>scriptor interno <strong>de</strong> un fichero a partir <strong>de</strong> su nombreexterno (lógico) y <strong>de</strong>l <strong>de</strong>scriptor interno <strong>de</strong> su directoriopadre. El <strong>de</strong>scriptor interno o i<strong>de</strong>ntificador <strong>de</strong>l inodo secompone <strong>de</strong>:• N bits <strong>de</strong> <strong>de</strong>legación que i<strong>de</strong>ntifican la entrada <strong>de</strong>linodo en la tabla <strong>de</strong> <strong>de</strong>legación o tabla hash. N es 15bits en la Fig. 2. Esta entrada informa <strong>de</strong>l volumen y<strong>de</strong> la sub-tabla <strong>de</strong>ntro <strong>de</strong> éste don<strong>de</strong> se encuentra elinodo.• 32-N bits que i<strong>de</strong>ntifican al inodo <strong>de</strong>ntro <strong>de</strong> la subtablaa la que apunta la entrada <strong>de</strong>l inodo en la tabla<strong>de</strong> <strong>de</strong>legación.N es un valor máximo, se pue<strong>de</strong>n usar menos bits si elnúmero <strong>de</strong> volúmenes es reducido; es <strong>de</strong>cir, en realidadse usa un hash extensible [10] para permitir unredimensionado <strong>de</strong> bajo coste <strong>de</strong> la tabla <strong>de</strong> <strong>de</strong>legación.El tamaño <strong>de</strong> la tabla <strong>de</strong> <strong>de</strong>legación va a <strong>de</strong>pen<strong>de</strong>r, portanto, <strong>de</strong>l número <strong>de</strong> volúmenes; es <strong>de</strong>cir, <strong>de</strong>l tamaño <strong>de</strong>lsistema. En el ejemplo <strong>de</strong> la Fig. 2 hay 32.768 entradasen la tabla <strong>de</strong> <strong>de</strong>legación y 16 volúmenes. En el sistema<strong>de</strong> ficheros IBM GPFS[4] y en la implementación <strong>de</strong>metadatos propuesta en [11] se utiliza un hash extensiblepara la gestión <strong>de</strong> gran<strong>de</strong>s directorios.Como se ha mencionado, cada entrada en la tabla <strong>de</strong><strong>de</strong>legación apunta a un volumen y a una sub-tabla <strong>de</strong>inodos <strong>de</strong>ntro <strong>de</strong> ese volumen (apunta al primer bloque<strong>de</strong> la sub-tabla). El número <strong>de</strong> sub-tablas <strong>de</strong> un volumeny, por consiguiente, el número <strong>de</strong> entradas <strong>de</strong> la tabla <strong>de</strong><strong>de</strong>legación asignadas a un volumen, <strong>de</strong>pen<strong>de</strong> <strong>de</strong> sutamaño. AbFS reparte las entradas aleatoriamente entrelos volúmenes teniendo en cuenta sus tamaños. Tiene encuenta el tamaño porque asume que la capacidad <strong>de</strong>almacenamiento <strong>de</strong> un servidor está relacionada con susprestaciones. De esta forma distribuye la gestión <strong>de</strong>metadatos entre los servidores para que que<strong>de</strong>balanceada. AbFS distribuye ficheros entre volúmenesen lugar <strong>de</strong> distribuirlos entre servidores <strong>de</strong> metadatos.En el caso <strong>de</strong> las implementaciones basadas en hash yFig. 2. Delegation table and ino<strong>de</strong> subtables<strong>JP2011</strong>-538


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011tabla <strong>de</strong> [12] se distribuyen ficheros entre servidores <strong>de</strong>metadatos y en la <strong>de</strong> [11] se distribuyen subdirectoriosentre servidores <strong>de</strong> metadatos.Si se aña<strong>de</strong> un nuevo volumen se modifican algunasentradas <strong>de</strong> la tabla <strong>de</strong> <strong>de</strong>legación para que algunosinodos migren al nuevo volumen, la migración se hacepara mantener balanceada la gestión <strong>de</strong> metadatos. Eluso <strong>de</strong> la tabla <strong>de</strong> <strong>de</strong>legación evita que añadir volúmenesimplique redistribuir todos los inodos entre todos losvolúmenes como ocurre en la implementación <strong>de</strong>metadatos <strong>de</strong>l sistema <strong>de</strong> ficheros Vesta [13]. En estesistema <strong>de</strong> ficheros se usa una hash para distribuir losficheros entre los servidores <strong>de</strong> metadatos. <strong>La</strong> hash usacomo entrada el nombre absoluto (camino completo) <strong>de</strong>lfichero. El servidor <strong>de</strong> metadatos se obtiene calculandoel módulo <strong>de</strong> esta salida con respecto al número <strong>de</strong>servidores. Dada la implementación, cuando se aña<strong>de</strong> unservidor, pue<strong>de</strong> cambiar el resultado <strong>de</strong>l módulo.Obsérvese que sólo cuando se <strong>de</strong>sconoce eli<strong>de</strong>ntificador <strong>de</strong> inodo <strong>de</strong> un fichero (se ejecuta unlookup) es cuando éste se obtiene a partir <strong>de</strong>li<strong>de</strong>ntificador inodo <strong>de</strong> su directorio padre y <strong>de</strong> sunombre usando una función hash (Fig. 2). En [12] y en[11] se usa una implementación basada en una funciónhash y una tabla, pero como entrada a la función hash seutiliza el camino completo (nombre absoluto) <strong>de</strong>lfichero. AbFS usa el nombre <strong>de</strong>l fichero en lugar <strong>de</strong>lcamino completo y mantiene el i<strong>de</strong>ntificador <strong>de</strong> inodo<strong>de</strong>l directorio padre constante por lo que, cuando serenombra el directorio, evita la redistribución <strong>de</strong> datosentre volúmenes ya que no cambia la salida <strong>de</strong> lafunción hash.Para mejorar las prestaciones adicionalmente,especialmente con un número <strong>de</strong> ficheros elevado, AbFSusa más <strong>de</strong> un nivel <strong>de</strong> hash/tabla para localizar la subtabla<strong>de</strong>l inodo buscado. Los inodos <strong>de</strong> una sub-tabla(Fig. 2) están in<strong>de</strong>xados en una estructura <strong>de</strong> hasta tresniveles para obtener un acceso rápido.B. Resultados experimentalesLos resultados experimentales mostrados en esteapartado se han obtenido con doce nodos, cada uno condos procesadores Quad-Core Intel Xeon E5450 <strong>de</strong> 3GHz y 16GB RAM, conectados con un conmutadorInfiniband MT25418 <strong>de</strong> Mellanox usando IPoIB.Para la evaluación <strong>de</strong> prestaciones se ha usado elbenchmark mdtest. En la entrada <strong>de</strong> mdtest se haespecificado que cada cliente genere tres directorios y50.000 ficheros/directorios en cada uno. Con mdtest sepue<strong>de</strong>n evaluar las prestaciones <strong>de</strong> las operaciones <strong>de</strong>metadatos más comunes, como son la creación y laoperación stat <strong>de</strong> ficheros y directorios. Utiliza MPI parala coordinación y sincronización entre nodos.En la Fig. 3 se pue<strong>de</strong>n ver las prestaciones para lacreación <strong>de</strong> ficheros y directorios usando 12 nodos. Seis<strong>de</strong> ellos se usan como servidores (<strong>de</strong> datos y metadatos).Como clientes se pue<strong>de</strong>n usar los doce nodos (el total <strong>de</strong>clientes <strong>de</strong>pen<strong>de</strong> <strong>de</strong>l número <strong>de</strong> procesos). <strong>La</strong> Fig. 4muestra las prestaciones para stat con la mismaconfiguración. Como se pue<strong>de</strong> observar en estas figuras,las prestaciones escalan linealmente hasta que se usanlos 12 clientes, es <strong>de</strong>cir, hasta 12 procesos. El escaladose frena cuando se supera el número <strong>de</strong> clientes porquelos procesos <strong>de</strong> un cliente compiten por los recursos.Fig. 3. Prestaciones <strong>de</strong> la creación (operaciones por segundo) <strong>de</strong>directorios y ficheros con 12 nodos: 6 servidores, 12 clientesFig. 4. Prestaciones <strong>de</strong> stat (operaciones por segundo) <strong>de</strong> directorios yficheros con 12 nodos: 6 servidores, 12 clientesFig. 5. Prestaciones <strong>de</strong> creación (operaciones por segundo) <strong>de</strong>directorios y ficheros con 12 nodos: 6 servidores más 6 clientesFig. 6. Prestaciones <strong>de</strong> stat (operaciones por segundo) <strong>de</strong> directoriosy ficheros con 12 nodos: 6 servidores más 6 clientes<strong>JP2011</strong>-539


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Esto se pue<strong>de</strong> ver con más claridad en las Figuras 5 y 6,en las que se muestran las prestaciones para creación(Fig. 5) y para stat (Fig. 6) con 12 nodos, seis <strong>de</strong> ellosservidores y los otros seis clientes.<strong>La</strong>s prestaciones <strong>de</strong> la gestión <strong>de</strong> metadatos en AbFSson claramente mejores que las prestaciones <strong>de</strong> Lustre(1.6, 20) [14, 15], PVFS [16] y Ceph [3] encontradas enla bibliografía. Los resultados <strong>de</strong> [15] se han obtenido en70 clientes con Pegasus+ bla<strong>de</strong>s <strong>de</strong> 4 procesadoresQuad-Core AMD Opteron(tm) 8380 16GB RAM y unservidor <strong>de</strong> metadatos Sun Fire X4540 (Thor) con 2Quad-Core AMD Opteron(tm) 2356 64GB RAM. <strong>La</strong>máxima velocidad <strong>de</strong> creación <strong>de</strong> directorios y ficherosalcanzada con Lustre 2.0 usando mdtest es <strong>de</strong> unos7.500 y unos 900 operaciones/segundo, respectivamente.Para stat las prestaciones son <strong>de</strong> unos 25.800operaciones/segundo para directorios y 25.000 paraficheros. Estas versiones <strong>de</strong> Lustre aún no distribuye lagestión <strong>de</strong> metadatos entre varios servidores, el uso <strong>de</strong>un único servidor <strong>de</strong> metadatos limita las prestaciones(tiene otro servidor <strong>de</strong> metadatos, pero lo usa <strong>de</strong>respaldo). Se prevé que Lustre 3 distribuya la gestión <strong>de</strong>metadatos entre varios servidores.III. CACHE EN CLIENTESA. Implementación <strong>de</strong> la cacheAbFS utiliza cache en los clientes para mejorar lasprestaciones en la lectura y escritura <strong>de</strong> datos ymetadatos. Aprovecha la cache <strong>de</strong> buffer <strong>de</strong> dispositivo<strong>de</strong> Linux para implementar la cache <strong>de</strong> datos <strong>de</strong>l clientey las caches <strong>de</strong> metadatos <strong>de</strong> Linux (ino<strong>de</strong> y <strong>de</strong>ntry) paraimplementar las caches <strong>de</strong> metadatos en los clientes. Deesta forma no ha sido necesario añadir capas extras paraimplementar estas caches. <strong>La</strong> cache <strong>de</strong> datos aprovechala lectura a<strong>de</strong>lantada (pre-captación) que implementaVFS (Virtual File System) para la cache <strong>de</strong> buffer <strong>de</strong>dispositivo.Usar caches mejora las prestaciones porque reducen eltiempo <strong>de</strong> acceso a los datos por estar más cerca y,adicionalmente, también porque disminuyen los accesosal servidor y, por tanto, su congestión. En AbFS, lascaches reducen la congestión <strong>de</strong> los servidores y <strong>de</strong> lascaches <strong>de</strong>l servidor también cuando se abre un ficheropara escritura. El primer nodo que abre un fichero paraescritura es el propietario <strong>de</strong>l fichero. Se consiguereducir la congestión porque los clientes que escriben enel fichero combinan las escrituras en la cache <strong>de</strong>lpropietario en lugar <strong>de</strong> ir al servidor y porque losclientes leen, cuando hay propietario, <strong>de</strong> la cache <strong>de</strong>lpropietario en lugar <strong>de</strong> leer <strong>de</strong>l servidor. En estasituación, es <strong>de</strong>cir, cuando hay propietario, la cachetiene unas prestaciones similares a la cache cooperativabasada en home <strong>de</strong> [17]. Como se pue<strong>de</strong> <strong>de</strong>ducir AbFSaña<strong>de</strong> comunicaciones cliente-cliente y servidorservidora las comunicaciones cliente-servidor utilizadasen sistemas <strong>de</strong> ficheros basados en el mo<strong>de</strong>lo clienteservidor,como NFS.<strong>La</strong> Fig. 7 resume el protocolo <strong>de</strong> coherencia <strong>de</strong> cacheen el cliente. Aunque los bloques <strong>de</strong> la cache <strong>de</strong> bufferNº Estado Evento Comentario Sig. estado1 (C) Interno al nodo: lookup o dir-create Inodo compartido (S)2 (C) Interno al nodo: fichero create Nodo gana la propiedad <strong>de</strong>l inodo (E)3 (C)Interno al nodo: lookup, o abre el fichero y está yaabierto para escritura en otro nodoNodo no gana la propiedad <strong>de</strong>l inodo (I)4 (S)Externo al nodo: invalidación.Interno al nodo: lookup, o abre fichero y otro nodo Nodo no gana la propiedad <strong>de</strong>l inodo (I)tiene la propiedad <strong>de</strong>l mismo5 (S)Interno al nodo: abre el fichero para escribir (1 er nodoque lo abre para escribir)Nodo gana la propiedad <strong>de</strong>l inodo (E)6 (E)Interno al nodo: cierra el fichero abierto paraescrituraInodo compartido y escritura al servidor (S)7 (E) Servidor <strong>de</strong>niega propiedad Excepción (I)8 (I) Interno al nodo: lookup, o abre el fichero para leer Inodo compartido (S)9 (I)Interno al nodo: abre el fichero para escribir (1 ernodo que lo abre para escribir)Nodo gana la propiedad <strong>de</strong>l inodo (E)Fig. 7. Resumen <strong>de</strong>l protocolo <strong>de</strong> coherencia <strong>de</strong> cache basado en propietario<strong>JP2011</strong>-540


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>de</strong> dispositivo son <strong>de</strong> 4KB, el bloque en el protocolo <strong>de</strong>mantenimiento <strong>de</strong> coherencia es un fichero (se aplica alinodo). Un inodo en la cache <strong>de</strong>l cliente o <strong>de</strong>l servidorpue<strong>de</strong> estar en uno <strong>de</strong> estos estados:• (C)lear: el inodo no está en la cache (pue<strong>de</strong> existir endisco). Es el estado inicial <strong>de</strong> todos los inodos.• (E)xclusivo: los datos y metadatos <strong>de</strong>l inodo sonválidos únicamente en esta cache, es <strong>de</strong>cir, en lacache <strong>de</strong>l nodo propietario. Los otros nodos no tienencopias válidas. El nodo propietario es el primer nodoque abre un fichero para escribir en él.• (S)hared o compartido: los datos y metadatos <strong>de</strong>linodo son válidos en este cache y pue<strong>de</strong>n ser válidostambién en las caches <strong>de</strong> otros nodos.• (I)nválido: los datos y metadatos <strong>de</strong>l inodo soninválidos.B. Resultados experimentales<strong>La</strong>s ejecuciones se han realizado en la misma plataformautilizada en los test <strong>de</strong> la Sección II.<strong>La</strong> Fig. 8 ilustra sobre la ventaja <strong>de</strong> usar la cache <strong>de</strong>datos. Los tiempos <strong>de</strong> lectura y escritura se reducen enun 97% aproximadamente si los datos se encuentran enla cache. <strong>La</strong>s prestaciones mejoran más que con la cacheque hemos implementado <strong>de</strong>s<strong>de</strong> cero para el sistema <strong>de</strong>ficheros PVFS [18].IV. CONCLUSIONESEste trabajo muestra unas buenas prestaciones <strong>de</strong> laimplementación <strong>de</strong> gestión <strong>de</strong> metadatos <strong>de</strong>l sistema <strong>de</strong>ficheros AbFS. Así, por ejemplo, con 12 nodos, 6servidores y hasta 12 clientes, se consiguen más <strong>de</strong>65.000 operaciones por segundo para creación <strong>de</strong>directorios, más <strong>de</strong> 90.000 para creación <strong>de</strong> ficheros,más <strong>de</strong> 5.500.000 para operaciones stat <strong>de</strong> directorios ymás <strong>de</strong> 5.800.000 para stat <strong>de</strong> ficheros.Igualmente muestra las buenas prestaciones <strong>de</strong> laimplementación <strong>de</strong> cache <strong>de</strong> datos en los clientes <strong>de</strong>AbFS, que aprovecha la cache <strong>de</strong> buffer <strong>de</strong> dispositivo<strong>de</strong> Linux. <strong>La</strong>s caches <strong>de</strong> metadatos y datosimplementadas permiten escritura en la cache sinintervención <strong>de</strong>l usuario ya que mantienen coherencia.Como trabajo futuro se preten<strong>de</strong> realizar experimentoscon un mayor número <strong>de</strong> nodos y comparaciones en laFig. 2. Prestaciones <strong>de</strong> la cache <strong>de</strong> datos. wr_no_cache y rd_no_cacheson escrituras y lecturas, respectivamente, sin cache. wr_cache yrd_cache son escrituras y lecturas, respectivamente, en la cachemisma plataforma con otros sistemas <strong>de</strong> ficheros, comoCeph, Lustre y PVFS.AGRADECIMIENTOSLos autores agra<strong>de</strong>cen a Catón Sistemas Alternativos susoporte y a la Fundación Centro <strong>de</strong> Supercomputación<strong>de</strong> Castilla y León (FCSCL) el acceso a uno <strong>de</strong> loscluster <strong>de</strong>l supercomputador Caléndula. Este trabajo hasido financiado parcialmente por el proyecto TEC2010-15396.REFERENCIAS[1] P. H. Carns, W. B. Ligon III, R. B. Ross and R. Thakur, "PVFS: Aparallel file system for linux clusters," in Proceedings of the 4thAnnual Linux Showcase and Conference, 2000, pp. 317-327.[2] P. J. Braam, "The Lustre Storage Architecture," November, 2002.[3] S. A. Weil, S. A. Brandt, E. L. Miller, D. D. E. Long and C.Maltzahn, "Ceph: A scalable, high-performance distributed filesystem," in OSDI '06: Proceedings of the 7th Symposium onOperating Systems Design and Implementation, Seattle,Washington, 2006, pp. 307-320.[4] F. Schmuck and R. Haskin, "GPFS: A shared-disk file system forlarge computing clusters," in FAST '02: Proceedings of the 1stUSENIX Conference on File and Storage Technologies, Monterey,CA, 2002, pp. 19.[5] S. R. Soltis, T. M. Ruwart and M. T. O'Keefe, "The global filesystem," in Proceedings of the Fifth NASA Goddard Conferenceon Mass Storage Systems and Technologies, 1996, pp. 319-342.[6] J. K. Ousterhout, H. Da Costa, D. Harrison, J. A. Kunze, M.Kupfer and J. G. Thompson, "A trace-driven analysis of the UNIX4.2 BSD file system," in SOSP '85: Proceedings of the TenthACM Symposium on Operating Systems Principles, Orcas Island,Washington, United States, 1985, pp. 15-24.[7] D. Roselli, J. R. Lorch and T. E. An<strong>de</strong>rson, "A comparison of filesystem workloads," in ATEC '00: Proceedings of the AnnualConference on USENIX Annual Technical Conference, San Diego,California, 2000, pp. 4-4.[8] SPEC, "SPECsfs2008 user's gui<strong>de</strong> v. 1.0," Standard PerformanceEvaluation Corporation (SPEC), 6585 Merchant Place, Suite 100,Warrenton, VA 20187, USA, 2008. 2008.[9] S. Ghemawat, H. Gobioff and S. Leung, "The google file system,"in SOSP '03: Proceedings of the Nineteenth ACM Symposium onOperating Systems Principles, Bolton <strong>La</strong>nding, NY, USA, 2003,pp. 29-43.[10] R. Fagin, J. Nievergelt, N. Pippenger and H. R. Strong,"Extendible hashing---a fast access method for dynamic files,"ACM Trans.Database Syst., vol. 4, pp. 315-344, 1979.[11] M. Xiong, H. Jin and S. Wu, "FDSSS: An efficient metadatamanagement scheme in large scale data environment," in FifthInternational Conference on Grid and Cooperative ComputingWorkshops, GCCW '06, 2006, pp. 71-77.[12] S. A. Brandt, E. L. Miller, D. D. E. Long and <strong>La</strong>n Xue, "Efficientmetadata management in large distributed storage systems,"Proceedings 20th IEEE/11th NASA Goddard Conference on MassStorage Systems and Technologies, MSST 2003., pp. 290-298,2003.[13] P. F. Corbett and D. G. Feitelson, "The vesta parallel file system,"in High Performance Mass Storage and Parallel {I/O}:Technologies and Applications, H. Jin, T. Cortes and R. Buyya,Eds. New York, NY: IEEE Computer Society Press and Wiley,2001, pp. 285-308.[14] W. Turek and P. Calleja, High Performance, Open Source, DellLustre Storage System. White Paper. Dell - University ofCambridge, 2010.[15] P. Kon<strong>de</strong>kar, MDS Performance Analysis. Sun Microsystems,2009.[16] J. M. Kunkel and T. Ludwig, "Performance evaluation of thePVFS2 architecture," in 15th EUROMICRO InternationalConference on Parallel, Distributed and Network-BasedProcessing, 2007, pp. 509-516.[17] I. Hwang, S. Maeng and J. Cho, "Home-based CooperativeCache for parallel I/O applications," Future Generation ComputerSystems, vol. 22, pp. 633-642, 2006/4.[18] H. E. Camacho, E. Nieto, M. Anguita, A. F."Client cache for PVFS2," in 1st International Conference on<strong>JP2011</strong>-541


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Parallel Distributed and Grid Computing (PDGC),2010, pp. 38-43.<strong>JP2011</strong>-542


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Comparación <strong>de</strong>l rendimiento entre loshipervisores XEN y KVM usando virtualizaciónIsaac Zablah por hardware1 , R. Valin 2 , A. García-Loureiro 2 , Javier López Cacheiro 3 , Fernando Gomez-Folgar 3Resumen 1 — El presente artículo muestra los resultadosobtenidos tras ejecutar un conjunto <strong>de</strong> benchmarks enanfitriones y máquinas virtuales gestionadas con loshipervisores Xen y KVM. <strong>La</strong> finalidad fue <strong>de</strong>terminar cuál<strong>de</strong> ellos era más eficiente para las aplicaciones tipo quepreten<strong>de</strong>mos ejecutar en la infraestructura computacional<strong>de</strong>l proyecto Formiga Cloud. En los resultados obtenidos,se observó que las máquinas virtuales <strong>de</strong> Xen presentan unmejor rendimiento con aplicaciones <strong>de</strong> cálculo que lasmáquinas virtuales <strong>de</strong> KVM, mientras que para laspruebas <strong>de</strong> escritura en disco, el rendimiento <strong>de</strong> lasmáquinas virtuales <strong>de</strong> KVM es mejor que el <strong>de</strong> lasmáquinas virtuales <strong>de</strong> Xen.Palabras clave— Benchmarks, XEN, KVM, máquinasvirtuales, hipervisores.I. INTRODUCCIÓNDurante los últimos años hemos asistido a un<strong>de</strong>sarrollo notable <strong>de</strong> las infraestructuras Cloud, asícomo <strong>de</strong> los fundamentos tecnológicos que permiten suimplementación, entre los que se <strong>de</strong>stacan laarquitectura orientada a servicios (SOA) y lavirtualización Hardware y Software [1]. En el caso <strong>de</strong>las tecnologías <strong>de</strong> virtualización, éstas son uno <strong>de</strong> losprincipales fundamentos <strong>de</strong>l mo<strong>de</strong>lo Cloud conocidocomo infraestructura como servicio (IaaS), basado en lagestión <strong>de</strong> los recursos hardware.El proyecto Formiga Cloud [2] propone la creación <strong>de</strong>una infraestructura Cloud, basada en el mo<strong>de</strong>lo IaaS,que permita el aprovechamiento <strong>de</strong> los recursoscomputaciones <strong>de</strong> las aulas <strong>de</strong> informáticapertenecientes a las universida<strong>de</strong>s para su uso tanto entareas docentes como en tareas <strong>de</strong> cálculo científico.En el marco <strong>de</strong> este proyecto, se <strong>de</strong>tectó la necesidad<strong>de</strong> realizar una evaluación <strong>de</strong>l rendimiento <strong>de</strong> loshipervisores compatibles con la infraestructura FormigaCloud. Esto es <strong>de</strong>bido a que es necesario utilizar latecnología <strong>de</strong> virtualización, para po<strong>de</strong>r sacar provecho<strong>de</strong> los or<strong>de</strong>nadores disponibles <strong>de</strong>ntro <strong>de</strong> una institucióndurante los períodos <strong>de</strong> inactividad. Con lo anterior, sepreten<strong>de</strong> instalar sistemas virtualizados que se gestionen<strong>de</strong> forma remota y en los que se pueda implementar unaarquitectura <strong>de</strong> computación distribuida, para que seanempleados con fines relacionados a la computaciónintensiva. A<strong>de</strong>más, la infraestructura también estará1 Sistema <strong>de</strong> Difusión <strong>de</strong> Radio y Televisión – <strong>Universidad</strong> NacionalAutónoma <strong>de</strong> Honduras, e-mail: mrzablah@unah.tv2 Dpto. Electrónica y Computación, <strong>Universidad</strong> <strong>de</strong> Santiago <strong>de</strong>Compostela, e-mail: raul.valin@usc.es, antonio.garcia.loureiro@usc.es3Dpto. <strong>de</strong> Sistemas, Centro <strong>de</strong> Supercomputación <strong>de</strong> Galicia(CESGA), e-mail: jlopez@cesga.es, fgfolgar@cesga.esdisponible para fines docentes, permitiendo a losprofesores y alumnos <strong>de</strong>splegar máquinas virtuales(MV) bajo <strong>de</strong>manda.Para este estudio se han seleccionado los hipervisoresXen 4.0.2-rc3 con Linux kernel 2.6.32.37, sobre CentOS5.6 (Xen4), Xen 3.1.2-238.9.1.el5 con Linux kernel2.6.18-238.9.1.el5xen sobre CentOS 5.5 (Xen3) y KVMsobre Ubuntu 10.04.2 LTS con Linux kernel 2.6.32-31-server en combinación con la versión <strong>de</strong> qemu-kvm0.12.3(KVM), ya que son compatibles con lainfraestructura propuesta. Ambos son <strong>de</strong> código abiertoy se encuentran entre los más ampliamente utilizados enla computación <strong>de</strong> altas prestaciones. Para evaluar surendimiento se han ejecutado una serie <strong>de</strong> benchmarksestandarizados para estos fines, y se ha utilizado,también, una aplicación <strong>de</strong> computación intensiva. Hayque señalar que la finalidad <strong>de</strong> evaluar dos versionesdistintas <strong>de</strong> Xen es tasar sus respectivos rendimientos ysu repercusión en las MV. Adicionalmente, se evaluó unsistema con el kernel original <strong>de</strong> la distribución CentOS5.5, cuya versión es 2.6.18-238.12.1.el5, para conocer <strong>de</strong>igual forma los cambios <strong>de</strong> rendimiento al tenerinstalado el kernel Xen.En este trabajo se han evaluado tres aspectosesenciales en lo que se refiere a la comparación <strong>de</strong>lrendimiento <strong>de</strong> la máquina virtual con la máquina física.El primero, la capacidad <strong>de</strong> cálculo usando LINPACK[3], el segundo, la evaluación <strong>de</strong> la entrada/salida <strong>de</strong>ldisco duro por medio <strong>de</strong> una medición <strong>de</strong> la tasa <strong>de</strong>transferencia <strong>de</strong> escritura empleando IOZone [4] y,finalmente, la evaluación <strong>de</strong>l rendimiento cuando seemplea una aplicación <strong>de</strong> cálculo científico.Este artículo se ha dividido en las siguientes secciones:en la sección dos se realiza una breve <strong>de</strong>scripción <strong>de</strong> loshipervisores usados. En la sección tres se hace una<strong>de</strong>scripción <strong>de</strong> los benchmarks empleados. En la seccióncuatro se <strong>de</strong>scriben los resultados obtenidos y,finalmente, en la sección quinta se plantean y discutenlas conclusiones <strong>de</strong>l trabajo realizado.II.DESCRIPCIÓN DE LOS HIPERVISORESEl hipervisor Xen [5] es una herramienta utilizadapara implementar la tecnología <strong>de</strong> virtualización, y quepermite la ejecución en las MV <strong>de</strong> una gran variedad <strong>de</strong>sistemas operativos como, por ejemplo, Linux, BSD oWindows, entre otros. En su última versión [6],introduce optimizaciones en la gestión <strong>de</strong> cargas <strong>de</strong>trabajo, disminuyendo la latencia en aplicaciones <strong>de</strong> redy audio, entre otras. Actualmente, Xen permite utilizar eljuego <strong>de</strong> instrucciones más reciente <strong>de</strong> los procesadoresINTEL, como las llamadas “Advanced Vector<strong>JP2011</strong>-543


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011eXtension, AVX”, entre otras. Se implementa a través <strong>de</strong>un kernel modificado con el soporte <strong>de</strong> virtualización.Xen pue<strong>de</strong> ejecutarse en modo paravirtualizado, don<strong>de</strong>se requiere adaptar el sistema operativo <strong>de</strong> la máquinavirtual (huésped), o en modo <strong>de</strong> virtualización completa,que no requiere efectuar modificaciones en el software<strong>de</strong>l huésped.El hipervisor KVM (Kernel Virtual Machine) [7],opera por medio <strong>de</strong> una serie <strong>de</strong> módulos cargadosdurante el arranque <strong>de</strong>l sistema operativo, convirtiendo atodo el sistema en un gestor <strong>de</strong> virtualización, adiferencia <strong>de</strong> otros hipervisores que reescriben partes <strong>de</strong>lsistema operativo creando un kernel personalizado. Conestos módulos, se ha logrado simplificar la gestión yaumentar el rendimiento <strong>de</strong> los entornos virtualizados,<strong>de</strong> manera que cada MV se ejecuta como un proceso<strong>de</strong>ntro <strong>de</strong>l sistema operativo. KVM requiere para suejecución contar con un microprocesador con soportepara virtualización por hardware [8].III.DESCRIPCIÓN DE LOS BENCHMARKSCon la finalidad <strong>de</strong> evaluar y comparar el rendimiento<strong>de</strong> las máquinas virtuales con las respectivas máquinasfísicas, se han seleccionado los siguientes benchmarks:IOZone [4]: es un benchmark sintético que se utilizapara conocer la medida <strong>de</strong> rendimiento <strong>de</strong>l disco en losprocesos <strong>de</strong> lectura y escritura. Se ha utilizado unapartición al final <strong>de</strong>l disco duro <strong>de</strong> 20 GB en la que seescribe el fichero temporal <strong>de</strong> esta aplicación, evitando,<strong>de</strong> esta forma, que los resultados se viesen alterados porescribir en distintas zonas <strong>de</strong>l disco. <strong>La</strong> versiónempleada es la 3.385.Linpack [3]: es un benchmark sintético que se utilizapara conocer el rendimiento <strong>de</strong>l sistema en cuanto acálculo. Fue <strong>de</strong>sarrollado en el Argone National<strong>La</strong>boratory por Jack Dongarra en 1976, y es uno <strong>de</strong> losmás usados a nivel científico [9]. Su característicafundamental es que hace un uso intensivo <strong>de</strong> lasoperaciones <strong>de</strong> punto flotante, y sus resultados son muy<strong>de</strong>pendientes <strong>de</strong> la capacidad <strong>de</strong> la unidad <strong>de</strong> puntoflotante (FPU) <strong>de</strong> los sistemas evaluados. Para esteartículo se utilizó la distribución <strong>de</strong>l Linpack versión10.3.3 que Intel tiene disponible como parte <strong>de</strong> susherramientas Math Kernel.Simulador <strong>de</strong> Nanodispositivos MOSFET: es unaaplicación <strong>de</strong> cálculo científico utilizada en el campo <strong>de</strong>la simulación <strong>de</strong> tipo Monte Carlo [10] para dispositivossemiconductores. Se ha aplicado al estudio <strong>de</strong>transistores MOSFET (Metal Oxi<strong>de</strong> SemiconductorField Effect Transistor), que son los dispositivoselectrónicos más utilizados en la industria electrónicahoy en día, ya que han permitido alcanzar una mayorcapacidad <strong>de</strong> integración en los diseños <strong>de</strong> circuitospermitiendo fabricar procesadores <strong>de</strong> mayorrendimiento.IV.RESULTADOSEn esta sección se muestran los resultados <strong>de</strong> laejecución <strong>de</strong> las distintas pruebas <strong>de</strong> rendimiento. Seempleó un or<strong>de</strong>nador TOSHIBA Qosmio X500 con unprocesador Intel Core i7 Q720 @ 1.60Ghz, con 4GB <strong>de</strong>RAM y disco duro <strong>de</strong> 500GB <strong>de</strong> 7200RPM SATAIIpara las pruebas <strong>de</strong>l hipervisor KVM. Para las pruebascon el hipervisor Xen se empleó un or<strong>de</strong>nador conprocesador Intel Xeon E5520 @ 2.27GHz, con 16GB <strong>de</strong>RAM y disco duro <strong>de</strong> 500GB <strong>de</strong> 7200RPM.<strong>La</strong>s características <strong>de</strong> configuración <strong>de</strong> las MV y <strong>de</strong>los sistemas anfitriones se <strong>de</strong>scriben a continuación:• Se <strong>de</strong>sactivó la memoria SWAP tanto en lossistemas anfitriones como en las máquinasvirtuales.• En todas particiones se empleó el formatoEXT2.• Se utilizó la misma cantidad <strong>de</strong> memoria RAMpara la ejecución <strong>de</strong> las pruebas en todos lossistemas (1GB).• Se <strong>de</strong>sactivó la funcionalidad <strong>de</strong>Hyperthreading <strong>de</strong>l microprocesador y a<strong>de</strong>mássólo se ha empleado un núcleo en todas laspruebas.• En el caso <strong>de</strong> la prueba <strong>de</strong> IOZone, se utilizóuna partición ubicada al final <strong>de</strong>l disco duro, <strong>de</strong>manera que todas las pruebas se ejecutaron enlas mismas condiciones (en la misma región <strong>de</strong>ldisco).• Se <strong>de</strong>sactivó la utilidad CPUSpeed, que vieneintegrada en varias distribuciones <strong>de</strong> Linux.• Todos los sistemas operativos se utilizaron ensu versión <strong>de</strong> 64bits.• En el caso <strong>de</strong> KVM, se empleó la utilidad “virtmanager”para gestionar las máquinas virtualesy, a<strong>de</strong>más, en ellas se emplearon loscontroladores VirtIO [11].A continuación, se presentan los resultados para cadauno <strong>de</strong> los benchmarks realizados:A. Prueba con LinpackEn esta prueba se utilizó un tamaño <strong>de</strong> problema y <strong>de</strong>dimensiones <strong>de</strong> 5000, con valores <strong>de</strong> alineación <strong>de</strong>4KBytes. Linpack proporciona una medida promedio <strong>de</strong>la capacidad <strong>de</strong> procesamiento en unida<strong>de</strong>s <strong>de</strong>GigaFLOPS (GFlops). Los resultados absolutos semuestran en la Tabla 1:SISTEMAGFlopsRESULTADOSTiempo (s)Anfitrión KVM 8.61 57.30MV KVM 5.54 85.07Anfitrión NoXen 8.36 59.49Anfitrión Xen3 8.44 59.59MV Xen3 6.76 74.47Anfitrión Xen4 8.16 60.95MV Xen4 8.12 61.13Tabla 1: Resultados con LINPACKLos resultados <strong>de</strong> la Tabla 1 muestran que en el caso<strong>de</strong> la MV en KVM tiene una pérdida <strong>de</strong> rendimiento <strong>de</strong>3.07 GigaFLOPS respecto al anfitrión; requiriendo la<strong>JP2011</strong>-544


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011MV sólo 27.77 segundos adicionales para completar laprueba. En Xen3, <strong>La</strong> MV fue menos eficiente que elanfitrión, perdiendo 1.68 GigaFLOPS y requiriendo14.88 segundos adicionales para completar la prueba. EnXen4, los rendimientos fueron muy parecidos entre laMV y el anfitrión, don<strong>de</strong> se presentó una mínimapérdida <strong>de</strong> 0.04 GigaFLOPS por parte la MV. Esimportante mencionar que el anfitrión Xen3 obtuvoresultados más altos en este benchmark que el anfitriónsin el kernel <strong>de</strong> Xen, superando a éste por 0.08GigaFLOPS. Sin embargo, el anfitrión Xen4 rindiómenos que el sistema con kernel original perdiendo 0.20GigaFLOPS.El rendimiento en GigaFLOPS <strong>de</strong> los sistemasevaluados siguió el comportamiento que muestra laGráfica 1:Gráfica 1: Comportamiento <strong>de</strong> los sistemas evaluados conLinpackEn cambio, el comportamiento relativo que existeentre las MV/anfitriones y entre los anfitriones y lamáquina sin modificar se muestra en la Tabla 2:MÁQUINA VIRTUALRENDIMIENTO RESPECTO ALANFITRIÓN (%)MV KVM 64.34%MV Xen3 80.09%MV Xen4 99.51%SISTEMAANFITRIÓNRENDIMIENTO RESPECTO ALANFITRIÓN SIN KERNELMODIFICADO(%)Anfitrión KVM 103.00%Anfitrión Xen3 101.00%Anfitrión Xen4 97.61%Tabla 2: Valores relativos porcentuales obtenidos entre lasmáquinas virtuales y sus respectivos anfitriones, y <strong>de</strong> estoscon el sistema con kernel sin modificar (Anfitrión NoXen).<strong>de</strong>l anfitrión KVM, éste obtuvo 3% más rendimiento queel sistema original sin modificaciones. Lo mismosucedió con el anfitrión con Xen3 que aumentó 1%. Encambio, el anfitrión con Xen4 perdió 2.39% <strong>de</strong>rendimiento frente al sistema sin modificaciones.B. Prueba con IOZoneCon el test <strong>de</strong> acceso al disco, se evaluó la tasa <strong>de</strong>transferencia para completar un proceso <strong>de</strong> escritura <strong>de</strong>un archivo <strong>de</strong> 4GB. <strong>La</strong> prueba se realizó en unapartición <strong>de</strong>dicada ubicada al final <strong>de</strong>l disco duro. Losresultados se muestran en la Tabla 3:SISTEMATasa <strong>de</strong>EscrituraKbytes/sRESULTADOSTasa <strong>de</strong> Re-EscrituraKbytes/sAnfitrión KVM 47273 50416MV KVM 45494 46906Anfitrión NoXen 95605 67530Anfitrión Xen3 92744 66445MV Xen3 47026 31639Anfitrión Xen4 86836 95387MV Xen4 49797 61480Tabla 3: Tasas <strong>de</strong> transferencia en escritura y re-escrituraen IOZone.En la Tabla 3, el mayor rendimiento en la tasa <strong>de</strong>escritura lo obtuvo el sistema con el kernel sinmodificar, y en la tasa <strong>de</strong> re-escritura el mejor resultadofue el <strong>de</strong>l anfitrión con Xen4. En KVM, la MV obtuvoun rendimiento en la tasa <strong>de</strong> escritura <strong>de</strong> 1779 Kbytes/sinferior al anfitrión, y en la tasa <strong>de</strong> re-escritura sucediólo mismo pero con una diferencia <strong>de</strong> 3510 Kbytes/s. Eneste caso, hay que señalar que el controlador VirtIOemplea por <strong>de</strong>fecto caché, para la gestión <strong>de</strong>lalmacenamiento, en modo Writethrough y ello repercuteen los resultados obtenidos. En el caso Xen3, la MVpresentó una diferencia <strong>de</strong> rendimiento <strong>de</strong> 45718Kbytes/s en tasa <strong>de</strong> escritura y <strong>de</strong> 34806 Kbytes/s entasa <strong>de</strong> re-escritura inferior al anfitrión. Lo mismosucedió con Xen4, don<strong>de</strong> la MV obtuvo diferencias <strong>de</strong>37039 Kbytes/s en tasa <strong>de</strong> escritura y <strong>de</strong> 33907 Kbytes/sen tasa <strong>de</strong> re-escritura frente al anfitrión. Todos losanfitriones presentaron rendimientos inferiores que lamáquina con el kernel sin modificar.En la Gráfica 2 se muestran las tasas <strong>de</strong> transferencia<strong>de</strong> los sistemas evaluados (anfitriones y MV), tomandocomo valor <strong>de</strong> comparación la tasa <strong>de</strong> transferencia <strong>de</strong>datos en los procesos <strong>de</strong> escritura y re-escritura.En la Tabla 2 se muestra una pérdida <strong>de</strong> rendimiento<strong>de</strong> la MV con respecto al anfitrión inferior a un 1% en elcaso <strong>de</strong>l hipervisor Xen4. Por otra parte, para el Xen3 laMV pier<strong>de</strong> 19.91% <strong>de</strong>l rendimiento obtenido por suanfitrión. En cambio, con KVM la MV perdió un35.66% <strong>de</strong> rendimiento frente a su anfitrión. En el casoGráfica 2: Resultados <strong>de</strong> la prueba <strong>de</strong> IOZone.<strong>JP2011</strong>-545


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011El comportamiento relativo que existe entre lasMV/anfitriones y entre los anfitriones y la máquina sinmodificar se muestra en la Tabla 4:MÁQUINA VIRTUALRENDIMIENTO RESPECTO ALANFITRIÓN (%)Tasa <strong>de</strong>EscrituraTasa <strong>de</strong> Re-EscrituraMV KVM 96.24% 93.04%MV Xen3 50.71% 47.62%MV Xen4 57.35% 64.45%SISTEMAANFITRIÓNRENDIMIENTO RESPECTO ALANFITRIÓN SIN KERNELMODIFICADO(%)Tasa <strong>de</strong> Re-EscrituraTasa <strong>de</strong>EscrituraAnfitrión Xen3 97.01% 98.39%Anfitrión Xen4 90.82% 141.25%Tabla 4: Resultados relativos entre MV y anfitriones. Seincluye la relación entre los anfitriones con Xen y lamáquina con kernel sin modificar.En la Tabla 5, la MV en KVM requirió <strong>de</strong> 876.47segundos adicionales más que el anfitrión paracompletar la prueba. En caso <strong>de</strong> Xen3, la MV necesitó<strong>de</strong> 440.353 segundos más que el anfitrión y en Xen4 laMV requirió <strong>de</strong> 373.11 segundos más que el anfitrión.Entre las MV la más eficiente fue la <strong>de</strong> KVM al igualque el anfitrión; superando a la misma máquina con elkernel sin modificar.<strong>La</strong> Gráfica 3 representa las diferencias en los tiemposnecesarios para completar la prueba <strong>de</strong> nanodispositivos:En la Tabla 4, la MV en KVM obtuvo un rendimiento3.76% menor en escritura y 6.96% menor en re-escrituracon respecto al anfitrión. Para el caso <strong>de</strong> Xen3, ladiferencia entre los sistemas fue <strong>de</strong> un 49.29% enescritura y <strong>de</strong> un 52.38% en re-escritura obteniendomenos rendimiento la MV frente a su anfitrión. En elcaso <strong>de</strong> Xen4, las diferencias entre ambos sistemasfueron más pronunciadas, <strong>de</strong> forma que en modoescritura el sistema invitado presentó un 42.65% menosrendimiento que el anfitrión, y en el modo re-escritura elsistema invitado presentó 35.55% menos. Entre losanfitriones, el que presentó un mejor rendimiento en latasa <strong>de</strong> escritura fue Xen3 respecto al sistema sinmodificaciones, y en la tasa <strong>de</strong> re-escritura el anfitriónXen4 superó por 41.25% al sistema sin modificaciones.No se ha incluido en la comparación el anfitrión conKVM <strong>de</strong>bido a diferencias importantes <strong>de</strong> hardwareexistentes con la máquina que ejecuta el kernel sinmodificar.C. Prueba con el Simulador <strong>de</strong> NanodispositivosMOSFETEn esta prueba se somete a todo el sistema a unaevaluación <strong>de</strong> la aplicación <strong>de</strong> cálculo científico que<strong>de</strong>scribimos en la sección anterior. El resultado <strong>de</strong> lamisma se cuantifica con el tiempo que requiere elsistema para obtener la simulación, <strong>de</strong> manera quecuanto menor sea el tiempo empleado mejor será elresultado. Los resultados se muestran en Tabla 5:SISTEMARESULTADOSTiempo (s)Anfitrión KVM 3600.89MV KVM 4477.36Anfitrión NoXen 4406.59Anfitrión Xen3 4901.35MV Xen3 5341.71Anfitrión Xen4 4486.63MV Xen4 4859.74Tabla 5: Resultados <strong>de</strong> la simulación <strong>de</strong> nanodispositivos.Gráfica 3: Tiempo (s) para completar prueba <strong>de</strong>Nanodispositivos MOSFET en los sistemas evaluados.Los rendimientos relativos entre MV, anfitriones ymáquina con kernel sin modificar se encuentran en laTabla 6:PORCENTAJE DE TIEMPOMÁQUINA VIRTUAL ADICIONAL REQUERIDORESPECTO AL ANFITRIÓN (%)MV KVM 24.34%MV Xen3 8.98%MV Xen4 8.31%SISTEMAANFITRIÓNRELACION DE TIEMPONECESITADO PARA LAPRUEBA RESPECTO ALANFITRIÓN SIN KERNELMODIFICADO (%)Anfitrión Xen3 111.23%Anfitrión Xen4 101.82%Tabla 6: Resultados relativos entre los sistemas evaluados.Los resultados <strong>de</strong> la Tabla 6 muestran que en el caso<strong>de</strong> la máquina virtual sobre KVM requirió un 24.34%más <strong>de</strong> tiempo para completar la simulación que elsistema anfitrión, a diferencia <strong>de</strong> la MV sobre elhipervisor Xen3 que requirió 8.98% más tiempo que suanfitrión, mientras que Xen4 sólo requirió un 8.31% más<strong>de</strong> tiempo que su anfitrión. En el caso <strong>de</strong>l anfitrión Xen3requirió 11.23% más tiempo y en Xen4 los tiemposfueron casi iguales, solo requiriendo un 1.82% más <strong>de</strong>tiempo para completar la prueba.En la Gráfica 4 se representa la pérdida <strong>de</strong> rendimientorelativa entre la MV y el anfitrión para los hipervisores<strong>JP2011</strong>-546


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011evaluados, y para cada uno <strong>de</strong> los benchmarksempleados. En el caso <strong>de</strong> las pruebas <strong>de</strong> escritura y reescritura,la MV en KVM presentó rendimiento relativosuperior con respecto a la MV <strong>de</strong> Xen3 45.53% para leprueba <strong>de</strong> escritura y <strong>de</strong> un 45.42% para la prueba <strong>de</strong> reescrituray en relación a la MV en Xen4 <strong>de</strong> un 38.89%para la prueba <strong>de</strong> escritura, y <strong>de</strong> un 28.58% para la reescritura.Para las pruebas <strong>de</strong> Linpack y el simulador <strong>de</strong>nanodispositivos la MV <strong>de</strong> Xen4 tiene mejorrendimiento que la MV <strong>de</strong> KVM, apreciándose para eltest <strong>de</strong> Linpack una diferencia <strong>de</strong> un 34.65% y en el test<strong>de</strong>l simulador <strong>de</strong> nanodispositivos una diferencia <strong>de</strong> un11.88%. Al comparar los resultados entre la MV enXen4 y la MV en Xen3; se observa que la nueva versión<strong>de</strong>l hipervisor ha mejorado en varios aspectos; <strong>de</strong>manera que en la prueba <strong>de</strong> IOZone en tasa <strong>de</strong> escrituraobtuvo un resultado 6.64% mejor y en la tasa <strong>de</strong> reescrituraha obtenido un 17.28% mejor. En el caso <strong>de</strong> laprueba <strong>de</strong> Linpack, la MV en Xen4 apenas mostrópérdida con el anfitrión, mientras que la MV con Xen3perdió un 19.91%.diferencia con la MV con Xen3), ya que requirióúnicamente un 8% más tiempo que el anfitrión paracompletar la simulación; siendo mucho más eficienteque la MV en KVM.En general, po<strong>de</strong>mos concluir que las MV que seejecutan con el hipervisor Xen mostraron un mayorrendimiento en las tareas evaluadas que estabanrelacionadas con el cálculo y procesamiento intensivo.En cambio, la situación es distinta en cuanto a la tasa <strong>de</strong>transferencia <strong>de</strong> escritura en disco, en la cual la MVsobre KVM mostró un mejor rendimiento que la MV <strong>de</strong>Xen.Finalmente, según los resultados obtenidos, se observauna diferencia consi<strong>de</strong>rable en el rendimiento <strong>de</strong> lasmáquinas virtuales <strong>de</strong>pendiendo <strong>de</strong> si la aplicación haceun mayor uso <strong>de</strong>l disco o <strong>de</strong>l procesador. Por lo tanto,sería conveniente, como trabajo futuro, analizar lascausas <strong>de</strong> estas diferencias, y en caso <strong>de</strong> que no fueraninevitables se podría seleccionar previamente elhipervisor con el que <strong>de</strong>splegar la máquina virtual enfunción <strong>de</strong>l tipo <strong>de</strong> aplicación que se <strong>de</strong>see ejecutar.Probablemente esta situación sea causada por lapresencia <strong>de</strong> los controladores VirtIO que mejoran estafuncionalidad.AGRADECIMIENTOSEl presente trabajo ha sido financiado por la Xunta <strong>de</strong>Galicia mediante los proyectos 09TIC001CT eINCITE08PXIB206094PR, y por el Gobierno <strong>de</strong> España(MCYT) y fondos FEDER mediante el proyectoTEC2010-17320.Gráfica 4: Resultados <strong>de</strong> la pérdida <strong>de</strong> rendimiento entrela MV y el anfitrión para Xen y KVM.V. CONCLUSIONESEste trabajo se ha centrado en comparar el rendimiento<strong>de</strong> los hipervisores Xen y KVM. Para ello, se hanejecutado tres test correspondientes a los benchmarksIOZone y Linpack, y <strong>de</strong> la aplicación <strong>de</strong> cálculocientífico <strong>de</strong> simulación Monte Carlo <strong>de</strong>nanodispositivos MOSFET. Éstos se han ejecutado enlos anfitriones y máquinas virtuales gestionadas por loshipervisores <strong>de</strong> código abierto Xen y KVM,compatibles con el diseño <strong>de</strong>l proyecto Formiga Cloud.En el test Linpack, la MV que se ejecutó con elhipervisor Xen4 presentó el mayor rendimiento; ya quela diferencia con el anfitrión fue menor <strong>de</strong>l 1%.En el test <strong>de</strong> IOZone se evaluó la tasa <strong>de</strong> transferenciaen modo Escritura en la cual la MV bajo KVM presentóla menor pérdida respecto al anfitrión, siendo ésta <strong>de</strong> tansólo un 3.76%. En cambio, los resultados obtenidos conla MV en Xen3 y Xen4, en la misma prueba, mostrabanuna pérdida mucho más pronunciada. Cuando se evaluóla tasa <strong>de</strong> transferencia en modo Re-Escritura, la MV enKVM sólo perdió un 6.96% frente al anfitrión, siendomucho más eficiente que la MV en Xen3 y Xen4.En el test <strong>de</strong> cálculo científico, presentó un mayorrendimiento la MV en Xen4 (aunque con muy pocaREFERENCIAS1. Zhang, Liang-Jie, et al. Hot Topics in CloudComputing. IT Professional, Septiembre 2010, Vol. 12,pp. 17-19.2. Gomez-Folgar, F., et al., An e-Scienceinfraestructure for nanoelectronic simulations based ongrid and cloud technologies., Electron Devices (CDE),2011 Spanish Conference, pp. 1-4, 8-11.3. INTEL Corp. . INTEL Math Kernel Library.http://software.intel.com/en-us/articles/intel-mathkernel-library-linpackdownload/?wapkw=(intel+linpack).4. Benchmark, IOZone File System. IOZone.org.http://www.iozone.org.5. Xen.org. Xen Hypervisor Web Site.http://www.xen.org/files/Xen_4_1_Datasheet.pdf.6. Xen Hypervisor 4.1 Release.http://blog.xen.org/in<strong>de</strong>x.php/2011/03/25/xen-4-1-releases/.7. Habib, Irfan. Linux Journal. Virtualization withKVM. http://www.linuxjournal.com/article/9764.8. M. Tim Jones, EMULEX Corp. IBM -DeveloperWorks. Discover The Linux KErnel VirtualMachine.http://www.ibm.com/<strong>de</strong>veloperworks/linux/library/llinux-kvm/.9. Lilja, David J. Measuring Computer Performance.s.l. : Cambridge University Press, 2004.<strong>JP2011</strong>-547


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 201110. Knuth, D.E. The Art of Computer Programming,Vol. 2. s.l. : Addison-Wesley, 1997.11. M. Tim Jones, EMULEX Corp. IBM -DeveloperWorks. VirtIO: Marco <strong>de</strong> Virtualización <strong>de</strong>E/S para Linux.http://www.ibm.com/<strong>de</strong>veloperworks/ssa/linux/library/lvirtio/in<strong>de</strong>x.html.<strong>JP2011</strong>-548


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Arquitecturas <strong>de</strong>l subsistema <strong>de</strong> memoria yalmacenamiento secundario<strong>JP2011</strong>-549


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-550


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20111A Novel Approach for a Metadata ClusterAna Avilés–González, Juan Piernas and Pilar González–Férez 1Resumen— This paper presents the <strong>de</strong>sign and implementationof a metadata cluster based on a newenhanced type of OSD <strong>de</strong>vice, the OSD+ <strong>de</strong>vice, whichsupports both data objects and directory objects. Unlikethe “data” objects of a traditional OSD <strong>de</strong>vice, adirectory object stores file names and attributes, andsupports metadata–related operations. Thanks to theOSD+ <strong>de</strong>vices, metadata of a parallel file system canbe managed by all the <strong>de</strong>vices of the system, improvingthe performance and scalability of the metadataoperations. Our metadata cluster’s performance hasbeen evaluated and compared with that achieved byLustre. The results show that: our proposal obtains abetter throughput than Lustre when both use a singlemetadata server, getting improvements of more than60–80%, and it scales with the number of OSD+s.I. IntroductionThe avoidance of bottlenecks is critical in mo<strong>de</strong>rndistributed storage systems to achieve the <strong>de</strong>siredfeatures of high performance and scalability. Thesesystems <strong>de</strong>al not only with a large volume of data butalso with an increasing number of file. Accordingly,an efficient metadata management becomes a fundamentalaspect of a system storage’s architecture toprevent such bottlenecks [1].Although metadata is usually less than 10% ofthe overall storage capacity of a system, its operationsrepresent between 50% and 80% of all the requests[2]. Metadata operations are also very CPUconsuming: a single metadata server can easily beoverloa<strong>de</strong>d by a few clients. Hence, to improve theperformance and scalability of metadata operations,a cluster of servers is nee<strong>de</strong>d. PVFS [3] and Ceph [4],e.g., use a small set of servers as a metadata cluster.In this paper, we propose the use of OSD <strong>de</strong>vices[5] as metadata servers by extending the typeof objects and operations an OSD supports. Specifically,the new <strong>de</strong>vices, that we call OSD+, supportdirectory objects. Unlike objects found in a traditionalOSD (referred here as data objects), they storefile names and attributes and support metadata–related operations. OSD+s allow us to <strong>de</strong>sign a newparallel file system called FPFS (Fusion Parallel FileSystem) which combines data and metadata serversinto a single type of server capable of processing allI/O operations. By using all the available storage<strong>de</strong>vices as both data and metadata servers we gainseveral advantages: hardware resources are betterused; administration costs are reduced; and metadataperformance and scalability are improved.Because nowadays there are no commodity OSDbaseddisks available, their implementation is doneby means of mainstream computers which export anOSD-based interface, and use a regular local file systemto store objects. We take advantage of this fact1 University of Murcia (Spain), email: ana.aviles,piernas, pilar@ditec.um.esby directly mapping directory–object operations inFPFS to directory operations in the local file system,exporting many of its features, and reducingthe possible overhead of the OSD+ implementation.Our OSD+s can be seen as members of two separateclusters: a data and a metadata cluster. Sincemo<strong>de</strong>rn file systems already have a good data performanceand failure recovery, FPFS’s data clusterworks as and borrows i<strong>de</strong>as from them. For the metadatacluster, however, our goal is to provi<strong>de</strong> a servicebetter than that produced by existing file systems.Therefore, this work specially focuses on the <strong>de</strong>signand implementation of such a service in FPFS.In or<strong>de</strong>r to leverage the new features provi<strong>de</strong>dby the OSD+ <strong>de</strong>vices, the FPFS metadata clusterspreads directories (and its corresponding objects)across the OSD+s. This is done by hashing directorypathnames. Clients use the same hashing to directlycontact the OSD+ which hosts the directory objectserving a given metadata request. Due to the hashingtechnique, renames and permission changes mayaffect the location and accessibility of a large numberof directories. In this case, a lazy approach [6] isused for <strong>de</strong>aling with these operations.Given that some metadata operations affect morethan one directory and, hence, more than one OSD+,two key aspects of the metadata cluster <strong>de</strong>sign arethe atomicity of the operations, and the coordinationof the OSD+s. In<strong>de</strong>ed, this coordination allows theOSD+ <strong>de</strong>vices to provi<strong>de</strong> a global metadata service.We have evaluated our metadata cluster and comparedits performance with Lustre [7]. The experimentalresults show that a single OSD+ can easilyimprove the throughput of a Lustre metadata serverby more than 60–80%. They also prove that our implementationscales with the number of OSD+s.II. Related WorkAn important issue regarding the metadata managementis where to store the metadata. Ceph [4]uses objects located in the OSDs themselves, althoughthe management is handled by a small setof servers which contact the OSDs to read and writemetadata. Ali et al. [8] explore the use of OSD <strong>de</strong>vicesto store and partially manage directories. Theysave directory entries as attributes of empty objects,and introduce a new OSD operation to make attributechanges atomic. But, they do not discussother important issues: the directory distribution,the handling of renames and permission changes, andthe atomicity of operations involving several OSDs.FPFS addresses these topics through the directoryobjects, making OSDs capable of storing and managinga complete directory hierarchy.The distribution of the file system namespace<strong>JP2011</strong>-551


2<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011across metadata servers is crucial to make a balanceduse of resources and to achieve a good performance.It also <strong>de</strong>termines scalability problems related to certainmetadata operations or changes in the clusterdue to additions, removals or failures of servers.Static Subtree Partition, used by Coda [9],AFS [10], etc., statically assigns portions of the filehierarchy to metadata servers. This preserves directorylocality, but is vulnerable to distribution imbalancesas the file system and workload change. A variantis Dynamic Subtree Partition, used by Ceph [4],which <strong>de</strong>legates authority for subtrees of the directoryhierarchy to different metadata servers. Periodically,busy servers transfer subtrees to other non–busy servers.Hashing approaches can be used [11], [6], [12] toimprove metadata distribution, but present severaldrawbacks like the loss of directory locality and massivedata migration due to a cluster size change ora rename. <strong>La</strong>zy Hybrid (LH) [6] mitigates the migrationwith a metadata look–up table (MLT) whichmaps hash value ranges to servers ids. Further, it applieslazy policies to <strong>de</strong>fer a migration until the datais next accessed. It also inclu<strong>de</strong>s a dual–entry accesscontrol list (ACL) to avoid directory traversals whenchecking access permissions.Features introduced by LH have been wi<strong>de</strong>lyborrowed by schemes such as Dynamic Hashing(DH) [12] or MHS [11]. DH combines lazy policiesand an MLT with several new strategies to dynamicallyadjust the metadata distribution. MHS is adirectory hashing scheme that uses LH’s access controlmechanisms; it avoids data migrations due torename operations by assigning to every directory aunique id which never changes (a global in<strong>de</strong>x tableis used for this purpose).III. The Metadata Cluster: DesignThe metadata cluster uses the OSD+ <strong>de</strong>vices toprovi<strong>de</strong> a high performance and scalable metadataservice. It also takes advantage of them to provi<strong>de</strong>replication and fault tolerance, and to tackle withsome metadata issues like directory renames, linksand permission changes, in a consistent and atomicmanner.A. Metadata DistributionOur proposal distributes the directory objects (thefile–system namespace) across the metadata clusterto make metadata operations scalable with thenumber of OSD+s. The distribution is based onCRUSH [4], a <strong>de</strong>terministic pseudo–random functionthat guarantees a probabilistically balanced distributionof objects through the system. For a directory,CRUSH outputs its placement group (PG), a list of<strong>de</strong>vices ma<strong>de</strong> up of a primary no<strong>de</strong> and a set of replicas.These <strong>de</strong>vices are chosen according to weightsand placement rules that restrict the replica selectionacross failure domains. So, potential sources offailures and load imbalance are avoi<strong>de</strong>d with no needof extra structures. As input, CRUSH receives an integerwhich results from hashing the full pathnameof the directory.Hash partition strategies present different scalabilityproblems during cluster resizing, renames andpermission changes. In case of adding and removingno<strong>de</strong>s in the cluster, our <strong>de</strong>sign avoids the metadatamigration or imbalance through CRUSH. Likewise,for minimizing renames management, permissionchanges, and links, FPFS employs lazy techniques[6]. Nevertheless, it is important to note that,in our case, renames and permission changes onlyaffect directories. As the experimental results willshow, these operations are infrequent in directories.This fact, along with the use of lazy techniques andCRUSH, will further minimize the impact of theseoperations on the metadata cluster performance.Although directory objects are scattered across thecluster, the directory hierarchy of the parallel filesystem is also maintained to provi<strong>de</strong> standard directorysemantics (e.g., when listing directory entries),and to <strong>de</strong>termine file and directory access permissions(they are <strong>de</strong>termined from the root directory).B. Directory RenamesWhenever a directory name changes, so does itslocation as well as the location of the un<strong>de</strong>rlying directoriesin the hierarchy. This can incur in a massivemigration of metadata. To minimize the migrationimpact, lazy policies, similar to those used by LH [6],are applied. Unlike LH, file renames do not involvemetadata migration, because their locations do not<strong>de</strong>pend on their pathnames.Rename requests are sent to the parent directoriesof the corresponding target directories. When therename of a directory occurs, the OSD+ of its parentdirectory broadcasts the rename to inform theother OSD+s in the cluster. Accordingly, when anOSD+ receives an operation on a directory whosepathname has changed, but whose object has notbeen migrated yet, instead of returning an error, theOSD+ starts the migration of the object to carry outthe operation.Figure 1 shows this migration process. First, afterobtaining the list of servers containing the directoryobject (steps 1 and 2), the client contacts one targetOSD+ (step 3). Then, the failed request forces theOSD+ to migrate the object by looking in the log,and contacting the source OSD+ (step 4). Once themigration is done (step 5), the initial operation is carriedout and the result is returned to the client (step6). Due to a previous rename, the source OSD+ maynot contain the directory object either. The processis then repeated recursively, moving backwards untilthe directory object is found and migrated.C. Permission ChangesTo directly <strong>de</strong>termine access permissions and avoiddirectory traversals, dual–entry ACL are used [6].Given a directory, one ACL contains its permissions,whereas the other represents its path permissions(these are the intersection of the directory’s own per-<strong>JP2011</strong>-552


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20113HashCRUSHFig. 1.Directory object migration.Fig. 2. Access to a directory containing a symbolic link./usr/new is a soft link to /usr/old.missions and its parent’s path permissions). UnlikeLH, only directories have dual–entry ACLs in FPFS.A file’s permissions are <strong>de</strong>rived from its ACL, andits directory’s dual–entry ACL.When checking permissions, the OSD+ containingthe target directory object searches in the metadatalog for invalidations along the requested objectpath. If they exist, the parent directory is accessedto get its dual–entry ACL. Once permissions are updated,the requested ACL is calculated. Since parent’spermissions might also be invalid, this processis repeated recursively until the changed directory isreached, or an updated directory is reached. Permissionsare updated in a lazy fashion, minimizing thepart of the hierarchy traversed.D. LinksPlacing directories by hashing their pathnamespresents the problem of locating the correct OSD+sfor paths that inclu<strong>de</strong> symbolic links. Any access toa subtree of the linked directory hierarchy will fail, asit happens with a renamed directory whose objectshave not been migrated.LH [6] proposes the creation of shortcuts to <strong>de</strong>alwith files whose pathnames contains symbolic links.A shortcut to one of these files is created the firsttime the file is accessed by traversing the directoryhierarchy. Any subsequent access to the same filewill use the shortcut. But this approach presentstwo problems: shortcuts take up space and, moreimportantly, when the access to a file fails, there isno way to know if the failure is due to a missingfile or the existence of symbolic links in the name.This ambiguity always produces the traversal of thedirectory hierarchy up to the root directory whenaccessing to any missing file.Our proposal for symbolic links does not suffer themissing file problem of LH. In FPFS, a symbolic linkis treated as a directory rename. The differences arethat: any access to a directory containing a symboliclink never produces the migration of the directory,and a client accessing one of these directories receivesthe resolved path to contact with the original OSD+(see Fig. 2).E. AtomicityAn important aspect is that all the metadata operationsmust be atomic to provi<strong>de</strong> a coherent view.When a metadata operation is performed by a singleOSD+ (e.g., create, unlink, etc.), the backend filesystem itself guarantees its atomicity, POSIX semantics,and atomicity when clients access in parallel.However, there are operations, such as rename,mkdir or rmdir, which usually involve two OSD+s.Now, atomicity is guaranteed by means of the backendfile system, and a three–phase commit protocol(3PC) [13] where one no<strong>de</strong> acts as the coordinatordirecting the remaining no<strong>de</strong>s or participants.IV. The Metadata Cluster: ImplementationA prototype of the metadata cluster has been builton a Linux environment. Each OSD+ is a user–space multithrea<strong>de</strong>d process, running on a mainstreamcomputer, which uses a conventional file systemas storage backend. The Linux syscall interfaceis used to access the backend file system, whichmust be POSIX–compliant and support exten<strong>de</strong>d attributes.Our FPFS implementation not only exploitsthe un<strong>de</strong>rlying file system’s features (atomicity,errors checking, etc.), but also exports them tothe parallel file system.For every new established connection from anFPFS client or another OSD+, one thread islaunched. It lasts as long as the communicationchannel remains open; hence, performance is improveddue to the absence of connection establishmentand termination handshakes, associated witheach message. In the current implementation, connectionsuse TCP/IP and UDP/IP protocols.A. Directory ObjectsInternally, a directory object is implemented as aregular directory whose path is its directory pathnamein the parallel file system. Thus, the directoryhierarchy is imported within each OSD+ by replicatinga partial namespace of the global hierarchy.To preserve the hierarchy, directory objects maintainan entry for every file and subdirectory theycontain. Hence, several types of directories are differentiatedthrough exten<strong>de</strong>d attributes: a first type toimplement directory objects; a second one to maintainthe hierarchy (e.g., the subdirectories); a thirdto internally construct the paths of the directoriesobjects; and finally, temporal directories to keep renamedmetadata which has not been migrated yet.<strong>JP2011</strong>-553


4<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Figure 3 shows how an FPFS’ directory hierarchyis mapped to a four–OSD+s cluster. Directory objects(marked with o) are stored along with theirfiles and subdirectories (i<strong>de</strong>ntified by h). Note thata directory object and the corresponding parent’s directoryobject are usually placed in different OSD+s,except for /home/usr1, where both objects meet, bychance, in the same OSD+. Fig. 3. Implementation of the parallel file system hierarchyin the OSD+ <strong>de</strong>vices.B. Client–OSD+ InteractionCommunication between clients and OSD+s is establishedvia TCP/IP connections and request/replymessages. As requests, FPFS supports the most frequentlyused metadata operations (see Sec. V-A):mkdir, rmdir, opendir, readdir, create, unlink,open, close, lookup, stat, utime and rename.A client request is usually sent to the OSD+ storingthe parent’s directory object. For instance, if aclient opens /home/usr2/docs/info.pdf, it sends amessage to the OSD+ containing the directory objectof /home/usr2/docs.When an operation involves several OSD+s, theone contacted by the client carries out the operationcollaborating with other OSD+s. For example,when creating /home/usr2 (see Fig. 3), OSD+ 1,which contains /homeo, initially creates the directory/home/usr2 h . If the creation is successful, OSD+ 2conclu<strong>de</strong>s the request creating the directory object/home/usr2o.C. Files and Data ObjectsA file’s metadata is initially stored as an emptyfile in its parent directory. This improves operationslike stat, since the directory entry and its metadataare in the same OSD+. Clients are able to see allthe usual attributes (timestamps, mo<strong>de</strong>, etc.) an<strong>de</strong>xten<strong>de</strong>d attributes stored in the empty file.To make a fair comparison with Lustre (seeSec. V), FPFS also creates data objects for files.They are implemented as regular files in the OSD+s.Each data object has an id which is stored as an exten<strong>de</strong>dattribute in the file’s metadata, and is composedof 2 values: object name, and OSD+ where itis stored.D. Logs<strong>La</strong>zy techniques implementation requires eachOSD+ to store a metadata log with permissionchanges and directory renames. All the incomingrequests are first checked against this log to provi<strong>de</strong>a coherent and consistent reply to clients accessingmetadata that may not have been updated. Asi<strong>de</strong>from the metadata log, the three–phase commit protocolemploys another log to rollback in case of failure.Both logs are sync’ed to disk every 5 seconds.V. Experimental ResultsThe performance of the proposed FPFS’s metadatacluster has been evaluated and compared withLustre by using different benchmarks. This sections<strong>de</strong>scribes those benchmarks, the system un<strong>de</strong>r testand the achieved experimental results.A. System un<strong>de</strong>r Test and BenchmarksThe testbed system is a cluster ma<strong>de</strong> up of 16 computeand 1 frontend no<strong>de</strong>s. Each compute no<strong>de</strong> hastwo Intel Xeon E5420 Quad-core CPUs at 2.50GHz,4GB of RAM, and two Seagate ST3250310NS disksof 250GB. One of the disk has a 64-bit Fedora Core11 distribution which supports version 1.8.2 of Lustre.The other one is exported as either an FPFSOSD+ or a Lustre MDS–MGS/OST server. The interconnectis a Gigabit network with a D-Link DGS-1248T switch.Experiments use up to 8 compute no<strong>de</strong>s. ForFPFS, two configurations are set up: one with 1OSD+, and another with 4 OSD+s. Both use Ext4as the backend file system. For Lustre, only one configurationis set up with 1 no<strong>de</strong> running all its services(MGS/MDS, and one OST), equivalent to ourconfiguration with one OSD+. As clients, 1 to 4no<strong>de</strong>s are used <strong>de</strong>pending on the test.Since the metadata performance <strong>de</strong>pends on theformatting options, FPFS has been formatted withthe same options Lustre uses in its un<strong>de</strong>rling file system.In or<strong>de</strong>r to evaluate and compare the performanceof FPFS and Lustre in metadata workloads, threebenchmarks have been carried out:• HP Trace: it is a 21-hour trace which is, inturn, a subset of a 10-day trace of all file systemaccesses done by a medium-sized workgroup usinga 4-way HP-UX time-sharing server attachedto several disk arrays and a total of 500 GB ofstorage space [14]. The selected period coversfrom 6am on the fifth trace day to 3am on thenext day, one of the most active.Table I provi<strong>de</strong>s an overview of the metadatarequests in the trace. Since we are only interestedin metadata operations, data operationsare omitted.The trace is replayed by a multithrea<strong>de</strong>d programwhich allows us to simulate a system withconcurrent metadata operations. The programtakes into account possible <strong>de</strong>pen<strong>de</strong>ncies betweenmetadata operations.• Creation/traversal of a directory tree: thisbenchmark is ma<strong>de</strong> up of two tests: one thatcreates directory hierarchies with empty regularfiles, and another one which traverses those hierarchies.Every directory hierarchy is created byuncompressing the source tree of a Linux kernel<strong>JP2011</strong>-554


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20115TABLA IOverview of the 21-hour HP trace.Operation type Count Operation type CountLookup 13908189 File rename 7683Stat 2827387 Mkdir 7389Open 2572124 Rmdir 6973Unlink 67883 Directory rename 5Create 417552.6.32.9, whose files have been truncated to zerobytes. In these tests, each process accesses itsown copy of the Linux source tree.• Metarates: program [15] for evaluating therate at which metadata transactions are performed.It measures aggregate transaction rateswhen multiple processes (coordinated by MPI)read or write metadata concurrently. Our experimentsuses 640000 files in total, distributedinto as many directories as processes. The programtests the performance achieved by eachsystem for three types of metadata transactions:create–close, (in our tests, without calling fsyncbefore closing a file), stat, and utime calls.The results shown for every system configurationare the average of five runs of each benchmark. Confi<strong>de</strong>nceintervals are also shown as error bars, for a95% confi<strong>de</strong>nce level. The disk is formatted betweenruns, and unmounted/remounted between the directorytree creation and traversal tests. The number ofclient processes per benchmark varies from 1 to 256processes, in powers of two.For any benchmark, the scalability is calculatedfrom 1 and 4 OSD+s results. Also, FPFS and Lustre’sperformances are compared using one no<strong>de</strong> aseither an OSD+ or a Lustre server containing bothan MDS/MGS and OST service.B. HP TraceAlthough Lustre is a full-fledged parallel file systemand FPFS only implements an incomplete metadataservice, both roughly perform the same operations.This fact, along with the large performancedifferences in this benchmark (see Fig. 4.(a)) whichreaches 82% for 16/32 threads, ensures that FPFSrepresents a significant improvement with respect toLustre in time-sharing environments.These differences are mainly due to the thin layerFPFS adds on top of the backend file system, whichdirectly translates FPFS requests into backend filesystem ones, producing little overhead. Instead, Lustreadds several abstraction layers. Moreover, we useExt4 while Lustre uses a customized Ext3 (ldiskfs).FPFS’s scalability (see in Fig. 4.(b)), reaches 2.43for 32 threads. This value is smaller than the i<strong>de</strong>al4, due to the <strong>de</strong>pen<strong>de</strong>ncies between metadata operationsin the trace, which limit the parallel executionof operations. However, as the number of threadsincreases, the number of possible ongoing metadataoperations also grows. Accordingly, scalability is betterfor a large number of threads, showing that FPFScan properly <strong>de</strong>al with large time-sharing systems.C. Creation/Traversal of a Directory TreeFigure 4.(c) shows FPFS’s improvement over Lustreis around 70% for both tests, but the improvementof directory traversal plummets from 64 processeson. This is due to a <strong>de</strong>fault Ext4’s optionwhich is unset in ldiskfs by <strong>de</strong>fault. The flag flex bgbenefits the directory traversal for high number ofprocesses, but makes the directory creation worse.So, to get an optimum performance, <strong>de</strong>pending onthe workload, the formatting options can be changed,as well as the backend file system. Thanks to thisflexibility, FPFS can be adjust to get the best performance,while Lustre is not so adaptable.The scalability achieved in the directory tree creation(see Fig. 4.(d)) is not as high as in HP tracesfor small amount of clients due to a network trafficincrease when there are four OSD+s. This incrementis produced by the mkdir and create operations inFPFS, since they involve two OSD+s and so messageexchanges between them (see Sec. III-E). Yet,<strong>de</strong>spite of the additional messages, FPFS reaches abetter scalability as the number of clients grows.D. MetaratesPerformance results of metarates transactions areshown in Fig. 4.(e). FPFS’ gain is larger for a fewprocesses, and <strong>de</strong>creases with the number of processesfor the create test. One of the reason is thatFPFS manages large directories better than Lustre.Although the number of files is fixed, there are asmany directories as processes are run, so the lesserthe number of processes, the higher the number offiles per directory.FPFS also greatly reduce the application time forthe stat and utime transactions, but the results donot <strong>de</strong>pend on the number of processes. These transactionsfirst create the files, and then perform thecorresponding operations. Accordingly, thousands ofino<strong>de</strong>s and directory entries are already in the operatingsystem’s caches and, hence, the performance islimited by CPUs and network bandwidth, and notby hard disks or directory sizes. Lustre, however,makes a less efficient use of the system caches andits abstraction layers introduce a larger overhead.In this test, FPFS achieves a super-lineal scalability(see Fig. 4.(f)), mainly due to the use of the operatingsystem’s write–back caches, and the number ofprocesses itself: when having more processes, the increaseof OSD+s reduces the application time and, in<strong>JP2011</strong>-555


6<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Improvement over Lustre (%)100806040200HP Trace1 2 4 8 16 32 64 128 256# of threads (clients)Improvement over Lustre (%)100500-50-100Creation/Traversal of a directory treeCreationTraversalCreation (-O ^flex_bg)Traversal (-O ^flex_bg)1 2 4 8 16 32 64 128 256# of processes (clients)Improvement over Lustre (%)100806040200CreationStatUtime(a) (c) (e)Metarates1 2 4 8 16 32 64 128 256# of processes (clients)Speedup43.532.521.510.50HP Trace1 2 4 8 16 32 64 128 256# of threads (clients)Speedup76543210Creation/Trasversal of a directory treeCreationTrasversal1 2 4 8 16 32 64 128 256# of processes (clients)Speedup121086420File creationStatUtime(b) (d) (f)Metarates1 2 4 8 16 32 64 128 256# of processes (clients)Fig. 4. Improvement obtained by FPFS 1 OSD+ over Lustre 1MDT/OST: (a) HP Trace; (c) Creation and raversalof a Directory Tree; (e) create-close, stat and utime transactions. FPFS Scalability for 1 OSD+ and 4 OSD+s: (c)Improvement obtained by FPFS over Lustre; (d) FPFS Scalability.turn, the number of write operations to disk duringthe tests. Further, the pending metadata writes incache do not affect the application time, which benefitscreate and utime transactions. Also, the largertotal cache size provi<strong>de</strong>d by four OSD+s <strong>de</strong>creasesthe number of metadata reads from disk, which alsoimproves stat and utime transactions.VI. Conclusions and Future WorkWe have introduced OSD+, a new type of OSD <strong>de</strong>vicewhich supports both data and directory objects.While data objects store data of any type and supportread and write operations, directory objectsimplement directories and support metadata–relatedoperations (create, unlink, mkdir, etc). By usingOSD+s, data and metadata of a parallel file systemcan be managed by all the OSD+s in a cluster, improvingits performance and scalability.The paper also presents the implementation ofa metadata cluster based on OSD+s, and discusssome <strong>de</strong>sign and implementation issues like directorydistribution, rename operations, file permissionchanges, and atomicity. Our implementation’s performancehas been compared with Lustre’s. The resultsshow that our proposal easily outperforms aLustre metadata server by more than 60–80%, andthat it scales with the number of OSD+s.AcknowledgmentWork supported by the Spanish MEC andMICINN, as well as European Comission FEDERfunds, un<strong>de</strong>r Grants CSD2006–00046 and TIN2009–14475–C04.Referencias[1] Swapnil Patil and Garth Gibson, “Scale and concurrencyof giga+: File system directories with millions of files,”in In Proc. of the 9th USENIX Conference on File andStorage Technology (FAST’11), Feb. 2011, pp. 15–30.[2] D. Roselli, J. Lorch, and T. An<strong>de</strong>rson., “A comparisonof file system workloads,” in Proc. of the 2000 USENIXAnnual Tech. Conf., June 2000, pp. 41–54.[3] R. <strong>La</strong>tham, N. Miller, R. Ross, and P. Carns., “A nextgenerationparallel file system for linux clusters,” Linux-World, pp. 56–59, Jan. 2004.[4] S. Weil., Ceph: reliable, scalable, and high-performancedistributed storage, Ph.D. thesis, University of California,Santa Cruz, (CA), Dec. 2007.[5] M. Mesnier, G. R Ganger, and E. Rie<strong>de</strong>l, “Object-basedstorage,” IEEE Commun. Magazine, pp. 84–90, Ago.2003.[6] S. A. Brandt, E. L. Miller, D. D. E. Long, and L. Xue.,“Efficient metadata management in large distributedstorage systems,” in Proc. of the 20 th IEEE/11 th NASAGoddard Conf. on Mass Storage Systems and Technologies,2003.[7] P. J. Braams, “High-performance storage architectureand scalable cluster file system,” 2008.[8] N. Ali, A. Devulapalli, D. Dalessandro, P. Wyckoff, andP. Sadayappan., “An OSD-based approach to managingdirectory operations in parallel file systems,” in IEEEInternational Conf. on Cluster Computing, 2008.[9] M. Satyanarayanan, J. J. Kistler, P. Kumar, M. E.Okasaki, and E. H. Siegel., “Coda: A highly available filesystem for a distributed workstation enviroment,” IEEETrans. on Computers, vol. 39, no. 4, pp. 447–459, 1990.[10] J. H. Morris, M. Satyanarayanan, M. H. Conner, J. H.Howard, D. S. Rosenthal, and F. D. Smith., “Andrew: Adistributed personal computing enviroment,” Commun.ACM, vol. 29, pp. 184–201, March 1986.[11] J. Wang, D. Feng, F. Wang, , and Chengtao Lu., “MHS:A distributed metadata management strategy,” in TheJournal of Systems and Software, July 2009.[12] L. Weijia, X. Wei, J. Shu, and Weimin Zheng., “Dynamichashing: Adaptive metadata management for petabytescalefile systems,” in Proc. of the 14th IEEE / 23rdNASA Goddard Conf. on Mass Storage Systems andTechnologies, May 2006.[13] D. Skeen and M. Stonebraker, “A formal mo<strong>de</strong>l of crashrecovery in a distributed system,” IEEE Trans. on SoftwareEngineering, vol. 9, pp. 219–228, May 1983.[14] L.P. Hewlett-Packard Development Company, “Fstrace,”2002.[15] University Corporation for Atmospheric Research,“metarates,” 2004.<strong>JP2011</strong>-556


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Algoritmo <strong>de</strong> reemplazo para cache <strong>de</strong> últimonivel basado en periodos MRUAlejandro Valero, Julio Sahuquillo, Salvador Petit, Pedro López y José Duato 1Resumen— El diseño <strong>de</strong> la jerarquía <strong>de</strong> memoria esun aspecto importante en los microprocesadores actuales.Muchos trabajos <strong>de</strong> investigación se centranen el último nivel <strong>de</strong> cache, el cual se diseña para ocultarla elevada latencia <strong>de</strong> acceso a la memoria principal.Para reducir los fallos <strong>de</strong> capacidad y <strong>de</strong> conflicto,estas caches forman estructuras <strong>de</strong> memoria gran<strong>de</strong>scon un gran número <strong>de</strong> vías.Para explotar la localidad temporal, el algoritmo <strong>de</strong>reemplazo típicamente implementado en caches es elLRU. Sin embargo, para caches con un gran número<strong>de</strong> vías, su implementación es costosa en términos <strong>de</strong>área y consumo <strong>de</strong> potencia. De hecho, el uso <strong>de</strong> LRUno es conveniente en caches <strong>de</strong> último nivel porqueno pue<strong>de</strong>n lidiar con la localidad temporal. Esto se<strong>de</strong>be a que las caches <strong>de</strong> último nivel no ven todoslos accesos a memoria. A<strong>de</strong>más, los bloques <strong>de</strong>ben<strong>de</strong>scen<strong>de</strong>r hasta la última posición <strong>de</strong> la pila LRU paraser reemplazados.En este trabajo se muestra que la mayoría <strong>de</strong> losbloques no se vuelven a referenciar una vez han <strong>de</strong>jadola posición MRU. Más aún, la probabilidad <strong>de</strong> volvera ser referenciados no <strong>de</strong>pen<strong>de</strong> siempre <strong>de</strong> la posiciónque ocupan en la pila. Basándose en estas observaciones,se <strong>de</strong>fine el número <strong>de</strong> periodos MRU (pMRU)<strong>de</strong> un bloque como el número <strong>de</strong> veces que un bloqueocupa la posición MRU mientras permanece en lacache, y se propone el algoritmo <strong>de</strong> reemplazo pMRU,que selecciona la víctima entre aquellos bloques quetienen un solo pMRU. También se proponen variaciones<strong>de</strong> este algoritmo para explotar la recencia <strong>de</strong>información.Los resultados experimentales muestran que, en lamedia, la mejor versión <strong>de</strong> algoritmo pMRU obtieneuna reducción <strong>de</strong> MPKI <strong>de</strong> un 19% comparado conLRU. A<strong>de</strong>más, la versión más sencilla tan sólo necesita2 bits <strong>de</strong> estado por bloque in<strong>de</strong>pendientemente<strong>de</strong> la asociatividad <strong>de</strong> cache. Por consiguiente, la complejidadhardware y el coste <strong>de</strong> actualizar estos bitsse reduce significativamente comparado con LRU.Palabras clave— Algoritmo <strong>de</strong> reemplazo en caches,caches <strong>de</strong> último nivel, periodo MRU.I. IntroducciónLOS arquitectos <strong>de</strong> computadores han implementadomemorias cache [1] <strong>de</strong>s<strong>de</strong> finales <strong>de</strong> los años60 para mitigar la diferencia <strong>de</strong> velocidad existenteentre el procesador y la memoria principal. Este problemase solventó al principio mediante el uso <strong>de</strong>un solo nivel <strong>de</strong> cache, pero conforme la diferencia<strong>de</strong> velocidad ha sido mayor, se han requerido másniveles para no <strong>de</strong>gradar las prestaciones. El primernivel (cache <strong>de</strong> L1) es el más cercano al procesadory se diseña para conseguir velocidad alta <strong>de</strong> accesoa memoria, mientras que el segundo o tercer nivel(si existe) se diseña para ocultar en la medida <strong>de</strong>lo posible la latencia elevada <strong>de</strong>bido al acceso a lamemoria principal, que conlleva cientos <strong>de</strong> ciclos <strong>de</strong>procesador en los microprocesadores actuales.1 Grupo <strong>de</strong> Arquitecturas Paralelas, Universitat Politècnica<strong>de</strong> València, e-mails: alvabre@gap.upv.es, {jsahuqui,spetit, plopez, jduato}@disca.upv.es.<strong>La</strong>s prestaciones <strong>de</strong>l sistema <strong>de</strong>pen<strong>de</strong>n en gran medida<strong>de</strong> las prestaciones <strong>de</strong> la jerarquía <strong>de</strong> memoria.Es por ello que muchos trabajos <strong>de</strong> investigación sehan centrado en mejorar las prestaciones <strong>de</strong> la cache,aunque normalmente lo han hecho en un solo nivel<strong>de</strong> cache (L1, L2 o L3). Algunos ejemplos son lastécnicas <strong>de</strong> load-bypassing, way-prediction o prefetching,que han sido ampliamente investigadas e implementadasen muchos productos comerciales. Aunqueestas técnicas se han implementado en procesadoresmonolíticos, la presión <strong>de</strong>l controlador <strong>de</strong> memoriaes mayor en sistemas multinúcleo. Por tanto, lasprestaciones relativas a la jerarquía <strong>de</strong> memoria engeneral, y <strong>de</strong> la cache <strong>de</strong> último nivel en particular,son un aspecto importante en los microprocesadoresactuales.<strong>La</strong>s caches <strong>de</strong> último nivel forman una estructura<strong>de</strong> memoria gran<strong>de</strong> entre cientos <strong>de</strong> KB y <strong>de</strong>cenas <strong>de</strong>MB [2], para así reducir los fallos <strong>de</strong> capacidad. Másaún, se prevé que esta capacidad aumente conformeel tamaño <strong>de</strong> los transistores continúe reduciéndoseen las futuras tecnologías. A<strong>de</strong>más, las caches <strong>de</strong>último nivel implementan un gran número <strong>de</strong> vías(p.e., 16 vías) para reducir los fallos <strong>de</strong> conflicto.En general, las caches explotan la localidad temporalmediante el algoritmo <strong>de</strong> reemplazo LRU (LeastRecently Used). Este algoritmo actúa como una pilaque contiene el bloque MRU (Most Recently Used)en la primera posición y el bloque LRU en la última,siendo este último bloque la víctima cuando se requiereespacio. Aunque este algoritmo resulta eficienteen caches <strong>de</strong> L1 con poca asociatividad, encaches <strong>de</strong> último nivel con asociatividad mayor como8 y 16 vías, la implementación <strong>de</strong>l algoritmo LRUtradicional es <strong>de</strong>masiado compleja. Esto conduce aque se hayan propuesto aproximaciones a LRU, perolas prestaciones obtenidas se apartan <strong>de</strong> las <strong>de</strong>l LRUtradicional [3]. Por otra parte, las prestaciones <strong>de</strong>LRU se encuentran lejos <strong>de</strong> las obtenidas por el algoritmo<strong>de</strong> reemplazo óptimo conocido como algoritmo<strong>de</strong> Belady [4], que reduce los fallos <strong>de</strong> cache a unmínimo teórico eligiendo como víctima el bloque quese referenciará más tar<strong>de</strong> en el futuro.Existen varias razones que explican por qué el algoritmoLRU no obtiene buenas prestaciones en caches<strong>de</strong> último nivel con pilas gran<strong>de</strong>s. En primer lugar,los accesos a memoria que resultan en acierto en lacache <strong>de</strong> L1 quedan ocultos a la cache <strong>de</strong> último nively se pier<strong>de</strong> la localidad temporal. En segundo lugar,LRU sufre el efecto conocido como cache thrashingen aquellas aplicaciones don<strong>de</strong> la cantidad <strong>de</strong> datoses mayor que la capacidad <strong>de</strong> cache disponible, resultandoen accesos <strong>de</strong> bloque cíclicos. Estos blo-<strong>JP2011</strong>-557


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011ques recorren la pila sin ser utilizados <strong>de</strong> nuevo ycuando se requieren ya han sido reemplazados. Porúltimo, LRU fuerza que un bloque tenga que llegarhasta la última posición para ser la víctima <strong>de</strong> reemplazo.Esto pue<strong>de</strong> afectar a las prestaciones <strong>de</strong>bido aque, como los resultados experimentales mostrarán,muchos bloques almacenados en L2 no vuelven a serutilizados <strong>de</strong> nuevo. Por ejemplo, en una cache <strong>de</strong>16 vías, un bloque que <strong>de</strong>ja la posición MRU y novuelve a ser referenciado, no será la víctima hastaque se hayan completado quince accesos a bloquesmapeados en el mismo conjunto. Esto significa queotros bloques más útiles pue<strong>de</strong>n ser elegidos comovíctima y por tanto, <strong>de</strong>gradar las prestaciones. Algunostrabajos <strong>de</strong> investigación actuales han atacadoeste problema prediciendo cuando un bloque pue<strong>de</strong>ser candidato a reemplazo antes <strong>de</strong> que llegue a laposición LRU [5] [6]. Otros trabajos manejan losreemplazos mediante la gestión <strong>de</strong> una cola para losbloques [7]. En estos casos, la víctima proviene <strong>de</strong> laprimera o última posición <strong>de</strong> la cola.<strong>La</strong> mayoría <strong>de</strong> bloques no se referencian otra vezcuando <strong>de</strong>jan la posición MRU. A<strong>de</strong>más, la probabilidad<strong>de</strong> un bloque <strong>de</strong> ser referenciado otra vez no<strong>de</strong>pen<strong>de</strong> siempre <strong>de</strong>l or<strong>de</strong>n que ocupa en la pila LRU.Esto significa que, en general, el or<strong>de</strong>n <strong>de</strong> acceso noes importante para las aplicaciones en caches con ungran número <strong>de</strong> vías porque la probabilidad no disminuyeconforme el bloque <strong>de</strong>scien<strong>de</strong> por la pila. Sinembargo, la política LRU necesita un número <strong>de</strong> bits<strong>de</strong> estado por bloque consi<strong>de</strong>rable para mantener elor<strong>de</strong>n <strong>de</strong> la pila.En este trabajo se <strong>de</strong>fine el número <strong>de</strong> periodosMRU (pMRU) <strong>de</strong> un bloque como el número <strong>de</strong> vecesque un bloque acce<strong>de</strong> a la posición MRU durante sutiempo <strong>de</strong> vida. Teniendo en cuenta que la mayoría<strong>de</strong> bloques exhiben un pMRU, este trabajo proponeel algoritmo pMRU con el objetivo <strong>de</strong> explotar estecomportamiento para mejorar las prestaciones. Losbloques que muestran un pMRU serán consi<strong>de</strong>radosen el reemplazo, seleccionando uno <strong>de</strong> ellos al azar.De esta manera, la complejidad <strong>de</strong>l algoritmo se reducerespecto a LRU y otras propuestas recientes.También se propondrán variantes <strong>de</strong> este algoritmoque exploten la recencia <strong>de</strong> información.El algoritmo pMRU propuesto mejora las prestacionesrespecto a LRU y otros algoritmos propuestosrecientemente. <strong>La</strong> mejor versión <strong>de</strong>l algoritmo entérminos <strong>de</strong> prestaciones se refiere como pMRU-b3,y consigue reducir el MPKI en un 8% y 19% comparadocon el algoritmo reciente llamado DC-Bubbley LRU, respectivamente. Para finalizar, la propuestarequiere menos bits <strong>de</strong> estado que LRU, ya que los algoritmospMRU no necesitan mantener todo el or<strong>de</strong>n<strong>de</strong> la pila. Por ejemplo, para una cache <strong>de</strong> 16-vías,la versión más sencilla <strong>de</strong>l algoritmo pMRU tan sólonecesita 2 bits <strong>de</strong> estado por bloque, mientras queLRU requiere 4. A<strong>de</strong>más, el número <strong>de</strong> bits <strong>de</strong> estadoque se <strong>de</strong>ben actualizar en el peor caso <strong>de</strong> cadapolítica es 3, 4 y 30 para pMRU, DC-Bubble y LRU,respectivamente.El resto <strong>de</strong>l artículo se organiza <strong>de</strong> la siguientemanera: la Sección II muestra algunos trabajos relacionados.<strong>La</strong> Sección III discute la motivación <strong>de</strong>lpresente trabajo. <strong>La</strong> Sección IV presenta el algoritmobasado en periodos MRU. <strong>La</strong> Sección V analizalos resultados experimentales. <strong>La</strong> Sección VI discutela complejidad hardware <strong>de</strong> los algoritmos estudiadosy finalmente la Sección VII presenta las conclusionesmás relevantes.II. Trabajos relacionadosExisten gran cantidad <strong>de</strong> trabajos que han centradosus esfuerzos en las políticas <strong>de</strong> ubicación yreemplazo <strong>de</strong> los bloques para mejorar las prestaciones<strong>de</strong> la jerarquía <strong>de</strong> cache. Estos trabajos lospo<strong>de</strong>mos dividir en tres categorías: uso <strong>de</strong> informaciónsobre el comportamiento <strong>de</strong> los bloques encaches <strong>de</strong> L1, mejora <strong>de</strong> las prestaciones <strong>de</strong> la políticaLRU en caches <strong>de</strong> L2 y propuestas que utilizan estructurashardware diferentes a una pila para manejarla estrategia <strong>de</strong> reemplazo.En el primer grupo se encuentra la propuesta NTS<strong>de</strong> Tyson et al. [8] y la propuesta MAT <strong>de</strong> Johnsonet al. [9]. <strong>La</strong> primera propuesta marca un bloquecomo cacheable basándose en el comportamiento <strong>de</strong>lmismo en el pasado, mientras que la segunda clasificalos bloques como temporales o no temporales segúnel comportamiento <strong>de</strong> los mismos durante sus tiempos<strong>de</strong> vida. Rivers et al. [10] propone explotar elcomportamiento basándose en la dirección efectiva<strong>de</strong> los datos referenciados así como en el contador <strong>de</strong>programa <strong>de</strong> la instrucción <strong>de</strong> carga.Otros trabajos se centran en mejorar las prestaciones<strong>de</strong> la política LRU, principalmente en L2. Porejemplo, el pseudo-LRU trata <strong>de</strong> reducir la complejidadhardware <strong>de</strong>l LRU tradicional. Otros trabajospredicen el bloque a reemplazar en lugar <strong>de</strong>lLRU. En [5], la propuesta <strong>de</strong> Lin y Reinhardt predicecuando reemplazar un bloque antes <strong>de</strong> que llegue a laposición LRU. Esto se consigue utilizando un contadorque almacena el número <strong>de</strong> accesos al mismo conjuntodurante un intervalo <strong>de</strong> acceso a una línea <strong>de</strong>cache. Si el contador llega a superar un valor umbral(aprendido <strong>de</strong>l comportamiento previo <strong>de</strong> la línea), lalínea asociada es candidata a ser reemplazada. Otraspropuestas mejoran las prestaciones <strong>de</strong> LRU con unalgoritmo LRU modificado [11] [12] [13] o medianteuna pila pseudo-LIFO [6].El esquema Bubble, propuesto por Zhang yXue [7], es una propuesta interesante clasificada enla última categoría. Esta propuesta hace uso <strong>de</strong> unacola en lugar <strong>de</strong> una pila. Los bloques entrantes sealojan en el final <strong>de</strong> la cola, que es la localidad querepresenta la menor frecuencia <strong>de</strong> acceso. Los bloquespromocionan hacia la cabeza <strong>de</strong> la cola conformeson referenciados. <strong>La</strong> víctima se elige <strong>de</strong>l finalo la cabeza <strong>de</strong> la cola según si el acceso previo alconjunto resultó en un fallo o acierto <strong>de</strong> cache, respectivamente.Este trabajo también presenta unatécnica <strong>de</strong> divi<strong>de</strong>-y-vencerás, que divi<strong>de</strong> los conjuntosen grupos <strong>de</strong> bloques in<strong>de</strong>pendientes que aplican<strong>JP2011</strong>-558


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA IPorcentaje <strong>de</strong> bloques con un solo pMRU para cada aplicación <strong>de</strong> SPEC2000 en una cache <strong>de</strong> L2 <strong>de</strong> 1MB-16vías.ammp applu apsi art bzip2 crafty eon equake facerec fma3d galgel gap gcc100% 93% 35% 95% 35% 15% – 80% 85% – 15% 65% 75%gzip lucas mcf mesa mgrid parser perlbmk sixtrack swim twolf vortex vpr wupwise56% 61% 89% 65% 21% 40% – 29% 68% 34% 32% 59% 92%el algoritmo Bubble <strong>de</strong> manera in<strong>de</strong>pendiente. Estapolítica se conoce como DC-Bubble. Cuando se requiereespacio, se elige un grupo al azar, reduciendo<strong>de</strong> este modo la complejidad frente a LRU y el efecto<strong>de</strong> cache thrashing.III. MotivaciónCuando se utiliza el algoritmo LRU, un bloqueque no se referencia <strong>de</strong>scien<strong>de</strong> paso a paso por lapila hasta que se aloja en la posición LRU. Duranteeste <strong>de</strong>scenso, la referencia a este bloque hace quevuelva a ocupar la posición MRU. Para caches con ungran número <strong>de</strong> vías, la probabilidad <strong>de</strong> retorno a laposición MRU no se distribuye <strong>de</strong> manera uniformeen las posiciones <strong>de</strong> la pila. <strong>La</strong> Figura 1 muestra losresultados para una cache <strong>de</strong> L2 <strong>de</strong> 1MB-16vías. Eltérmino pos2 hace referencia a la posición siguientea la MRU en la pila, pos3 a la posición siguientea pos2, etcétera. Debido a restricciones <strong>de</strong> espacio,pos5-7 hace referencia a las posiciones comprendidasentre la quinta y la séptima, etcétera. Nótese que laprobabilidad <strong>de</strong> referencia en la posición MRU no seha tenido en cuenta.Aunque en algunas aplicaciones, los bloques másreferenciados son aquellos cercanos a la posición LRU(pos16 ), la mayoría <strong>de</strong> cargas presentan una probabilidadalta <strong>de</strong> retorno en bloques cercanos a laposición MRU. En general, se pue<strong>de</strong> concluir quemantener todo el or<strong>de</strong>n <strong>de</strong> la pila LRU no es importanteen caches con un gran número <strong>de</strong> vías. Sinembargo, la política LRU requiere un número significante<strong>de</strong> bits (4 por bloque en una cache <strong>de</strong> 16-vías)para mantener todo el or<strong>de</strong>n <strong>de</strong> la pila.IV. Algoritmo basado en periodos MRUEsta sección presenta en primer lugar el concepto<strong>de</strong> periodo MRU (pMRU) y <strong>de</strong>spués <strong>de</strong>talla en quéconsiste el algoritmo basado en pMRU.Los conceptos <strong>de</strong> tiempos <strong>de</strong> vida y muerte <strong>de</strong> unbloque [14] han sido muy utilizados en la investigación.El tiempo <strong>de</strong> generación <strong>de</strong>fine el tiempotranscurrido <strong>de</strong>s<strong>de</strong> que un bloque entra en la cachehasta que se reemplaza. Este tiempo se pue<strong>de</strong> dividiren los tiempos <strong>de</strong> vida y muerte <strong>de</strong> un bloque.El primero se refiere al tiempo <strong>de</strong>s<strong>de</strong> que el bloqueentra en la cache hasta la última referencia al mismo.El segundo alu<strong>de</strong> al tiempo <strong>de</strong>s<strong>de</strong> la última referenciahasta que se reemplaza.<strong>La</strong> Figura 2 ilustra el concepto <strong>de</strong> pMRU en el contexto<strong>de</strong>l tiempo <strong>de</strong> vida <strong>de</strong>l bloque A. Asumiendola política LRU, A se aloja en la posición MRU entiempo t1. El bloque permanece en esta posiciónmientras es accedido. Después, <strong>de</strong>ja esta posiciónporque el bloque B se referencia. En este momentose dice que A ha finalizado su primer pMRU. Pasadocierto tiempo, A es accedido otra vez, con lo quevuelve a la posición MRU e inicia su segundo pMRU.<strong>La</strong> marca t2 indica el final <strong>de</strong> este pMRU que coinci<strong>de</strong>con el último acceso a A. El tiempo <strong>de</strong> muerteempieza en este punto y acaba en la marca t3 cuandoel bloque A es expulsado.Con el objetivo <strong>de</strong> explorar el potencial <strong>de</strong>l conceptopMRU sobre el algoritmo LRU, se ha obtenidoel porcentaje <strong>de</strong> bloques que presentan un solopMRU cuando son reemplazados. <strong>La</strong> Tabla I muestralos resultados para el conjunto <strong>de</strong> aplicaciones <strong>de</strong>SPEC2000 [15] y una cache <strong>de</strong> L2 <strong>de</strong> 1MB-16vías. Enlíneas generales, la mayoría <strong>de</strong> aplicaciones presentanun porcentaje elevado <strong>de</strong> bloques con un pMRU. <strong>La</strong>saplicaciones que no presentan valor son aquellas enlas que todos los fallos <strong>de</strong> L2 contabilizados son forzosos(ver Sección V).El algoritmo basado en pMRU hace uso <strong>de</strong> la información<strong>de</strong> un pMRU o múltiples <strong>de</strong> cada bloque.Para ello, requiere un bit por bloque (pMRU-bit) queindica si el mismo ha experimentado un pMRU o varios.El algoritmo funciona como sigue. Cada vez queun bloque entra en la cache, el valor <strong>de</strong> su pMRU-bitasociado se actualiza a ’0’ para indicar que su primerpMRU ha empezado. El bloque es candidato a serreemplazado cuando <strong>de</strong>ja la posición MRU por vezprimera. Después, si el bloque se referencia <strong>de</strong> nuevo,Fig. 1. Probabilidad <strong>de</strong> un bloque <strong>de</strong> ser referenciado en laposición X utilizando LRU.Fig. 2. Tiempo <strong>de</strong> generación <strong>de</strong>l bloque A.<strong>JP2011</strong>-559


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA IIIPorcentaje <strong>de</strong> fallos forzosos para cada aplicación <strong>de</strong> SPEC2000 en una cache <strong>de</strong> L2 <strong>de</strong> 1MB-16vías.ammp applu apsi art bzip2 crafty eon equake facerec fma3d galgel gap gcc0% 24% 75% 0% 5% 28% 100% 100% 4% 100% 2% 100% 12%gzip lucas mcf mesa mgrid parser perlbmk sixtrack swim twolf vortex vpr wupwise100% 30% 2% 63% 22% 16% 100% 15% 25% 1% 50% 34% 80%TABLA IIParámetros <strong>de</strong> la máquina.Política issuePredictor <strong>de</strong> saltosNúcleo <strong>de</strong>l microprocesadorPenalización predictorAncho fetch, issue y commitTamaño ROB (entradas) 256# Int. ALUs 4# FP ALUs 4Jerarquía <strong>de</strong> memoriaFuera <strong>de</strong> or<strong>de</strong>nHybrid gshare/bimodal:gshare: 14-bits <strong>de</strong> historiaglobal y 16K contadores<strong>de</strong> 2-bitsbimodal: 4K contadores<strong>de</strong> 2-bits y selector <strong>de</strong>predictor con 4Kcontadores <strong>de</strong> 2-bits10 ciclos4 instr/cicloPuertos memoria 4Cache datos/instr. L1 16KB-2vías, 64B-línea<strong>La</strong>tencia L11 cicloCache unificada L21MB-16vías, 128B-línea<strong>La</strong>tencia L26 ciclos<strong>La</strong>tencia memoria200 ciclosvuelve a ser el MRU y empieza otro pMRU. Esto seindica marcando su pMRU-bit a ’1’. De esta manerael bit indica que el bloque ha tenido varios pMRU.Este algoritmo tiene como objetivo seleccionarpara reemplazo aquellos bloques que han tenido unpMRU. Si un bloque exhibe buena localidad, acudirámás <strong>de</strong> una vez a la posición MRU y no será candidatoa reemplazo. Para que el hardware sea simple,la víctima se selecciona al azar entre aquellos bloquesque tienen un pMRU excepto el bloque MRU. Si nohay ningún candidato, la víctima se selecciona al azarentre todos los bloques <strong>de</strong>l conjunto excepto el MRU.Por otro lado, como se ha visto en la Figura 1, almacenarel or<strong>de</strong>n <strong>de</strong> los últimos bloques accedidospue<strong>de</strong> ser importante en términos <strong>de</strong> prestacionespara la mayoría <strong>de</strong> aplicaciones. Por ello se <strong>de</strong>finela familia <strong>de</strong> algoritmos pMRU-bX, que extien<strong>de</strong> lapropuesta original para explotar el comportamientopMRU y la recencia <strong>de</strong> información. En este caso,se mantiene el or<strong>de</strong>n <strong>de</strong> los últimos X bloques referenciadosy no son candidatos para reemplazo. Porejemplo, el algoritmo etiquetado como pMRU-b2 noconsi<strong>de</strong>ra como candidatos el bloque MRU y el inmediatamenteposterior. Nótese que pMRU-b1 se refiereal algoritmo original. <strong>La</strong> complejidad se reducerespecto a LRU porque estos algoritmos no necesitanguardar todo el or<strong>de</strong>n <strong>de</strong> la pila.V. Evaluación experimentalEsta sección presenta el entorno <strong>de</strong> simulación ylas aplicaciones utilizadas en la evaluación <strong>de</strong> losFig. 3. MPKI <strong>de</strong> los algoritmos pMRU, Bubble y LRU enuna cache <strong>de</strong> 1MB-16vías.algoritmos, los cuales han sido mo<strong>de</strong>lados en unaversión extendida <strong>de</strong>l simulador SimpleScalar [16].Los resultados experimentales han sido obtenidosconfigurando el simulador para el juego <strong>de</strong> instruccionesAlpha y lanzando las aplicaciones <strong>de</strong> SPEC2000,que se evalúan utilizando las entradas ref, ejecutando1000M <strong>de</strong> instrucciones antes <strong>de</strong> recolectarestadísticas y simulando posteriormente 500M <strong>de</strong>instrucciones con <strong>de</strong>talle. <strong>La</strong> Tabla II muestra losparámetros arquitectónicos utilizados en los experimentos.<strong>La</strong>s aplicaciones que no estresan la cache <strong>de</strong> L2 hansido eliminadas <strong>de</strong>l estudio. Para ello, se ha obtenidoel porcentaje <strong>de</strong> fallos forzosos <strong>de</strong> cada aplicación. <strong>La</strong>Tabla III muestra los resultados para una cache <strong>de</strong> L2<strong>de</strong> 1MB-16vías. Se ha prescindido <strong>de</strong> las aplicacionescon un porcentaje <strong>de</strong> fallos forzosos mayor que un75% o con un MPKI menor que uno 1 .A. Prestaciones <strong>de</strong>l algoritmo pMRUEsta sección evalúa las prestaciones <strong>de</strong>l algoritmopropuesto. Para ello, sus prestaciones han sido comparadascontra las obtenidas con el algoritmo LRUy la reciente propuesta <strong>de</strong>l algoritmo Bubble. <strong>La</strong>Figura 3 muestra el MPKI <strong>de</strong> las políticas analizadas.El algoritmo pMRU obtiene, en la media, losmejores resultados y reduce el MPKI en un 6% y 15%comparado con Bubble y LRU, respectivamente. Sepue<strong>de</strong> observar que la propuesta obtiene los mejoresresultados en aquellas aplicaciones que presentan unMPKI elevado.Cabe analizar con <strong>de</strong>talle los resultados obtenidoscon las aplicaciones ammp y art. En la primera, elMPKI es 68.7, 63.5 y 49.7 en los algoritmos LRU,Bubble y pMRU, respectivamente. En art, el algoritmopMRU reduce el MPKI en un 37% respectoa LRU. El MPKI tan elevado <strong>de</strong> LRU pue<strong>de</strong> expli-1 <strong>La</strong>s diferencias en MPKI observadas para todos los algoritmosanalizados en este trabajo son menores que 0.4 en lasaplicaciones eliminadas.<strong>JP2011</strong>-560


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011carse mediante los resultados <strong>de</strong> la Figura 1. En elcaso <strong>de</strong> ammp, los bloques que se encuentran en posicionesalejadas <strong>de</strong> la MRU, es <strong>de</strong>cir, los bloques queLRU reemplaza tienen una gran probabilidad <strong>de</strong> retorno.El comportamiento <strong>de</strong> art se pue<strong>de</strong> razonar<strong>de</strong> la misma manera. A<strong>de</strong>más, <strong>de</strong> acuerdo con losresultados <strong>de</strong> la Tabla I, la mayoría <strong>de</strong> bloques <strong>de</strong>estas cargas se llevan a la cache y no se vuelven areferenciar una vez abandonan la posición MRU. Elalgoritmo propuesto obtiene los mejores resultadosporque reemplaza rápidamente estos bloques y trata<strong>de</strong> mantener los que vuelven a ser referenciados enposiciones no-MRU.B. Mejorando las prestaciones <strong>de</strong>l algoritmo pMRUAunque la política pMRU consigue mejores resultadosen algunas aplicaciones comparado con LRU,no lo consigue con otras cargas. Esto pue<strong>de</strong> explicarsemediante el hecho <strong>de</strong> que el algoritmo pMRUoriginal no tiene en cuenta la recencia <strong>de</strong> información.Este problema se ataca mediante los algoritmospMRU-bX. <strong>La</strong> Figura 4 muestra los resultadosvariando X entre 1 y 4.<strong>La</strong> política pMRU-b3 muestra, en la media, unMPKI mejor que las otras variantes. De nuevo,la razón pue<strong>de</strong> ser explicada mediante los resultadospresentados en la Figura 1. Comparado conlos algoritmos pMRU-b1 y LRU, pMRU-b3 reduceel MPKI en un 4% y 19% en la media, respectivamente.Nótese que incrementar X no siempre mejoralas prestaciones. Este el caso, por ejemplo, <strong>de</strong> facerec.<strong>La</strong> razón es que la probabilidad <strong>de</strong> acce<strong>de</strong>ra bloques localizados en la cuarta posición es muybaja en la mayoría <strong>de</strong> aplicaciones. Por tanto, el hecho<strong>de</strong> que estos bloques no sean consi<strong>de</strong>rados comocandidatos para el reemplazo provoca que otros bloquescon mayor probabilidad <strong>de</strong> retorno (localizadosen posiciones inferiores) puedan ser reemplazados <strong>de</strong>forma errónea.C. Dividiendo los conjuntos en gruposEl algoritmo Bubble fue diseñado también paradividir los bloques <strong>de</strong> los conjuntos en grupos y asíresolver sus problemas. En un fallo <strong>de</strong> cache, se elige<strong>de</strong> manera aleatoria un grupo <strong>de</strong>l conjunto y se seleccionael bloque víctima <strong>de</strong> ese grupo. Esta seccióncompara las prestaciones <strong>de</strong> las políticas Bubbley pMRU aplicadas en grupos. Se ha utilizado elprefijo ’DC’ para <strong>de</strong>notar esta técnica <strong>de</strong> divi<strong>de</strong>-yvencerás.Cada grupo está compuesto por 4 bloquesporque Bubble obtiene los mejores resultadoscon este número. Así, en una cache <strong>de</strong> 16-vías cadaconjunto está formado por 4 grupos.Nótese que hemos tenido sólo en cuenta los algoritmosDC-pMRU-b1 y -b2 porque -b3 consi<strong>de</strong>ra siempreun solo candidato para reemplazo. <strong>La</strong> Figura 5muestra los resultados. Se pue<strong>de</strong> observar que DCpMRU-b1obtiene mejor MPKI que -b2 y DC-Bubbleen la media.En resumen, los mejores resultados son aquellosobtenidos con la política pMRU-b3 trabajando enconjuntos <strong>de</strong> 16-vías. Esta versión obtiene una reducción<strong>de</strong> un 8%, 10% y 19% comparado con DC-Bubble, Bubble y LRU, respectivamente. A<strong>de</strong>más, lapropuesta aplicada en condiciones adversas (DC) obtienemejores resultados que DC-Bubble (reducción<strong>de</strong> MPKI en un 4% en la media).VI. Complejidad hardwareEsta sección analiza la complejidad hardware <strong>de</strong>los algoritmos estudiados en base al número <strong>de</strong> bits<strong>de</strong> estado por bloque y el número máximo <strong>de</strong> estosbits que cambian su valor en el peor caso <strong>de</strong> cadaalgoritmo.<strong>La</strong> política LRU requiere log 2 (n) bits por bloque(contadores LRU) para mantener el or<strong>de</strong>n <strong>de</strong> la pilaen una cache asociativa por conjuntos <strong>de</strong> n-vías. Enel peor caso, es <strong>de</strong>cir, un acierto en la vía LRU o unfallo <strong>de</strong> cache, se <strong>de</strong>ben actualizar todos los contadores,lo que supone un cambio <strong>de</strong> valor <strong>de</strong> 30 bitsen una cache <strong>de</strong> 16-vías.Por otra parte, el algoritmo pMRU más sencilloreduce el número <strong>de</strong> bits a 2 por bloque in<strong>de</strong>pendientemente<strong>de</strong> la asociatividad <strong>de</strong> cache. Estos bitsson el pMRU-bit y un bit adicional para indicar elbloque MRU (MRU-bit). En el peor caso, sólo se requiereactualizar el valor <strong>de</strong> 3 bits. A<strong>de</strong>más, eligiendola víctima al azar entre los candidatos se reduce lacomplejidad <strong>de</strong>l circuito. Con todo, la propuesta reduceen gran medida el consumo energético <strong>de</strong> losbits <strong>de</strong> estado.Los algoritmos <strong>de</strong> la familia pMRU-bX requierenY = ⌈log 2 (X+1)⌉ bits <strong>de</strong> estado para indicar el or<strong>de</strong>n<strong>de</strong> los últimos X bloques referenciados. PorFig. 4. MPKI <strong>de</strong> los algoritmos pMRU-bX, variando X entre1 y 4.Fig. 5. MPKI <strong>de</strong> los algoritmos pMRU-b1, pMRU-b2 y Bubbleaplicados en grupos.<strong>JP2011</strong>-561


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011ejemplo, para las políticas pMRU-b2 y -b3, se necesitan3 bits <strong>de</strong> estado (2 MRU-bits y un pMRU-bit).En el peor caso, es <strong>de</strong>cir, un fallo <strong>de</strong> cache o el accesoa un bloque no incluido en los últimos X, laspolíticas pMRU-b2 y -b3 sólo actualizan 5 y 7 bits,respectivamente.En contraste con los algoritmos propuestos, Bubblerequiere tantos bits <strong>de</strong> estado como LRU porque<strong>de</strong>be mantener todo el or<strong>de</strong>n <strong>de</strong> los bloques. A<strong>de</strong>más,se requiere un bit adicional por conjunto para indicarsi el acceso anterior fue un acierto o un fallo. En elpeor caso, esto es dos fallos consecutivos, <strong>de</strong>ben actualizarsehasta 26 bits <strong>de</strong> estado.Finalmente, dividir los conjuntos en grupos resultabeneficioso en términos <strong>de</strong> número <strong>de</strong> bits <strong>de</strong> estado.Aunque DC-Bubble requiere el bit por conjunto aligual que Bubble, en una cache <strong>de</strong> 16-vías y 4 bloquespor grupo, sólo se necesitan 2 bits <strong>de</strong> estado porbloque. En cada grupo, 4 bits cambian su valor enel caso <strong>de</strong> dos fallos consecutivos. Aplicando pMRUen grupos, DC-pMRU-b1 sólo necesita un pMRU-bity otro MRU-bit por bloque y pue<strong>de</strong> prescindir <strong>de</strong>lbit por conjunto, con lo cual reduce la complejidadrespecto a DC-Bubble. En el peor caso, sólo se actualizan3 bits <strong>de</strong> estado.VII. ConclusionesEn este trabajo se han presentado algoritmos basadosen el concepto <strong>de</strong> periodo MRU (pMRU) con elobjetivo <strong>de</strong> que sean aplicados en caches <strong>de</strong> últimonivel. Se ha <strong>de</strong>finido el número <strong>de</strong> pMRU <strong>de</strong> unbloque como el número <strong>de</strong> veces que ese bloque ocupala posición MRU. A<strong>de</strong>más, se ha observado que utilizandoel algoritmo LRU, la mayoría <strong>de</strong> los bloquestienen un solo pMRU en el momento en que sonreemplazados. En este trabajo también se ha evaluadola probabilidad <strong>de</strong> un bloque <strong>de</strong> retornar a laposición MRU estando en una posición no-MRU. Losresultados han mostrado que la mayoría <strong>de</strong> aplicacionesexhiben una probabilidad <strong>de</strong> acceso alta envías cercanas a la MRU, pero esta probabilidad nodisminuye siempre conforme los bloques se acercan ala posición LRU.Basándose en estas i<strong>de</strong>as, se ha propuesto el algoritmopMRU que trata <strong>de</strong> seleccionar como víctimaaquellos bloques con un solo pMRU. En su versiónmás sencilla, sólo requiere un bit por bloque para indicaruno o varios pMRU y otro bit adicional paraindicar cual es el bloque MRU. Con objeto <strong>de</strong> simplificarel circuito, la víctima entre los candidatos conun pMRU excepto el bloque MRU se selecciona alazar. Si todos los bloques presentan varios pMRU,la víctima se selecciona al azar entre los bloques no-MRU.Los resultados experimentales han mostrado que,en la media, el MPKI se reduce en un 15% respectoa LRU. Esta reducción se eleva hasta un 37% enalgunas aplicaciones. Para tener en cuenta el hecho<strong>de</strong> que existe una probabilidad <strong>de</strong> acceso elevadaen vías cercanas a la MRU, se ha explorado sobreel algoritmo pMRU que los últimos X bloques referenciadosno sean candidatos en el reemplazamiento.Los resultados han mostrado que fijando X = 3 lareducción <strong>de</strong> MPKI es <strong>de</strong> un 8% y 19% comparadocon DC-Bubble y LRU, respectivamente. A<strong>de</strong>más, elalgoritmo pMRU más sencillo reduce la complejidadhardware comparado con DC-Bubble y LRU. Estealgoritmo sólo necesita 2 bits <strong>de</strong> estado por bloque yactualiza como máximo 3 bits en el peor caso, mientrasque DC-Bubble y LRU requieren 2 y 4 bits <strong>de</strong>estado por bloque, respectivamente. En el peor caso,DC-Bubble actualiza 4 bits y LRU actualiza 30 bits.Agra<strong>de</strong>cimientosEl presente trabajo ha sido financiado mediantelos proyectos CICYT TIN2009-14475-C04-01y Consoli<strong>de</strong>r-Ingenio CSD2006-00046.Referencias[1] A. J. Smith, ”Cache Memories,” ACM Computing Surveys,vol. 14, pp. 473-530, 1982.[2] R. Kalla, B. Sinharoy, W. J. Starke, and M. Floyd,”Power7: IBM’s Next-Generation Server Processor,”IEEE Micro, vol. 30, pp. 7-15, 2010.[3] J.-L. Baer, Microprocessor Architecture: From SimplePipelines to Chip Multiprocessors, Cambridge UniversityPress, 2010[4] L. A. Belady, ”A Study of Replacement Algorithms forVirtual-Storage Computer,” IBM Systems Journal, vol.5, no. 2, pp. 78-101, 1966.[5] W.-F. Lin and S. Reinhardt, ”Predicting <strong>La</strong>st-Touch Referencesun<strong>de</strong>r Optimal Replacement,” in Technical ReportCSE-TR-447-02, University of Michigan, 2002.[6] M. Chaudhuri, ”Pseudo-LIFO: The Foundation of a NewFamily of Replacement Policies for <strong>La</strong>st-level Caches,” inProceedings of the 42nd Annual IEEE/ACM InternationalSymposium on Microarchitecture. 2009, pp. 401-412.[7] C. Zhang and B. Xue, ”Divi<strong>de</strong>-and-Conquer: A BubbleReplacement for Low Level Caches,” in Proceedings of the23rd International Conference on Supercomputing. 2009,pp. 80-89.[8] G. Tyson, M. Farrens, J. Matthews, and A. R. Pleszkun,”A Modified Approach to Data Cache Management,” inProceedings of the 28th Annual International Symposiumon Microarchitecture. 1995, pp. 93-103.[9] T. L. Johnson, D. A. Connors, M. C. Merten, and W.-M.W. Hwu, ”Run-Time Cache Bypassing,” IEEE Transactionson Computers, vol. 48, pp. 1338-1354, 1999.[10] J. A. Rivers, E. S. Tam, G. S. Tyson, E. S. Davidson, andM. Farrens, ”Utilizing Reuse Information in Data CacheManagement,” in Proceedings of the 12th InternationalConference on Supercomputing. 1998, pp. 449-456.[11] H. Dybdahl, P. Stenström, and L. Natvig, ”An LRUbasedReplacement Algorithm Augmented with Frequencyof Access in Shared Chip-Multiprocessor Caches,” ACMSIGARCH Computer Architecture News, vol. 35, pp. 45-52, 2007.[12] S. Jiang and X. Zhang, ”LIRS: An Efficient Low InterreferenceRecency Set Replacement Policy to ImproveBuffer Cache Performance,” in Proceedings of the 2002ACM SIGMETRICS International Conference on Measurementand Mo<strong>de</strong>ling of Computer Systems. 2002, pp.31-42.[13] W. A. Wong and J.-L. Baer, ”Modified LRU Policiesfor Improving Second-Level Cache Behavior,” High-Performance Computer Architecture, vol. 0, pp. 49, 2000.[14] D. Wood, M. D. Hill, and R. E. Kessler, ”A Mo<strong>de</strong>l for EstimatingTrace-Sample Miss Ratios,” in Proceedings of the1991 ACM SIGMETRICS International Conference onMeasurement and Mo<strong>de</strong>ling of Computer Systems. 1991,pp. 79-89.[15] Standard Performance Evaluation Corporation, availableonline at http://www.spec.org/cpu2000[16] D. Burger and T. M. Austin, ”The SimpleScalar ToolSet, Version 2.0,” ACM SIGARCH Computer ArchitectureNews, vol. 25, pp. 13-25, 1997.<strong>JP2011</strong>-562


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011A Comparison of Cache Hierarchies for SMTProcessorsDarío Suárez Gracia 1 , Teresa Monreal Arnal 2 , and Víctor Viñals Yúfera 1Abstract—In the multithread and multicore era, programsare forced to share part of the processor structures.On one hand, the state of the art in multithreading<strong>de</strong>scribes how efficiently manage and distributeinner resources such as reor<strong>de</strong>r buffer or issuewindows. On the other hand, there is a substantialbody of works focused on outer resources, mainly onhow to effectively share last level caches in multicores.Between these ends, first and second level caches haveremained apart even if they are shared in most commercialmultithrea<strong>de</strong>d processors.This work analyzes multiprogrammed workloadsas the worst-case scenario for cache sharing amongthreads. In or<strong>de</strong>r to obtain representative results, wepresent a sampling-based methodology that for multiplemetrics such as STP, ANTT, IPC throughput,or fairness, reduces simulation time up to 4 or<strong>de</strong>rs ofmagnitu<strong>de</strong> when running 8-thread workloads with anerror lower than 3% and a confi<strong>de</strong>nce level of 97%.With the above mentioned methodology, we compareseveral state-of-the-art cache hierarchies, and observethat Light NUCA provi<strong>de</strong>s performance benefitsin SMT processors regardless the organization of thelast level cache. Most importantly, Light NUCA gainsare consistent across the entire number of simulatedthreads, from one to eight.Keywords— Cache Hierarcy, Multithreading, Simulation,Sampling, NUCAI. IntroductionMULTITHREADING (MT) is supported by anample spectrum of current processors <strong>de</strong>votedto uneven computing segments such as: embed<strong>de</strong>d,high throughput, or high performance. Examplesof representatives from these segments areNetlogic XLP832 (4-way multithreading, 8-cores), OracleSPARC T3 (8-way multithreading, 16-cores), orIBM POWER7 (4-way multithreading, 4-6-8 cores),respectively [1], [2], [3].All previous examples share a powerful multilevelcache hierarchy with large <strong>La</strong>st Level Caches (LLC),and only the XLP832 <strong>de</strong>parts from the conventionalorganization including a ring for communicating theprivate L2 caches, the eight L3 cache banks, andthe four DDR ports. While these LLCs seem ableto accommodate the multiple working sets of SMTexecution, sharing in the levels close to the processorsproves to be more complex. On one hand, L1 andL2 caches <strong>de</strong>al with the latency-power vs. size tra<strong>de</strong>off.On the other hand, MT architectures add a newtra<strong>de</strong>-off, number of threads in execution vs. miss rate.With many threads, cache misses can be tolerate<strong>de</strong>xecuting instructions from other threads, but as1 Computer Architecture Group (gaZ). Dpto. <strong>de</strong> Informáticae Ingeniería <strong>de</strong> Sistemas. Instituto <strong>de</strong> Investigación en Ingeniería<strong>de</strong> Aragón. <strong>Universidad</strong> <strong>de</strong> Zaragoza. e-mail {dario,victor}@unizar.es2 Department of Computer Architecture. Universitat Politécnica<strong>de</strong> Catalunya (UPC). e-mail: teresa@ac.upc.eduthe number of threads grows, the collective workingset becomes larger and more changing, resulting inmiss ratios potentially harmful to performance. Thelarger their number, the larger and size changing thecollective working set becomes and the larger themiss rate. So when the miss rate reaches a criticalvalue in which threads execution fails to overlap, theprocessor stalls and has the same problem that singlethread machines.SMT architectures may be favored by caches <strong>de</strong>signedto support working set awareness such us theL-NUCA [4]. L-NUCAs belong to a family of cacheorganizations that has received much attention forimproving cache performance: Non-Uniform CacheArchitecture (NUCA) [5]. The seminal NUCA worktargets the wire <strong>de</strong>lay problem 1 , and proposes themelting of the L2 and L3 caches into a meshed arrayof caches banks. Nevertheless, to the best of ourknowledge, there is little work on evaluating NUCAwith simultaneous multithreading processors (SMT).Part of the complexity of assessing multiple cachehierarchies lies in the required simulation framework.So to carry out the experiments, we propose a simpleyet efficient MT simulation methodology ensuring theaccuracy of the results abreast with a sort simulationtime. The methodology is based on statisticalsampling, and contrary to other alternatives does notrequire a prior long profiling of the applications.This work gives two main contributions. The firstone is introducing a powerful methodology to evaluateMT architectures. The second one is the comparisonand evaluation of several state-of-the-art cache hierarchyorganizations driven by the SPEC CPU2006benchmark suite. From the results, we conclu<strong>de</strong> thatregardless the number of threads L-NUCAs outperformconventional multibanked and dynamic NUCAorganizations, both in terms of throughput and fairness.The rest of the paper is organized as follows. SectionII elaborates on previous work. Section IIIpresents the proposed evaluation methodology. SectionIV <strong>de</strong>scribes our experimental framework andthe hierarchies un<strong>de</strong>r test. Section V comments onthe results, and Section VI conclu<strong>de</strong>s the paper.II. BackgroundTullsen, Eggers, and Levy in their SMT seminalwork compare the performance of private and sharedL1 caches (for both instruction and data) and observethat regardless the number of threads (from 1 to 8)shared data caches are the best choice and private1 The wire <strong>de</strong>lay is longer than the bank <strong>de</strong>lay and representsmost part of the total cache latency in LLCs.<strong>JP2011</strong>-563


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011instruction ones are only preferable for the 8-threadcase [6]. Also they point out that shared cachesdo not require any special hardware for coherencesupport. Then, Tullsen and Brown observed that inmany cases when a thread experiences a very longlatency operation, such as a cache miss, it is better toflush the resources of the stalled thread rather thankeeping them ready [7].Hily and Seznec studied how secondary cache bandwidthlimited SMT performance in a trace-drivenenvironment [8]. They point out that the larger thenumber of executed threads the larger the L1 cachesize has to be. Besi<strong>de</strong>s, when the number of threadsincreases, the memory references generated by thesimultaneous execution of in<strong>de</strong>pen<strong>de</strong>nt threads exhibitless spatial locality than that of a single thread,increasing conflict misses.Block size is more criticalthan associativity and as the number of threads rise,it is preferable to keep small block sizes (16 to 32BS).To improve SMT performance, Settle et al. <strong>de</strong>finea cache partitioning scheme based on column caching[9]. Two policies can control the partitioning: (a)synchronous in which each 1 million cycles, the partitionis heuristically set for the next interval. (b)asynchronous in which the LRU algorithm is affectedby some thread reuse counters.Nemirovsky and Yamamoto analyzed the effect ofvarying cache capacity, associativity, and line sizeon miss rate for multistreamed architectures [10].They observe that increasing both cache capacity andassociativity reduces miss ratio specially for smallcaches and that large block size increase miss ratio.The Multithrea<strong>de</strong>d Virtual Processor (MVP) isa coarse-grain multithrea<strong>de</strong>d system with softwaresupport that explicitly forces context switching onlong latency events such as cache misses, I/O, orsynchronization [11]. The evaluation comprised parallelworkloads, and they show that when threadsshare a few data, the increment in miss rate affectsperformance.Garcia et al. studied several data cache organizationsfor multithrea<strong>de</strong>d processors using a tracedrivenenvironment [12]. In accordance with otherauthors [8], [13], they observe that large associativitiesreduce inter-thread misses and that XOR-basedplacement reduces inter-thread miss rate in somecases. Besi<strong>de</strong>s, they proposed several organizationscombining the hash-rehash caches and static cachesplitting.Sarkar and Tullsen proposed two strategies to minimizeinter-object data cache misses at compilationtime [14]. Lopez et al. studied control strategies forreconfigurable caches in SMT GALS processors witha limited set of SPEC CPU2000 benchmarks. Theyconclu<strong>de</strong> that the best control strategy to maximizeperformance is the harmonic mean of the per-threadweighted access time [15], [16].Several authors have proposed SMT methodologiesfor selecting representative mixes of programs.Raasch and Reinhardt propose to profile individualapplications and with the extracted characteristicschoose the most representative pairs [17]. By combiningthe pairs, they also generate 4-thread workloads.Van Biesbrouck et al. proposed a methodology consi<strong>de</strong>ringall starting phases and points but it requiresa complex profiling and an advanced work flow togather the results [18].On the contrary our approach neither require profilingnor complex output information gathering, butit does not consi<strong>de</strong>r multiple starting points by <strong>de</strong>fault.Nevertheless, since we employ last simulationpolicy 2 , faster programs execute multiple times untilthe slower ones finishes, so they run together startingat different points.Finally, our proposal cares about how to selectrepresentative mixes of multiprogrammed workloadsand not when to finalize simulations for obtainingaccurate metrics. In fact, this work pairs perfectlymethods such as FAME [19].III. A Simple Statistic-based Methodologyfor Multiprogrammed WorkloadsThe generation of simulation traces is always a timeconsuming and costly process. Single program tracesextracted with solid approaches such as SimPointsor SimFlex provi<strong>de</strong> accurate simulation results [20],[21]; however, no gui<strong>de</strong>lines are found in the literatureabout how to obtain a representative set ofthread mixes from representative samples of threadindividuals. Our goal is to provi<strong>de</strong> a simple methodto efficiently simulate multiprogramed workloads formultiple metrics.The key i<strong>de</strong>a is instead of executing all possiblecombinations for a given number of threads, to executea representative sample based on statisticalsampling [22], [21] so that simulation time reducesby several or<strong>de</strong>rs of magnitu<strong>de</strong> while keeping measurementsbelow a given error within a confi<strong>de</strong>ncelevel large enough. In this work, we focus on mixescomposed of different threads (combinations withoutrepetition), but the proposed methodology can beused with repetition as well.Fig. 1.selection ofmetrics of interestset preliminarysample sizerunsimulationserror withinconfi<strong>de</strong>nceintervalyesresultsreadyselection ofmicro-architecturalconfigurationsincreasesample sizeFlowchart of the proposed methodologyFigure 1 shows the required steps to obtain thesample:Selection of metrics of interest: For exampleif we want to compare the impact of different cache2 Simulation finishes when all threads have executed at least100M instructions.no<strong>JP2011</strong>-564


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011hierarchies on SMT processors we can take adjustedSTP and ANTT, IPC throughput 3 , and fairness [23],[24].ST P =n∑i=1IP C througput =CP IiSPCP IiMP , ANT T = 1 nn∑i=1CP I MPiCP I SPi(n∑min iIP C i , fairness =i=1maxiCP I MPiCP I SPi(CP I MPiCP I SPiMP and SP refer to the multithrea<strong>de</strong>d and singlethrea<strong>de</strong><strong>de</strong>xecution of a program.Selection of micro-architectural configurations:Pick some of the configurations to be analyzed.In general those with lower performance arepreferable because they tend to experiment the highestvariances of the metrics. In our cache hierarchycomparison, we can take a conventional multibankedorganization, a dynamic NUCA, and a light NUCA.Set preliminary sample size: In this step, wehave to choose a sample size—the larger the numberof threads, the lower this value [25]—, and then, torandomly pick the combinations of programs for theirsimulation. This value should be big enough [22],larger than 30 at least, but tractable in the <strong>de</strong>siredsimulation environment.Run simulations: Run the selected combinationsand compute the sample size for your given confi<strong>de</strong>nceinterval with the next formula [22]:( ) 2 100 × z × sn =(1)r × xwhere n, z, s, r, and x stand for the sample size,normal variate of the confi<strong>de</strong>nce interval, error (in%), sample standard <strong>de</strong>viation, and population mean,respectively.Error within confi<strong>de</strong>nce level?: Check if theobtained n is lower of equal than your preliminarysample size. If not, pick some different extra combinations,run them, and repeat the last steps until theresults are ready.Once a sample size has been established, all the configurationsun<strong>de</strong>r test must be run in or<strong>de</strong>r to checkthat their results also fit within the confi<strong>de</strong>nce interval.Adding new configurations require the same procedure,so if the initial selection of micro-architecturalconfigurations is carefully done, the sample size willnot grow.IV. Comparing SMT cache HierarchiesA. Common Baseline ParametersWe have heavily exten<strong>de</strong>d Simplescalar 3.0d [26]for Alpha with: Simultaneous Multithreading Support[6], Reor<strong>de</strong>r buffer and three issue windows (IW)for integer, floating point, and memory instructions,speculative wake-up support and selective recovery3 IPC throughput is advantageous because it allows anabsolute comparison among configurations. We can useIPC throughput whenever mixes are ma<strong>de</strong> from in<strong>de</strong>pen<strong>de</strong>ntthreads, because then no unpredictable instruction spinningcan arise; e.g., before entering a critical section.))(as in the Intel Pentium 4 [27]), one-cycle payloadand register file stages, accurate timing mo<strong>de</strong>ls fornon-blocking caches, write buffers, buses, networkcontention, flow control, and request arbitration. Forthe rest of parameters see Table I.TABLE IBaseline Processor ConfigurationFetch ICOUNT.2.8Deco<strong>de</strong> / Commit Width 4Branch bimodal + gshare, ROB / LSQ 198 / 96Predictor 16 bitIssue 4 (INT + MEM) + Issue 64(INT) / 32Width 4 (FP)Queues (FP & MEM)FunctionalUnits4 INT + 4 FP ALU, 2 INT MULT + 4 FPMULT/DIVL1 cache 64KB-4Way-32B BS-2ports-LRU, <strong>La</strong>t 2, Init.Rate 1L2 128KB:1MB-8Way-32B BS-1port-LRUD-NUCA 128KB:512KB-4Way-128B BS-1port-LRU, 8columnsL-NUCA 2:5Levels-16KB-4Way-32B BS-1port-LRFL3 8MB-16W-128B BS-1port-LRU, 8 banksMainMemoryFirst chunk: 200 cycles, 4-cycle inter chunk,16B wiresThread fetch is prioritized based on the ICOUNTpolicy [28]. Structures such as ROB, IWs, STB,WB,. . . are shared among threads. To avoid starvationat commit, a thread can not occupy morethat three quarters of L2/L-NUCA/D-NUCA WriteBuffers. Threads commit in Round Robin fashionwith a maximum of 4 instructions committed by allthe threads (RR.4.X), where X corresponds to thenumber of threads in execution [28].B. Cache Memory OrganizationsFocussing in the first and second cache levels, wehave selected three very distinct organizations. Thefirst one is the baseline, corresponding to a conventional3-level hierarchy with a 4-banked L2 cache,and an 8-banked, 8-MB L3 cache, see Figure 2.In any cycle, the L2 cache can start servicing upto two L1 load misses from the MSHR, the rest ofbanks can simultaneously begin the processing of awrite buffer entry, and two whole cache blocks canbe in transit to the L1 MSHR. For this configuration,we tested L2 sizes from 128KB to 1MB organized ineither 1, 2, 4, and 8 banks. The output crossbar hasa fixed latency of 2 cycles with an initiation rate of 1in configurations with 2 or more banks.L2_0mshrL2 bank0 L2 bank1 L2 bank2 L2 bank3L2: fetch-on-missL1: fetch-on-missFig. 2.L2_1mshrL1cache ports(a) Loadsto/fromnext cache levelL2_2mshr...L1 mshrL2_3mshrL2_0mshrL2 bank0 L2 bank1 L2 bank2 L2 bank3wb0 wb1 wb2 wb3L2: copy-back,fetch-on-writeL1: write-through,write-aroundL2_1mshrL1cache ports(b) Storesto/fromnext cache levelL2_2mshrBaseline L2 cache organization with 4 banksThe second hierarchy replaces the L2 and L3 cachesby a dynamic NUCA (D-NUCA) [5], Figure 3, inL2_3mshr<strong>JP2011</strong>-565


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011DN bank0 DN bank1 DN bank2 DN bank3 DN bank4 DN bank5 DN bank6 DN bank7............DN bank0 DN bank1 DN bank2 DN bank3 DN bank4 DN bank5 DN bank6 DN bank7............entries as threads are simultaneously executing. Asstated by Hily and Seznec, bandwidth can be thelimiting factor of the cache hierarchy in SMT [8], andthe larger the number of banks (up to 8), the biggerthe performance.D-NUCA: fetch-on-missL1: fetch-on-missL1cache ports...L1 mshrFig. 3. Multibanked Dynamic NUCA. A block can be mappedto any of the columns surroun<strong>de</strong>d by a dashed linewhich its original interface with the L1 cache andshared mapping have been replaced by a crossbar toprovi<strong>de</strong> more bandwidth and by a simple mapping 4 ,respectively. As in the conventional organization,there is a write buffer for each column. In this waywe can inject the same number of requests per cycle,so the conventional hierarchy can be consi<strong>de</strong>red asa particular case of a NUCA with a single row andwithout the partial tags [5].The last one is Light NUCA (L-NUCA) [4], butalso modified to provi<strong>de</strong> more bandwidth, see Figure4. Changes inclu<strong>de</strong> wi<strong>de</strong>ning the search linksfrom word to block size (from 8 to 32B), increasingthe write buffer size to match the rest of organizations(the buffer in between the r-tile and the rest oftiles). Besi<strong>de</strong>s the replacement buffers are managedwith an improved back-pressure policy, so that theeviction of blocks from the r-tile does not stall untilthe replacement buffer of the r-tile becomes full.We tested 2 organizations based on L-NUCA, oneincluding the same L3 than the baseline organization,and another in which the LLC is a dynamic NUCA,similarly to previous work [4].level 2tilelevel 2tileRESTT tilesL-NUCAmiss queueto next cache levellevel 2tileRTcache portsRESTT: no-fetch-on-missRT: fetch-on-missRT mshr(a) Loads...level 2tilelevel 2tilefrom nextcache levellevel 2tilelevel 2tileRESTT tilesnext cachewblevel 2tileRTcache ports(b) StoresRESTT: copy-back,write-aroundRT: copy-back,write-aroundin-flightstoreshift reg.RESTTwblevel 2tilelevel 2tileFig. 4. 2-level L-NUCA load and store logical organization.For the sake of clarity, the Figure inclu<strong>de</strong>s neither allnetwork nor control flow linksDuring the setup or the organizations, we observedtwo interesting <strong>de</strong>sign <strong>de</strong>tails helping to maximizeperformance. First, regarding the priority of L1/rtilemisses, loads should have priority over writesexcept when a miss hits in the write buffer 5 in whichcase priorities are reversed until the requested datacan be served by the cache. Second, a centralizedwrite buffer reduces performance except when thenumber of entries at each distributed write buffer isvery small. As an approximate rule of thumb, eachbank requires a coalescing write buffer with as many4 A block can only resi<strong>de</strong> in one column.5 Write buffers do not provi<strong>de</strong> data.C. WorkloadsOur multiprogrammed workload comprises combinationsof 2, and 4, 6, and 8 programs from SPECCPU2006 without repetition, namely, all benchmarksbut 483.xalanbmk [29]. For this type of study, multiprogramedloads are preferable over parallel onesbecause they stress more the memory hierarchy sincethere is no sharing among threads. For each program,we have selected a representative trace consisting of100 million instruction following the SimPoint gui<strong>de</strong>lines[20]. Simulations terminate when all threadshave executed at least 100M instructions, last policy,but program statistics are gathered for the first 100M.V. Experimental ResultsA. Sample Sizes and Simulation TimeTable II shows the number of all combinations withoutrepetition of our traces executing 2, 4, 6, and 8threads, the average time required for running onecombination of programs 6 , and the sample size requiredto obtain accurate results, with an error lessthan 3% with a 97% confi<strong>de</strong>nce level for all configurationsun<strong>de</strong>r test. This means for example thatin 97 of 100 times a randomly chosen sample of 251combinations will have an error than 3% in all themetric compared to the whole population of 6-threadscombinations (37674). For the 2 threads case, we executeall combinations because total execution timeis affordable. Nevertheless, as we increase the numberof threads, our methodology obtains savings insimulation time of ×93, ×150, and ×9743, for 4, 6,and 8 threads, respectively.TABLE IISample sizes varying the number of threads# Threads2 4 6 8Total combinations 378 20475 37674 3108105Avrg. sim. time (min) 18.5 45.7 60.4 90.5Sample size — 220 251 319Table II provi<strong>de</strong>s the minimum sample size for allmetrics of interest with an error less than 3%, inour case: STP, ANTT, IPT throughput, and fairness.Since fairness represents the ratio between the minimumand maximum slowdowns, it has the largestvariance, and, hence, <strong>de</strong>termines the required samplesize.If we focus on a single number of threads, for example4, we can show the sample size of the bestconfigurations from each organization as table IIIdoes. L2, NC-IxJ, LNI, LNI-NC-JxK correspond6 This value is for the L-NUCA + D-NUCA simulator, theslowest in our simulation framework, in an Intel Nehalem 2.33GHz.<strong>JP2011</strong>-566


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011to the conventional baseline, D-NUCA with I columnsand J rows, L-NUCAs with I levels, and L-NUCAscombined with D-NUCAs organizations, respectively.Besi<strong>de</strong>s, each configuration inclu<strong>de</strong>s its total size forthe L2 and L-NUCAs and the size of their banks forD-NUCA.TABLE IIISample sizes for the different metrics andconfigurations in 4SMT executionMetricIPCSTP ANTT Throughtput FairnessL2-256KB-8Banks 126 111 85 162L2-1MB-8Banks 126 113 90 160NC-8x2-512KB 111 132 119 218NC-8x4-256KB 118 141 128 220LN3-240KB 103 96 51 194LN4-448KB 103 96 51 193LN2-NC-8x2 104 96 48 189LN2-NC-8x4 105 97 47 188LN3-NC-8x2 106 96 46 210LN3-NC-8x4 103 95 47 211Irrespective of the organization, we observe thatthe required sample size follows a common trend:computing IPC throughput requires small sizes whilefairness, due to its greater variance, requires doublingor even quadrupling the sample size. STP and ANNTlie in a middle ground. Across all organizations, IPCthroughput is the metric giving the more unevensample sizes, meaning that L-NUCA organizationsachieve less IPC variability among individual threadcombinations. From these results, we conclu<strong>de</strong> thatin general adding a different configuration to test doesnot require a large investment in new simulations forthe preexisting configurations. Finally, fairness is theonly metric that requires more samples as the numberof threads rise. While many threads are able to keepall functional units busy, they tend to bother eachother starving some of them. Conclusions are similarfor other number of threads, and we do not showthem for the sake of brevity.B. STP, ANTT, IPC throughput, and FairnessFigure 5 shows the results for the four metrics ofinterest for the best configuration of each hierarchyorganization. STP and ANTT are metrics relative tothe performance of a single thread system aimed atprograms that may expend time in spin-lock loops,which is not our case [24]. In both metrics, L2 overpassesthe rest of hierarchies from 4 threads andbeyond, and the L-NUCA ones dominates in the 2thread case. This results are mostly due to the factthe L2 has the worst IPC in single-thread mo<strong>de</strong> andthe maximum IPC for all configurations is 4, so L2 relativeslowdowns are smaller as the number of threadrises.IPC throughput is an absolute metric representingthe amount of committed instructions per unit oftime. LN+NC achieves the best results regardlessthe number of threads close followed by LN. Thesmall difference between them is mostly due to theNUCA partial tags not present in the L3 [5]. As thenumber of threads and bandwidth <strong>de</strong>mand increase,the L2 overpasses the NC.Fairness is <strong>de</strong>fined as the quotient between theprograms that have suffered the lowest and the highestslowdowns. A value of zero means complete starvationof one thread,and a value of one means all threadsexperience the same slowdown.VI. ConclusionsThe adoption of thread level parallelism as themainstream way to continue improving the performancepace of computers requires novel mechanismand the reevaluation of those which are well establishedsuch as cache hierarchies. While large <strong>La</strong>stLevel Caches have received a lot of attention in recentyears, first and second levels have remained apart.This work analyzes multiple state-of-the-art cachehierarchies executing multiprogramed workloads from2 to 8 threads. In or<strong>de</strong>r to provi<strong>de</strong> accurate resultsin a reasonable amount of time, we propose a samplingbased methodology reducing simulation timeby up 4 or<strong>de</strong>rs of magnitu<strong>de</strong> for 8 thread workloads,respectively. These savings do not occur at the costof fi<strong>de</strong>lity because their error is less than 3% for a97% confi<strong>de</strong>nce level for a high variance metric suchas fairness.From the analysis we observe that regardless ofthe <strong>La</strong>st Level Cache and the number of threads, L-NUCA provi<strong>de</strong>s the more efficient solution in termsof both throughput and fairness.AcknowledgementThis work was partially supported by grantsTIN2010-21291-C02-01 (Spanish Government andEuropean ERDF), gaZ: T48 research group(Aragón Government and European ESF), Consoli<strong>de</strong>rCSD2007-00050 (Spanish Government), and HiPEAC-2 NoE (European FP7/ICT 217068).References[1] Tom R. Halfhill, “Netlogic broa<strong>de</strong>ns XLP family,” MicroprocessorReport, vol. 24, no. 7, pp. 1–11, 2010.[2] J. L. Shin, K. Tam, D. Huang, B. Petrick, H. Pham,Changku Hwang, Hongping Li, A. Smith, T. Johnson,F. Schumacher, D. Greenhill, A. S. Leon, and A. Strong,“A 40nm 16-core 128-thread cmt sparc soc processor,” inProc. IEEE Int. Solid-State Circuits Conf. Digest of TechnicalPapers (ISSCC), 2010, pp. 98–99.[3] Ron Kalla, Balaram Sinharoy, William J. Starke, andMichael Floyd, “Power7: Ibm’s next-generation serverprocessor,” IEEE Micro, vol. 30, pp. 7–15, 2010.[4] Darío Suárez, Teresa Monreal, Fernando Vallejo, RamónBeivi<strong>de</strong>, and Víctor Viñals, “Light NUCA: a proposalfor bridging the inter-cache latency gap,” in Prooceedingsof the 12 th Design, Automation and Test in EuropeConference and Exhibition (DATE’09), April 2009.[5] Changkyu Kim, Doug Burger, and Stephen W. Keckler,“An adaptive, non-uniform cache structure for wire-<strong>de</strong>laydominated on-chip caches,” in Proceedings of the 10thinternational conference on architectural support for programminglanguages and operating systems (ASPLOS-X).October 2002, pp. 211–222, ACM Press.[6] D.M. Tullsen, S.J. Eggers, and H.M. Levy, “Simultaneousmultithreading: Maximizing on-chip parallelism,” inProceedings. 22nd Annual International Symposium onComputer Architecture, Jun 1995, pp. 392–403.[7] Dean M. Tullsen and Jeffery A. Brown, “Handling longlatencyloads in a simultaneous multithreading processor,”in MICRO 34: Proceedings of the 34th annual<strong>JP2011</strong>-567


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011adjusted STP21.510.5L2NCLNLN+NCadjusted ANTT54321L2NCLNLN+NC01 2 4 6 8Number of Threads01 2 4 6 8Number of Threads43.53L2NCLNLN+NC10.8L2NCLNLN+NCIPC Throughput2.521.510.5Fairness0.60.40.201 2 4 6 8Number of Threads01 2 4 6 8Number of ThreadsFig. 5. Results for the best configuration of each organization: L2, NC, LN, and LN+NC correspond to the L2-256KB,NC-8x4-256KB, LN3-240KB, and LN2-NC-8x4, respectivelyACM/IEEE international symposium on Microarchitecture,Washington, DC, USA, 2001, pp. 318–327, IEEEComputer Society.[8] Sébastien Hily and André Seznec, “Contention on 2 ndlevel cache may limit the effectiveness of simultaneousmultithreading,” Tech. Rep. 1086, IRISA, fébrier 1997.[9] Alex Settle, Dan Connors, Enric Gibert, and AntonioGonzález, “A dynamically reconfigurable cache for multithrea<strong>de</strong>dprocessors,” J. Embed<strong>de</strong>d Comput., vol. 2, no.2, pp. 221–233, 2006.[10] Mario Nemirovsky and Wayne Yamamoto, “Quantitativestudy of data caches on a multistreamed architecture,” inIn Workshop on Multithrea<strong>de</strong>d Execution, Architectureand Compilation, 1998.[11] Hantak Kwak, Ben Lee, Ali R. Hurson, Suk-Han Yoon,and Woo-Jong Hahn, “Effects of multithreading on cacheperformance,” IEEE Transactions on Computers, vol. 48,pp. 176–184, 1999.[12] Montse García, José González, and Antonio González,“Data caches for multithrea<strong>de</strong>d processors,” in Proc. ofthe Workshop on Multithrea<strong>de</strong>d Execution, Architectureand Compilation, 2000.[13] Sébastien Hily and André Seznec, “Standard memory hierarchydoes not fit simultaneous multithreading,” in Proceedingsof the 2 nd Workshop on MULTI-THREADEDEXECUTION, ARCHITECTURE and COMPILATION(MTEAC-2), 1998.[14] Subhradyuti Sarkar and Dean M. Tullsen, “Data layoutfor cache performance on a multithrea<strong>de</strong>d architecture,”in Transactions on high-performance embed<strong>de</strong>d architecturesand compilers III, Per Stenström, Ed., chapter Datalayout for cache performance on a multithrea<strong>de</strong>d architecture,pp. 43–68. Springer-Verlag, Berlin, Hei<strong>de</strong>lberg,2011.[15] Sonia López, Steve Dropsho, David H. Albonesi, OscarGarnica, and Juan <strong>La</strong>nchares, “Dynamic capacity-speedtra<strong>de</strong>offs in smt processor caches,” in Proceedings ofthe 2nd international conference on High performanceembed<strong>de</strong>d architectures and compilers, Berlin, Hei<strong>de</strong>lberg,2007, HiPEAC’07, pp. 136–150, Springer-Verlag.[16] Sonia Lopez, Oscar Garnica, David H. Albonesi, StevenDropsho, Juan <strong>La</strong>nchares, and Jose I. Hidalgo, “Adaptivecache memories for smt processors,” Digital SystemsDesign, Euromicro Symposium on, vol. 0, pp. 331–338,2010.[17] Steven E. Raasch and Steven K. Reinhardt, “The impactof resource partitioning on smt processors,” in Proceedingsof the 12th International Conference on Parallel Architecturesand Compilation Techniques, Washington, DC,USA, 2003, PACT ’03, pp. 15–, IEEE Computer Society.[18] Michael Van Biesbrouck, Lieven Eeckhout, and BradCal<strong>de</strong>r, “Representative multiprogram workloads for multithrea<strong>de</strong>dprocessor simulation,” in IEEE WorkloadCharacterization Symposium. September 2007, pp. 193–203, IEEE Computer Society.[19] F.J. Cazorla, A. Pajuelo, O.J. Santana, E. Fernan<strong>de</strong>z,and M. Valero, “On the problem of evaluating the performanceof multiprogrammed workloads,” IEEE Trans. onComputers, vol. 59, no. 12, pp. 1722 –1728, 2010.[20] Greg Hamerly, Erez Perelman, Jeremy <strong>La</strong>u, and BradCal<strong>de</strong>r, “Simpoint 3.0: Faster and more flexible programanalysis,” in Proceedings of Workshop on Mo<strong>de</strong>ling,Benchmarking and Simulation, 2005.[21] Thomas F. Wenisch, Roland E. Wun<strong>de</strong>rlich, Michael Ferdman,Anastassia Ailamaki, Babak Falsafi, and James C.Hoe, “Simflex: Statistical sampling of computer systemsimulation,” IEEE Micro, vol. 26, pp. 18–31, July 2006.[22] Raj Jain, The Art of Computer Systems PerformanceAnalysis: Techniques for Experimental Design, Measurement,Simulation, and Mo<strong>de</strong>ling, John Wiley & Sons,Inc., April 1991.[23] Ron Gabor, Shlomo Weiss, and Avi Men<strong>de</strong>lson, “Fairnessand throughput in switch on event multithreading,” inProceedings of the 39th Annual IEEE/ACM InternationalSymposium on Microarchitecture, Washington, DC, USA,2006, MICRO 39, pp. 149–160, IEEE Computer Society.[24] S. Eyerman and L. Eeckhout, “System-level performancemetrics for multiprogram workloads,” Micro, IEEE, vol.28, no. 3, pp. 42 –53, may. 2008.[25] M. Ekman and P. Stenstrom, “Enhancing multiprocessorarchitecture simulation speed using matched-pair comparison,”in Proceedings of the IEEE International Symposiumon Performance Analysis of Systems and Software,2005, Washington, DC, USA, 2005, pp. 89–99, IEEEComputer Society.[26] Todd Austin and Doug Burger, SimpleScalar Tutorial(for tool set release 2.0), SimpleScalar LCC, 1997.[27] Glenn Hinton, Dave Sager, Mike Upton, Darrell Boggs,Doug Carmean, Alan Kyker, and Patrice Roussel, “Themicroarchitecture of the Pentium R○ 4 processor,” IntelTechnology Journal, vol. 1st quarter, pp. 1–13, 2001.[28] Dean M. Tullsen, Susan J. Eggers, Joel S. Emer, Henry M.Levy, Jack L. Lo, and Rebecca L. Stamm, “Exploitingchoice: instruction fetch and issue on an implementablesimultaneous multithreading processor,” in Proceedings.23nd Annual International Symposium on Computer Architecture,New York, NY, USA, 1996, vol. 24, pp. 191–202, ACM.[29] John L. Henning, “Spec cpu2006 benchmark <strong>de</strong>scriptions,”SIGARCH Comput. Archit. News, vol. 34, no. 4, pp. 1–17,2006.<strong>JP2011</strong>-568


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Metodología para Analizar y Evaluar los Sistemas<strong>de</strong> Entrada/Salida ParalelosSandra Mén<strong>de</strong>z, Dolores Rexachs y Emilio LuqueDepartamento <strong>de</strong> Arquitectura <strong>de</strong> Computadores y Sistemas OperativosUniversitat Autònoma <strong>de</strong> Barcelona, Barcelona, España{sandra.men<strong>de</strong>z,dolores.rexachs,emilio.luque}@uab.esResumen—El aumento <strong>de</strong> las unida<strong>de</strong>s <strong>de</strong> procesamiento enlos clústers, los avances en velocidad y potencia <strong>de</strong> cómputo yla creciente complejidad <strong>de</strong> las aplicaciones científicas <strong>de</strong>mandanmayores exigencias a los sistemas <strong>de</strong> Entrada/Salida <strong>de</strong> los computadoresparalelos. En este trabajo se propone una metodologíapara el análisis <strong>de</strong> las prestaciones <strong>de</strong> E/S en los clústers <strong>de</strong>computadores, que permita analizar cómo afectan diferentesconfiguraciones a la aplicación. <strong>La</strong> metodología contempla lacaracterización <strong>de</strong>l sistema <strong>de</strong> E/S a distintos niveles: dispositivo,sistema y aplicación; configuración <strong>de</strong> diferentes elementos quetienen impacto en las prestaciones y evaluación teniendo encuenta tanto la aplicación como la arquitectura <strong>de</strong> E/S.In<strong>de</strong>x Terms—E/S Paralela, Arquitectura <strong>de</strong> E/S, Librerías <strong>de</strong>E/S, Almacenamiento MasivoI. INTRODUCCIÓNEl aumento <strong>de</strong> las unida<strong>de</strong>s <strong>de</strong> procesamiento en losclústers, los avances tanto en velocidad como en potencia <strong>de</strong>cómputo <strong>de</strong> las unida<strong>de</strong>s <strong>de</strong> procesamiento y la creciente complejidad<strong>de</strong> las aplicaciones científicas que utilizan cómputo <strong>de</strong>altas prestaciones <strong>de</strong>mandan mayores exigencias a los sistemas<strong>de</strong> Entrada/Salida (E/S) <strong>de</strong> los computadores paralelos. En muchoscasos, <strong>de</strong>bido al gap que existe entre las prestaciones <strong>de</strong>lcómputo y el sistema <strong>de</strong> E/S, éste se vuelve el cuello <strong>de</strong> botella<strong>de</strong> los sistemas paralelos. Para po<strong>de</strong>r ocultar el gap se <strong>de</strong>beni<strong>de</strong>ntificar los factores que influyen en las prestaciones. Estolleva a plantear las siguientes preguntas: ¿<strong>La</strong>s aplicaciones<strong>de</strong>ben adaptarse a la E/S? ¿El administrador <strong>de</strong>be configurarun sistema <strong>de</strong> E/S que se adapte a los requerimientos <strong>de</strong> lasaplicaciones <strong>de</strong> forma transparente? ¿Qué factores <strong>de</strong> E/S influyenen el rendimiento? ¿Cómo configurar el sistema <strong>de</strong> E/Spara adaptarse a las requisitos <strong>de</strong> las aplicaciones? Respon<strong>de</strong>ra estas preguntas no es trivial. <strong>La</strong>s aplicaciones se comportan<strong>de</strong> forma diferente y si bien los programadores o diseñadorespue<strong>de</strong>n realizar las modificaciones necesarias para realizareficientemente las operaciones <strong>de</strong> E/S, estas modificacionesson específicas para una aplicación y computador paralelo.Por otro lado, sacar mayores prestaciones al sistema <strong>de</strong> E/Srequiere que el programador conozca todos los niveles <strong>de</strong>l E/S.Para utilizar eficientemente el sistema <strong>de</strong> E/S <strong>de</strong> un clústeres necesario conocer su capacidad <strong>de</strong> E/S para <strong>de</strong>terminar sipue<strong>de</strong> cumplir con los requisitos que exigen las aplicacionescientíficas intensivas en E/S. Con este objetivo en mente estetrabajo presenta una metodología que permite analizar lasprestaciones <strong>de</strong>l sistema <strong>de</strong> E/S centrándose en las caracteristicas<strong>de</strong> las aplicaciones científicas intensivas <strong>de</strong> E/S y en laconfiguración <strong>de</strong> la arquitectura <strong>de</strong> E/S.<strong>La</strong> metodología propuesta consta <strong>de</strong> una fase <strong>de</strong> caracterización,análisis <strong>de</strong> la configuración <strong>de</strong> E/S y evaluación <strong>de</strong> lasprestaciones. <strong>La</strong> fase <strong>de</strong> caracterización se centra en obtenerlos requisitos <strong>de</strong> E/S <strong>de</strong> la aplicación, evaluar el ancho <strong>de</strong>banda y la latencia en cada uno <strong>de</strong> los niveles implicados,sistema <strong>de</strong> fichero, red <strong>de</strong> interconexión, librería <strong>de</strong> E/S ydispositivos <strong>de</strong> E/S. En la fase <strong>de</strong> análisis <strong>de</strong> la configuraciónse i<strong>de</strong>ntifican los factores que pue<strong>de</strong>n ser configurables yque tienen impacto en las prestaciones que da el sistema<strong>de</strong> E/S, se analizan a nivel <strong>de</strong> sistema <strong>de</strong> fichero, red <strong>de</strong>interconexión, y redundancia <strong>de</strong> datos y servicio, a partir <strong>de</strong>estos factores y los requisitos <strong>de</strong> la aplicación se pue<strong>de</strong> analizary comparar las distintas configuraciones <strong>de</strong> E/S que pue<strong>de</strong>nser implementadas en el clúster. Para evaluar el impacto <strong>de</strong>la configuración <strong>de</strong> E/S <strong>de</strong>l clúster se evalúa el impacto enlos índices <strong>de</strong> prestaciones <strong>de</strong> la aplicación y se <strong>de</strong>terminala ineficiencia analizando la diferencia con los valores picocaracterizados.Este trabajo se estructura en las siguientes secciones, los trabajosrelacionados se presentan en la sección 2, la metodologíapropuesta se presenta en la sección 3, los experimentos realizadosen la sección 4, el mo<strong>de</strong>lo que da soporte al proceso <strong>de</strong>análisis se presenta en la sección 5, y finalmente, en la sección6 las conclusiones y trabajos futuros son reportados.II.TRABAJOS RELACIONADOSExisten varios estudios realizados para evaluar las prestaciones<strong>de</strong> la E/S <strong>de</strong> los computadores paralelos. <strong>La</strong> ten<strong>de</strong>nciaactual es trabajar tanto en entornos reales como en entornossimulados a partir <strong>de</strong> trazas. Dado que las prestaciones <strong>de</strong>lsistema <strong>de</strong> E/S <strong>de</strong>pen<strong>de</strong> <strong>de</strong>l software y hardware estos estudiosson realizados para configuraciones <strong>de</strong> E/S <strong>de</strong> computadoresparalelos específicos. En [1] se realiza una caracterización<strong>de</strong> la E/S <strong>de</strong> las aplicaciones <strong>de</strong>l supercomputador Jaguarformado por máquinas CRAY, presentan una herramienta quepermite generar trazas <strong>de</strong> las operaciones <strong>de</strong> E/S para aplicacionesMPI. A partir <strong>de</strong> estas trazas se pue<strong>de</strong>n i<strong>de</strong>ntificarlas zonas que pue<strong>de</strong>n ser optimizadas a nivel <strong>de</strong> E/S. En[2] se presenta un trabajo don<strong>de</strong> se da un or<strong>de</strong>n al análisisque realizan, consi<strong>de</strong>rando los factores <strong>de</strong> número <strong>de</strong> clientes,tamaño y número <strong>de</strong> stripe. Estos estudios se realizaron sobreCRAYs para mejorar las prestaciones <strong>de</strong> su sistema <strong>de</strong> E/S. Eltrabajo presentado en [3] realiza un análisis <strong>de</strong> prestaciones<strong>JP2011</strong>-569


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Figura 2. Fase <strong>de</strong> CaracterizaciónFigura 1. Metodología para evaluar las prestaciones <strong>de</strong>l sistema <strong>de</strong> E/Scentrándose en la configuración <strong>de</strong> la E/S para mostrar laeficiencia <strong>de</strong>l sistema <strong>de</strong> E/S <strong>de</strong>l supercomputador Red Storm,presenta un estudio <strong>de</strong> los límites teóricos <strong>de</strong> la arquitectura<strong>de</strong> E/S y realizan pruebas <strong>de</strong> prestaciones para file-per-processy shared-file a nivel <strong>de</strong> arquitectura. En [4] se <strong>de</strong>scribe elsimulador SIMCAN, que permite estudiar el comportamientoen ambientes distribuidos complejos con varios propósitos, la<strong>de</strong>tección <strong>de</strong> los cuellos <strong>de</strong> botellas <strong>de</strong>l sistema, cálculo <strong>de</strong>lgrado <strong>de</strong> escalabilidad <strong>de</strong>l sistema y probar la prestaciones <strong>de</strong>aplicaciones sin usar el sistema real.En los casos anteriores el estudio se realiza sobre una arquitecturay no se consi<strong>de</strong>ran directamente las características <strong>de</strong>la aplicación relacionandolos con los recursos que se tendríanque asignar <strong>de</strong> acuerdo a esas necesida<strong>de</strong>s. <strong>La</strong> propuesta <strong>de</strong>este trabajo es analizar el sistema <strong>de</strong> E/S teniendo en cuentael impacto en las distintas aplicaciones.III.METODOLOGÍA PROPUESTA<strong>La</strong> metodología propuesta consta <strong>de</strong> 3 fases (figura 1): Caracterización,Análisis <strong>de</strong> la configuración <strong>de</strong> E/S y Evaluación.<strong>La</strong>s prestaciones <strong>de</strong>l sistema <strong>de</strong> E/S están en función <strong>de</strong>ltiempo <strong>de</strong> ejecución y el tiempo <strong>de</strong> E/S <strong>de</strong> las operaciones<strong>de</strong> E/S <strong>de</strong> la aplicación sobre una <strong>de</strong>terminada configuración<strong>de</strong>l sistema <strong>de</strong> E/S. Dado que las prestaciones pue<strong>de</strong>n <strong>de</strong>pen<strong>de</strong>r<strong>de</strong> las características <strong>de</strong> la aplicación y <strong>de</strong>l sistema <strong>de</strong> E/S, secaracteriza la aplicación y el sistema <strong>de</strong> E/S (incluyendo losdispositivos <strong>de</strong> E/S) para <strong>de</strong>terminar los posibles puntos <strong>de</strong>ineficiencia y a<strong>de</strong>más proporcionar información para buscarla configuración que mejor se adapte a los requisitos <strong>de</strong>la aplicación. Si bien en este trabajo se <strong>de</strong>staca la fase <strong>de</strong>caracterización, ésta es la base para po<strong>de</strong>r <strong>de</strong>terminar en unfuturo los puntos <strong>de</strong> ineficiencia.III-A. Caracterización<strong>La</strong> fase <strong>de</strong> caracterización esta <strong>de</strong>stinada a obtener losfactores <strong>de</strong> la aplicación, sistema paralelo <strong>de</strong> E/S y dispositivos<strong>de</strong> E/S que brin<strong>de</strong>n la información necesaria para po<strong>de</strong>rrealizar la comparación entre los valores experimentales ylos caracterizados. En la figura 2 se muestra la informaciónFigura 3. Sistema <strong>de</strong> E/S <strong>de</strong>l Clúster Aohyperque se obtiene en la fase <strong>de</strong> caracterización. Para explicarel proceso <strong>de</strong> caracterización se aplica la metodología parael problema <strong>de</strong>l Block Tridiagonal(BT), consi<strong>de</strong>rando la E/S(IO), <strong>de</strong>l NAS Parallel Benchmark (NAS) [5]. El sistema <strong>de</strong>E/S que se analiza correspon<strong>de</strong> al clúster <strong>de</strong> la figura 3 quepresenta las siguientes características: 8 nodos <strong>de</strong> cómputoAMD Athlon(tm) 64 X2 Dual Core Processor 3800+, memoriaRAM <strong>de</strong> 2GB y un disco <strong>de</strong> 150 GB para acceso local ysistema <strong>de</strong> fichero linux ext4; 1 servidor NFS con un RAID 1(2 discos) con capacidad=230GB y un RAID5 (3 discos) constripe=256KB y capacidad=917GB ambos con write-cacheenabled (write back); una red <strong>de</strong> comunicación y otra <strong>de</strong> datos<strong>de</strong> 1Gbps Ethernet.III-A1. Aplicación Científica: Se obtienen sus requisitos<strong>de</strong> E/S (cuadro I), se <strong>de</strong>termina el tipo, cantidad y tamaño <strong>de</strong>las operaciones <strong>de</strong> E/S a nivel <strong>de</strong> librería. Esta informaciónes usada en la fase <strong>de</strong> evaluación para <strong>de</strong>terminar si lasprestaciones <strong>de</strong> la aplicación están limitadas por el sistema<strong>de</strong> E/S o por la aplicación.Para realizar la caracterización <strong>de</strong> la aplicación se <strong>de</strong>sar-ParametersnumF ilesnumIO readnumIO writebk readbk writenumIO seeknumIO createnumIO opennumIO closenumP rocesosCuadro ICARACTERÍSTICAS DE LA APLICACIÓNDescriptionNúmero <strong>de</strong> archivos que usa la aplicacióncantidad <strong>de</strong> operaciones readcantidad <strong>de</strong> operaciones writetamaño <strong>de</strong> bloque para readtamaño <strong>de</strong> bloque para writecantidad <strong>de</strong> operaciones seekcantidad <strong>de</strong> operaciones createcantidad <strong>de</strong> operaciones opencantidad <strong>de</strong> operaciones closenúmero <strong>de</strong> procesos en las operaciones <strong>de</strong> E/S<strong>JP2011</strong>-570


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Cuadro IICARACTERÍSTICAS DE NAS BT-IOParámetros MPI POSIXnumF iles 1 1numIO read 640 320 y 320numIO write 640 320 y 320bk read 10 MB 4MB y 16MBbk write 10 MB 4MB y 16MBnumIO seek 0 638numIO create 0 1numIO open 32 32numIO close 32 32numP rocesos 16 16Figura 4. Caracterización <strong>de</strong>l Sistema <strong>de</strong> E/Srolló una extensión <strong>de</strong>l trazador <strong>de</strong> la herramienta PAS2P[6] para obtener información <strong>de</strong> E/S a nivel <strong>de</strong> proceso.Para obtener los patrones <strong>de</strong> acceso <strong>de</strong> la aplicación y lasoperaciones a nivel <strong>de</strong> POSIX I/O se utiliza la herramientaDARSHAN [7]. En el cuadro II se muestra la caracterizaciónrealizada para NAS BT-IO para la clase C en el subtipo full.III-A2. Sistema Paralelo <strong>de</strong> E/S: El sistema paralelo escaracterizado a nivel <strong>de</strong> librería <strong>de</strong> E/S y sistema <strong>de</strong> ficheros(local, distribuido o paralelo).Se caracterizan los bandwidth e IOPs en cada uno <strong>de</strong> losniveles, como se pue<strong>de</strong> observar en figura 4. Para los sistemas<strong>de</strong> ficheros se pue<strong>de</strong>n utilizar los benchmarks IOzone [8] y/obonnie++ [9] y para las librerías se pue<strong>de</strong> utilizar b eff io[10] o IOR [11].<strong>La</strong> caracterización <strong>de</strong>l sistema paralelo y los dispositivos <strong>de</strong>almacenamiento se hicieron con IOzone (cuadro III). En estecaso el factor limitante para el ancho <strong>de</strong> banda va a ser lalibrería <strong>de</strong> E/S.<strong>La</strong>s operaciones se realizaron sobre un archivo <strong>de</strong>l doble<strong>de</strong> tamaño que la memoria <strong>de</strong> los nodos <strong>de</strong> cómputo y <strong>de</strong> lamemoria <strong>de</strong>l nodo <strong>de</strong> E/S variando los tamaños <strong>de</strong> bloques <strong>de</strong>32KB a 16MB. Para la librería <strong>de</strong> E/S se uso IOR configuradopara 8 segmentos con tamaños <strong>de</strong> bloques <strong>de</strong> 16MB a 128MBy para tamaños <strong>de</strong> transferencia <strong>de</strong> 32 a 256 KB para 8Cuadro IIISISTEMA DE E/S DE AOHYPERMedida en MB/seg read write read write read writehome home raid1 raid1 raid5 raid5Librería <strong>de</strong> E/S 27 48 28 48 29 48Filesystem Local 68 85 133 113 273 193Filesystem Distribuido 47 50 48 50 47 50Cuadro IVRED DE INTERCONEXIÓN PARA EL CLUSTER AOHYPERTamaño <strong>de</strong> PaqueteDatos(ms) Com(ms)64 a 1024 bytes 0.16 0.262048 bytes 0.26 0.284096 bytes 0.36 0.328192 bytes 0.56 0.4816384 bytes 0.99 0.5432768 bytes 1.82 0.9165515 bytes 3.55 1.58y 16 procesos. En el caso <strong>de</strong> la red <strong>de</strong> interconexión seusaron simples medidas a través <strong>de</strong>l comando <strong>de</strong> sistema pingvariando el tamaño <strong>de</strong>l paquete −s y −c cantidad <strong>de</strong> paquetesy tomando valores medios. <strong>La</strong>s pruebas se realizaron <strong>de</strong>s<strong>de</strong> losnodos <strong>de</strong> cómputo al nodo <strong>de</strong> E/S para la red <strong>de</strong> comunicacióny para la <strong>de</strong> datos (IV).III-B.Análisis <strong>de</strong> la Configuración <strong>de</strong> E/SPara hacer un análisis <strong>de</strong>l impacto <strong>de</strong> la configuración en eltiempo <strong>de</strong> E/S se evaluan los componentes que se presentanen la figura 4. Por lo general, el usuario no conoce en <strong>de</strong>talleel sistema <strong>de</strong> E/S, confía que el sistema paralelo procesesus solicitu<strong>de</strong>s <strong>de</strong> E/S y <strong>de</strong>spués espera recuperar los datosprocesados cuando lo requiera. En este trabajo se plantea queuna aplicación pue<strong>de</strong> usar <strong>de</strong> diferentes formas el conjunto <strong>de</strong>recursos <strong>de</strong> la configuración existente, en función <strong>de</strong> los recursosutilizados se crea lo que llamamos una subconfiguración,don<strong>de</strong> se han dado valores <strong>de</strong>terminados a distintos parámetros<strong>de</strong>l sistema, y que tienen impacto en las prestaciones y serándiferente en cada subconjunto. Por lo tanto, se <strong>de</strong>bería po<strong>de</strong>rasignar a la aplicación aquella subconfiguración más eficiente.III-B1. I<strong>de</strong>ntificación <strong>de</strong> Factores <strong>de</strong> E/S configurables:Se analizan las capas <strong>de</strong> librería <strong>de</strong> E/S y arquitectura <strong>de</strong>E/S. El cluster Aohyper tiene como filesystem local ext4 yun servidor NFS para datos compartidos. En cuanto a la red<strong>de</strong> interconexión se i<strong>de</strong>ntifican el número y tipo <strong>de</strong> red <strong>de</strong>interconexión que tiene el cluster. Si existen más <strong>de</strong> una redse pue<strong>de</strong>r elegir con cuales trabajar por medio <strong>de</strong> las librerías<strong>de</strong> paso <strong>de</strong> mensaje.Otra aspecto que se pue<strong>de</strong> consi<strong>de</strong>rar es la selección <strong>de</strong>lnivel <strong>de</strong> redundancia. De acuerdo al nivel <strong>de</strong> protección anteslos fallos <strong>de</strong> los dispositivos <strong>de</strong> E/S se pue<strong>de</strong> elegir un RAID 1,RAID 5 u otro nivel. Esto implica el uso <strong>de</strong> recursos extras y<strong>de</strong>pendiendo <strong>de</strong> los patrones <strong>de</strong> accesos <strong>de</strong> las aplicaciones, laredundancia pue<strong>de</strong> penalizar las prestaciones que la aplicaciónpercibe.III-B2. Selección <strong>de</strong> subconfiguraciones <strong>de</strong> E/S: Una vezevaluados estos parámetros se pue<strong>de</strong> seleccionar un conjunto<strong>de</strong> subconfiguraciones <strong>de</strong>l cluster y evaluar las prestacionesque ofrecen a la aplicación. En el ejemplo se realiza el análisisutilizando 3 subconfiguraciones: un sistema <strong>de</strong> E/S sin RAID(llamada NFS en la figura 6), uno con RAID 1 y otro conRAID5, se han realizado pruebas haciendo otra selección<strong>de</strong> recursos, por ejemplo utilizando 1 ó 2 re<strong>de</strong>s, diferentesconfiguraciones <strong>de</strong> RAID SW sobre los discos locales, peropara el ejemplo se <strong>de</strong>scribe el comportamiento utilizando 3subconfiguraciones.<strong>JP2011</strong>-571


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Figura 5. Fase <strong>de</strong> EvaluaciónIII-C.EvaluaciónUna vez completadas las fases <strong>de</strong> Caracterización y Análisis<strong>de</strong> la configuración <strong>de</strong> E/S se <strong>de</strong>be probar la aplicación sobrecada subconfiguración. En la figura 5 se muestran los pasosconsi<strong>de</strong>rados para hacer la evaluación.III-C1. Configuración <strong>de</strong>l Entorno <strong>de</strong> Evaluación: <strong>La</strong>preparación <strong>de</strong>l entorno <strong>de</strong> evaluación implica establecer losparámetros para: aplicación científica, librerías <strong>de</strong> E/S y arquitectura<strong>de</strong> E/S. Para nuestro ejemplo, la aplicación elegidaes NAS BT-IO en su clase C, la librería MPI es MPICH y serealizará la prueba sobre las 3 subconfiguraciones.III-C2. Índices <strong>de</strong> E/S Paralela: Los índices consi<strong>de</strong>radospara la fase <strong>de</strong> evaluación son tiempo <strong>de</strong> ejecución (duración<strong>de</strong> la ejecución <strong>de</strong> la aplicación), tiempo <strong>de</strong> E/S (tiempo quelleva hacer las operaciones <strong>de</strong> lectura y <strong>de</strong> escritura), IOPs(Cantidad <strong>de</strong> operaciones <strong>de</strong> E/S por segundo) y el throughput(cantidad <strong>de</strong> Megabytes transferidos por segundos para lasoperaciones <strong>de</strong> E/S).III-C3. Análisis <strong>de</strong> la relación factores e índices <strong>de</strong> E/S:Los IOPs y el throughput se comparán con los valoresobtenidos en la etapa <strong>de</strong> caracterización. Si las prestacionesque la aplicación obtiene son próximos a algunos <strong>de</strong> los elementos<strong>de</strong>l conjunto A = {bw lib , bw mpi , bw fs , bw net , bw disk }será necesario analizar las características <strong>de</strong> ese componente<strong>de</strong>l sistema <strong>de</strong> E/S porque pue<strong>de</strong> estar limitando las prestacionespara la aplicación. Para el ejemplo <strong>de</strong> NAS BT-IO, en lafigura 6 se pue<strong>de</strong> ver los tiempos <strong>de</strong> E/S, tiempos <strong>de</strong> ejecucióny las tasa <strong>de</strong> transferencia que la aplicación percibe para 16procesos para la clase C para las 3 subconfiguraciones. Elanálisis es realizado para el subtipo full (con colectivas <strong>de</strong> E/S)y simple (sin colectivas). En la figura 6(a), tiempo expresadoen minutos, se observa una tasa <strong>de</strong> transferencia baja, laaplicación esta usando el 50 % <strong>de</strong> la tasa <strong>de</strong> transferenciaproporcionada por la librería <strong>de</strong> E/S que es el valor más bajoen el sistema <strong>de</strong> E/S. Esto se <strong>de</strong>be a que la aplicación realiza4.199.040 writes y 4.199.040 reads con tamaño <strong>de</strong> bloque <strong>de</strong>1600 bytes y 1640 bytes. Lo que reporta una penalizaciónmuy elevada por las solicitu<strong>de</strong>s <strong>de</strong> read y write (expresadasen minutos). En la figura 6(b), tiempo expresado en segundos,muestra el subtipo full don<strong>de</strong> las solicitu<strong>de</strong>s son realizadasen forma colectiva. Para tamaños <strong>de</strong> write y read <strong>de</strong> 10MB sealcanza una tasa <strong>de</strong> transferencia <strong>de</strong> 50 MB/seg, el 100 % <strong>de</strong> latasa <strong>de</strong> transferencia que se obtiene como pico en el filesystemdistribuido. Otro aspecto que se ha <strong>de</strong>tectado en la fase <strong>de</strong>(a) Tiempos NAS BT-IO sin colectivas <strong>de</strong> E/S(b) Tiempos NAS BT-IO con colectivas <strong>de</strong> E/SFigura 6. Resultados Experimentales para NAS BT-IOCuadro VSISTEMA DE E/S DEL CLUSTER BMedida en MB/seg read writeraid5 raid5Librería <strong>de</strong> E/S 32 51Filesystem Local 260 200Filesystem Distribuido 89 79caracterización es la velocidad <strong>de</strong> las re<strong>de</strong>s <strong>de</strong> interconexión yse observa como la red <strong>de</strong> datos baja las prestaciones cuandoel tamaño <strong>de</strong> paquete se incrementa, también se observó queun nodo <strong>de</strong> cómputo esta trabajando al 25 % <strong>de</strong> velocidad conrespecto a los otros. El proceso <strong>de</strong> caracterización permite vervarios aspectos <strong>de</strong>l sistema E/S que afectan las prestaciones<strong>de</strong>l sistema y permite <strong>de</strong>terminar que recursos se asignan parareducir las penalizaciones.IV.EXPERIMENTACIÓNPara evaluar la metodología se realizó una evaluación <strong>de</strong>lNAS BT-IO en un clúster diferente, que <strong>de</strong>nominamos clústerA compuesto por 32 nodos <strong>de</strong> cómputo: 2 x Dual-Core Intel(R)Xeon(R) 3.00GHz, 12 GB <strong>de</strong> RAM , disco 160GB SATA yDual Gigabit Ethernet. Un nodo front-end que hace <strong>de</strong> servidorNFS: Dual-Core Intel(R) Xeon(R) 2.66GHz, 8 GB <strong>de</strong> RAM,RAID 5 <strong>de</strong> 1.8 TB y Dual Gigabit Ethernet. <strong>La</strong> caracterización<strong>de</strong>l sistema <strong>de</strong> E/S <strong>de</strong>l clúster A se presenta en el cuadro V.<strong>La</strong> prueba realizada con IOR para evaluar la librería <strong>de</strong> E/S espara 8 segmentos, tamaño <strong>de</strong> bloque <strong>de</strong> 256MB y un tamaño<strong>de</strong> transferencia <strong>de</strong> 256KB.En la figura 7 se muestra las prestaciones para el benchmarkNAS BT-IO para un número variable <strong>de</strong> procesos. Para el<strong>JP2011</strong>-572


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011(a) Tiempos NAS BT-IO sin colectivas <strong>de</strong> E/SParámetrosBW readBW writetime opentime closenumF ilesnumIO readnumIO writebk readbk writenumIO opennumIO closek r, k w, k o, k cCuadro VIPARÁMETROS DEL MODELO DE E/S DE LA APLICACIÓNDescripciónbandwidth para read en el sistema <strong>de</strong> E/Sbandwidth para read en el sistema <strong>de</strong> E/Stiempo para open en el sistema <strong>de</strong> E/Stiempo para close en el sistema <strong>de</strong> E/SNúmero <strong>de</strong> archivos que usa la aplicacióncantidad <strong>de</strong> operaciones readcantidad <strong>de</strong> operaciones writetamaño <strong>de</strong> bloque para readtamaño <strong>de</strong> bloque para writecantidad <strong>de</strong> operaciones opencantidad <strong>de</strong> operaciones closefactor para ajustar el mo<strong>de</strong>lo (a <strong>de</strong>terminar)T execution = T compute + T io (1)(b) Tiempos NAS BT-IO con colectivas <strong>de</strong>E/SFigura 7. Tiempos <strong>de</strong> ejecución, tiempo <strong>de</strong> E/S y tasa <strong>de</strong> transferencia.subtipo simple <strong>de</strong>l NAS BT-IO (figura 7(a)) para 16 procesosen el clúster A, la aplicación tiene una tasa <strong>de</strong> transferencia<strong>de</strong> 1.2 MB/seg, este valor es el 2 % para write y 4 % pararead <strong>de</strong>l pico que entrega el sistema para la librería <strong>de</strong> E/S.En la figura 7(b) el subtipo full logra pasar la barrera <strong>de</strong> lalibrería <strong>de</strong> E/S con una tasa <strong>de</strong> transferencia <strong>de</strong> 45MB/segque es el 90 % para write y 140 % para read. Los cuadros <strong>de</strong>prestaciones para el Clúster A (cuadro V) y Aohyper (cuadroIII para RAID 5) muestran que el clúster A tiene mayoresprestaciones para la librería y el filesystem distribuido. Sinembargo, el NAS BT-IO en el subtipo simple tiene mejoresprestaciones en el clúster Aohyper. Pero el subtipo full tienesimilares prestaciones en ambos clústers. Del análisis realizadose pue<strong>de</strong> observar que el menor tiempo <strong>de</strong> E/S se logra con unatasa <strong>de</strong> transferencia <strong>de</strong> 54MB/seg. En ambos clúster esta es latasa <strong>de</strong> transferencia que consume NAS BT-IO para hacer lasoperaciones <strong>de</strong> E/S para la clase C. De aquí también po<strong>de</strong>mosobservar que Aohyper es mejor para aquellas aplicaciones quetengan un patrón <strong>de</strong> acceso similar a NAS BT-IO simple.V. MODELO DE E/S DE LA APLICACIÓNPara dar soporte a este proceso <strong>de</strong> Evaluación <strong>de</strong>l sistema<strong>de</strong> E/S y al diseño <strong>de</strong> subconfiguraciones (para respon<strong>de</strong>r apreguntas <strong>de</strong>l tipo ¿qué pasaría si se cambia un parámetro<strong>de</strong> la configuración?) se esta elaborando un mo<strong>de</strong>lo <strong>de</strong> E/Sque permita ayudar a buscar la configuración más eficientepara la aplicación. Para esto se expresa el tiempo <strong>de</strong> E/S <strong>de</strong>la aplicación en función <strong>de</strong> los valores caracterizados en lametodología <strong>de</strong> evaluación. A continuación se presenta unmo<strong>de</strong>lo preliminar <strong>de</strong> E/S para una aplicación con un proceso.Para realizar el estudio <strong>de</strong> la E/S <strong>de</strong> un aplicación científicase hizo un análisis similar al que se hace para el cómputo. Seplantea un mo<strong>de</strong>lo <strong>de</strong> la E/S para una aplicación con 1 procesoy <strong>de</strong>spués se exten<strong>de</strong>rá el mo<strong>de</strong>lo para n procesos. El tiempo<strong>de</strong> ejecución <strong>de</strong> una aplicación se pue<strong>de</strong> expresar como en laecuación 1.<strong>La</strong>s primeras preguntas que se plantean son ¿Cuanto impactael tiempo <strong>de</strong> E/S a las prestaciones <strong>de</strong> la aplicación? ¿<strong>La</strong>aplicación usa eficientemente el sistema <strong>de</strong> E/S? ¿El sistema<strong>de</strong> E/S es eficiente para una aplicación <strong>de</strong>terminada? Pararespon<strong>de</strong>r estas preguntas se hace un estudio <strong>de</strong> la E/S <strong>de</strong> laaplicación. Se expresan los requisitos <strong>de</strong> E/S en un mo<strong>de</strong>loque permita <strong>de</strong>terminar las prestaciones que la aplicaciónpercibirá en función <strong>de</strong> los valores obtenido durante la etapa<strong>de</strong> caracterización. Para esto se expresa el tiempo <strong>de</strong> E/S <strong>de</strong> laaplicación en función <strong>de</strong> los requisitos <strong>de</strong> E/S y BW obtenidosen el camino <strong>de</strong> E/S. Este mo<strong>de</strong>lo se plantea primero para unproceso para <strong>de</strong>spués exten<strong>de</strong>rlo a n procesos. Se consi<strong>de</strong>ranlas operaciones read, write, open y close. El tiempo <strong>de</strong> E/Spara una aplicación con un solo proceso se presenta en laecuación 2.T io = T open + T read + T write + T close (2)Debido a que los tiempos más influyentes durante la ejecuciónen aplicaciones limitadas por la E/S son las reads (ecuación3) y writes (ecuación 4), el estudio se centra en estos tiempos.El significado <strong>de</strong> cada parámetro se presenta en el cuadroVI.Para cada configuración se aplica el mo<strong>de</strong>lo para BW min =mín(A) don<strong>de</strong> A = {bw lib , bw mpi , bw fs , bw net , bw disk }.T read = numIO read ∗ ( bk readBW read) + k r (3)T write = numIO write ∗ ( bkwriteBW write) + k r (4)El tiempo <strong>de</strong> E/S esperado en una configuración para lecturay escritura se muestra en las ecuaciones 5 y 6.bk readT read = numIO read ∗ () + kr (5)BW read (Cn)T write = numIO write ∗ (bk writeBW write(Cn)) + kr (6)don<strong>de</strong> BW read (Cn) y BW write (Cn) son los valores observadosdurante la fase <strong>de</strong> caracterización para la configuración n.<strong>La</strong> configuración que menor T io proporcione será consi<strong>de</strong>rada<strong>JP2011</strong>-573


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Figura 9. Error RelativoFigura 8. Comparación Mo<strong>de</strong>lo <strong>de</strong> E/S y experimentosla más eficiente para la aplicación. Se <strong>de</strong>fine el error absolutoerror abs = |¯x − x| y relativo error rel = 100 ∗ ( error absx) para<strong>de</strong>terminar la <strong>de</strong>sviación con respecto a las prestaciones reales.Don<strong>de</strong>, ¯x son valores para T write y T read en el mo<strong>de</strong>lo <strong>de</strong> E/S<strong>de</strong> la aplicación y x son medidas obtenidas en los experimentospara cada configuración <strong>de</strong> E/S.El mo<strong>de</strong>lo se evaluó para una aplicación sintética intensiva<strong>de</strong> E/S que realiza 4000 write y 3985 read para diferentestamaños <strong>de</strong> bloques que van <strong>de</strong>s<strong>de</strong> 1024 KB hasta 8192 KBgenerando <strong>de</strong> archivos <strong>de</strong> 4 GB a 32 GB. <strong>La</strong> aplicación trabajasobre un archivo en el que escribe en forma secuencial. <strong>La</strong>única parte <strong>de</strong> cómputo que realiza es una suma <strong>de</strong> matrices.<strong>La</strong> evaluación se hizo para el Clúster Aohyper (cuadro III) sinRAID, con RAID1 y con RAID5. En la figura 8 se muestra eluso <strong>de</strong>l mo<strong>de</strong>lo con los valores <strong>de</strong> la caracterización para cadaconfiguración y valores observados en la experimentación. Elmo<strong>de</strong>lo <strong>de</strong>be <strong>de</strong>terminar, sin ejecutar la aplicación en cadasubconfiguración, la subconfiguración más eficiente para laaplicación. El estudio se centra en el comportamiento <strong>de</strong> laaplicación. En la figura 9 se pu<strong>de</strong> observar los errores relativosy se observa como se reduce cuando el tamaño archivo seincrementa.Como se esperaba esta aplicación tiene mejores prestacionesen RAID5 (figura 8). Pero el error esta entre el 10 % y 60 %.Esto indica que se <strong>de</strong>be refinar el mo<strong>de</strong>lo para consi<strong>de</strong>rarque factores estan influyendo en la prestaciones y no se estánconsi<strong>de</strong>rando.VI.CONCLUSIÓNSe ha propuesto una metodología para el análisis <strong>de</strong> prestaciones<strong>de</strong> E/S para computadores paralelos que ha permitidoestablecer pautas para el análisis, i<strong>de</strong>ntificación <strong>de</strong> factoresconfigurables y evaluar las prestaciones para diferentes configuraciones.<strong>La</strong> metodología contempla la caracterización <strong>de</strong>lsistema <strong>de</strong> E/S a distintos niveles: dispositivo, sistema yaplicación; análisis <strong>de</strong> la configuración <strong>de</strong> diferentes elementosque tienen impacto en las prestaciones y evaluación teniendoen cuenta tanto la aplicación como la arquitectura <strong>de</strong> E/S. Estametodología se aplicó en dos clústers para el benchmark NASBT-IO. Se evalúo las características <strong>de</strong> ambos sistemas <strong>de</strong> E/Sy se pudo <strong>de</strong>terminar como influyen en las prestaciones quela aplicación percibe. Por otro lado, se presenta un mo<strong>de</strong>lopreliminar para la E/S <strong>de</strong> una aplicación. Este mo<strong>de</strong>lo estaen función <strong>de</strong> las características <strong>de</strong> la aplicación y el sistema<strong>de</strong> E/S que se realiza en la metodología <strong>de</strong> evaluación. Estemo<strong>de</strong>lo se está elaborando para <strong>de</strong>terminar que configuración<strong>de</strong> E/S cumple con los requisitos <strong>de</strong> eficiencia <strong>de</strong>l usuario,teniendo en cuenta el comportamiento <strong>de</strong> E/S <strong>de</strong> la aplicaciónen un sistema <strong>de</strong>terminado.AGRADECIMIENTOSEste trabajo ha sido subvencionado por MICINN-Españaproyecto TIN 2007-64974REFERENCIAS[1] P. C. Roth, “Characterizing the i/o behavior of scientific applications onthe cray xt,” in PDSW ’07: Procs of the 2nd int. workshop on Petascaledata storage. USA: ACM, 2007, pp. 50–55.[2] M. Fahey, J. <strong>La</strong>rkin, and J. Adams, “I/o performance on a massivelyparallel cray xt3/xt4,” in Parallel and Distributed Procs, 2008. IPDPS2008. IEEE Int. Symp. on, 14-18 2008, pp. 1 –12.[3] J. H. <strong>La</strong>ros et al., “Red storm io performance analysis,” in CLUSTER’07: Procs of the 2007 IEEE Int. Conf. on Cluster Computing. USA:IEEE Computer Society, 2007, pp. 50–57.[4] A. Núnez, et al., “Simcan: a simulator framework for computer architecturesand storage networks,” in Simutools ’08: Procs of the 1st Int.Conf. on Simulation tools and techniques for communications, networksand systems & workshops. Belgium: ICST, 2008, pp. 1–8.[5] P. Wong and R. F. V. D. Wijngaart, “Nas parallel benchmarks i/o version2.4,” Computer Sciences Corporation, NASA Advanced Supercomputing(NAS) Division, Tech. Rep., 2003.[6] A. Wong, D. Rexachs, and E. Luque, “Extraction of parallel applicationsignatures for performance prediction,” in HPCC, 2010 12th IEEE Int.Conf. on, sept. 2010, pp. 223 –230.[7] P. Carns et al., “24/7 characterization of petascale i/o workloads,” inCluster Computing and Workshops, 2009. CLUSTER ’09. IEEE Int.Conf. on, 31 2009-sept. 4 2009, pp. 1 –10.[8] W. D. Norcott, “Iozone filesystem benchmark,” Tech. Rep., 2006.[Online]. Available: http://www.iozone.org/[9] R. Coker, “Bonnie++ filesystem benchmark,” Tech. Rep., 2001.[Online]. Available: http://www.coker.com.au/bonnie++/[10] R. Rabenseifner and A. E. Koniges, “Effective file-i/o bandwidth benchmark,”in Euro-Par ’00: Procs from the 6th Int. Euro-Par Conference onParallel Procs. London, UK: Springer-Verlag, 2000, pp. 1273–1283.[11] . S. J. Shan, Hongzhang, “Using ior to analyze the i/o performance forhpc platforms,” LBNL Paper LBNL-62647, Tech. Rep., 2007. [Online].Available: www.osti.gov/bridge/servlets/purl/923356-15FxGK/<strong>JP2011</strong>-574


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Memory Hierarchy and Network Co-<strong>de</strong>signthrough Trace-Driven SimulationMario Lod<strong>de</strong> 1 , José Flich 1Abstract— CMP systems are usually <strong>de</strong>signed an<strong>de</strong>valuated through simulation tools. The NoC and thecache memory architecture are two key componentsthat tightly interact; changing parameters of one ofthese components affect the performances of the otherone, so they should be mo<strong>de</strong>led and tuned consi<strong>de</strong>ringhow they interact. In this paper we propose gMem-NoCsim, a simulation platform which allows to mo<strong>de</strong>lboth the NoC and the cache hierarchy and rapidlyrun trace-driven simulations.Keywords— CMP, NoC, cache memory, coherenceprotocols, simulationI. IntroductionAS VLSI technology advances an increasing numberof transistors can be be integrated into thesame chip. Instead of building powerful and complexprocessors, <strong>de</strong>signers have shifted to multicore<strong>de</strong>signs where several and simpler cores are inclu<strong>de</strong>dinto the same chip. The main reason for this shiftis the power dissipation and energy consumption ofcomplex processors. In these chip multiprocessorsystems (CMPs) each simpler processor core usuallyhas its own cache memory hierarchy. Additionally,one or more memory controllers are inclu<strong>de</strong>d in thechip to manage off-chip accesses. All these componentsare interconnected through an on-chip built-innetwork, referred to as network-on-chip (NoC)[1][2].The NoC has to provi<strong>de</strong> a very large bandwidth andultra low latencies to avoid introducing a bottleneckin inter-processor communications.A tile-based <strong>de</strong>sign is appealing when <strong>de</strong>signing aCMP system. An elemental block or tile is <strong>de</strong>signedand replicated all over the same die, forming a tilematrix. Each tile inclu<strong>de</strong>s one or more cores, a subsetof their cache memories, a network interface and aswitch that interconnects the tiles through a networkof point-to-point links, typically a 2D mesh. The tilebased<strong>de</strong>sign provi<strong>de</strong>s scalability and reduces <strong>de</strong>signtime and <strong>de</strong>sign and verification costs since a singletile is <strong>de</strong>signed instead of the whole chip. Figure1 shows a possible CMP <strong>de</strong>sign with 16 tiles, eachone with one core, two separate private L1 caches, ashared L2 cache bank, and a switch. Two memorycontrollers are attached to two of the tiles at thecorners of the chip.Most current CMP systems support a sharedmemoryprogramming mo<strong>de</strong>l where main memoryis seen by all the processors. This mo<strong>de</strong>l is simplerand convenient to programmers as communicationbetween processors is implicitly performed by shar-1 Dpto. <strong>de</strong> Informática <strong>de</strong> Sistemas y Computadores, UniversitatPolitecnica <strong>de</strong> Valencia, e-mail: mlod<strong>de</strong>@gap.upv.es,jflich@disca.upv.es.ing variables between processes. A coherence protocolneeds to be <strong>de</strong>signed and implemented to keepcoherency between multiple copies of the same memoryblock spread over the caches in the chip. On theother hand, in the message-passing mo<strong>de</strong>l the programmerexplicitly needs to care about sending messagesbetween processors, and a coherence protocoldoes not need to be implemented.The <strong>de</strong>sign of the coherence protocol is key for thescalability of the CMP <strong>de</strong>sign. In<strong>de</strong>ed, the protocolneeds to be scalable to allow building larger systems,specially in a tiled CMP <strong>de</strong>sign. As technologyadvances it is appealing to use the same tile-based<strong>de</strong>sign and simply increase performance by addingmore tiles to the chip. Scalability of the coherenceprotocol should come in terms of keeping memoryaccess latency, area implementation cost, and powerconsumption. In<strong>de</strong>ed, the increased memory accesslatency of the coherence protocol (due to indirection)and the area overhead (to keep the coherence info)are seen as the major issues that may prevent sharedmemoryCMP systems from scaling to hundred coreno<strong>de</strong>s.In a shared-memory CMP chip most of the trafficthrough the NoC comes from the cache coherenceprotocol. The network must service packetssent between caches and to/from memory controllers.Therefore, the coherence protocol influences the waythe NoC has to be <strong>de</strong>signed. A proper NoC <strong>de</strong>signshould minimize the impact of message <strong>de</strong>liveringto the protocol (reduced access latencies an<strong>de</strong>nough data bandwidth) while optimizing its <strong>de</strong>sign(low area and power consumption costs). In otherwords, the NoC <strong>de</strong>sign should be driven by the coherenceprotocol <strong>de</strong>sign. On the other hand, thenetwork may influence the way the coherence protocolis implemented. As an example, the access tothe memory controllers and the access to L2 cachebanks can be influenced by the topology chosen tointerconnect the tiles. In<strong>de</strong>ed, both the network andthe coherence protocol should be co-<strong>de</strong>signed.II. MotivationSimulation is usually the preferred method for performanceexploration when <strong>de</strong>signing different CMPcomponents (including the coherence protocol andthe NoC). With simulations, accurate mo<strong>de</strong>ls canbe built and performance metrics can be extracted(e.g. network throughput and access latency for theNoC and average memory access and total executiontime for the coherence protocol). Many differentsimulation platforms are being used by the community,most of them handcrafted and specialized in<strong>JP2011</strong>-575


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 1.Tile-based CMP <strong>de</strong>sign with 16 tiles on a 4 × 4 mesh configuration.a particular CMP component. Usually, the NoC ismo<strong>de</strong>led in isolation without consi<strong>de</strong>ring the coherenceprotocol. Synthetic traffic patterns or messagetraces captured from higher-level system mo<strong>de</strong>ls aretypically used. These methods do not take into accountthe implications of the memory hierarchy onthe on-chip network. Vice-versa, different coherenceprotocol analysis take into consi<strong>de</strong>ration a given andstatic on-chip network configuration, thus not benefitingfrom the real potential impact of co-<strong>de</strong>signingboth components.A proper CMP simulation mo<strong>de</strong>l should <strong>de</strong>tail thememory hierarchy of the CMP system: the numberand organization of cache banks of on-chip cache,their access latency, and the cache coherence protocolused to ensure data consistency. At the same timethe simulation platform should mo<strong>de</strong>l the on-chip interconnectionnetwork, which should be co-<strong>de</strong>signed,co-simulated and evaluated together with the memoryhierarchy system. In<strong>de</strong>ed, their behavior andperformance are tightly coupled.There are different simulation platforms that enablemo<strong>de</strong>ling both components. One such wi<strong>de</strong>lyused platform is SIMICS/GEMS [3][4], which is commonlyused to mo<strong>de</strong>l and evaluate the memory hierarchy.SIMICS/GEMS mo<strong>de</strong>ls the entire CMP systemincluding the Operating System (OS), the application/benchmarkbeing run, the CMP hardware resourcesand even the on-chip network (via the GAR-NET network simulator [5]). With this environment,however, simulation overhead is prohibitively largeand simulation experiments take from hours to weeks<strong>de</strong>pending on the simulation benchmark analyzed.In<strong>de</strong>ed, various benchmark suites have been releasedto the community to evaluate the performanceof multiprocessor and CMP systems, such as Splash-2 [6] or PARSEC [7]. These benchmarks inclu<strong>de</strong> differentapplications and kernels that are representativeof common real applications of multiprocessorsystems, being appealing for a proper evaluation ofCMPs. In<strong>de</strong>ed, these benchmarks are available forGEMS/SIMICS and are commonly used.However, synthetic patterns still pose an interestingflavor, as their use permit a rapid exploration ofthe component being analyzed. In<strong>de</strong>ed, by meansof synthetic traffic patterns on-chip networks can beanalyzed in a wi<strong>de</strong> range of load conditions, evenif the final application will not <strong>de</strong>mand such loads.In some way, the system is evaluated in the fullrange of possible higher-level <strong>de</strong>mands. Uniformtraffic distributions together with specific patternslike bit-complement, tornado, or hot-spot traffic patternsare the mostly used ones in the on-chip community.Some of them have been acknowledged torepresent well-known and representative applicationtraffic patterns. However, still, such traffic patternsdo not take into account the memory hierarchy.When consi<strong>de</strong>ring the memory hierarchy, a largenumber of parameters may influence the final systemperformance. Those memory parameters, togetherwith the on-chip network parameters, mustbe fine-tuned to better un<strong>de</strong>rstand how they affectthe system performance. Complete and accurate <strong>de</strong>signspace exploration with full-system simulationlike GEMS/SIMICS becomes unfeasible and unpracticaldue to its large simulation time. Furthermore,exploration of large CMP systems (beyond 64 cores)is nowadays out of reach of these simulation platforms(memory requirements and exponential simulationtime).In this paper we propose gMemNoCsim, a tracedrivensimulation approach which inclu<strong>de</strong>s both theon-chip network mo<strong>de</strong>l as well the memory hierarchysystem (including different layers of caches, and anyconfiguration of memory controllers). Input memoryreferences (e.g. load and stores) instead of messagereferences are taken as an input for the simulator.Memory traces are obtained from real applications(SPLASH-2) and synthetic memory access patternsare <strong>de</strong>fined as well, which allow a rapid performanceexploration of both the memory hierarchy (with thecoherence protocol) and the on-chip network.With gMemNoCsim any critical parameter of boththe network and the memory hierarchy can be specifiedby the user. Whenever a memory access is readby the simulator, the required coherence actions areperformed possibly injecting messages into the onchipnetwork. The behavior of the coherence proto-<strong>JP2011</strong>-576


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011col is <strong>de</strong>fined by the proper FSM easily <strong>de</strong>scribed interms of states, events and actions to be performed.Thus, different coherence protocols can easily be <strong>de</strong>fined.The rest of the paper is organized as follows.In Section III the simulation platform is <strong>de</strong>scribed.Then, in Section IV we show some examples of theresults obtained with the platform for different networkand memory hierarchy configurations. Finally,Section V conclu<strong>de</strong>s the paper.III. Simulation Platform DescriptionA. Overall Platform OrganizationFigure 2 shows the overall gMemNoCsim platformorganization. Two main layers exist and communicatewith each other. The memory layer which mo<strong>de</strong>lsthe memory hierarchy (cache structures and thecoherency protocol) and the on-chip network layerwhich mo<strong>de</strong>ls the on-chip network.Fig. 2.Overall simulation platform organizationThe trace files are the input of the simulator (readby the memory layer). A trace file is used per eachmo<strong>de</strong>led core in the CMP system (to keep processorin<strong>de</strong>pen<strong>de</strong>nce). Trace files are in<strong>de</strong>pen<strong>de</strong>nt of eachother, although memory access <strong>de</strong>pen<strong>de</strong>ncies can bead<strong>de</strong>d between load and store operations of differentprocessors (<strong>de</strong>scribed later). Whenever a trace entryis read, the memory layer performs the coherence actionsspecified in the protocol configuration file which<strong>de</strong>scribes the cache coherence protocol. The memorylayer may issue one or several packets into thenetwork (e.g. an L1 miss triggering an access to aremote L2 cache bank), thus, communicating withthe network layer. This layer, in turn, simulates cycleby cycle as the packet crosses the network. Whenthe packet reaches its <strong>de</strong>stination the network layertriggers an event at the memory layer. Then, thememory layer evolves as specified by the cache coherenceprotocol.The memory mo<strong>de</strong>l blocks the processor on eachload and store operation (in-or<strong>de</strong>r processors are assumed).Also, a processor is blocked if the load operationhas an input <strong>de</strong>pen<strong>de</strong>ncy with a store operation(inclu<strong>de</strong>d in the trace). The load will progress oncethe store operation is performed. Whenever a memoryaccess is performed by a processor, the processoris unblocked and the next memory access is readfrom the trace. The simulation ends when there areno more traces to read and all the cores have receivedthe data they requested.The simulator is cycle accurate and both layersadvance at the same pace, cycle by cycle. Table Isummarizes the current parameters the simulationplatform supports in the <strong>de</strong>finition of the memoryand network mo<strong>de</strong>ls.B. Memory Access TracesMemory access traces are <strong>de</strong>fined per each processorand follow a simple format. A trace file is ma<strong>de</strong>of memory access entries, with one access per entry.Each entry <strong>de</strong>fines the following fields:• Memory address. The global memory address ofthe access.• Type of access. Either load, store, or fetch operation.• Time. Represents the amount of time the processorperforms internal operations between theprevious memory access and the current one.• Output <strong>de</strong>pen<strong>de</strong>ncy. Allows to <strong>de</strong>fine an output<strong>de</strong>pen<strong>de</strong>ncy between a store operation anda load operation. A value of -1 means no output<strong>de</strong>pen<strong>de</strong>ncy.• Input <strong>de</strong>pen<strong>de</strong>ncy. Allows to <strong>de</strong>fine an input <strong>de</strong>pen<strong>de</strong>ncybetween a load operation and a storeoperation. A value of -1 means no input <strong>de</strong>pen<strong>de</strong>ncy.• Number of output <strong>de</strong>pen<strong>de</strong>ncies. Indicates howmany processors will have a <strong>de</strong>pen<strong>de</strong>ncy withthis access.Memory <strong>de</strong>pen<strong>de</strong>ncies allow keeping the originalflow of the application. For instance, synchronizationbarriers and spin lock operations can easily be mo<strong>de</strong>ledwith memory <strong>de</strong>pen<strong>de</strong>ncies. Figure 3 shows anexample of a barrier synchronization by several processors.The figure shows the <strong>de</strong>finition of the tracefile for each processor (address field is omitted).Fig. 3.Traces <strong>de</strong>scribing a barrier synchronizationMemory access traces can easily be obtained fromreal applications. In<strong>de</strong>ed, SIMICS/GEMS can beused to output all the memory references of a givenapplication un<strong>de</strong>r the assumption of an i<strong>de</strong>al memoryand network mo<strong>de</strong>l. Memory <strong>de</strong>pen<strong>de</strong>ncies can easily<strong>JP2011</strong>-577


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Memory parametersNetwork parametersParameter Values Parameter ValuesCoherence protocol Invalidation-based Topology tipe mesh, ring, customL1 and L2 sets any Packet size anyL1 and L2 ways any Flit size anyL1 and L2 cache latency any Flow control stop&go, VCTlite, credits, mixedL1 and L2 tag latency any Virtual networks anyVirtual channelsanyBroadcast supportY/NRouting typeXY, lbdrTABLE IMemory and network parameters supported in gMemNoCsim.be obtained by inspecting the final file and matchingreferences to the same address. This, however, isleft for future work. In addition, synthetic memoryaccess traces can easily be obtained, enabling theevaluation of different coherence protocols in wellknownmemory access patterns. Figure 4 shows anexample of memory traces for a migratory sharingpattern (an address is updated sequentially by a setof processors).4-stage switch. Flit size is set to four bytes. Aninvalidation-based coherence protocol is mo<strong>de</strong>led.Figure 5 shows the average execution time whenthe number and location of memory controllers inthe chip are varied. Memory controllers are locatedat the corners of the chip except for the 4mc centercase where is placed at the center of each 2×2 quadrantin the chip. As can be noticed, the location andthe number of memory controllers does not pay anexcessive overhead. We have a mo<strong>de</strong>st reduction inexecution time of 3% when moving from one memorycontroller in a corner to four memory controllersspread through the chip.Fig. 4.Traces <strong>de</strong>scribing a migratory sharing patternIV. A Brief Evaluation Experience withgMemNoCsimIn this section we provi<strong>de</strong> the results for a briefexploration of parameter <strong>de</strong>finitions for a CMP system.The gMemNoCsim simulation platform is usedin both synthetic memory access patterns and tracesobtained from SPLASH-2 applications. Two syntheticpatterns are evaluated. In the first one eachprocessor issues a random memory access every 10cycles, whereas in the second one the memory accessesare performed on every cycle (stress scenario).In both cases, 70% of the accesses are loads andfetches. For the applications we get the traces for fft,lu, raytrace, volrend, watersp, barnes, fmm, ocean,and radiosity. We provi<strong>de</strong> average results for all thesescenarios in a set of configurations <strong>de</strong>scribed next.The <strong>de</strong>fault configuration is a 2D mesh with 16 tiles,each with two private 64KB L1 caches (instructionsand data), a shared 512KB L2 bank, and a pipelinedFig. 5. Average execution time for different number and locationof memory controllers. Flit size is 4 bytes. Onevirtual channel.The previous result has been achieved with flitsize set to 4 bytes and with no virtual channel supportat switches. In Figure 6 we can see the resultswhen the number of virtual channels available is upgra<strong>de</strong>dto four. Now, the average execution time isslightly reduced by 5%. We can conclu<strong>de</strong> that thenumber of virtual channels and the number of memorycontrollers help in the same direction alleviatingthe network. Maximum performance improvement isachieved with four memory controllers and with fourvirtual channels but not representing a large benefit.Now, in Figure 7 we can see the impact of theflit size on execution time. This time we can see alarge impact as execution time is reduced by almost20% on average when flit is wi<strong>de</strong>ned to 32 bytes.In<strong>de</strong>ed, same results are obtained for 64-byte flits.In those cases the network latency is highly reduced(and also the contention within the network) thus<strong>JP2011</strong>-578


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 6. Average execution time for different number of memorycontrollers. Flit size is 4 bytes. Four virtual channels.slower cache configurations. Execution time is impactedwhen caches are 4X time slower than the <strong>de</strong>faultcase (6% performance <strong>de</strong>gradation). With evenslower caches we <strong>de</strong>tect a 15% performance <strong>de</strong>gradation.The cache size, however, does not impact muchon execution time. In<strong>de</strong>ed, the size of the L1 cacheis more important than the size of the L2 cache. Onaverage, performance is <strong>de</strong>gra<strong>de</strong>d by 4% when usingsmaller L1s and 2% when using L2s. The combine<strong>de</strong>ffect raises 8% performance <strong>de</strong>gradation.reducing execution time. From this figure we can<strong>de</strong>duce that the flit size is a major <strong>de</strong>sign parameterfor the CMP system.Fig. 9. Average execution time for different cache configurations.One memory controller. One virtual channel.4-byte flit size.Fig. 7. Average execution time for different flit sizes. Onememory controller. One virtual channel.Next, in Figure 8 we can see the performanceachieved when different topologies when different flitsizes are used. In particular, the 2D mesh (case 1mc),rings and concentrated meshes (four cores attachedto the same switch) are evaluated. We can see howthe limited bandwidth of the ring impacts on executiontime by almost 20% overhead. However, thering can obtain good results (no performance overhead)if the flit size is tuned to 8 bytes. Thus, weget similar performance when comparing a 4-byte flit2D mesh with a 8-byte flit ring. Also, we can noticehow the lower average hop count of the concentratedmesh helps in reducing execution time by 4% andfurther attain 20% performance improvement withmo<strong>de</strong>rate flit sizes (8-byte flits).Fig. 8. Average execution time for different topologies andflit sizes. One memory controller. One virtual channel.Finally, Figure 9 shows the impact on executiontime of a different configuration in the L1/L2 cachememories. In particular, we use smaller and/orA. A Coherence Protocol Analysis ExampleAs a final example, we provi<strong>de</strong> here a first evaluationof a cache coherence protocol <strong>de</strong>sign analysis.In particular, the migratory sharing pattern of somevariables can be efficiently tracked by the coherenceprotocol with a minor modification. In a migratorysharing pattern processors read and write a sharedvariable in a sequential or<strong>de</strong>r [8]. In an standard coherenceprotocol the variable is shared between theprocessor that wrote the variable and the processorthat now has a miss read. This is unneficient asthe processor will write the variable that is in sharedmo<strong>de</strong>, thus, will need exclusive ownership before performingthe write. In contrast, the coherency protocolcan be modified in or<strong>de</strong>r to <strong>de</strong>tect the migratorysharing pattern. Upon a read miss, the coherenceprotocol reassigns ownership of the memory block.The copy in the L1 of the former producer is invalidatedand exclusive ownership is provi<strong>de</strong>d to the newsharer. Thus, when performing the write no coherenceactions will be required. Figure 11 shows themain coherence protocol changes performed to supportmigratory sharing. Normally incoming read requestfor a private block are forwar<strong>de</strong>d to the ownerL1 cache, and the block becomes shared, as in Figure10. When the L2 <strong>de</strong>tects a migratory sharing pattern,an incoming read request is forwar<strong>de</strong>d to theowner as a write request: the current owner will invalidateand send the block with exclusive grants tothe requestor.Table II shows some results obtained with a syntheticbenchmark that exploits the migratory sharingpattern. In particular, 20000 memory accesses (50%loads and 50% writes) are issued by all the processors<strong>JP2011</strong>-579


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 10.Managing read requests for a private blockherency protocols are <strong>de</strong>fined with the simple <strong>de</strong>finitionof events, actions, and transitions, easily co<strong>de</strong>din a text-based file and following simple rules. Thenetwork is also <strong>de</strong>fined with many parameters as thetopology, the routing algorithm, and the pipelinedswitch <strong>de</strong>sign.gMemNoCsim has been <strong>de</strong>veloped to overcome theproblem of long simulation time required by complexsystem-wi<strong>de</strong> environments like GEMS/SIMICS.With gMemNoCsim, memory access traces are usedto speed up simulation time. To keep simulationaccuracy we instrument the traces with the inclusionof memory access <strong>de</strong>pen<strong>de</strong>ncies which temporarilyblock processors following synchronization eventsand barriers. As future work we plan to analyzethe impact of memory <strong>de</strong>pen<strong>de</strong>ncies computation onsimulation accuracy. Also, we plan to use the platformas an effective tool for network and memoryhierarchy co-<strong>de</strong>sign.AcknowlegmentThis work was supported by the Spanish MEC andMICINN, as well as European Commission FEDERfunds, un<strong>de</strong>r Grant TIN2009-14475-C04-01. It wasalso partly supported by the project NaNoC (projectlabel 248972) which is fun<strong>de</strong>d by the European Commissionwithin the Research Programme FP7.Fig. 11. Managing read requests when a migratory sharingpattern has been <strong>de</strong>tected by the L2 cache bankto the same memory location (variable). Reads andwrites are performed sequentially following the migratorysharing pattern. As can be seen, executiontime is halved by the improved coherency protocol.In<strong>de</strong>ed, practically all the write operations have beenperformed in the updated protocol in the exclusivemo<strong>de</strong>, thus having exclusive access and not requiringany coherence action to be performed. This translatesalso to half the number of packets injected intothe network.V. ConclusionsIn this paper we have presented the gMemNoCsimsimulator. Memory coherency and on-chip networkcan be co-<strong>de</strong>signed with the new tool as it allows a<strong>de</strong>tailed and accurate mo<strong>de</strong>ling of both components.Besi<strong>de</strong>s, memory controllers are also mo<strong>de</strong>led. Co-Inv. Inv. with MSCycles 1269949 645099Stores in Shd mo<strong>de</strong> 9999 1Stores in Excl mo<strong>de</strong> 1 9999Injected packets 229997 110021L1 misses 19999 10001L1 hits 1 9999TABLE IIStatistics for two different protocolimplementations in gMemNoCsimReferences[1] Luca Benini, Giovanni De Micheli Networks on chips:technology and tools, Aca<strong>de</strong>mic Press, 2006.[2] Jose Flich, Davi<strong>de</strong> Bertozzi Designing Network On-ChipArchitectures in the Nanoscale Era, Chapman & Hall/CrcComputational Science Series, 2010.[3] P. S. Magnusson, M. Christensson, and J. Eskilson, et al.Simics: A full system simulation platform., IEEE Computer,35, Feb. 2002. IEEE Computer, 35, 2002.[4] M. M. Martin, D. J. Sorin, and B. M. Beckmann, et al. .Multifacet general execution-driven multiprocessor simulator(GEMS) toolset., Computer Architecture News, 33,2005 .[5] Niket Agarwal, Li-Shiuan Peh and Niraj K. Jha. Garnet:A Detailed Interconnect Mo<strong>de</strong>l Insi<strong>de</strong> a Full-SystemSimulation Framework, CE-P08-001, Dept. of ElectricalEngineering, Princeton University, 2008.[6] S. C. Woo, M. Ohara, E. Torrie, J. P. Singh, and A. Gupta.The SPLASH-2 programs: Characterization and methodologicalconsi<strong>de</strong>rations., 22nd Int. Symp. on ComputerArchitecture (ISCA), 1995.[7] Christian Bienia, Sanjeev Kumar, Jaswin<strong>de</strong>r Pal Singhand Kai Li. The PARSEC Benchmark Suite: Characterizationand Architectural Implications, Proceedings ofthe 17th International Conference on Parallel Architecturesand Compilation Techniques, 2008.[8] Per Stenstrom, Mats Brorsson, <strong>La</strong>rs Sandberg An adaptivecache coherence protocol optimized for migratory sharing,ISCA ’93 Proceedings of the 20th annual internationalsymposium on computer architecture , 1993.<strong>JP2011</strong>-580


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Docencia en arquitectura, tecnología <strong>de</strong> computadores yprogramación paralela<strong>JP2011</strong>-581


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-582


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011E-Assessment of Matlab Assignments inMoodle: Application to an IntroductoryProgramming Course for EngineersJulián Ramos, María A. Trenas, Sergio Romero, Eladio Gutiérrez 1Abstract — This article introduces a novel extension forMoodle supporting the automatic verification of co<strong>de</strong>swritten in Matlab. It has been applied when teaching thebasics of imperative programming in a course aimed atchemical engineering stu<strong>de</strong>nts. The extension <strong>de</strong>rives fromthe module CTPracticals, originally <strong>de</strong>veloped by theauthors to enable the automatic assessment of VHD<strong>La</strong>ssignments in Moodle. Several major changes have beenma<strong>de</strong>, mainly in the automatic verification engine, in thecore of the system, and in several user interfaces. Themodule partially frees teachers from the repetitive task ofverifying assignments, allowing them to invest more timeassisting stu<strong>de</strong>nts and tackling new pedagogical objectives.An anonymous stu<strong>de</strong>nt survey proved that stu<strong>de</strong>nts aresatisfied with the system because they find the feedbackand the constantly updated view of the status of theirassignments helpful.Keywords — Learning Management Systems (LMS),Moodle, E-Assessment / Computer Ai<strong>de</strong>d Assessment(CAA), Programming Teaching, Matlab.FI. INTRODUCTIONundamentals of Computers is a subject taught duringthe first course of the Chemical Engineering studiesin the aca<strong>de</strong>mic program of the University of Málaga(Spain), with 6 European credits, 3 of which arepractical. It should be mentioned that each learningcredit <strong>de</strong>fined by the European Credit Transfer System(ECTS) involves about 25 hours of stu<strong>de</strong>nt work. Astandard ECTS aca<strong>de</strong>mic year consists of 60 credits,which means a total workload of about 1500 hoursduring two semesters.The practical component is aimed at acquiring thebasic programming skills required in chemicalengineering. The Matlab programming language waschosen due to its learnability and its wi<strong>de</strong> application inscience and engineering. Because stu<strong>de</strong>nts find itdifficult to verify their co<strong>de</strong>s and solutions, a continuousassessment plan is required. However, providingstu<strong>de</strong>nts with frequent feedback had previously been atime-consuming task, as the teachers could onlymanually verify the assignments [1].In such situations, e-assessment and computer-ai<strong>de</strong>dassessment (CAA) can make the teacher’s work moreeffective, as shown by numerous experiences andstudies in the literature, including both the software [2,3, 5, 6] and the hardware si<strong>de</strong> of the Computer Science1 Department of Computer ArchitectureUniversity of Málaga, 29071 Málaga, Spaine-mail: {julian, matrenas, sromero, eladio}@uma.es.teaching [7, 8]. An overview of the diverse proposalsand systems for the automatic verification ofprogramming activities can be found in [9] and [10].Nevertheless, as pointed out in [9], it becomes difficultto adopt automatic verification in general due to the lackof interoperability of the different approaches, whichhave been <strong>de</strong>veloped for specific contexts. Additionally,following the stu<strong>de</strong>nts’ progress requires not only agood assessment mechanism but also an effectiveadministration. In fact, learning management systems(LMS) are taking a significant role in the currenteducational landscape. Through web interfaces, theyprovi<strong>de</strong> support for a wi<strong>de</strong> collection of activities,including forums, assignments and quizzes, an<strong>de</strong>ffective strategies for class management, such asgra<strong>de</strong>books or stu<strong>de</strong>nt annotations.The module CTPracticals [11, 12] is the result of theauthors’ effort to integrate CAA features into an LMS,particularly Moodle (Modular Object-Oriented DynamicLearning Environment) [13]. Originally, the module was<strong>de</strong>signed to support digital logic labworks in the contextof a course on computer organisation. It introduces anadvanced interface to manage assignments, submissionsand assessments, and it automates the verification of theVHDL-based <strong>de</strong>signs submitted by stu<strong>de</strong>nts, providing<strong>de</strong>tailed feedback from results for both teachers andstu<strong>de</strong>nts. Moodle is open-source software, with amodular organisation and interface that facilitates the<strong>de</strong>velopment of new modules and activities [14].According to moodle.org, there were about 50,000validated sites in December 2010, and, in particular, it isthe platform used by the Virtual Campus of theUniversity of Málaga.This article <strong>de</strong>scribes how CTPracticals has beenexten<strong>de</strong>d to support courses whose practical work isbased on Matlab assignments. The next section presentsthe course organisation and how CTPracticalsinfluences the applied teaching methodology. Then,there is a brief review of the main interfaces andfunctionality of the module, common for both VHD<strong>La</strong>nd Matlab-based lab works. Section 4 focuses on thechanges un<strong>de</strong>rtaken in the verification engine. Thearticle ends with some evaluation results andconclusions.II. COURSE ORGANISATION AND METHODOLOGYBecause Fundamentals of Computers is an introductorycourse targeted to chemical engineering stu<strong>de</strong>nts, theprogramming language Matlab was chosen to introducebasic programming skills. It has most of the <strong>de</strong>siredfeatures: it is easy to learn and use (compilation is notnecessary), and it is wi<strong>de</strong>ly used in science and<strong>JP2011</strong>-583


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011engineering. During the course, stu<strong>de</strong>nts will use it tosolve mathematical problems commonly found inchemical engineering, including basic algorithms, linearand nonlinear regression, equations, equation systems,and differentiation. <strong>La</strong>ter, stu<strong>de</strong>nts will be able to applythese skills in higher-level courses.Because the course belongs to the first semester of theirfirst aca<strong>de</strong>mic year, stu<strong>de</strong>nts have no prior programmingknowledge. The first classes are <strong>de</strong>voted to explainingthe basics of Matlab syntax and its interfaces. Differentgraphical representations, both in two and threedimensions, are presented in implicit and parametricform as a first application. Afterward, they learn thebasic flow control statements of imperativeprogramming: sequential, alternative, and iterative.Finally, they apply this knowledge by implementingsmall programs and practicing with functions provi<strong>de</strong>dby Matlab for statistical and numerical calculation.Two sorts of programming exercises are proposed toachieve these instructional objectives:Graphical representation of both data andmathematical expressions: Stu<strong>de</strong>nts mustimplement a script that generates or reads theinput data and represents this data graphically,according to some specifications (2-D or 3-Dplotting, axis scale, line colours, drawing shapes).Programming of simple functions: Stu<strong>de</strong>nts mustprogram simple functions that take certain inputparameters and should return some output valuescalculated according to the specification.An example of a labwork specification comprising bothkinds of exercises is inclu<strong>de</strong>d in Figure 2.As usual, a correct exercise is the one fulfilling all thespecified requirements. However, stu<strong>de</strong>nts find itdifficult to verify their labworks, and more personalisedsupervision of stu<strong>de</strong>nt work becomes necessary. Theycan now submit their labworks using the CTPracticalsmodule, whose automatic verification engine comes intoplay to make it feasible.On one hand, stu<strong>de</strong>nts can immediately see the state oftheir labwork. The teachers are able to configure thelevel of this automatic feedback, as shown in Section 4,and when this feedback information will be provi<strong>de</strong>d.Teachers can <strong>de</strong>ci<strong>de</strong> on these <strong>de</strong>tails based on theirteaching objectives, which will differ in various stagesof a course. Due to the stu<strong>de</strong>nts' inexperience,immediate feedback with a <strong>de</strong>eper level of <strong>de</strong>tail isrequired in the first stages, encouraging the <strong>de</strong>mand forteacher tutoring. However, feedback should be graduallyreduced in subsequent stages as stu<strong>de</strong>nts graduallyimprove their verification skills. These features ofCTPracticals lead the stu<strong>de</strong>nts to i<strong>de</strong>ntify theirknowledge gaps and resolve their doubts through groupor personal tutoring sessions with the teacher. Thestu<strong>de</strong>nts can collaborate in their solution through theMoodle forums (as shown in Figure 1).On the other hand, as the tool expedites the verificationof the labworks, teachers gain more time to advisestu<strong>de</strong>nts. When individual problems are <strong>de</strong>tected, notonly is personalised attention to the stu<strong>de</strong>nts improvedduring the laboratory sessions but personal tutoringappointments can also be established. The Moodlescheduler module can be used to make theseappointments (Figure 1). Moreover, because the moduleallows the teacher to have a global view of the groupevolution, it is possible to <strong>de</strong>tect general problemsencountered by the stu<strong>de</strong>nts, which can be analysed an<strong>de</strong>xplained in special class sessions if necessary. TheMoodle forums are also a great help (see Figure 1).Figure 1: Teacher’s view of a typical Moodle course includingCTPracticals activities.III. MODULE FEATURESThis section will briefly review the interfaces andfunctionality of the module that have remainedunchanged after its extension to Matlab labworks. Therea<strong>de</strong>r may refer to [12] for further <strong>de</strong>tails. CTPracticalsis fully integrated in the Moodle system together withthe other modules available in a standard installation. Itinvolves two different elements: the activity moduleitself and a control block (see Figure 1). The moduleallows one to <strong>de</strong>fine the different activity instances thatwill appear insi<strong>de</strong> the course sections. The control block,on a si<strong>de</strong> panel, provi<strong>de</strong>s access to control actions. Boththe activity instance and the control block have differentbehaviours for teachers and stu<strong>de</strong>nts.The stu<strong>de</strong>nt's view of a CTPracticals activity is shownin Figure 2(a). Basically, it allows stu<strong>de</strong>nts to submittheir practical work and to find information aboutassignments. This information inclu<strong>de</strong>s the <strong>de</strong>finition ofthe assignment, including its specifications and <strong>de</strong>adline,and the feedback and results obtained from theautomatic verification process. Knowing whether asolution is right or wrong according to specificationswill be of special interest for the stu<strong>de</strong>nts. In addition,the module manages stu<strong>de</strong>nts in teams, each of whichhas a unique i<strong>de</strong>ntifier. An option of the si<strong>de</strong> controlblock allows stu<strong>de</strong>nts to make up new teams or join anexisting one with the permission of the current members.The activity view for the teacher (Figure 2(b)) isslightly more complex. It consists of three tabs: practicalassignments, testers, and submissions. Remarkablefeatures inclu<strong>de</strong>;Practical assignments: The teacher may configuredifferent parameters for each practical assignment:the submission <strong>de</strong>adline, the score, or anexpression forcing the name of the file thestu<strong>de</strong>nts will have to submit. Other configurableaspects are or<strong>de</strong>r of appearance and scope (publicin this course or in the whole Moodle site). The<strong>JP2011</strong>-584


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011teacher can also restrict the visibility of the resultsby controlling if the automatic feedback will beshown to the stu<strong>de</strong>nt immediately aftersubmission, if it will be <strong>de</strong>layed until a given dateor if it will remain totally hid<strong>de</strong>n.although one of them must be marked as the<strong>de</strong>fault.Submissions: A submission instance is <strong>de</strong>fined foreach pair team/practical assignment. It embracesthe file(s) submitted by a team for eachassignment and all report files and statusinformation generated after the verification of thesubmitted labwork. The teacher can inspect allthese elements to obtain an overall picture of thestu<strong>de</strong>nts’ progress. It is also possible to manuallyadd a short feedback message to the stu<strong>de</strong>nt.Other administrative functionalities, such as statisticreports (through the options course at a glance andstatistics), the management of the stu<strong>de</strong>nt teams(maximum number of members, <strong>de</strong>adline for its setup), and the updating of the Moodle gra<strong>de</strong>book withthe activity scores, are accessed through the si<strong>de</strong>control block (Figure 1).(a)Figure 3: Teacher view for creating and managing the testers.(b)Figure 2: Activity views for stu<strong>de</strong>nts (a) and teachers (b).Testers: This feature is used by the verification engineto check if a submitted labwork fulfills thespecifications. It is possible to add new testers orto edit previously created ones (Figure 3).Moreover, teachers can share testers or reuse theones <strong>de</strong>fined in preceding courses. Testers may beenabled or disabled by the teacher. If disabled,they will not be applied by the verification engine.An interesting feature is that several testers maybe <strong>de</strong>fined for the same practical assignment,IV. VERIFICATION ENGINE FOR MATLABThe automatic verification engine is in the core of theCTPracticals module. Stu<strong>de</strong>nts submit the requestedMatlab source files (.m) as one .zip file. The verificationengine uncompresses the submission and then runs theMatlab sources. According to the execution outputs,which are compared to a reference correct output, thestatus result of verification (right/wrong) is generatedtogether with the corresponding feedback information.The verification process takes place in three phases [9]<strong>de</strong>scribed in Table I. To extend the CTPracticalsfunctionality to Matlab labworks, changes werenecessary in the first two phases.At the time of submission, the verification process isautomatically triggered using the <strong>de</strong>fault tester.Additionally, it can be manually started by the teacher inbatch mo<strong>de</strong>, which may be useful when some changeshave been introduced after submitting or if severaltesters have been <strong>de</strong>fined for a same assignment. Apractical assignment can be resubmitted an unlimitednumber of times until the <strong>de</strong>adline expires. The feedbackinformation inclu<strong>de</strong>s not only the result (right/wrong)but also possible format errors in sources (static analysis<strong>JP2011</strong>-585


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011phase), a comparison between the execution output andthe reference result in a nicely printed format (dynamicanalysis phase) and a log of the whole verification. Thelatter two items are helpful in finding the cause of errors.A more exten<strong>de</strong>d log with internal execution <strong>de</strong>tails isavailable to teachers and administrators.1. Static analysis phaseSubmission format errorSyntax errorPlagiarism avoiding2. Dynamic analysis phaseFunctionalityEfficiencySecuritySemiautomatic verification3. Feedback phaseResults and logsMetricsWork promotionTABLE IFEATURES OF THE CTPRACTICALS VERIFICATION PROCEDURE.Does the submitted .zip contain required files?Bad scripts are <strong>de</strong>tected via try-catch Matlab statement.Filenames (.zip and its contents) and scripts can be based on the team’s i<strong>de</strong>ntifierin or<strong>de</strong>r to restrain plagiarism.Using Matlab on command line the tester script is invoked and will launchexecution of submissions.Script execution time is stored for statistical purposes.Script execution into a chroot sandbox prevents possible system crashes.A manual mo<strong>de</strong> allows the instructor to introduce his own verification results ifnecessary.A differences file resulting from comparison of the stu<strong>de</strong>nt’s output with areference right output, together with a log of execution.Assessment metrics are integrated in the Moodle gra<strong>de</strong>bookThe immediate availability of results can be restricted, in or<strong>de</strong>r to preventstu<strong>de</strong>nts from falling into trial-and-error attempts.The <strong>de</strong>finition of the tester is given by both theverification script (command file) and a reference outputfile (correct result file), as shown in Figure 3. It must becarefully carried out because the accuracy andhelpfulness of the verification will <strong>de</strong>pend on it. Asimple example of tester <strong>de</strong>sign is shown in Figure 4,with an outline of the verification flow and one scenarioof how the tester works on the submitted works. Theoutput of the verification script, which in turn invokesthe stu<strong>de</strong>nt Matlab source, is compared with thereference file. The output can inclu<strong>de</strong> simple numericalvalues (Figure 4(c)) or more complex messages obtainedfrom a test carried out insi<strong>de</strong> the verification script itself(Figure 5). The reference file must be <strong>de</strong>signedaccordingly. At this point, it is possible to control the<strong>de</strong>gree of <strong>de</strong>tail of the feedback information that will begenerated for the stu<strong>de</strong>nt. It <strong>de</strong>pends on the number ofvalues/messages that the teacher <strong>de</strong>ci<strong>de</strong>s to output when<strong>de</strong>signing the verification script.As shown, verifying Matlab functions with numericaloutputs is quite straightforward, but the co<strong>de</strong>sperforming graphical data representations requireanother approach. The comparison of the visualappearance of two plots is not at all trivial [15].However, it is possible to use another more precise an<strong>de</strong>fficient approach with the handler that Matlabassociates with each graphical plot (see example inFigure 5). This handler contains information aboutvalues, coordinates, colour, drawing line features, axisscale, and so on. These attributes can be compared withthe expected ones without the need for any graphicaldisplay output.Figure 4: Tester <strong>de</strong>sign and verification flow: verification script (b)and reference file (c) for a given assignment specification (a). Afterverifying the stu<strong>de</strong>nt’s submission, the status (OK/wrong) is available,together with a difference html output (d) and a log of the process (e).<strong>JP2011</strong>-586


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011that had been previously enrolled in the course. Theiropinion was of special interest to compare the newmethodology with respect to the previous one.Figure 6: Weekly distribution of the submissions during the course.Figure 5: Example of a more complex tester: verification script (a)and reference file (b). The assignment must compute a quadratic fittingfor the specified data and represent them in a plot.V. EVALUATIONThis section presents the authors’ experience applyingthe CTPracticals module in the teaching of the practicalcomponent of Fundamentals of Computers, as <strong>de</strong>scribedin Section 2. The module is currently running on a<strong>de</strong>partmental server using Moodle version 1.9. It hasbeen used extensively since the second semester of theaca<strong>de</strong>mic year 2007 for VHDL lab works. The Matlabextension <strong>de</strong>scribed in this contribution was ma<strong>de</strong>available to stu<strong>de</strong>nts at the beginning of the aca<strong>de</strong>micyear 2009/10. Specifically, 56 enrolled stu<strong>de</strong>nts,distributed into two classrooms, followed the practicalsessions of Fundamentals of Computers.Figure 6 corresponds to the distribution of the numberof submissions since the course started. Altogether, 30practical mini-assignments of increasing difficulty wereproposed during the course. The most complexproposals involved the <strong>de</strong>velopment of Matlab co<strong>de</strong>s ofno more than fifty lines. The distribution follows atypical shape with multiple peaks, which correspond tosubmissions near <strong>de</strong>adlines and periods of lower activityin holiday seasons. The submissions with format errorsor that are wrong, according to specifications, need to beresubmitted. Stu<strong>de</strong>nts can resubmit them as many timesas they want until the <strong>de</strong>adline expires for a givenassignment. Observe that the ratio of correctsubmissions with regard to erroneous ones increases asthe course progresses. Two causes may explain this fact:stu<strong>de</strong>nts are trained on the use of the system, and, mostimportantly, they gain increasingly more programmingskills.To evaluate the <strong>de</strong>gree of satisfaction of stu<strong>de</strong>nts whenusing the CTPracticals module, an anonymous opinionpoll was carried out. Table II summarises the results foreach questionnaire item on a Likert scale from one tofive. The first block of questions was inten<strong>de</strong>d toevaluate the experience for all the enrolled stu<strong>de</strong>nts. Thesecond block of questions was addressed to the stu<strong>de</strong>ntsAccording to the marks, it can be conclu<strong>de</strong>d thatstu<strong>de</strong>nts were in generally pleased with the system. ItemA.7 had a lower punctuation; stu<strong>de</strong>nts find it difficult toun<strong>de</strong>rstand the feedback output of the automaticverification. They expected more direct messages, suchas “you must fix this one”, which would lead them touse the evaluator as a <strong>de</strong>bugger, working on a trial an<strong>de</strong>rror basis. To prevent this usage, teachers are able tocontrol the <strong>de</strong>pth of the feedback and the date forpublishing, especially for more advanced labworks.After all, stu<strong>de</strong>nts find it very difficult to verify theirco<strong>de</strong>s and solutions, and one of the objectives of thecourse is to bridge this gap.In previous years, stu<strong>de</strong>nts were provi<strong>de</strong>d with ananswer book. Thus, stu<strong>de</strong>nts would routinely copy theanswer to an exercise, without making the effort toarrive at the solution on their own and verify andsubsequently amend the intermediate malfunctioningsolutions. Looking at the poll results (item B.3), it isremarkable that, previously enrolled stu<strong>de</strong>nts <strong>de</strong>rivemore motivation from CTPracticals in verifying theirlabworks than from simply looking in the answer book.Finally, a positive influence on the aca<strong>de</strong>micperformance was observed after the use of theaforementioned teaching methodology based on the useof the CTPracticals Moodle module. During theaca<strong>de</strong>mic year 2009/10, the number of stu<strong>de</strong>nts passingthe exam (marks greater than 5/10) was about 60%higher than in the previous year. After all, today'sstu<strong>de</strong>nts are moving comfortably in the field of newtechnologies. The CTPracticals module, as a part of alearning platform, fits this way of thinking and working,and it provi<strong>de</strong>s elements that stu<strong>de</strong>nts expect, such as anintegrated tracking of practical work and nearlyimmediate feedback.VI. CONCLUSIONSDeveloped by the authors and fully integrated in theMoodle platform, CTPracticals is a module that allowsthe remote automatic verification of the stu<strong>de</strong>nt'slabwork with an effective administration of results.Originally, the module was aimed at the automaticverification of VHDL-based assignments, but it has beenexten<strong>de</strong>d to support Matlab programming. Thisextension involved modifications of the verificationengine of the module and several of its interfaces.As <strong>de</strong>scribed in this work, some importantmethodological changes were introduced into anintroductory computing course given in the first year ofChemical Engineering. Not only did it consi<strong>de</strong>rably<strong>JP2011</strong>-587


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011improve some organisational aspects of the course, but itwas able to motivate stu<strong>de</strong>nts to accomplish theirlabworks correctly. The automatic verification featureincreases the dynamism of laboratory; stu<strong>de</strong>nts canknow the state of their labworks immediately, andteachers have, at all times, an overall picture of theirstu<strong>de</strong>nt group, which improves their feedback andallows them to tackle new pedagogical objectives.In addition, the module can mitigate some negativeeffects commonly associated with automatic assessmentsystems. Because it is possible to control both the <strong>de</strong>pthand the date for publishing the feedback results, the riskof stu<strong>de</strong>nts using the system on a trial-and-error basiscan be mitigated. Plagiarism may be controlled to someextent as well; submitting copies is more difficult if theteacher <strong>de</strong>fines testers and filenames as a function of theuser's i<strong>de</strong>ntifier.TABLE IIDISTRIBUTION AND AVERAGE OF MARKS FOR THE STUDENT QUESTIONNAIRE (1=STRONGLY DISAGREE, 5=STRONGLY AGREE)A. Questions for all currently enrolled stu<strong>de</strong>nts: 1 2 3 4 5 Avg.A.1. I consi<strong>de</strong>r it is important for a chemical engineer to learn computer programming 5% 5% 24% 35% 31% 3.8A.2. Comparing with other subjects, I find programming a difficult task 5% 3% 8% 30% 54% 4.2A.3. I have a positive global opinion of the CTPracticals module 3% 3% 38% 32% 24% 3.7A.4. I find easy to learn how to use the system 5% 11% 14% 22% 48% 4.0A.5. I have discovered errors in my labworks that otherwise would have remained hid<strong>de</strong>n for 5% 3% 27% 35% 30% 3.8meA.6. I find automatic feedback after labwork submission quite fast 5% 8% 14% 35% 38% 3.9A.7. I find automatic feedback reports are quite un<strong>de</strong>rstandable 11% 16% 43% 24% 6% 3.0A.8. I find the automatic feedback useful in or<strong>de</strong>r to check my labwork 8% 0% 35% 32% 25% 3.6A.9. I think that system feedback helps me to amend my labwork 11% 22% 35% 22% 10% 3.0A.10 I find the availability of my labworks without time or place restrictions quite useful 3% 5% 8% 32% 52% 4.2B. Questions for stu<strong>de</strong>nts enrolled in the course on previous years: 1 2 3 4 5 Avg.B.1 This year, I find that it is easier to learn Matlab 0% 23% 31% 15% 31% 3.5B.2 I have accomplished the exercises more quickly 0% 15% 38% 15% 32% 3.6B.3. I find CTPracticals more motivating in or<strong>de</strong>r to verify my labworks, than just looking to 0% 8% 38% 8% 46% 3.9the answers bookB.4. I find it easier to check the correctness of my labwork 0% 8% 23% 62% 7% 3.7VII. DEMONSTRATION SITEA <strong>de</strong>mo site is available at http://guac.ac.uma.es/<strong>de</strong>mo[User: <strong>de</strong>mouser, password: <strong>de</strong>mo].REFERENCES[1] Amelung M., Piotrowski M. and Rösner D. EduComponents:experiences in e-assessment in computer science education.ITICSE’06: Proceedings of the 11th annual SIGCSE conference onInnovation and technology in computer science education, ACM,2006; 88–92.[2] Malmi L., Korhonen A. and Saikkonen R. Experiences inautomatic assessment on mass courses and issues for <strong>de</strong>signing virtualcourses. SIGCSE Bulletin 2002; 34(3):55–59.[3] Douce C., Livingstone D. and Orwell J. Automatic test-basedassessment of programming: A review. Journal on EducationalResources in Computing 2005; 5(3):4:1–13.[4] Rößling, G., Joy, M., Moreno, A., Ra<strong>de</strong>nski, A., Malmi, L.,Kerren, A., Naps, T., Ross, R. J., Clancy, M., Korhonen, A., Oechsle,R., and Iturbi<strong>de</strong>, J. Á. Enhancing learning management systems tobetter support computer science education. SIGCSE Bulletin 40, 4;2008, 142-166.[5] Barchino R., et al. Assessment <strong>de</strong>sign: A step towardsinteroperability. Computer Applications in Engineering Education.May 2009; DOI: 10.1002/cae.20363.[6] Liu X. A new automated grading approach for computerprogramming. Computer Applications in Engineering Education. Oct2010; DOI: 10.1002/cae.20494[7] Rodriguez, S. et al. Computer-based management environment foran assembly language programming laboratory. ComputerApplications in Engineering Education, April 2007; 15(1): 41-54.[8] Kurmas Z. Improving stu<strong>de</strong>nt performance using automatedtesting of simulated digital logic circuits. ITiCSE ’08: Proceedings ofthe 13th annual conference on Innovation and technology in computerscience education, ACM, 2008; 265–270.[9] Ala-Mutka K. A survey of automated assessment approaches forprogramming assignments. Computer Science Education, 2005;15(2):83–102.[10] Chatzopoulou, D.I. and Economi<strong>de</strong>s, A.A. Adaptive assessmentof stu<strong>de</strong>nt's knowledge in programming courses. Journal of ComputerAssisted Learning, Aug. 2010; 26(4):258-269.[11] Corbera, F., Gutiérrez, E., Ramos, J., Romero, S., and Trenas, M.A. Development of a new Moodle module for a basic course oncomputer architecture. SIGCSE Bull. 40, 3, Aug. 2008; 349-349.[12] Gutierrez E., Trenas M.A., Ramos J., Corbera F. and Romero S.A new Moodle module supporting automatic verification of VHDLbasedassignments. Computers and Education, Feb 2010; 54(2):562–577.[13] Moodle site. URL: http://moodle.org.[14] Moore J. and Churchward M. Moodle 1.9 ExtensionDevelopment. Pack Publishing. April 2010.[15] English J. Automated assessment of GUI programs using JEWL.Proceedings of the 9th annual SIGCSE conference on innovation andtechnology in computer science education, ACM New York, NY,USA, 2004; 137–141.<strong>JP2011</strong>-588


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Sobre la integración <strong>de</strong>l Curriculum Initiativeon Parallel and Distributed Computing enlos planes <strong>de</strong> estudio <strong>de</strong>l Grado en IngenieríaInformáticaFrancisco Almeida 1 Domingo Giménez 2 José-Miguel Mantas 3 Antonio M. Vidal 4Resumen— Recientemente el Technical Committeeof Parallel Processing (TCPP) <strong>de</strong> IEEE realizó unapropuesta <strong>de</strong> contenidos sobre Computación Paralelay Distribuida a incluir en los estudios universitarios.En este artículo se analiza la inclusión <strong>de</strong> los distintostópicos <strong>de</strong>l NSF/TCPP Curriculum Initiative on Paralleland Distributed Computing en los planes <strong>de</strong> estudio <strong>de</strong>lGrado <strong>de</strong> Ingeniería informática.Palabras clave— Computación Paralela, Grado <strong>de</strong> IngenieríaInformática, Planes <strong>de</strong> Estudios.I. IntroducciónLOS estudios <strong>de</strong> informática en España estánsiendo reorganizados. Han cambiado <strong>de</strong> una organizaciónen dos carreras técnicas <strong>de</strong> tres cursosy una superior <strong>de</strong> cinco cursos a un único Grado<strong>de</strong> Ingeniería Informática (GII) <strong>de</strong> cuatro cursos.<strong>La</strong> mayoría <strong>de</strong> las universida<strong>de</strong>s españolas tienenaprobado el plan <strong>de</strong> estudios <strong>de</strong>l GII, y en el curso2010/2011 han puesto en marcha el primer o los dosprimeros cursos.Por otro lado, <strong>de</strong>bido a los avances tecnológicos, lacomputación paralela se ha difundido ampliamente.En la actualidad este tipo <strong>de</strong> computación ya nose encuentra sólamente en clusters <strong>de</strong> or<strong>de</strong>nadoresy en supercomputadores, sino que se ha convertidoen el tipo <strong>de</strong> computación <strong>de</strong> los sistemas computacionalesestándares: los or<strong>de</strong>nadores personales y losportátiles son sistemas multicore e incluyen tarjetasGPU que se pue<strong>de</strong>n programar en paralelo. Debido ala gran importancia actual <strong>de</strong> la computación paralela,el IEEE Technical Committee on Parallel Processing[1] ha lanzado una iniciativa para <strong>de</strong>finir lostópicos <strong>de</strong> computación paralela y distribuida que<strong>de</strong>berían incluirse en los curricula <strong>de</strong> los estudios universitarios<strong>de</strong> informática.Por todo esto, consi<strong>de</strong>ramos que en este momentoes conveniente discutir cómo se están integrando ycómo se podrían integrar en los GII los tópicos sobreparalelismo incluidos en la propuesta <strong>de</strong>l TCPP;y en este artículo analizamos la situación <strong>de</strong> lostemas <strong>de</strong> paralelismo en el GII en varias universida<strong>de</strong>sespañolas en relación con la propuesta <strong>de</strong>l1 Dpto. <strong>de</strong> Estadística, Investigación Operativa y Computación,Univ. <strong>La</strong> <strong>La</strong>guna, e-mail: falmeida@ull.es2 Dpto. <strong>de</strong> Informática y Sistemas, Univ. Murcia, e-mail:domingo@um.es3 Dpto. <strong>de</strong> Lenguajes y Sistemas Informáticos, Univ.Granada, e-mail: jmmantas@ugr.es4 Dpto. <strong>de</strong> Sistemas Informáticos y Computación, Univ.Politécnica <strong>de</strong> Valencia, e-mail: avidal@dsic.upv.esTCPP.Los autores <strong>de</strong> este artículo estamos colaborandoen los últimos años en temas <strong>de</strong> docencia <strong>de</strong>l paralelismo,en particular con la elaboración <strong>de</strong> un libro<strong>de</strong> introducción a la programación paralela [2], yartículos sobre docencia <strong>de</strong>l paralelismo [3]. El librose publicó en 2008, pero su escritura comenzó en el2004, y <strong>de</strong>s<strong>de</strong> entonces la computación paralela haexperimentado un gran cambio, principalmente conla generalización <strong>de</strong>l uso <strong>de</strong> multicores y la popularización<strong>de</strong> las GPUs y su uso como sistemas <strong>de</strong>cómputo <strong>de</strong> propósito general. Así, con la popularizacióny universalización <strong>de</strong> los sistemas paralelos<strong>de</strong>bemos repensar la forma en que se <strong>de</strong>be impartirel paralelismo, y en este sentido hemos presentadoen mayo <strong>de</strong> 2011 un poster <strong>de</strong>ntro <strong>de</strong>l workshopEduPar11 [4], organizado por el IEEE TCPPy <strong>de</strong>dicado a la docencia <strong>de</strong> la programación paralela.Este trabajo es una versión extendida <strong>de</strong> dichoposter, y presenta nuestra visión sobre la situación<strong>de</strong> la programación paralela en el GII en las universida<strong>de</strong>sespañolas. Los autores trabajamos en diferentesuniversida<strong>de</strong>s (Granada, <strong>La</strong> <strong>La</strong>guna, Murciay Politécnica <strong>de</strong> Valencia), y llevamos varios añosimpartiendo docencia <strong>de</strong> programación paralela endistintos niveles, y trabajando en diferentes líneas<strong>de</strong>ntro <strong>de</strong> la computación paralela, por lo que enten<strong>de</strong>mosque nuestra visión no es una visión local,sino que es múltiple, aunque <strong>de</strong>s<strong>de</strong> el campo <strong>de</strong> laprogramación y la computación.El artículo está organizado <strong>de</strong> la siguiente forma.En la sección 2 discutimos nuestras i<strong>de</strong>as generalessobre la situación actual y la <strong>de</strong>seable <strong>de</strong> la docencia<strong>de</strong> la programación paralela en los estudios <strong>de</strong> informáticaen la universidad española. En la sección3 analizamos los tópicos <strong>de</strong> paralelismo que aparecenen los planes <strong>de</strong> estudio <strong>de</strong>l GII <strong>de</strong> las universida<strong>de</strong>sdon<strong>de</strong> impartimos docencia, y comparamosla situación con la que consi<strong>de</strong>ramos <strong>de</strong>seable y conla propuesta <strong>de</strong>l TCPP. En la sección 4 se analizacómo se tratan en nuestras universida<strong>de</strong>s los diferentestópicos <strong>de</strong> paralelismo <strong>de</strong> la propuesta <strong>de</strong>lTCPP. En la sección 5 se resume el trabajo realizadoy se proponen posibles colaboraciones para ampliarla discusión sobre la inclusión <strong>de</strong> temas <strong>de</strong> paralelismoen los GII.<strong>JP2011</strong>-589


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011II. I<strong>de</strong>as sobre contenidos <strong>de</strong> ComputaciónParalela en los estudios universitarios<strong>de</strong> informática<strong>La</strong>s i<strong>de</strong>as generales <strong>de</strong> nuestra propuesta coinci<strong>de</strong>ncon las <strong>de</strong> otras propuestas y estudios:• Los contenidos <strong>de</strong> computación paralela enlos curricula <strong>de</strong> informática están aumentandogradualmente [5], y normalmente se organizanen la misma forma que en las universida<strong>de</strong>sdon<strong>de</strong> trabajan los autores:– se introducen nociones <strong>de</strong> sistemas paralelos encursos <strong>de</strong> arquitectura <strong>de</strong> computadores,– aparecen algunos cursos introductorios <strong>de</strong> concurrenciao programación paralela (en algunoscasos optativos),– y se encuentran cursos optativos <strong>de</strong> computaciónparalela en algunas especialida<strong>de</strong>s oen estudios <strong>de</strong> máster.Pero los sistemas computacionales son en la actualidadsistemas paralelos, y la introducción ala computación paralela <strong>de</strong>bería ser obligatoriapara todos los estudiantes <strong>de</strong>l Grado <strong>de</strong> IngenieríaInformática.• No está clara (y nosotros no tenemos ningunasolución) la forma en que se <strong>de</strong>bería introducirla programación paralela en los primeros niveles<strong>de</strong> los estudios universitarios, pero parece claroque <strong>de</strong>bería introducirse <strong>de</strong> alguna manera: loslibros más populares <strong>de</strong> algoritmos [6], [7] incluyencapítulos sobre algoritmos paralelos enlas últimas ediciones, y el curriculum <strong>de</strong> ACM[8] menciona la necesidad <strong>de</strong> introducir la computaciónparalela entre los tópicos obligatorios,aunque no da ninguna indicación <strong>de</strong> cómo se incluirían.• <strong>La</strong>s nociones básicas <strong>de</strong> sistemas paralelos se introducennormalmente en cursos <strong>de</strong> arquitecturas<strong>de</strong> or<strong>de</strong>nadores en los diferentes cursos<strong>de</strong> los estudios <strong>de</strong> informática, pero en programaciónparalela la situación es diferente, yusualmente se ignora en las asignaturas obligatorias,o se introduce separada <strong>de</strong> los cursosdon<strong>de</strong> se estudian conceptos <strong>de</strong> programaciónsecuencial (cursos <strong>de</strong> programación o <strong>de</strong> estructuras<strong>de</strong> datos y <strong>de</strong> algoritmos). Esto produceuna separación entre lo que estudian los futurosprofesionales <strong>de</strong> la informática y los entornos enlos que trabajarán en su vida profesional: lossistemas computacionales a los que tendrán accesoson paralelos, y por tanto <strong>de</strong>berían estudiarsistemas paralelos y también conceptos <strong>de</strong> programaciónparalela.Así, nuestra propuesta (que coinci<strong>de</strong> con otraspropuestas, lo que difícilmente podría ser <strong>de</strong> otramanera dada la situación actual) es incluir tópicosobligatorios <strong>de</strong> programación paralela <strong>de</strong>s<strong>de</strong> losprimeros cursos en los curricula <strong>de</strong>l Grado <strong>de</strong> IngenieríaInformática, incluyendo <strong>de</strong> forma progresivanociones <strong>de</strong> paralelismo en los sucesivos cursos, conalgún curso obligatorio sobre paralelismo (sistemas,arquitecturas, programación, concurrencia, etc.) ycursos optativos <strong>de</strong> paralelismo <strong>de</strong>pendiendo <strong>de</strong> la especializaciónpor la que se <strong>de</strong>cante cada estudiante.El curriculum <strong>de</strong>l IEEE TCPP <strong>de</strong> Computación Paralelay Distribuida significa una oportunidad paradiscutir cómo <strong>de</strong>be realizarse la inclusión <strong>de</strong> los conceptos<strong>de</strong> paralelismo en los curricula <strong>de</strong>l GII. Por lotanto, comparamos la propuesta <strong>de</strong>l TCPP [1] con lanuestra [3] y con la situación en las cuatro universida<strong>de</strong>sdon<strong>de</strong> trabajamos.III. <strong>La</strong> Computación Paralela en el Gradoen Ingeniería Informática<strong>La</strong> figura 1 resume <strong>de</strong> forma gráfica nuestra propuestasobre la inclusión <strong>de</strong> conceptos <strong>de</strong> ComputaciónParalela en el Grado en Ingeniería Informática.<strong>La</strong>s i<strong>de</strong>as generales son:Fig. 1. Propuesta <strong>de</strong> organización <strong>de</strong> contenidos <strong>de</strong> ComputciónParalela en el Grado en Ingeniería Informática.• Los conceptos básicos <strong>de</strong> paralelismo no <strong>de</strong>beríanintroducirse mucho <strong>de</strong>spués <strong>de</strong> los <strong>de</strong> programaciónsecuencial (por ejemplo, se podríanintroducir en el segundo año <strong>de</strong> los estudios), yse <strong>de</strong>berían tratar tanto en cursos <strong>de</strong> arquitecturay tecnología <strong>de</strong> computadores como en cursos<strong>de</strong> programación. Los cursos <strong>de</strong> arquitecturase representan en azul en la figura, los <strong>de</strong> programaciónse representan en ver<strong>de</strong>, y los contenidoscorrespondientes <strong>de</strong> paralelismo se representanen azul o en ver<strong>de</strong> oscuro.• Los conceptos básicos <strong>de</strong> concurrencia, herramientas<strong>de</strong> programación paralela y <strong>de</strong> computacióndistribuida se incluirían en cursos <strong>de</strong>arquitecturas y <strong>de</strong> programación, y posiblementepodría haber algún curso específico (representadoen rojo en la figura) para estudiarestos conceptos más en profundidad.• Algunos aspectos algorítmicos <strong>de</strong>l paralelismo(representados en amarillo) se incluirían en elúltimo semestre común, posiblemente <strong>de</strong>ntro <strong>de</strong>algún curso <strong>de</strong> programación o <strong>de</strong> concurrencia.• En las cinco especializaciones (Ingeniería <strong>de</strong>Computadores, Ingeniería <strong>de</strong>l Software, Computación,Tecnología <strong>de</strong> la Información y Sis-<strong>JP2011</strong>-590


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011temas <strong>de</strong> Información) se incluirían aspectosdistintos <strong>de</strong> paralelismo, con diferentes orientacionessegún la especialidad:– En la intensificación <strong>de</strong> Ingeniería <strong>de</strong> Computadoresincluiríamos especialización en arquitecturasparalelas, herramientas <strong>de</strong> programacióncentradas en la explotación <strong>de</strong>sistemas paralelos, y algunos aspectos <strong>de</strong>programación y metodologías, principalmentecentrados en la aplicación <strong>de</strong> la supercomputacióna la solución eficiente <strong>de</strong> problemascientíficos, y una parte <strong>de</strong>dicada a laintegración <strong>de</strong> distintos aspectos <strong>de</strong>l paralelismo,por ejemplo a la planificación e implementación<strong>de</strong> la organización física y lógica <strong>de</strong>un laboratorio <strong>de</strong> supercomputación.– El énfasis en la especialidad <strong>de</strong> Ingeniería<strong>de</strong>l Software se pondría en el estudio <strong>de</strong>herramientas para computación distribuiday gestión <strong>de</strong> la web, y en la tecnología ymetodología <strong>de</strong> la programación paralela.– En la intensificación <strong>de</strong> Computación se estudiaríanalgunos aspectos algorítmicos <strong>de</strong> laprogramación paralela.– En la especialidad <strong>de</strong> Tecnologías <strong>de</strong> la Informaciónse tratarían algunos aspectos tecnológicos<strong>de</strong> la computación distribuida, especialmente<strong>de</strong>s<strong>de</strong> el punto <strong>de</strong> vista <strong>de</strong> lossistemas, pero también con algunos aspectoslógicos.– Finalmente, en la intensificación <strong>de</strong> Sistemas<strong>de</strong> Información se estudiarían algunos aspectos<strong>de</strong> los sistemas distribuidos y la programaciónparalela, principalmente estudiando laintegración <strong>de</strong> diferentes tópicos, pero sin laimplementación física propia <strong>de</strong> la especialidad<strong>de</strong> Ingeniería <strong>de</strong> Computadores.A continuación resumimos y comentamos brevementela situación en nuestras cuatro universida<strong>de</strong>s.<strong>La</strong>s figuras 2 (Granada), 3 (<strong>La</strong> <strong>La</strong>guna), 4 (Murcia)y 5 (Politécnica <strong>de</strong> Valencia) muestran unavisión aproximada <strong>de</strong> la situación <strong>de</strong>l paralelismoen los planes <strong>de</strong> estudio <strong>de</strong>l GII en estas universida<strong>de</strong>s.Los planes <strong>de</strong> estudios están ya aprobados,pero en el curso 2010/2011 se han puesto en marchaúnicamente el primer o los dos primeros cursos <strong>de</strong> losestudios <strong>de</strong> grado, por lo que las figuras representansólo una aproximación a la realidad, pues la profundidada la que se tratará cada tópico <strong>de</strong>pen<strong>de</strong> <strong>de</strong> unaserie <strong>de</strong> factores y no pue<strong>de</strong> conocerse hasta que esténimplantados todos los cursos. <strong>La</strong>s figuras las hemosgenerado a partir <strong>de</strong> los planes <strong>de</strong> estudio, y consultandoa profesores y <strong>de</strong>partamentos que han participadoen la elaboración <strong>de</strong> los planes y que seránlos responsables <strong>de</strong> la impartición <strong>de</strong> los temas relacionadoscon el paralelismo una vez se hayan puestoen marcha todas las asignaturas.Comparamos nuestra propuesta con la situaciónen las cuatro universida<strong>de</strong>s:• Todas las universida<strong>de</strong>s incluyen conceptos <strong>de</strong>Fig. 2. Organización <strong>de</strong> contenidos <strong>de</strong> Computación Paralelaen el Grado en Ingeniería Informática en la <strong>Universidad</strong><strong>de</strong> Granada.Fig. 3. Organización <strong>de</strong> contenidos <strong>de</strong> Computación Paralelaen el Grado en Ingeniería Informática en la <strong>Universidad</strong><strong>de</strong> <strong>La</strong> <strong>La</strong>guna.computación paralela en asignaturas <strong>de</strong> tecnologíay arquitectura <strong>de</strong> or<strong>de</strong>nadores, empezandoen el segundo año <strong>de</strong> los estudios.• <strong>La</strong> situación es muy diferente en las asignaturas<strong>de</strong> programación, don<strong>de</strong> la programación secuencialno se estudia siempre junto con conceptos<strong>de</strong> programación paralela, y cuando seincluye programación paralela es normalmentesólo en un semestre y al final <strong>de</strong> los cursos comunes.En las universida<strong>de</strong>s <strong>de</strong> Granada, <strong>La</strong><strong>La</strong>guna y Politécnica <strong>de</strong> Valencia se estudian algunosaspectos <strong>de</strong> programación paralela <strong>de</strong>ntro<strong>de</strong> asignaturas generales <strong>de</strong> programación, en lossemestres tercero (Granada), quinto (Valencia)o sexto (<strong>La</strong> <strong>La</strong>guna).• <strong>La</strong> mayoría <strong>de</strong> las universida<strong>de</strong>s incluyen enel segundo curso <strong>de</strong>l GII alguna asignaturaespecífica sobre computación paralela o distribuida,don<strong>de</strong> se estudian los conceptos básicos<strong>de</strong> la concurrencia, sistemas distribuidos y paralelosy herramientas. <strong>La</strong> única universidad queincluye una cierta orientación <strong>de</strong> metodología<strong>JP2011</strong>-591


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 4. Organización <strong>de</strong> contenidos <strong>de</strong> Computación Paralelaen el Grado en Ingeniería Informática en la <strong>Universidad</strong><strong>de</strong> Murcia.programación paralela en Granada y Murcia.• En la <strong>Universidad</strong> Politécnica <strong>de</strong> Valencia se incluyentópicos <strong>de</strong> programación paralela en la intensificación<strong>de</strong> Computación, don<strong>de</strong> se estudiannociones <strong>de</strong> computación distribuida y <strong>de</strong> herramientas<strong>de</strong> programación paralela. Al contrario<strong>de</strong> lo que proponemos, no se incluyen tópicos <strong>de</strong>algoritmos paralelos. <strong>La</strong> única universidad queincluye algunos aspectos <strong>de</strong> algoritmos paralelosen esta intensificación es la <strong>de</strong> <strong>La</strong> <strong>La</strong>guna.• En la intensificación <strong>de</strong> Tecnologías <strong>de</strong> la Informaciónse tratan algunos aspectos <strong>de</strong> computacióndistribuida, con más énfasis en sistemas(Murcia) o en aspectos lógicos (Granaday <strong>La</strong> <strong>La</strong>guna). <strong>La</strong> <strong>Universidad</strong> <strong>de</strong> Granadatambién incluye un módulo <strong>de</strong> integración <strong>de</strong> aspectosfísicos y lógicos <strong>de</strong>l paralelismo.• <strong>La</strong>s universida<strong>de</strong>s <strong>de</strong> Granada y <strong>La</strong> <strong>La</strong>guna incluyenen la intensificación <strong>de</strong> Sistemas <strong>de</strong> Informaciónlos mismos tópicos <strong>de</strong> computacióndistribuida que en la <strong>de</strong> Tecnologías <strong>de</strong> la Información.IV. Tópicos <strong>de</strong> paralelismo en la propuesta<strong>de</strong>l IEEE TCPPFig. 5. Organización <strong>de</strong> contenidos <strong>de</strong> Computación Paralelaen el Grado en Ingeniería Informática en la <strong>Universidad</strong>Politécnica <strong>de</strong> Valencia.<strong>de</strong> la programación paralela es la <strong>de</strong> Granada.<strong>La</strong> <strong>Universidad</strong> <strong>de</strong> <strong>La</strong> <strong>La</strong>guna incluye estostópicos en un curso <strong>de</strong> programación en el sextosemestre.• <strong>La</strong> <strong>Universidad</strong> <strong>de</strong> Granada es la única que incluyealgunos aspectos <strong>de</strong> algoritmos paralelosen los cursos comunes.• Todas las universida<strong>de</strong>s incluyen intensificaciónen arquitecturas paralelas y herramientas <strong>de</strong>programación paralela en la especialidad <strong>de</strong> Ingeniería<strong>de</strong> Computadores, pero ninguna incluyeun módulo <strong>de</strong>dicado a integrar los diferentes aspectos<strong>de</strong>l paralelismo. En la <strong>Universidad</strong> <strong>de</strong>Murcia se contemplan algunos aspectos <strong>de</strong> programaciónparalela, y en la Politécnica <strong>de</strong> Valenciase intensifica en programación paralela ysus aplicaciones.• En las universida<strong>de</strong>s <strong>de</strong> Granada, <strong>La</strong> <strong>La</strong>guna yMurcia se incluyen tópicos <strong>de</strong> computación paralelaen la intensificación <strong>de</strong> Ingeniería <strong>de</strong>l Software,y los tópicos que se tratan correspon<strong>de</strong>na programación distribuida en las tres universida<strong>de</strong>s,y adicionalmente <strong>de</strong> metodología <strong>de</strong> laEn esta sección analizamos la inclusión en losplanes <strong>de</strong> estudio <strong>de</strong>l GII <strong>de</strong> los diferentes tópicos quese incluyen en la propuesta <strong>de</strong>l IEEE TCPP sobrela computación paralela en estudios <strong>de</strong> informática.<strong>La</strong> propuesta <strong>de</strong>l TCPP analiza una gran cantidad<strong>de</strong> tópicos, y para nuestro análisis se han agrupadoalgunos tópicos, <strong>de</strong> manera que se generan tablasmás pequeñas. Para cada uno <strong>de</strong> los tópicos analizamossi se trata en las asignaturas comunes <strong>de</strong>lGII, y con qué profundidad se trata. Volvemos aseñalar que nuestras conclusiones son muy subjetivas,pues la mayoría <strong>de</strong> las asignaturas no se estánimpartiendo todavía. También analizamos la intensificaciónen cada uno <strong>de</strong> los tópicos que se realiza encada una <strong>de</strong> las especialida<strong>de</strong>s. Al igual que se haceen la propuesta <strong>de</strong>l TCPP, agrupamos los tópicosen Arquitectura, Programación, Algoritmos y TemasTransversales. El análisis se resume en las figuras 6(Arquitectura), 7 (Programación), 8 (Algoritmos) y9 (Temas Transversales), don<strong>de</strong> los tópicos aparecenen inglés por su correspon<strong>de</strong>ncia con la propuesta <strong>de</strong>lTCPP. En todas las figuras, los colores ver<strong>de</strong>, amarilloy rojo representan la profundidad con la que setrata cada uno <strong>de</strong> los tópicos en las asignaturas comunes.Ver<strong>de</strong> significa que el tópico es una partecentral <strong>de</strong> alguna asignatura común, amarillo indicaque el tópico se trata en alguna asignatura común,pero que no es parte central <strong>de</strong> ninguna, y rojo indicaque no se incluye en ninguna <strong>de</strong> las asignaturas comunes.Para los tópicos que se tratan someramente(amarillo) se indican las especialida<strong>de</strong>s en las quese estudian en más profundidad. En nuestra propuesta,cuando se incluye un tópico en una intensificación<strong>de</strong>be tratarse como parte central en algunaasignatura (C, <strong>de</strong> core). Para cada universidad, se indicapara cada tópico tratado en una intensificación<strong>JP2011</strong>-592


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011si se trata en profundidad en alguna asignatura (C),o si no se profundiza en él (N, <strong>de</strong> non-core).Fig. 8. Tópicos <strong>de</strong> Algoritmos en el Grado <strong>de</strong> IngenieríaInformática.Fig. 6. Tópicos <strong>de</strong> Arquitectura en el Grado <strong>de</strong> IngenieríaInformática.Fig. 9. Tópicos <strong>de</strong> temas transversales en el Grado <strong>de</strong> IngenieríaInformática.Fig. 7. Tópicos <strong>de</strong> Programación en el Grado <strong>de</strong> IngenieríaInformática.Comentamos los tópicos que aparecen en las figuras:• Pensamos que todos los tópicos <strong>de</strong> arquitecturasparalelas <strong>de</strong>ben tratarse en las asignaturas comunes,y prácticamente todos se tratan con lasuficiente profundidad en las cuatro universida<strong>de</strong>s.El único tópico que no se trata tan enprofundidad es el <strong>de</strong> Heterogeneidad.• Los tópicos básicos <strong>de</strong> programación paralela(nociones básicas <strong>de</strong> concurrencia,sincronización, hilos, comunicaciones,cliente/servidor, etc.) <strong>de</strong>berían tratarse enprofundidad en asignaturas obligatorias, juntocon algunas herramientas <strong>de</strong> programaciónparalela tanto <strong>de</strong> memoria compartida como<strong>de</strong> paso <strong>de</strong> mensajes, y algunos conceptos<strong>de</strong> medidas <strong>de</strong> prestaciones. El resto <strong>de</strong> lostópicos <strong>de</strong> programación también se trataríanen asignaturas obligatorias, pero en menorprofundidad. En todas las universida<strong>de</strong>s seintensifica suficientemente en estos tópicos enla especialidad <strong>de</strong> Ingeniería <strong>de</strong> Computadores,pero la única universidad que parece cubrirnuestra propuesta en las asignaturas comuneses la <strong>de</strong> Granada, mientras que la situación enel resto <strong>de</strong> universida<strong>de</strong>s está lejos <strong>de</strong> lo queconsi<strong>de</strong>ramos <strong>de</strong>seable.• <strong>La</strong> situación en cuanto a los tópicos <strong>de</strong> algoritmoses incluso peor. Consi<strong>de</strong>ramos que todosestos tópicos <strong>de</strong>ben ser obligatorios para todoslos estudiantes, y que la mayoría <strong>de</strong> ellos <strong>de</strong>beríantratarse en profundidad. Muchos <strong>de</strong> estostópicos no se tratan en las asignaturas comunesen nuestras universida<strong>de</strong>s, y la propuesta quehacemos para las especialida<strong>de</strong>s se cubre sóloparcialmente. <strong>La</strong>s universida<strong>de</strong>s <strong>de</strong> Granada,Murcia y Politécnica <strong>de</strong> Valencia incluyen estostópicos en la especialidad <strong>de</strong> Ingeniería <strong>de</strong> Computadores,y las <strong>de</strong> Granada y Murcia tambiénlos incluyen en la <strong>de</strong> Ingeniería <strong>de</strong>l Software. <strong>La</strong>única universidad que trata estos temas en la especialidad<strong>de</strong> Computación es la <strong>de</strong> <strong>La</strong> <strong>La</strong>guna.• <strong>La</strong> situación en cuanto a temas transversales ogenerales es más diversa. Algunos tópicos <strong>de</strong>beríantratarse en profundidad en asignaturas<strong>JP2011</strong>-593


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011comunes, y <strong>de</strong> otros se podrían dar algunas i<strong>de</strong>asbásicas. Adicionalmente, proponemos intensificaciónen las especialida<strong>de</strong>s (excepto en la <strong>de</strong>Computación) en algunos <strong>de</strong> los que no se tratanen profundidad en los cursos comunes. En la<strong>Universidad</strong> Politécnica <strong>de</strong> Valencia la mayoría<strong>de</strong> los tópicos se tratan en profundidad en asignaturascomunes, y en las otras universida<strong>de</strong>sla mayoría <strong>de</strong> los tópicos que no consi<strong>de</strong>ramosfundamentales no aparecen en asignaturas comunes,pero se tratan en las especialida<strong>de</strong>s.V. Conclusiones y posibles colaboracionesEn este trabajo hemos realizado una revisión <strong>de</strong>los contenidos <strong>de</strong> computación paralela en los planes<strong>de</strong> estudio <strong>de</strong>l Grado en Ingeniería Informática encuatro universida<strong>de</strong>s (Granada, <strong>La</strong> <strong>La</strong>guna, Murciay Politécnica <strong>de</strong> Valencia), y se ha analizado eltratamiento previsible en las asignaturas comunesy en las distintas especialida<strong>de</strong>s <strong>de</strong> los diferentestópicos que se incluyen en la propuesta <strong>de</strong>l IEEETCPP. El estudio es parcial y aproximado: compren<strong>de</strong>sólo cuatro universida<strong>de</strong>s y se están impartiendoúnicamente el primero o los dos primeros cursos<strong>de</strong>l grado.Consi<strong>de</strong>ramos que la situación actual <strong>de</strong> la computación(que se ha convertido en paralela al ser paralelosloc componentes básicos <strong>de</strong> los sistemas computacionalesactuales), junto con la reorganización<strong>de</strong> los estudios universitarios <strong>de</strong> informática y laaparición <strong>de</strong> la propuesta <strong>de</strong>l IEEE TCPP, hace quesea conveniente repensar cómo y qué contenidos <strong>de</strong>computación paralela se <strong>de</strong>ben incluir en los planes<strong>de</strong> estudio <strong>de</strong>l GII. Hemos i<strong>de</strong>ntificado algunas <strong>de</strong>ficiencias(en nuestra opinión) <strong>de</strong> la planificación <strong>de</strong> lacomputación paralela en los estudios <strong>de</strong> informáticaen España, y realizamos algunas propuestas paracorregir esas <strong>de</strong>ficiencias.Nuestro análisis es parcial, aproximado y sesgado(nuestro punto <strong>de</strong> vista está condicionado por lo quecada uno <strong>de</strong> nosotros enten<strong>de</strong>mos como computaciónparalela), por lo que proponemos a otros profesoresque puedan estar interesados en la docencia <strong>de</strong>l paralelismoque compartan su experiencia con nosotros,por ejemplo, corrigiendo nuestra visión <strong>de</strong> la organización<strong>de</strong> la docencia <strong>de</strong> la computación paralela enlas universida<strong>de</strong>s analizadas, haciendo propuestas <strong>de</strong>modificación <strong>de</strong> nuestra propuesta, haciendo análisissimulares para otras universida<strong>de</strong>s, etc. <strong>La</strong> finalidad<strong>de</strong> este trabajo es propiciar la discusión (y consecuentementela mejora) sobre cómo enseñar computaciónparalela, <strong>de</strong> manera que formemos a nuestrosalumnos para trabajar con el tipo <strong>de</strong> sistemascon los que se van a encontrar al acabar sus estudios.Este trabajo ha sido parcialmente financiado porla Consejería <strong>de</strong> Educación <strong>de</strong> la Región <strong>de</strong> Murcia(Fundación Séneca, 08763/PI/08) y por el Ministerio<strong>de</strong> Ciencia e Innovación (TIN2008-06570-C04).Queremos agra<strong>de</strong>cer a los compañeros <strong>de</strong> los distintos<strong>de</strong>partamentos <strong>de</strong> informática <strong>de</strong> las universida<strong>de</strong>s<strong>de</strong> Granada, <strong>La</strong> <strong>La</strong>guna, Murcia y Politécnica<strong>de</strong> Valencia que nos han asesorado en la i<strong>de</strong>ntificación<strong>de</strong> las asignaturas don<strong>de</strong> se tratan o tratarán losdistintos tópicos que aparecen en la propuesta <strong>de</strong>lTCPP.Referencias[1] IEEE Technical Committee on Parallel Processing,http://tcpp.cs.gsu.edu/.[2] Francisco Almeida, Domingo Giménez, José Miguel Mantasy Antonio M. Vidal, Introducción a la programaciónparalela, Paraninfo Cengage Learning, 2008.[3] Domingo Giménez, Francisco Almeida, José Miguel Mantasy Antonio M. Vidal, “Sobre la situación <strong>de</strong> la programaciónparalela en los grados <strong>de</strong> informática,” ReVisión:Revista Hispanoamericana <strong>de</strong> Educación Universitaria <strong>de</strong>la Informática, vol. 3, no. 1, pp. 11–21, 2010.[4] Francisco Almeida, Domingo Giménez, José-Miguel Mantasand Antonio M. Vidal, “On the integration ofthe Curriculum Initiative on Parallel and DistributedComputing in the Spanish university system,” inFirst NSF/TCPP Workshop on Parallel and DistributedComputing Education (EduPar-11), 2011.[5] David J. Me<strong>de</strong>r, Victor Pankratius and Walter F.Tichy, http://www.multicore-systems.org/separs/downloads/GI-WG-SurveyParallelismCurricula.pdf,2008.[6] G. Brassard and P. Bratley, Fundamentals of Algorithms,Prentice-Hall, 1996.[7] Thomas H. Cormen, Charles E. Leiserson and Ronald L.Rivest, Introduction to Algorithms, The MIT Press, 1990.[8] ACM, Curricula recommendations, http://www.acm.org/education/curricula-recommendations.Agra<strong>de</strong>cimientos<strong>JP2011</strong>-594


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Experiencias en Docencia <strong>de</strong> Diseño yEvaluación <strong>de</strong> ConfiguracionesA.M. Mora, P. García-Sánchez, P.A. Castillo, M.G. Arenas, J.J. Merelo, J. Ortega 1Resumen— El presente trabajo expone las experienciasdocentes <strong>de</strong> los profesores <strong>de</strong> la asignatura Diseñoy Evaluación <strong>de</strong> Configuraciones (optativa <strong>de</strong> las IngenieríasTécnicas en Informática en la <strong>Universidad</strong> <strong>de</strong>Granada), durante los últimos cinco años. Dicha asignaturaestá encuadrada <strong>de</strong>ntro <strong>de</strong>l área <strong>de</strong> Arquitecturay Tecnología <strong>de</strong> Computadores y tiene como objetivomostrar una metodología para la evaluación <strong>de</strong>prestaciones (o rendimiento) <strong>de</strong> un computador. Sedivi<strong>de</strong>, a gran<strong>de</strong>s rasgos, en tres partes: la primer <strong>de</strong>dicadaa los monitores (encargados <strong>de</strong> medir la carga<strong>de</strong> un or<strong>de</strong>nador), la segunda enfocada a la mejora <strong>de</strong>prestaciones (<strong>de</strong> un equipo informático), y la última<strong>de</strong>dicada a la reproducción <strong>de</strong> la carga <strong>de</strong> un computador(los llamados benchmarks). Del mismo modo, enel artículo se presentan una serie <strong>de</strong> herramientas utilizadaspara gestionar dicha asignatura, así como parafacilitar, tanto a los alumnos, como al profesor, todaslas tareas propias <strong>de</strong> la misma.Palabras clave— Diseño y Evaluación <strong>de</strong> Configuraciones,Docencia, Benchmark, Monitor, Rendimiento,Profiler, Wiki, BlogI. IntroducciónLA asignatura Diseño y Evaluación <strong>de</strong> Configuracionestiene como objeto <strong>de</strong> estudio los sistemasinformáticos, es <strong>de</strong>cir, cualquier sistema queuse medios informáticos, abarcando, todos los sistemassituados en diferentes niveles <strong>de</strong>l mo<strong>de</strong>lo <strong>de</strong>capas OSI [12]: <strong>de</strong>s<strong>de</strong> la más baja, la física, hasta lamás alta, la <strong>de</strong> aplicación; junto con las diferentes capas<strong>de</strong> un sistema operativo. Des<strong>de</strong> el punto <strong>de</strong> vista<strong>de</strong> esta asignatura, un sistema pue<strong>de</strong> ser tanto unchip, una tarjeta <strong>de</strong> red, o una red completa, comoun programa que ofrezca servicios en esa red, o elprograma junto con todo el sistema necesario paraejecutarse.Durante el ciclo <strong>de</strong> vida <strong>de</strong> un sistema informático,resulta muchas veces necesario evaluar sus prestacioneso rendimiento, habitualmente con el objetivo<strong>de</strong> mejorarlas o bien <strong>de</strong> comparar diversos sistemasinformáticos entre sí. Esa evaluación <strong>de</strong> prestacionesse <strong>de</strong>be hacer <strong>de</strong> forma objetiva, a fin <strong>de</strong> po<strong>de</strong>r comparardistintos valores a lo largo <strong>de</strong>l tiempo o bienel mismo valor para diversos sistemas informáticos.Tales mediciones pue<strong>de</strong>n servir también para i<strong>de</strong>ntificarlos problemas que tiene un sistema informático,con el objetivo <strong>de</strong> solucionarlos.Esta asignatura se ha convertido en los últimosaños en una <strong>de</strong> las más exitosas en cuanto al número<strong>de</strong> alumnos matriculados <strong>de</strong>ntro <strong>de</strong> las asignaturasoptativas <strong>de</strong> las Ingenierías Técnicas Informáticas enla <strong>Universidad</strong> <strong>de</strong> Granada. Gran parte <strong>de</strong> su éxito1 Departamento <strong>de</strong> Arquitectura <strong>de</strong> Computadores.ETSIIT, CITIC. <strong>Universidad</strong> <strong>de</strong> Granada. e-mail:{amorag,fergu,pedro,mgarenas,jmerelo}@geneura.ugr.es,julio@atc.ugr.esse basa tanto en la novedosa forma <strong>de</strong> evaluación alos alumnos, no fundamentada en exámenes, sino ensu trabajo en clase, como en la orientación que se hadado a la misma, primando la parte práctica sobrela teórica. Otro factor relevante ha sido la forma<strong>de</strong> trabajo, centrada en el uso <strong>de</strong> herramientas webampliamente conocidas y extendidas, a la par quellamativas para los alumnos (como Sistemas web <strong>de</strong>ayuda a la docencia, Wikis, Blogs o Foros).En este trabajo <strong>de</strong>tallareos la estrategia <strong>de</strong> evaluación,así como el modo <strong>de</strong> funcionamiento e integración<strong>de</strong> las herramientas en la asignatura.II. Diseño y Evaluación <strong>de</strong> ConfiguracionesEn esta sección se <strong>de</strong>scriben los temas teóricos yprácticos <strong>de</strong> la asignatura.A. TeoríaA.1 Tema 1: Sistemas informáticos y su evaluación.En este primer tema se analizan las diferentesmagnitu<strong>de</strong>s observables <strong>de</strong> un sistema informático ycomo se pue<strong>de</strong>n medir, con una serie <strong>de</strong> ejemplos queindican como se hace en diversos sistemas operativos,como UNIX y Windows.Inicialmente se realiza una introducción a los sistemasinformáticos y las fases en la evaluación <strong>de</strong>estos sistemas. El siguiente apartado explica cómoelegir las métricas [7] <strong>de</strong> prestaciones y las distintastécnicas <strong>de</strong> evaluación. El último apartado <strong>de</strong>este tema explica cómo monitorizar la carga <strong>de</strong> unsistema y explica varias formas <strong>de</strong> hacerlo utilizandovarios monitores, tanto para monitorizar el hardware(ver Figura 1), como el software (mediante un profiler)[6].A.2 Tema 2: Representación gráfica <strong>de</strong> las prestaciones<strong>de</strong> los sistemas.Para presentar y analizar los resultados obtenidos<strong>de</strong> la ejecución <strong>de</strong> un monitor sobre un sistema,o una comparativa entre varios sistemas, normalmentese usa algún tipo <strong>de</strong> gráfico, como por ejemplográficos <strong>de</strong> barras <strong>de</strong> evolución temporal (las llamadasstrip chart). Más habitualmente, para resumirel rendimiento <strong>de</strong> todo el sistema se suele usarun diagrama <strong>de</strong> Gantt [11], [4], o bien un gráfico <strong>de</strong>Kiviatt [4].En esta parte <strong>de</strong> la asignatura también se explicanalgunos <strong>de</strong> los errores comunes en la representacióngráfica <strong>de</strong> resultados, así como unas reglas y consejospara realizar dichas representaciones gráficas.<strong>JP2011</strong>-595


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 1.Monitor <strong>de</strong> Windows NT. Este monitor da información <strong>de</strong>l sistema en tiempo real.A.3 Tema 3: Mejora <strong>de</strong> prestaciones.Este tema está principalmente <strong>de</strong>dicado a examinarqué elementos pue<strong>de</strong>n fallar (o estar sujetos aerror) en un equipo informático [5], principalmenteUnix o Windows NT, qué herramientas se usan parael diagnóstico, y una vez diagnosticado, qué medidashay que tomar para mejorar las prestaciones.• Gestión <strong>de</strong> carga y prestaciones en el sistemaoperativo• Políticas <strong>de</strong> gestión <strong>de</strong>l sistema• Mejora <strong>de</strong> prestaciones <strong>de</strong> la CPU• Sintonización <strong>de</strong> la memoria• Mejora <strong>de</strong> prestaciones en entrada/salida• Optimización <strong>de</strong> un servidor webA.4 Tema 4: Caracterización <strong>de</strong> la carga: benchmarks.En este tema se explica qué es lo que se tiene quetener en cuenta para medir la carga <strong>de</strong> un equipo, yqué es un benchmark [6], el cual es un programa oconjunto <strong>de</strong> programas que evalúan las prestaciones<strong>de</strong> un sistema informático, reproduciendo una carga<strong>de</strong> trabajo genérica o específica en dicho sistema informático.Al proceso <strong>de</strong> comparar dos o más sistemasmediante la obtención <strong>de</strong> medidas se le <strong>de</strong>nominabenchmarking.En general, para evaluar las prestaciones <strong>de</strong> unsistema informático es necesario conocer y caracterizarpreviamente cuál es la carga <strong>de</strong> trabajo, comose habrá visto en temas anteriores. Sin embargo, enmuchos casos tal carga no se conoce <strong>de</strong> antemano,es difícil <strong>de</strong> caracterizar o es suficientemente ampliacomo para consi<strong>de</strong>rarla una carga genérica.En esta sección se explican los pasos para diseñar oescoger un buen benchmark, siguiendo lo propuestopor [10], así como los tipos que existen y las métricasy errores más comunes. Finalmente se presentan algunosejemplos <strong>de</strong> benchmarks, como son los propuestospor la SPEC 1 (Standard Performance EvaluationCorporation) o LINPACK, que son los utilizadospara medir la lista <strong>de</strong> los computadores máspotentes o Top 500 2 .B. PrácticasEsta sección explica las distintas prácticas que losalumnos <strong>de</strong>ben realizar para superar la asignatura.Por regla general, para realizar estas prácticas hayque seguir la metodología <strong>de</strong> la asignatura, es <strong>de</strong>cirproponer un objetivo, hacer medidas, diagnosticar,proponer una solución, volver a tomar medidas, ycomparar el sistema viejo con el sistema nuevo.B.1 Práctica 1: Búsqueda <strong>de</strong> recursos relacionadoscon la asignatura.Esta primera práctica consiste en buscar sitios webo referencias bibliográficas (libros, revistas, artículos,noticias, etc) o cualquier otra fuente don<strong>de</strong> se puedaencontrar información útil relacionada con los temastratados en la asignatura.B.2 Práctica 2: Instalación y configuración <strong>de</strong> sistemas<strong>de</strong> medición <strong>de</strong> prestaciones.Utilizando los recursos <strong>de</strong> la práctica anterior, estapráctica consiste en <strong>de</strong>scargar <strong>de</strong> Internet monitores(<strong>de</strong> prestaciones), y configurarlos e instalarlos paramedir las prestaciones <strong>de</strong>l or<strong>de</strong>nador personal <strong>de</strong>lalumno o bien <strong>de</strong> los or<strong>de</strong>nadores <strong>de</strong> las aulas <strong>de</strong>prácticas.B.3 Práctica 3: Uso <strong>de</strong> un profiler.Se hará uso <strong>de</strong> uno <strong>de</strong> estas herramientas paraevaluar las prestaciones <strong>de</strong> un programa propio re-1 http://www.spec.org2 http://www.netlib.org/benchmark/top500.html<strong>JP2011</strong>-596


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011alizado en cualquier lenguaje, y ver en qué puntosse está empleando más tiempo, para que, a partir <strong>de</strong>ahí, se busquen modos <strong>de</strong> mejorarlo. Se tendrá quebuscar cómo configurarlo, como hacerlo funcionar, yfinalmente, usarlo. <strong>La</strong> Figura 2 muestra la ejecución<strong>de</strong> un profiler sobre un programa Java realizado porun alumno.B.4 Práctica 4: Uso <strong>de</strong> programas <strong>de</strong> monitorización<strong>de</strong> un sistema.Esta práctica consiste en la <strong>de</strong>finición <strong>de</strong> unacarga computacional, y la utilización <strong>de</strong> herramientas<strong>de</strong> monitorización <strong>de</strong>l sistema para visualizar cómoejercita al sistema esas cargas. Estas herramientaspresentan medidas <strong>de</strong>l mismo en tiempo real,permitiendo medir y cuantificar su carga, medir suevolución y pre<strong>de</strong>cir su comportamiento. <strong>La</strong> herramienta<strong>de</strong> monitorización la elegirá el alumno enfunción <strong>de</strong> lo hecho en otras prácticas (especialmentela segunda) y <strong>de</strong> su a<strong>de</strong>cuación para las magnitu<strong>de</strong>sque <strong>de</strong>see medir.B.5 Práctica 5: Mejora <strong>de</strong> las prestaciones <strong>de</strong> unsistema.Se trata <strong>de</strong> poner en práctica lo aprendido en elTema 3 <strong>de</strong> la asignatura sobre mejora <strong>de</strong> prestaciones<strong>de</strong> sistemas informáticos y aplicarlo a un caso <strong>de</strong>terminado.Por ejemplo, modificar un programa paraque consuma menos recursos o cambiar la configuración<strong>de</strong> un servidor web para que procese mejor lacola <strong>de</strong> peticiones. Una vez establecido el objetivo, setomarán medidas <strong>de</strong>, al menos, un aspecto, antes <strong>de</strong>realizar ningún tipo <strong>de</strong> diagnóstico, con la carga <strong>de</strong>trabajo con la que se vaya a hacer la práctica. Ésteserá el sistema base. En función <strong>de</strong> esto, se <strong>de</strong>cidiráqué medidas tomar para mejorar las prestaciones <strong>de</strong>lsistema.B.6 Práctica 6: Programación <strong>de</strong> un benchmarkportable.En ella se hace énfasis en la programación in<strong>de</strong>pendiente<strong>de</strong> la máquina, y se trata <strong>de</strong>, utilizandoun lenguaje <strong>de</strong> alto nivel, comparar las prestaciones<strong>de</strong> diferentes máquinas o <strong>de</strong> la misma con diferentessistemas operativos. En resumen, el alumno realizaráun programa en un lenguaje <strong>de</strong> alto nivel que permitamedir y comparar las prestaciones <strong>de</strong> dos sistemas.Comparar, por ejemplo, diferentes equiposcon diferentes sistemas operativos, o el mismo equipocon dos sistemas operativos diferentes. Como entodas las prácticas, hay que establecer claramentecuál es el objetivo <strong>de</strong>l benchmark, obtener resultados,analizarlos, presentarlos y obtener un índiceque indique qué sistema es mejor para los objetivosplanteados.C. Evaluación<strong>La</strong> evaluación <strong>de</strong> la asignatura se realiza comosigue:• 1/6 <strong>de</strong> la nota será nota <strong>de</strong> clase (participaciónen activida<strong>de</strong>s y ejercicios <strong>de</strong> autoevaluación)• 2/6 <strong>de</strong> la nota correspon<strong>de</strong>rá a la media pon<strong>de</strong>rada(por sesiones) <strong>de</strong> la nota obtenida enprácticas• 3/6 <strong>de</strong> la nota será la correspondiente a un trabajofinal, entregado al término <strong>de</strong> las clases,que agrupará todo lo aprendido para evaluar ymejorar un sistema a elección <strong>de</strong>l alumno, pero<strong>de</strong> cierta ’entidad’Como se pue<strong>de</strong> ver, no existe ningún tipo <strong>de</strong> examena lo largo <strong>de</strong> la asignatura y únicamente sevalora el trabajo <strong>de</strong> los alumnos (tanto en clase,como en casa). Este tipo <strong>de</strong> evaluación resulta bastanteexitosa y, a tenor <strong>de</strong> lo <strong>de</strong>mostrado por losalumnos, éstos retienen gran parte <strong>de</strong> los contenidos(conocimientos adquiridos).III. Herramientas utilizadas en laasignaturaEsta asignatura ha sido pionera en varias facetas<strong>de</strong> compaginación <strong>de</strong> herramientas y utilida<strong>de</strong>s web<strong>de</strong>ntro <strong>de</strong> las clases, permitiendo, e incluso fomentandoel uso <strong>de</strong>l or<strong>de</strong>nador portátil en las aulas (llegandoincluso a proveer <strong>de</strong> varios <strong>de</strong> estos portátilesa los alumnos).El objetivo que se persigue es el <strong>de</strong> involucrarlosen mayor medida en las clases, haciendo que tomenapuntes y notas en un Wiki <strong>de</strong> la asignatura (páginaweb dinámica en la que se generan contenidos entrelos usuarios <strong>de</strong> la misma) (http://dyec-ugr.wikispaces.com/), que todos los <strong>de</strong>más (incluidoel profesor) podrán consultar y completar posteriormente.El uso <strong>de</strong> wikis en docencia ha sido estudiadopor [1], entre otros. De esta forma, el conocimientogenerado (siguiendo la filosofía <strong>de</strong> los wikis) va siendocada vez más completo y riguroso, uniendo a<strong>de</strong>más elpunto <strong>de</strong> vista que los alumnos le quieran dar parafacilitar su comprensión. Los alumnos encargados<strong>de</strong> estas labores reciben parte <strong>de</strong> la nota <strong>de</strong> participaciónen clase como premio.El profesor a<strong>de</strong>más, hace uso <strong>de</strong> dicho Wiki paraponer ejemplos y ejercicios, que los alumnos realizan,comentan y corrigen. Esta experiencia ha <strong>de</strong>mostradoser ampliamente aceptada en la comunida<strong>de</strong>studiantil, como pue<strong>de</strong> verse en [3], [2].Por otra parte, otro aspecto fomentado es lacreación <strong>de</strong> Blogs <strong>de</strong> alumnos, en los que se <strong>de</strong>scribanlas inquietu<strong>de</strong>s, intereses, enlaces y trabajos <strong>de</strong> losmismos en relación a la asignatura. Esto suele teneruna buena acogida, y <strong>de</strong> hecho, muchos siguen manteniendosu blog en a<strong>de</strong>lante. A<strong>de</strong>más, se insta a losalumnos a que hagan la entrega <strong>de</strong> sus prácticas enformato HTML (páginas web), pudiendo colgarlas enel futuro en un servidor web.<strong>La</strong> otra herramienta utilizada es SWAD: SistemaWeb <strong>de</strong> Apoyo a la Docencia (http://swad.ugr.es)[9], [8], una plataforma libre <strong>de</strong> teleformación <strong>de</strong>sarrolladay utilizada en la <strong>Universidad</strong> <strong>de</strong> Granada enlos últimos 11 cursos académicos. SWAD integra diversasfunciones <strong>de</strong> apoyo al aprendizaje, a la docenciay a la gestión <strong>de</strong> los datos <strong>de</strong> los estudiantes. Entreellas el acceso a información sobre las asignaturas<strong>JP2011</strong>-597


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 2.Captura <strong>de</strong> pantalla <strong>de</strong>l profiler para Java incluido en el editor NetBeans.(guía docente, horarios, bibliografía,...), la <strong>de</strong>scarga<strong>de</strong> documentos (transparencias, relaciones <strong>de</strong> problemas),las listas y fichas <strong>de</strong> alumnos y profesores, losforos <strong>de</strong> discusión, la asignación <strong>de</strong> activida<strong>de</strong>s, laautoevaluación mediante exámenes interactivos o laconsulta individual <strong>de</strong> calificaciones.En dicha plataforma se hace el seguimiento <strong>de</strong> losalumnos, la publicación <strong>de</strong> los temarios y guiones<strong>de</strong> prácticas, la entrega <strong>de</strong> ejercicios, trabajos yprácticas, y la publicación (con consulta individual)<strong>de</strong> la notas.Respecto al software a utilizar en la asignatura,todo el propuesto y presentado en secciones anterioreses software libre (o tiene alternativa libre), <strong>de</strong>hecho se fomenta también la búsqueda <strong>de</strong> nuevas utilida<strong>de</strong>s<strong>de</strong> libre distribución, con lo que el coste parael alumno es nulo.Todas estas herramientas y las peculiarida<strong>de</strong>s oventajas <strong>de</strong>l sistema <strong>de</strong> evaluación, hacen <strong>de</strong> la asignaturauna <strong>de</strong> las más populares entre las optativas,contando generalmente con un gran número <strong>de</strong> alumnosen cada curso académico.IV. Conclusiones y Trabajos FuturosEn este trabajo se ha presentado la asignaturaDiseño y Evaluación <strong>de</strong> Configuraciones (optativa <strong>de</strong>las Ingenierías Técnicas en Informática en la <strong>Universidad</strong><strong>de</strong> Granada), encuadrada <strong>de</strong>ntro <strong>de</strong>l área <strong>de</strong>Arquitectura y Tecnología <strong>de</strong> Computadores.En este trabajo se <strong>de</strong>tallan los temarios teóricos yprácticos <strong>de</strong> la misma, así como las estrategias docentesutilizadas en su impartición en los últimos cursos.Con la entrada <strong>de</strong> los títulos <strong>de</strong> Grado, esta asignaturaacabará extinguiéndose, para dar entradaa dos asignaturas directamente relacionadas, Ingeniería<strong>de</strong> Servidores y Servidores Web <strong>de</strong> AltasPrestaciones, en las cuales se espera po<strong>de</strong>r utilizarlas mismas herramientas y aplicar las estrategias docentesque hemos presentado.Agra<strong>de</strong>cimientosEste trabajo se ha llevado a cabo <strong>de</strong>ntro <strong>de</strong> losproyectos TIC-3903 <strong>de</strong> la Junta <strong>de</strong> Andalucía y CEIBioTIC GENIL (CEB09-0010) <strong>de</strong>l Programa CEI <strong>de</strong>lMICINN (PYR-2010-13).Referencias[1] Bergin, J. Teaching on the wiki web. En ITiCSE ’02:Proceedings of the 7th annual conference on Innovationand technology in computer science education, pages 195–195, New York, NY, USA, 2002. ACM Press.[2] Merelo-Guervós, J.J. Castillo, P.A. y Priento, A. Integración<strong>de</strong> una asignatura en Internet: el caso <strong>de</strong> Diseño yEvaluación <strong>de</strong> Configuraciones. En <strong>Actas</strong> JENUI´01, VIIJornadas <strong>de</strong> Enseñanza Universitaria <strong>de</strong> la Informática,2001.[3] Merelo, J.J., Hassan-Montero, C., Tricas, F. y Jiménez,J.L. Anonym: SWECAI: Sistema web centrado en elalumno inteligente. En <strong>Actas</strong> <strong>de</strong> las XIII Jornadas <strong>de</strong>Enseñanza Universitaria <strong>de</strong> Informática (JENUI), pages1–2, 2007.[4] Jain, R. The art of computer systems performance analysis:techniques for experimental <strong>de</strong>sign, measurement,simulation, and mo<strong>de</strong>ling, volume 491. Wiley New York,1991.[5] Lilja, D.J. Measuring Computer Performance. CambridgeUniversity Press United Kingdom;, 2000.[6] Louki<strong>de</strong>s, M.K. System performance tuning. O’Reilly &Associates, Inc. Sebastopol, CA, USA, 1996.[7] Molero, X., Juiz,C., y Ro<strong>de</strong>ño, J. Evaluación y mo<strong>de</strong>lado<strong>de</strong>l rendimiento <strong>de</strong> los sistemas informáticos. Pearson Education,2004.[8] Cañas, A. Díaz, A.F. y Priento, A. Sistema <strong>de</strong> serviciosweb <strong>de</strong> apoyo a la docencia y gestión <strong>de</strong> una asignatura.<strong>Actas</strong> <strong>de</strong> las VIII Jornadas <strong>de</strong> Enseñanza Universitaria<strong>de</strong> la Informática (JENUI’2002), 2002.[9] Cañas, A. y Ortigosa, E.M. y Aragón, Y. <strong>La</strong> plataformaSWAD como recurso docente para la innovación educativa.En Congreso internacional sobre el profesoradoante el reto <strong>de</strong> las nuevas tecnologías en la sociedad <strong>de</strong>lconocimiento, 1235.[10] Puigjaner, R., Serrano, J.J. y Rubio, A. Evaluación yexplotación <strong>de</strong> sistemas informáticos. Síntesis, 1993.[11] Wikipedia. Diagrama <strong>de</strong> gantt.http://es.wikipedia.org/wiki/Diagrama <strong>de</strong> Gantt.[12] Zimmermann, H. Osi reference mo<strong>de</strong>l. IEEE Transactionson Communications, 28(4):425–432, April 1980.<strong>JP2011</strong>-598


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Diseño <strong>de</strong> un cluster <strong>de</strong> computadores comoactividad para Arquitectura <strong>de</strong> ComputadoresF. Javier Fernán<strong>de</strong>z-Baldomero 1 y Mancia Anguita 1Resumen— Esta contribución <strong>de</strong>scribe una actividad <strong>de</strong>aprendizaje basado en proyectos realizada los dos últimosaños en una asignatura universitaria <strong>de</strong> Ingeniero enInformática, consistente en el diseño, compra, montaje,instalación, configuración y explotación <strong>de</strong> un pequeñocluster <strong>de</strong> computadores orientado a cálculo científico. Eldiseño inicial consistió en 3 nodos Core i7 con switch KVMy GbE montados en rack. El segundo año se añadió unservidor SAN y un switch Infiniband. Se <strong>de</strong>scribe elmétodo aplicado para <strong>de</strong>sarrollar y evaluar la actividad, elcluster diseñado por los estudiantes y su configuraciónsoftware, así como los resultados <strong>de</strong> encuestas <strong>de</strong> opinión<strong>de</strong> los estudiantes que participaron, posibles variacionespara futuras ediciones <strong>de</strong> la experiencia, y las conclusionesalcanzadas con la realización <strong>de</strong>l proyectoPalabras clave— Aprendizaje basado en proyectos,Clusters, Computación paralela.EI. INTRODUCCIÓNL Aprendizaje por Proyectos [8] es un métododocente ampliamente reconocido por su capacidadpara estimular la participación <strong>de</strong> los estudiantes ymantenerlos motivados hacia la asignatura. Comocaracterísticas básicas distintivas <strong>de</strong>l método se pue<strong>de</strong>n<strong>de</strong>stacar el menor énfasis en la enseñanza mecánica ymemorística para <strong>de</strong>dicarse a un trabajo más retador ycomplejo, el enfoque interdisciplinario (apropiado a untrabajo complejo) en lugar <strong>de</strong> orientado al área oasignatura, y el trabajo cooperativo frente al individual.Adoptar el método puro <strong>de</strong> Aprendizaje basado enProyectos implicaría una fuerte coordinación entre elprofesorado <strong>de</strong> las distintas asignaturas implicadas [5][9], y eventualmente una reforma completa en laestrategia docente <strong>de</strong> la titulación. En este trabajo hemosoptado por introducir un pequeño proyecto voluntario ennuestra asignatura “Arquitectura <strong>de</strong> Computadores II”(ACII) <strong>de</strong> 5º curso <strong>de</strong> Ingeniero en Informática, con laintención obvia <strong>de</strong> mejorar la motivación <strong>de</strong> losestudiantes, y en segundo término para observar laactitud <strong>de</strong> los mismos ante lo que podría ser una práctica<strong>de</strong> las nuevas asignaturas en los próximos planes <strong>de</strong>estudio <strong>de</strong> los Grados.En la Sección II se resume en qué consiste el trabajo ycómo se puntúa. En las secciones III y IV se muestra elresultado (hardware y software) <strong>de</strong>l proyecto, esto es, elcluster diseñado por los estudiantes y su configuraciónsoftware. <strong>La</strong> Sección V muestra los resultados <strong>de</strong> lasencuestas rellenadas por los estudiantes. Por último, laSección VI resume posibles variaciones <strong>de</strong>l proyecto yla Sección VII las conclusiones.1 Dpto. Arquitectura y Tecnología <strong>de</strong> Computadores, <strong>Universidad</strong> <strong>de</strong>Granada, e-mail: {jfernand,manguita}@ugr.esII. ENUNCIADO, EVALUACIÓN Y DESARROLLO DE LAACTIVIDADAl plantearse como actividad voluntaria y nopresencial, el enunciado se proporcionó anticipadamentea los estudiantes a través <strong>de</strong> la web <strong>de</strong> los profesores [6].Básicamente, se proponía diseñar el cluster orientado ala ejecución <strong>de</strong> aplicaciones científicas en un plazo <strong>de</strong> 5semanas, para posteriormente instalarle el S.O., pasarlebenchmarks (para comprobar si las prestaciones eran lasesperadas según el diseño) y que diera tiempo a ejecutaren él las prácticas <strong>de</strong> programación paralela <strong>de</strong> laasignatura antes <strong>de</strong> que acabara el curso. <strong>La</strong>s prácticas<strong>de</strong> la asignatura estaban orientadas principalmente a laprogramación paralela y evaluación <strong>de</strong> prestacionesaunque en la asignatura también se estudian loscomponentes <strong>de</strong> un computador paralelo. <strong>La</strong>financiación <strong>de</strong> 3.650€ corrió a cargo <strong>de</strong>l Plan <strong>de</strong>Innovación Docente <strong>de</strong> la UGR [7].<strong>La</strong>s normas <strong>de</strong> evaluación <strong>de</strong> la asignatura se alteraron<strong>de</strong> la forma indicada en la Tabla 1. <strong>La</strong>s ventajas para losestudiantes que participaran eran un menor umbral paraaprobar, y un tope <strong>de</strong> nota algo mayor (11 puntos). Sejustifica esta bajada <strong>de</strong>l umbral y subida <strong>de</strong>l máximo enque el estudiante tiene que <strong>de</strong>dicar horas <strong>de</strong> trabajo <strong>de</strong> laasignatura al proyecto <strong>de</strong>l cluster en lugar <strong>de</strong> al resto <strong>de</strong>activida<strong>de</strong>s <strong>de</strong> la asignatura.TABLA 1. PUNTUACIÓN DE ACII EN LOS CURSOS 08/09 Y 09/10.2008 / 2009 2009 / 2010resto clase grupo clusterActividad max umbral max umbral max umbralExamen 7.0 3.5 5.0 1.5 7.0 3.00Prácticas 3.0 1.5 3.0 1.0Proy. Cluster 3.0 1.03.0 1.25Suma 10.0 5.0 11.0 3.5 10.0 4.25Se <strong>de</strong>cidió añadir 3 puntos adicionales, por el trabajorealizado en el Proyecto Cluster (2p) y un cuestionariofinal sobre el mismo (1p), mantener los 3 puntos <strong>de</strong>prácticas, y prorratear a 5 puntos el examen <strong>de</strong> teoría.A pesar <strong>de</strong>l cambio <strong>de</strong> umbrales en la encuesta <strong>de</strong>lcurso 2008/09 los estudiantes que participaron en elproyecto cluster opinaron que el trabajo era excesivo.Por este motivo, en el curso 2009/10, hemos preferidoplantear el proyecto (instalación, configuración,evaluación y explotación <strong>de</strong>l cluster) como alternativa alas prácticas normales (Tabla 1). <strong>La</strong> alternativa se<strong>de</strong>nominó “Centro <strong>de</strong> Procesamiento <strong>de</strong> Datos”, dando aenten<strong>de</strong>r que esta actividad u otras similares podríanpracticarse en la futura asignatura <strong>de</strong> Grado <strong>de</strong> dichonombre.Para supervisar el <strong>de</strong>sarrollo <strong>de</strong> la actividad se hautilizado el sistema SWAD <strong>de</strong> la UGR [1] [2] [3],<strong>JP2011</strong>-599


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011aprovechando el foro para comunicación profesoresestudiantes(Figura 1) y la zona común <strong>de</strong> archivos paraentregar documentos <strong>de</strong> trabajo (Figura 2). En el curso08/09 se enviaron 16 trabajos y 348 posts (58 <strong>de</strong> losprofesores).<strong>La</strong> web <strong>de</strong> la actividad [6] sugería unas cuantasactivida<strong>de</strong>s que los estudiantes podían realizarautónomamente (Tabla 2) y apuntaba algunas webs <strong>de</strong>fabricantes y ven<strong>de</strong>dores <strong>de</strong> don<strong>de</strong> obtener informaciónpara realizar los diseños. <strong>La</strong> web se ha utilizado tambiénpara ir anotando comentarios y resumiendo lasaportaciones realizadas a lo largo <strong>de</strong>l proyecto.<strong>La</strong> experiencia <strong>de</strong>l curso 2008/09 ha permitidoaquilatar <strong>de</strong> forma más precisa la cantidad <strong>de</strong> trabajo quelos estudiantes consi<strong>de</strong>ran apropiada para 3 puntos <strong>de</strong>calificación, <strong>de</strong> forma que en el curso 2009/10 sólo se haplanteado la instalación, configuración, evaluación yexplotación <strong>de</strong>l cluster ya montado. <strong>La</strong>s activida<strong>de</strong>s serealizaban presencialmente en horario <strong>de</strong> prácticas ytutorías, sobre el cluster real, anotando los profesores lastareas en las que cada estudiante participabaactivamente. Los estudiantes realizaron su informe [4]como documento GoogleDocs, también enlazado en laweb <strong>de</strong>l Proyecto [6].Ya sea como actividad voluntaria adicional (curso2008/09) o alternativa (2009/10) a las prácticasnormales, nos ha sucedido que pocos estudiantesescogen el proyecto, razonando que implica realizar mástrabajo que las prácticas normales para obtener la mismanota. En el curso 2008/09 participaron 15 estudiantes <strong>de</strong>un total <strong>de</strong> 150 (10%), y en el 2009/10, 7 <strong>de</strong> un total <strong>de</strong>134 (5%).En el curso 2008/09 la etapa <strong>de</strong> diseño colaborativo enel foro no convergió a un diseño consensuado. Habíados opiniones distintas: una que apuntaba adquirir nodoscon una buena GPU a consta <strong>de</strong>l resto <strong>de</strong> componentes,y la otra que opinaba lo contrario argumentando unamejor relación prestaciones/precio. Lo que se hizofinalmente es agrupar a los estudiantes en dos grupos yque cada uno presentara una propuesta <strong>de</strong>tallada yjustificada por escrito apoyándose en el trabajo realizadoen el foro. Paradójicamente, los dos diseños entregadosfueron virtualmente idénticos (hay que tener en cuentaque el foro se discutieron las prestaciones y precio <strong>de</strong>todos los componentes: procesador, chasis, fuente <strong>de</strong>alimentación, cables, etc.).<strong>La</strong> etapa <strong>de</strong> instalación <strong>de</strong> software tuvo másinci<strong>de</strong>ncias, lo cual sirvió <strong>de</strong> argumento para <strong>de</strong>dicarleplena atención en el curso siguiente (sección 4).Básicamente, nos proponíamos elucidar si dichasinci<strong>de</strong>ncias se <strong>de</strong>bían a una falta <strong>de</strong> habilida<strong>de</strong>s <strong>de</strong> base,o a un exceso <strong>de</strong> tarea. Ambos motivos podrían sercausa <strong>de</strong> la baja participación. En el curso 2009/10 seresaltó que el proyecto consistía exclusivamente eninstalar, configurar y evaluar el cluster, y administrarlodurante el periodo <strong>de</strong> explotación (las últimas semanas<strong>de</strong>l curso) para que los restantes compañeros pudieranejecutar en él los programas paralelos realizados comoprácticas. Como ya se ha indicado, las activida<strong>de</strong>s se hanrealizado presencialmente, anotando el profesor laparticipación <strong>de</strong> cada estudiante. Los estudiantes nomostraron discrepancias con el <strong>de</strong>sarrollo <strong>de</strong>l proyectodurante las sesiones presenciales.Figura 1. Foro SWAD usado para el diseño, curso 2008/09.Figura 2. Zona común <strong>de</strong> trabajos SWAD, curso 2008/09.TABLA 2. ALGUNAS CTIVIDADES DEL PROYECTO (08/09), Y SUPUNTUACIÓN APROXIMADA.Actividadpuntosaportar componente, precio, caract.técnicas (en el foro) 0.1-0.3matizar aportación previa (€, caract. o conceptos clase) 0.1-0.3encontrar <strong>de</strong>fectos <strong>de</strong> diseño en aportaciones previas 0.1-0.2encontrar oferta similar a diseño aportado 0.1-0.2relacionar faceta diseño con conceptos estudiados clase 0.1-0.2documentar instalacion / configuración <strong>de</strong> software 0.3tarea <strong>de</strong> instalación / configuración <strong>de</strong> un software 0.3otrassegúnIII. CLUSTER DISEÑADO POR LOS ESTUDIANTESEn el curso 2008/09 se realizó una reunión tras losdiseños presentados por los dos grupos <strong>de</strong> estudiantescon el fin <strong>de</strong> afinar algunos <strong>de</strong>talles, tras la cual serealizó la primera compra por un precio <strong>de</strong> 3000€ aprox.(Tabla 3). El resto <strong>de</strong>l presupuesto se liquidóposteriormente, tras haber montado el cluster ycomprobado su correcto funcionamiento. El colchón <strong>de</strong>500€ hubiera permitido reponer algún componente vitalsi se hubiera estropeado durante el montaje. Al no surgirninguna contingencia, se utilizó para darle un acabadoprofesional al equipo (Tabla 4). En la Figura 3 se pue<strong>de</strong>ver el cluster ACII con todos los componentes instalados(incluyendo los <strong>de</strong>talles <strong>de</strong> acabado como termostato,panel <strong>de</strong> parcheo, cepillos pasacables…), las puertas<strong>JP2011</strong>-600


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011retiradas y los nodos parcialmente extraídos. Es posibleapreciar un antiguo switch FastEthernet (<strong>de</strong>l que ya sedisponía) entre el panel <strong>de</strong> parcheo y el switch GbE,muy útil para comparar prestaciones.TABLA 3. COMPONENTES BÁSICOS DEL CLUSTER ACII.ComponenteCPU Intel Core i7-920Placa Madre ASUSP6T SEKit Memoria 6GBDDR3 1066 KVR-N7K3Switch GbE TL-SG1016Tarjeta GbE D-Link DGE-530Tcant precio3 734,973 662,313 284,971 76,991 18,99TABLA 4. DETALLES DE ACABADO DEL CLUSTER ACII.Componente cant precioGuías lateralestelescópicasPanel <strong>de</strong> parcheo24x RJ-45HerramientaImpacto3 91,111 63,281 27,42cable parcheo1m 4 4,84bolsa tornilleríaM6TermostatoDigital 1U1 26,261 137,47cable RJ-45 Cat63mKVM Level-OneKVM-0410cable KVM PS/21.8mHDD 500GBSATA-II4 15,081 89,004 16,003 143,97Regleta 19” 6tomasPasacable 1Ucepillo/peineAnilla guiacable1U horizontalAnilla guiacable1U verticalCable TwisTies30m1 49,962 50,348 31,688 31,681 2,96Total 517,00Grabador DVDSATA1 24,44Lector DVD SATA 2 27,84FuenteAlimentación500WTarjeta VGA PCIeGF7200 256MB3 84,873 76,77Monitor LCD 19”LG W1941STeclado LogitechPS/2Ratón Logitechóptico PS/21 99,991 7,541 5,40Armario 19” 22U 1 434,90Caja Rack 19” 4U 3 236,70Regleta 19” 8tomas1 48,60Total 3089,33Figura 3. El cluster ACII con los <strong>de</strong>talles <strong>de</strong> acabado.<strong>JP2011</strong>-601


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011IV. CONFIGURACIÓN SOFTWAREAunque en el curso 2008/09 se realizaron trabajosescritos sobre instalación <strong>de</strong> software, en la etapa <strong>de</strong>instalación surgieron inci<strong>de</strong>ncias difíciles <strong>de</strong> reconducir.Restrospectivamente, <strong>de</strong>beríamos haber previsto el casoen que el responsable <strong>de</strong> una instalación no la lleva acabo, ya sea por falta <strong>de</strong> tiempo o cualquier otra razón.Para distinguir si este problema se <strong>de</strong>bió a un exceso<strong>de</strong> tarea o a una carencia formativa (y aprovechando queel cluster ya estaba montado), al año siguiente laactividad se simplificó, limitándose a instalación,configuración, evaluación y explotación <strong>de</strong>l cluster.Para evitar la situación <strong>de</strong> que un solo estudiantepudiera bloquear el proceso <strong>de</strong> instalación, se propusorepartir el trabajo <strong>de</strong> forma que al menos dos estudiantesse responsabilizaran <strong>de</strong> cada tarea. Aunque losestudiantes prefirieron organizarse entre ellos,comprometiéndose a que el cluster estuviera operativoen la fecha indicada.Para evitar la situación <strong>de</strong>l estudiante que hace untrabajo escrito sin sentirse comprometido a que elproceso <strong>de</strong> instalación y configuración <strong>de</strong>scrito <strong>de</strong>bafuncionar, o a que se <strong>de</strong>ban resolver los problemas quesurjan más tar<strong>de</strong> relacionados con su uso, se propusoque todo el trabajo fuera presencial, y que se fueragenerando un diario o bitácora, para disponer <strong>de</strong> unareferencia que permitiera reproducir todo el trabajorealizado.En el curso 2009/10 los estudiantes que escogieron elproyecto realizaron la instalación <strong>de</strong>l Sistema OperativoDebian con servidor DHCP y firewall IPTables, clonado<strong>de</strong> nodos con CloneZilla, paso <strong>de</strong> mensajes con Open-MPI, sistema <strong>de</strong> colas Torque, monitorización Ganglia yautentificación LDAP. No dio tiempo a probar ningúnbenchmark, <strong>de</strong>bido fundamentalmente a la cantidad <strong>de</strong>sesiones <strong>de</strong>dicadas a instalar Torque y LDAP. Losprofesores sugirieron la instalación <strong>de</strong> algunadistribución Linux más apropiada para servidores, comoCentOS, pero los estudiantes prefirieron Debian.El cluster estuvo operativo en la fecha indicada sin quese produjeran inci<strong>de</strong>ncias durante las sesionespresenciales.V. RESULTADO DE LAS ENCUESTAS DE OPINIÓNEn ambos cursos, 2008/09 y 2009/10, se invitó a losestudiantes a rellenar un cuestionario anónimo <strong>de</strong>stinadoa evaluar en qué medida se habían alcanzado losobjetivos <strong>de</strong>l proyecto, y si se <strong>de</strong>bía mantener elpróximo curso, con o sin modificaciones, o se <strong>de</strong>beríaeliminar. Estos objetivos <strong>de</strong>l cuestionario se lescomunicaban explícitamente a los estudiantes en elpropio formulario. <strong>La</strong>s preguntas <strong>de</strong>l cuestionario sepue<strong>de</strong>n ver en la Tabla 5.De los 12 estudiantes que entregaron la encuesta en elcurso 2008/09, casi la mitad eran matriculados <strong>de</strong>primera vez (5 <strong>de</strong> 12), frente al 100% (6 <strong>de</strong> 6) <strong>de</strong>l curso2009/10. En la Tabla 6 se resumen las respuestas másfrecuentes, junto con su frecuencia. En general, losestudiantes opinan que la actividad les ha permitidoapren<strong>de</strong>r y se <strong>de</strong>be mantener.En atención a las opiniones 2008/09, en 2009/10 seredujo drásticamente la cantidad <strong>de</strong> trabajo a realizar (ala parte software exclusivamente), se bajaron losumbrales mínimos, no se prorrateó el examen final, y sereplanteó el proyecto como unas Prácticas alternativas(en sustitución <strong>de</strong> las “normales”). Los 6 estudiantes queentregaron el cuestionario anónimo volvieron a opinarmayoritariamente que <strong>de</strong>bería darse más nota, y que lapuntuación es injusta en comparación con las otrasPrácticas. <strong>La</strong>s calificaciones obtenidas se resumen en laTabla 7, para mostrar que no se trata <strong>de</strong> un caso <strong>de</strong>evaluación cicatera por parte <strong>de</strong>l profesoradoRetrospectivamente, no se <strong>de</strong>bería haber dado tantaimportancia a las opiniones positivas en 2008/09 sobrela libertad para escoger tarea, y se <strong>de</strong>bería haberintervenido frecuentemente durante las sesiones (sindarle tanta importancia al ambiente distendido) pararecapitular sobre los hitos alcanzados y los quequedaban por cumplir. Cubrir las competencias <strong>de</strong> esteproyecto en una asignatura con temario propio resolveríamuchas <strong>de</strong> estas objeciones (participación, puntuación,organización, etc.).Por tener una cierta i<strong>de</strong>a <strong>de</strong> la popularidad que pudieraalcanzar la web <strong>de</strong>l Proyecto Cluster, se le añadió en sudía (Julio 2009) el tracker para las analíticas Google. Elnúmero <strong>de</strong> visitas que alcanzó en pocos meses nos hizoconsi<strong>de</strong>rar la posibilidad <strong>de</strong> traducirla a inglés (Sept.2009). Ambas versiones <strong>de</strong> la web muestran distintaestacionalidad, como se pue<strong>de</strong> comprobar en susgráficas <strong>de</strong> visitas (Figura 4, Figura 5). <strong>La</strong> versiónespañola ha llegado a acercarse recientemente a 50visitas semanales, mientras que la inglesa llegó a 40 elpasado 2º cuatrimestre, y no se consulta tanto en losprimeros cuatrimestres (15-20 visitas semanales, verFigura 5 a izquierda y <strong>de</strong>recha <strong>de</strong>l tramo con más visitas,2º cuatrimestre 2010).TABLA 5. CUESTIONARIO ANÓNIMO DEL PROYECTO CLUSTER.Pregunta¿Es el primer año cursando la asignatura?El proceso <strong>de</strong> diseño cluster le ha permitido apren<strong>de</strong>rSe <strong>de</strong>be mantener este trabajo en la asignaturaJustifique 2 anteriores respuestas¿Qué es lo que más le ha gustado?¿Por qué?¿Qué cambiaría?En la forma <strong>de</strong> calificar al estudiante…¿qué cambiaría? ¿qué conservaría?VI. POSIBLES VARIANTES DE LA ACTIVIDADformatos/n-2…2-2…2librelibrelibrelibrelibreEn vista a futuras variaciones <strong>de</strong>l proyecto, se pue<strong>de</strong>argumentar (mediante las encuestas recolectadas) quelos estudiantes <strong>de</strong>sean una planificación rigurosa conhitos marcados en don<strong>de</strong> se obtenga puntuación que seconozca sobre la marcha, sobre un plan <strong>de</strong> trabajopreviamente fijado por los profesores. Sólo un pequeñoporcentaje <strong>de</strong> estudiantes prefiere un trabajo con máslibertad, frente a la mayoría que preferiría cambiar laorganización <strong>de</strong> la experiencia (5 <strong>de</strong> 6 en 2010). <strong>La</strong>paradójica poca satisfacción con la nota obtenida (sólo 4<strong>de</strong> 12 en 2009, 2 <strong>de</strong> 6 en 2010, siempre 66%insatisfecho) indica que estos temas <strong>de</strong>bieran cubrirse enuna asignatura con temario (y calificación) propios.<strong>La</strong> variación que quedaría por intentar sería realizarunos diarios <strong>de</strong>tallados <strong>de</strong> instalación, temporizados porlos profesores, para eliminar radicalmente el argumento<strong>JP2011</strong>-602


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA 6. RESULTADOS DE LA ENCUESTA ANÓNIMA.2008/2009 2009/2010Universo 12 6Primer año 41.7% (5 <strong>de</strong> 1er año / 7 repetidores) 100% (6 <strong>de</strong> 1er año)Apren<strong>de</strong>r 1.42 (-2:1 -1:0 0:0 1:3 2:8) 1.50 (-2:0 -1:0 0:0 1:3 2:3)Mantener 1.33 (-2:1 -1:0 0:0 1:4 2:7) 1.33 (-2:0 -1:0 0:0 1:4 2:2)frec. respuesta frec. respuestajustificación 5x aplicar teoría 2x trabajo satisfactorio, interesante4x temas no cubiertos en otras asignaturas,motiva, interesa, es voluntario2x trabajo diferente,no cubierto en otras asignaturas3x apren<strong>de</strong>r mediante la práctica,2x se apren<strong>de</strong> <strong>de</strong> los compañerostrabajar en grupogustado más 6x el clúster ha sido realforo (por su nivel, formato, ambiente)3x <strong>de</strong>sarrollar capacida<strong>de</strong>s profesiónútil para un futuro empleo3x los gruposapren<strong>de</strong>r sobre componentes2x ver el cluster funcionandoir resolviendo problemas instal. / config.2x libertad para todo2x entorno distendido(escoger tarea, proponer componentes)qué cambiaría 6x que haya más participaciónmucho trabajo para tan poca nota4xque que<strong>de</strong> más claro al principio losobjetivos, puntuación, lista tareas,y que no es competitivo5x2xorganizar mejor: falta experiencia,material apoyo, difícil apren<strong>de</strong>rque sea más guiado, menos libertadgrupos más pequeños: 7→5 máx.sesiones todas en <strong>La</strong>boratoriono en tutorías (probl. espacio)instalar Infiniband2xforma calificar 4x en general, correcta 4x más nota, injusto respecto otra Práctica2x se <strong>de</strong>be conocer la nota4x puntuar no según resultados,sobre la marcha, tras la aportaciónsino según esfuerzo / aprendizaje2x bajar más los umbrales, o quitarloscomentario 3x estoy satisfecho satisfecho con nuestro trabajo,he aprendido bastantes cosas2x espero que otros estudiantesagra<strong>de</strong>cer <strong>de</strong>dicación profesor y flexibilidadpuedan beneficiarse también<strong>de</strong>sarrollo trabajo2x se <strong>de</strong>be conocer la notasobre la marcha, tras la aportaciónhay que ser más realista, no da tiempo, montar2 SO es <strong>de</strong> locos, o menos objetivos o más notatanta libertad da quebra<strong>de</strong>ros cabeza,obligando (Debian, Torque) se ahorraría tiempoTABLA 7. CALIFICACIONES DEL PROYECTO CLUSTER.curso notas media2008/09 3.0 3.0 3.0 3.0 3.02.9 2.6 2.5 2.4 2.41.9 1.8 1.8 1.4 1.4 2.412009/10 3.0 2.9 2.8 2.7 2.62.5 2.5 2.71Figura 4. Analíticas Google <strong>de</strong> la web <strong>de</strong>l Proyecto [6] (español).Figura 5. Analíticas Google <strong>de</strong> la web <strong>de</strong>l Proyecto [6] (inglés). El tramocon más visitas es el 2º cuatrimestre <strong>de</strong> 2010.<strong>de</strong> que es <strong>de</strong>masiado trabajo para tan poca nota. Losestudiantes que <strong>de</strong>mostraran haberlos leído previamente(por ejemplo, respondiendo preguntas verbales o untest), tendrían <strong>de</strong>recho a intentar realizar la instalación yconfiguración <strong>de</strong>scrita en ellos, en las fechas indicadasen la temporización. Se podría ofrecer la posibilidad <strong>de</strong>abandonar el proyecto durante el curso, si consi<strong>de</strong>ranque la nota que van obteniendo no es suficiente, y otrapráctica alternativa les resultara más interesante.VII. CONCLUSIONESDurante los cursos 2008/09 y 2009/10 hemosconseguido poner en contacto a un total <strong>de</strong> 22estudiantes con el tipo <strong>de</strong> supercomputador más habitualactualmente, el cluster <strong>de</strong> computadores, salvando lasdiferencias en cuanto a cantidad y categoría <strong>de</strong> loscomponentes (nodos sobremesa en lugar <strong>de</strong> servidor,prestaciones y tamaño <strong>de</strong>l switch, etc.). <strong>La</strong>s activida<strong>de</strong>srealizadas han ido <strong>de</strong>s<strong>de</strong> el propio diseño y montajehasta la instalación y configuración <strong>de</strong>l software <strong>de</strong>sistema y middleware asociado. Los estudiantesconsi<strong>de</strong>ran en grado bastante alto que la actividad les haservido <strong>de</strong> aprendizaje y se <strong>de</strong>be mantener.<strong>La</strong> realización <strong>de</strong> este proyecto en estas fechas ha sidooportuna, ya que nos ha permitido <strong>de</strong>tectar unascompetencias que no se están cubriendo en nuestrosactuales planes <strong>de</strong> estudio y que están presentes en losnuevos Grados, llevándonos a proponer dos nuevasasignaturas que podrían incorporar este tipo <strong>de</strong> prácticas,“Ingeniería <strong>de</strong> Servidores” y “Centro <strong>de</strong> Procesamiento<strong>de</strong> Datos”. <strong>La</strong> primera, obligatoria <strong>de</strong> rama a impartir en3er curso, se va a <strong>de</strong>dicar al diseño, montaje, instalacióny evaluación <strong>de</strong> un servidor <strong>de</strong> gama baja, y la segunda,obligatoria <strong>de</strong> la especialidad Ingeniería <strong>de</strong>Computadores, al diseño y evaluación <strong>de</strong> un servidor <strong>de</strong>gama media/alta. <strong>La</strong>s competencias específicas <strong>de</strong>l<strong>JP2011</strong>-603


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Grado <strong>de</strong> Informática a las que contribuye estaexperiencia son (CVE: BOE-A-2009-12977):• E1: Capacidad para concebir, redactar, organizar,planificar, <strong>de</strong>sarrollar y firmar proyectos en elámbito <strong>de</strong> la ingeniería en informática que tenganpor objeto, <strong>de</strong> acuerdo con los conocimientosadquiridos, la concepción, el <strong>de</strong>sarrollo o laexplotación <strong>de</strong> sistemas, servicios y aplicacionesinformáticas.• E4: Capacidad para <strong>de</strong>finir, evaluar y seleccionarplataformas hardware y software para el <strong>de</strong>sarrolloy la ejecución <strong>de</strong> sistemas, servicios y aplicacionesinformáticas.• E6: Capacidad para concebir y <strong>de</strong>sarrollar sistemaso arquitecturas informáticas centralizadas odistribuidas integrando hardware, software y re<strong>de</strong>s.<strong>La</strong> experiencia adquirida nos servirá <strong>de</strong> referencia enel diseño <strong>de</strong> las prácticas <strong>de</strong> estas asignaturas.Añadir a las conclusiones, para acabar, que po<strong>de</strong>mosafirmar que la relación prestaciones/precio <strong>de</strong>l clusterdiseñado superó con creces lo que podía ofrecer en sumomento una empresa por el presupuesto con el que secontaba, entre otro motivos porque se adquirieron loscomponentes (procesador, memoria, placa, armario, etc.)por separado en Internet don<strong>de</strong> estaban más baratos.[7] Fernán<strong>de</strong>z, F.J., Anguita, M. Memoria <strong>de</strong>l Proyecto Clúster.http://serin.ugr.es/unidad_innovacion_docente/memorias/08-08.doc. Convocatoria <strong>de</strong> Proyectos <strong>de</strong> Innovación Docente 2008:http://innovaciondocente.ugr.es/pages/convocatoria-2008.[8] Railsback, J. Project-Based instruction: Creating excitement forlearning. Northwest Regional Educational <strong>La</strong>boratory, “ByRequest” series, 2002.[9] Valero García, M., Navarro, J.J. FAQ sobre la adaptación <strong>de</strong>asignaturas al EEES: docencia centrada en el aprendizaje <strong>de</strong>lestudiante. In: ReVisión, vol.1, no.2, AENUI, 2008. Disponibleonline en http://aenui.net/ReVision/. Consultar en concreto elpenúltimo párrafo en la sección §3.10.AGRADECIMIENTOSAgra<strong>de</strong>cemos la ayuda <strong>de</strong>l Plan <strong>de</strong> Innovación Docente<strong>de</strong> la UGR, que nos ha permitido diseñar un cluster quepodremos reutilizar en cursos futuros para seguirintentando motivar a los estudiantes, así como la ayuda<strong>de</strong>l Plan <strong>de</strong> Apoyo a la Docencia Práctica, que nos hapermitido adquirir la infraestructura Infiniband añadidaposteriormente a dicho cluster. Agra<strong>de</strong>cemos también lacolaboración <strong>de</strong>l proyecto <strong>de</strong> investigación TEC2010-15396 CITYC.Agra<strong>de</strong>cemos especialmente a los estudiantes PabloOrantes, Ignacio Robles, Luis Quesada y Manuel Martín(2008/09), y Juan Pablo Chinea y Rubén Ramos(2009/10) su valiosa colaboración y encomiable interéspor el buen término <strong>de</strong>l proyecto.REFERENCIAS[1] Cañas, A., Calandria, D.J., Ortigosa, E.M. et al. SWAD: WebSystem for Education Support. In: Computers and Education: E-learning - from Theory to Practice, Chapter 12, pp. 133-142,ISBN 978-1-4020-4913-2, Springer, 2007.[2] Cañas, A., Díaz, A.F., Prieto, A. Sistema <strong>de</strong> servicios web <strong>de</strong>apoyo a la docencia y gestión <strong>de</strong> una asignatura. In: <strong>Actas</strong> <strong>de</strong> lasVIII Jornadas <strong>de</strong> Enseñanza Universitaria <strong>de</strong> la Informática(JENUI'2002), pp. 611-614, 2002.[3] Cañas, A., Ortigosa, E.M., Fernán<strong>de</strong>z, F.J., Anguita, M., et al.SWAD (Sistema Web <strong>de</strong> Apoyo a la Docencia). In: <strong>Actas</strong> <strong>de</strong>l 6ºSimposio Internacional <strong>de</strong> Informática Educativa (SIIE’04),2004.[4] Chinea, J.P., Ramos, R. et al (estudiantes ACII 2009/10). InformeACII: Puesta en marcha y configuración <strong>de</strong> un clúster conDebian 5.0. Documento GoogleDoc disponible enhttps://docs.google.com/Doc?docid=0Aane43447qy1ZGRxMmp6MjdfNWRwMjNkcWZr.[5] Comellas, F., González-Cinca, R., Santamaría, E. Simulación:Un curso innovador en los estudios <strong>de</strong> Aeronáutica. In:ReVisión, vol.2, no.2, AENUI, 2009. Disponible online enhttp://aenui.net/ReVision/.[6] Web <strong>de</strong>l Proyecto Cluster, con su enunciado:http://atc.ugr.es/~javier/docencia/Proyecto_Cluster.html. Versióninglesa http://atc.ugr.es/~javier/docencia/Project_Cluster.html.<strong>JP2011</strong>-604


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Evaluación <strong>de</strong> prestaciones<strong>JP2011</strong>-605


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-606


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Achieving interactive multiagent simulationsover Jason through Java tuningVíctor Fernán<strong>de</strong>z-Bauset, Francisco Grimaldo, Miguel Lozano y Juan M. Orduña 1Resumen— Java-based simulation environments arecurrently used by many multiagent systems (MAS),since they mainly provi<strong>de</strong> portability as well as aninteresting reduction of the <strong>de</strong>velopment cost. However,this kind of MAS are rarely consi<strong>de</strong>red when <strong>de</strong>velopinginteractive applications with time responseconstraints. This paper analyses the performance provi<strong>de</strong>dby Jason, a well-known Java-based MAS platform,as a suitable framework for <strong>de</strong>veloping interactivemultiagent simulations. We show how to tuneboth the heap size and the garbage collection of theJava Virtual Machine in or<strong>de</strong>r to achieve a good performancewhile executing a simple locomotion benchmarkbased on crowd simulations. Furthermore, thepaper inclu<strong>de</strong>s an evaluation of Jason’s performanceover multi-core processors. The main conclusion <strong>de</strong>rivedfrom this work is that, by means of Java tuning,it is possible to run interactive MAS programmed usingJason.Palabras clave— Jason, Java, simulation, interactive,multiagent.I. Introduction and Related workMAS platforms capable of handling a largeamount of complex autonomous agents at interactiveresponse times are required by interactivemultiagent applications such as crowd simulationsand massive online games. Usually, these kinds ofsimulations involve a high number of agents (e.g.pe<strong>de</strong>strians) interacting in a shared environment. Interactivity,in turn, requires the use of parallel techniquesthat allow to validate and to execute the actionsrequested within a limited period of time (commonly,250 ms [1]).Java-based simulation environments are currentlybeing used by many MAS, since they mainly provi<strong>de</strong>portability as well as an interesting reductionof the <strong>de</strong>velopment cost. However, this kind of MASare rarely consi<strong>de</strong>red when <strong>de</strong>veloping interactive applicationswith time response constraints, becauseof Java being normally less efficient than other languagessuch as C or C++. This situation requestsperforming a specific Java tuning to be able to tacklethis type of applications. In this paper, we show theJava tuning carried out for the purpose of evaluatingthe performace of Jason [2], a well-known Java-basedMAS platform. The aim of this tuning is to adjustboth the heap size and the garbage collection of theJava Virtual Machine in or<strong>de</strong>r to satisfy the temporalrequirements of interactive multiagent simulations.Therefore, the results presented in this paper willalso be of great value to those researches consi<strong>de</strong>r-1 Computer Science Department, University ofValencia, Dr. Moliner 50, (Burjassot) Valencia,Spain. E-mail: victor.fernan<strong>de</strong>z-bauset@uv.es,francisco.grimaldo@uv.es, miguel.lozano@uv.es,juan.orduna@uv.es.ing Java-based simulation environments suitable for<strong>de</strong>veloping interactive multiagent applications.When <strong>de</strong>veloping this kind of interactive MASthree layers are normally consi<strong>de</strong>red: the computerarchitecture, the MAS platform and the graphical engine(if any). At the low level, different distributedcomputer architectures have been applied in or<strong>de</strong>r toallow massive interactive simulations to scale up withthe number of agents by simply adding new hardware(e.g. networked-server, P2P, etc.). For instance,a new approach has been presented for PLAYSTA-TION3 which supports simulation of simple crowdsof up to 15000 individuals at 60 frames per second[3]. Parallel simulation, based on classical Reynolds’sboids [4], has been also integrated in a PC-Clusterwith MPI communication [5] to finally produce smallsimulations (512 boids). At the top level, the graphicalengine of the application must ren<strong>de</strong>r the visualizationat interactive frame rates. The computergraphics community generally represents the MASas a particle system with local interactions [6], [7],though, few works inclu<strong>de</strong> socially complex and autonomousbehaviors [8]. However, they are not normallybased on standard agent architectures.In the middle level, the MAS platform is in chargeof providing the required data flow to the graphicalengine while efficiently using the computationalresources. Thus, it constitutes a key middlewarethat highly influences the global performance andthe scalability of the system. It mainly addressestwo important issues: mo<strong>de</strong>ling the behavior of theagents as well as their parallel lifecycle execution.Java is a popular language providing built-in supportfor concurrency that is commonly used by MAS platforms.Although Java performance has been studiedfrom different perspectives, probably the mostusual is to tune server applications running on largemulti-processor servers [9]. There are more specificworks focused on the evaluation of Java-based multiagentplatforms [10], [11], [12]. However, none ofthem <strong>de</strong>als with providing interactivity to the correspondingMAS. Some researchers have been also testingthe performance and scalability of a few existingMAS platforms [13], showing a lack of both importantissues in many of them. In a previous work [14],the authors analysed Jason’s architecture and evaluatedits performance un<strong>de</strong>r both centralised and distributedinfrastructures. Regardless the infrastructure,the results showed that the execution optionshad to be reviewed in or<strong>de</strong>r to achieve a more equilibratedresponse time distribution, an aspect that wehave covered in this work.The rest of the paper is organized as follows. Sec-<strong>JP2011</strong>-607


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011tion II briefly reviews Jason’s centralised infrastructureand <strong>de</strong>scribes the locomotion benchmark usedfor the evaluation. Section III <strong>de</strong>monstrates how totune Java in or<strong>de</strong>r to run interactive multiagent simulationsover Jason. Finally, section IV shows theperformance obtained with different multi-core processors.II. Test <strong>de</strong>scriptionThe goal of this work is to evaluate Jason as asuitable framework for running interactive multiagentsimulations. Jason is a Java-based interpreterfor an exten<strong>de</strong>d version of AgentSpeak, a BDI agentorientedlogic programming language [2]. Jason provi<strong>de</strong>sthree infrastructures to execute a MAS: Centralised,SACI and JADE. Whereas the Centralisedinfrastructure places all the components of the MASin the same host, it is also possible to distributethese components in several hosts using either SACIor JADE technologies. For the sake of simplicity,this paper focuses on the Centralised infrastructurebut the results obtained are fully applicable for bothdistributed infrastructures.Jason’s Centralised infrastructure can be seen infigure 1. Here the environment has its own executionthread and it is provi<strong>de</strong>d with a configurablepool of threads (PThE) <strong>de</strong>voted to executing the actionsrequested by the agents. In this way, the enviromentis able to <strong>de</strong>al with several agent requestsconcurrently. In turn, each agent owns by <strong>de</strong>faulta thread in charge of executing the agent reasoningcycle. In this manner, all the agents can run concurrentlywithin the MAS. As such, this approach couldlimit the number of agents that can be executed,since the total number of threads would be limited bythe Java Virtual Machine (JVM) heap size. However,Jason offers the possibility to optionally add anotherconfigurable pool of threads (PThA), so that the setof agents can share a smaller number of executionthreads but reducing the level of concurrency. Thenumber of threads in both PThE and PThA is initialisedduring the start-up of the MAS and it is notchanged along its execution. By <strong>de</strong>fault, the PThEholds 4 threads whereas the PThA is disabled, sothat each agent will have its own execution thread.In a previous work, we tuned both the PThE and thePThA in or<strong>de</strong>r to obtain the best performance [14].The main issue to be tackled when running interactivemultiagent simulations is that of being able ofefficiently handling a massive and concurrent actionprocessing. In this paper, we have used a locomotiontestbed. Here, a set of wan<strong>de</strong>rer agents requestmovement actions to a grid-like environment, whichreplies with the result of the execution, as can beseen in figure 2. Wan<strong>de</strong>rer agents are written inAgenSpeak and they cyclically execute the followingsteps: (i) take start time, (ii) request a random movementto the enviroment, and (iii) take finish time.On the other hand, the environment executes eachmovement action in a synchronized manner to ensurethe world consistency. That is, the environmentFig. 1.Jason architecture at its centralized infrastructureFig. 2. Action example between the environment and thewan<strong>de</strong>rer agentsperforms a simple collision test and informs whetherthe action can be carried out (i.e. Ok) or it cannot(i.e. Failure), when it would lead to a collisionsituation.The performance evaluation carried out along thepaper measures the environment response time andthe percentage of CPU utilization consumed whilerunning the locomotion benchmark. These measurementsrepresent respectively latency and throughput,the two performance parameters commonly consi<strong>de</strong>redwhen evaluating networked-based distributedcomputer platforms [15]. We <strong>de</strong>fine the ResponseTime (RT ) as the time elapsed between an agentasking for an action and receiving the reply fromthe environment. Our simulations stop when all theagents have performed 500 movements or cycles, butwe discard the first 200 cicles when computing theaverage response time (RT ). Thus, we measure thesystem behavior at full load, since the first measurementsare distorted due to the agent creation phase.As stated above, we are interested in exploring theperformace of Jason’s Centralised infrastructure in<strong>de</strong>pth. Thus, both the environment and the agentsare run on the same host. The results for the Centralisedinfrastructure shown in [14] indicated that,when simulating 1000 wan<strong>de</strong>rer agents, the 70% ofthe agents were able to act within 85 ± 264 ms. Thatis, even though the low value of RT (85 ms) indicatedthat many actions were processed very fast,there were a few agents that must wait more than250 ms for their actions to be executed. This problemwith the high standard <strong>de</strong>viation of the response<strong>JP2011</strong>-608


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 3. Influence of the Java Garbage Collection on the responsetimetime (σ RT ), found all over the measures in [14], is addressedin the following section.III. Java tuningThe source of the high standard <strong>de</strong>viation of theresponse time of Jason-based MAS can be envisonedin figure 3. The figure shows that the average responsetime per agent cicle (RT c ) peaks periodically.This points to a process that stops the system wheneverit is executed: the Java Garbage Collection.Thus, we have carried out Java Performance Tuningin or<strong>de</strong>r to provi<strong>de</strong> some general recommendationsfor running interactive multiagent simulations overJason. It should be noticed, though, that the optimaltuning parameters will finally <strong>de</strong>pend on theapplication and on the hardware un<strong>de</strong>rneath.In this section, we show the results obtained whenexecuting the testbed <strong>de</strong>fined in section II over anAMD Dual-Core Opteron processor with 4 Gb ofRAM, running a 64-bit version of Linux and theSun’s HotSpot TM Java Virtual Machine (JVM) release1.6.0 07. From version 1.5, this JVM has incorporateda technology to begin to tune itself, referredto as Ergonomics. Even though Ergonomics significantlyimproves the performance of many applications,optimal results often require manual tuning.There are two main aspects that have to be tunedin or<strong>de</strong>r to enhance Java performance: the heap sizeand the garbage collector (GC) [16]. Regarding theformer, by <strong>de</strong>fault, the initial heap size is 1/64th ofthe machine’s physical memory and the maximumheap size is 1/4th of the machine’s physical memory.In our case, this would mean using 64 Mb and1 Gb respectively. However, Java performance canbe enhaced by increasing the maximum heap size,as shown in figure 4. This figure shows the totalamount of time consumed by the garbage collectionwhen we use diferent GCs and increase the heap sizewhile simulating 2500 agents. This time is computedby adding the times nee<strong>de</strong>d to complete every invocationto the GC. Besi<strong>de</strong>s, we have set minimum andmaximum heap sizes equal for a faster startup. Notehow, regardless of the GC being used, the total GCtime strongly <strong>de</strong>creases when increasing the heap sizeup to 2 Gb. Further on, the gain is very low com-Fig. 4. Garbage colletion time nee<strong>de</strong>d for different heap sizesand GCs.pared to the fact of being using almost the wholephysical memory.With respect to the garbage collectors, Sun’sHotSpot TM JVM allows the programmer to chooseamong three of them: serial, throughput and concurrentlow pause collector. Whereas the serial GC is asequential collector, the throughput GC uses multiplethreads to collect garbage in parallel and it is suitablefor applications with a large number of threads allocatingobjects, such as the one being tested in thispaper. On the other hand, the concurrent GC doesmost of the collection concurrently with the executionof the application and it is appropriate for applicationsthat benefit from shorter GC pauses. Additionally,Java GCs organize the object memory intotwo generations: young (recently created objtects)and tenured (ol<strong>de</strong>r objects). Java allows to set theratio between the young and tenured generation bymeans of the JVM command-line option NewRatio.For more <strong>de</strong>tails on Java garbaje collection, see [16].Bearing all this informacion in mind, we have executedour benchmark using every GC available. Figure4 shows the most relevant results that we haveobtained. The line named Serial corresponds to thetotal amount of time consumed by the garbage collectionwhen simulating 2500 agents using the serialGC. The Parallel line relates to the use of thethroughput GC only for the collection of the younggeneration. In turn, the ParallelOld line refers to theuse of the throughput GC for the collection of boththe young and the tenured generation. For space reasons,we skip the results obtained with the concurrentGC since they are up to ten times higher thanthose obtained with the rest of the GCs, both for thetotal GC time and for the average response time. Aswe can observe, the serial GC behaves worse thanany configuration of the throughput GC. Moreover,parallelizing the collection of the tenured generationdoes not fasten but actually slows garbage collectionwhen the heap size is less than 2.5 Gb. This meansthat there is not a problem with the collection of oldobjects but with the young ones. The reason behindthis fact relies on how Jason represents agent’s beliefsand actions. Both are implemented as objectsthat are discar<strong>de</strong>d and created again whenever thereis a change in a belief or a new action is requested<strong>JP2011</strong>-609


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011throughput GC whenever your hardware has atleast 2 CPUs in or<strong>de</strong>r to reduce GC pause times.Besi<strong>de</strong>s, check whether you need the <strong>de</strong>faultnumber of collector threads (equal to the numberof processors) or you can save any, thus reducingthe workload of the whole machine.• Increase the size of the young generation up tothe size of the tenured generation (NewRatio=1)to <strong>de</strong>crease the need for slow major collections.Fig. 5. Performance when varying the number of threads usedby the throughput GCto the environment. As each wan<strong>de</strong>rer agent continuouslyasks the environment for movement actionsand changes its position, we can imagine the hugeamount of objects that “die young”. Thus, enlargingthe young generation will benefit garbage collection.The <strong>de</strong>fault NewRatio for the Server JVM is 2.That is, the tenured generation occupies 2/3 of theheap while the young generation occupies 1/3. Alarger young generation could accommodate manymore short-lived objects, <strong>de</strong>creasing the need for slowmajor collections. Meanwhile, the tenured generationwould still be large enough to hold many longlivedobjects. According to this, the line labeled asParallel-n=1 in figure 4 shows that we can obtain thelowest garbage collection times by using the throughputGC for the collection of the young generationalong with the minimum ratio possible between thegenerations (i.e. NewRatio = 1). Hence, half of theheap for the young generation and the other half forthe tenured generation.Finally, we have evaluated the effect of the numberof threads <strong>de</strong>voted to collect garbage when usingthe parallel throughput GC. By <strong>de</strong>fault, this GCuses as many garbage collector threads as the numberof processors available. Though, the number ofthreads can be tuned manually through the Parallel-GCThreads command-line option. For this test, wehave used a 16-core computer and we have varied thenumber of collector threads from 2 up to 16. Besi<strong>de</strong>s,we have tuned Java so it runs efficiently with 2 Gbof heap size and the NewRatio set to 1. Figure 5shows the values obtained for the average responsetime (RT ) plus its standard <strong>de</strong>viation (σ RT ) when increasingthe number of agents simulated. Evi<strong>de</strong>ntly,the worst values are obtained when only 2 threadsare used for garbage collection. However, in our testit is not necessary to use as many threads as thenumber of cores, since we get the same results for 8and 16 GC threads.Summing up, we can state the following generalrecommendations for running interactive multiagentsimulations over Jason:• Enlarge the heap size as much as possible withoutachieving the amount of physical memoryavailable. In addition, set minimum and maximumheap sizes equal for a faster startup.• Parallelize garbage collection by using theIV. Performance EvaluationIn this section we analyse the results obtainedwhen running the benchmark <strong>de</strong>scribed in section IIon the following distributed shared memory (DSM)multi-core computers: 2-Core (AMD Dual-CoreOpteron, 1.6 GHz, 4 GB RAM), 4-Core (AMD Quad-Core Opteron, 1.0 GHz, 8 GB RAM), 8-Core (Intel8-Core Xeon, 2.6 GHz, 16 GB RAM) and 16-Core(AMD Dual-Core 8218, 1.0 GHz, 32 GB RAM). Allof them run the same 64-bit version of Linux and theSun’s HotSpot TM JVM release 1.6.0 07.Table I shows the performance obtained when simulatingfrom 2500 to 5500 wan<strong>de</strong>rer agents on thecomputers <strong>de</strong>scribed above. The results for 1-corewere obtained through the taskset Linux command.When running the benchmark, we have followed theJava tuning recommendations stated in section III.Therefore, we have used the throughput GC for thecollection of the young generation with a number ofcollector threads equal to the number of cores. Besi<strong>de</strong>s,we have tuned Java so it runs with 4 Gb ofheap size and we have set NewRatio to 1. The leftcolumn in Table I shows the percentage of CPU utilizationmeasured during the execution of the simulation.The central column (RT ) shows the averageResponse Time in milliseconds for the actionsrequested by the agents when the system is at fullload, as explained in section II. Finally, the right columnshows the standard <strong>de</strong>viation of this ResponseTime (σ RT ).The results shown in Table I <strong>de</strong>monstrate that wecan run interactive multiagent simulations over Jason,since the values of the RT plus the σ RT aregenerally un<strong>de</strong>r the reference value of 250 ms. Asit was also expected, the CPU utilization <strong>de</strong>creasesas the number of cores increases. For instance, if wecompare the results obtained for 3500 agents on eachcomputer, it can be seen that the more cores in thecomputer, the lower the percentage of CPU utilization(the single CPU is shown only as a reference).However, the response time does not behave the sameway. Instead, whereas the RT values for the 2-Corecomputers are around a few milliseconds, the RT forthe computers with 4 up to 16 cores reaches tensof milliseconds. The worsening of the response timeoccurs in all the computer being tested, althoughit has a minor impact in the 8-Core computer becauseit has the highest processor speed. This factindicates that, beyond two cores, the <strong>de</strong>fault configurationused by Jason does not properly scale upwith the number of processor cores. Thus, a <strong>de</strong>eper<strong>JP2011</strong>-610


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA IPerformance obtained for Jason framework overdifferent computersCores-Agents CPU(%) RT (ms) σ RT (ms)1-1500 89,53 44,59 101,641-3500 90,01 40,39 189,571-5500 89,98 71,97 178,421-7500 87,87 85,93 193,031-9500 65,97 98,33 2196,682-1500 89,17 3,92 28,842-3500 91,13 5,55 27,592-5500 92,00 9,01 35,382-7500 91,10 10,39 79,092-9500 59,72 47,79 1152,104-1500 76,25 51,97 20,814-3500 81,11 132,88 50,714-5500 81,48 201,90 76,894-7500 83,35 290,71 118,304-9500 84,24 386,35 488,378-1500 59,88 31,01 8,588-3500 67,75 73,82 22,658-5500 72,09 114,10 40,628-7500 74,56 146,27 58,268-9500 74,92 185,81 278,0016-1500 39,77 57,38 9,6016-3500 46,45 145,86 38,1016-5500 48,27 242,87 62,2316-7500 57,58 282,57 85,7316-9500 57,51 253,53 534,66study must be carried out in or<strong>de</strong>r to allow it to takeadvantage of the multi-core processors.Although a fine tuning of the Jason framework formulti-core processors is beyond the scope of this paper,we have analysed the issue shown in Table I inor<strong>de</strong>r to clarify the path for future work. We thinkthat the reason behind this problem is thread contextswitching. Even though the Java Virtual Machineschedules its threads to run them as fast as possible,there is no guarantee of which core a given thread willbe assigned to for execution. The operating systemkernel can assing one single thread to different coresduring its execution time, thus provoking thread migrations.The probability of migration increases withthe number of cores in the processor, in such a waythat the overhead due to thread migrations coul<strong>de</strong>xceed the benefits of having more cores for executingthe threads in parallel. To verify this hypothesis,we have measured the number of migrations (i.e.changes in the core assigned for execution) sufferedby the threads along the simulation. To <strong>de</strong>tect migrations,we have used a system call retrieving thestate of the Java threads periodically and we haveanalysed the core where they were located.Figure 6 shows the total number of thread migrationscounted while executing the same simulationsthat produced the results of Table I. We can observehow the number of migrations is proportional to thenumber of cores in the computer. Since a thread mi-Fig. 6.Number of thread migrationsgration is a time consuming task, the high number ofmigrations produced by computers with more than2 cores can explain the behavior shown in Table I.Nevertheless, it should be noticed that these resultsdo not guarantee the absence of other still hid<strong>de</strong>naspects that could prevent the system from properlyscaling with the number of processor cores. In or<strong>de</strong>rto fully exploit the <strong>de</strong>gree of parallelism offered bymulti-core processors, tuning the processor affinityof Jason must be done.V. Conclusions and Future workIn this paper, we have evaluated Jason as a suitableJava-based MAS platform for <strong>de</strong>veloping interactivemultiagent simulations. We have shown howto tune the Java heap size as well as the gargabecollector in or<strong>de</strong>r to enhance the performance of thesimulations. Even though the optimal tuning parameterswill finally <strong>de</strong>pend on the application and onthe hardware un<strong>de</strong>rneath, we have state some generalrecommendations for minimizing the impact ofgarbage collection. Therefore, the results presentedin this paper will also be of great value to those researchesconsi<strong>de</strong>ring other Java-based simulation environmentsfor <strong>de</strong>veloping interactive multiagent applications.The paper also inclu<strong>de</strong>s a first evaluationof Jason’s performance over multi-core processors.As future work, we plan to carry out a <strong>de</strong>ep studyof the Jason framework in or<strong>de</strong>r to properly scale itup with the number of processor cores. Then, tuningthe Java processor affinity will be required to exploitthe <strong>de</strong>gree of parallelism offered by multi-core processors.Agra<strong>de</strong>cimientosThis work has been jointly supported by theSpanish MEC and the European CommissionFEDER funds, un<strong>de</strong>r grants Consoli<strong>de</strong>r-Ingenio 2010CSD2006-00046 and TIN2009-14475-C04-04..Referencias[1] Miguel Lozano, Pedro Morillo, Juan Manuel Orduna, andVicente Cavero, “On the <strong>de</strong>sign of an efficient architercturefor supporting large crowds of autonomous agents,”in Proceedings of IEEE 21th. International Conference<strong>JP2011</strong>-611


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011on Advanced Information Networking and Applications(AINA’07), 2007, pp. 716–723.[2] R. H. Bordini, J. F. Hübner, and M. Wooldrige, ProgrammingMulti-Agent Systems in AgentSpeak using Jason,Wiley, 2007.[3] Craig Reynolds, “Big fast crowds on ps3,” in Proc. ofthe 2006 ACM SIGGRAPH symposium on Vi<strong>de</strong>ogames.2006, pp. 113–121, ACM.[4] Craig W. Reynolds, “Flocks, herds and schools: A distributedbehavioral mo<strong>de</strong>l,” in SIGGRAPH ’87: Proc.of the 14th annual conference on Computer graphics andinteractive techniques. 1987, pp. 25–34, ACM.[5] Bo Zhou and Suiping Zhou, “Parallel simulation of groupbehaviors,” in WSC ’04: Proceedings of the 36th conferenceon Winter simulation. 2004, pp. 364–370, WinterSimulation Conference.[6] Simon Dobbyn, John Hamill, Keith O’Conor, and CarolO’Sullivan, “Geopostors: a real-time geometry/impostorcrowd ren<strong>de</strong>ring system,” ACM Trans. Graph., vol. 24,no. 3, pp. 933–933, 2005.[7] Adrien Treuille, Seth Cooper, and Zoran Popovic, “Continuumcrowds,” in SIGGRAPH ’06: ACM SIGGRAPH2006 Papers. 2006, pp. 1160–1168, ACM.[8] Nuria Pelechano, Jan M. Allbeck, and Norman I. Badler,“Virtual crowds: Methods, simulation, and control,”Synthesis Lectures on Computer Graphics and Animation,vol. 3, no. 1, pp. 1–176, 2008.[9] Jack Shirazi, Java Performance Tuning, O’Reilly, 2003.[10] E. Cortese, F. Quarta, and G. Vitaglione, “Scalabilityand performance of JADE message transport system,”in AAMAS Workshop on AgentCities, 2002.[11] Robert Tobias and Carole Hoffman, “Evaluation of freejava-libraries for social-scientific agent based simulation,”Journal of Artificial Societies and Social Simulation, vol.7, no. 1, 2004.[12] Cynthia Nikolai and Gregory Ma<strong>de</strong>y, “Tools of the tra<strong>de</strong>:A survey of various agent based mo<strong>de</strong>ling platforms,”Journal of Artificial Societies and Social Simulation, vol.12, no. 2, pp. 2, 2009.[13] Luis Mulet, Jose M. Such, and Juan M. Alberola,“Performance evaluation of open-source multiagent platforms,”in Proc. of the fifth international joint conferenceon Autonomous agents and multiagent systems. 2006, pp.1107–1109, ACM.[14] Victor Fernán<strong>de</strong>z, Francisco Grimaldo, Miguel Lozano,and Juan Manuel Orduña, “Evaluating Jason for distributedcrowd simulations,” in Proc. of the 2nd. InternationalConference on Agents and Artificial Intelligence.2010, vol. 2, pp. 206–211, INSTICC Press.[15] J. Duato, S. Yalamanchili, and L. Ni, InterconnectionNetworks: An Engineering Approach, Morgan Kaufmann,2002.[16] Oracle Sun Depeloper Network, “Java Tuning WhitePaper,” 2010, Available at http://java.sun.com /performance/reference/whitepapers/tuning.html.<strong>JP2011</strong>-612


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Dynamically Tuning Master/WorkerApplications with MATEAndrea Martínez, Anna Morajko, Eduardo César and Joan Sorribes 1Abstract— Programming parallel/distributed applicationsis a difficult task that requires a high <strong>de</strong>greeof knowledge and expertise, especially to achieve thepotential performance offered by HPC. Analysis andtuning tools can be helpful for automatically improvingapplications performance, but these tools mustbe adapted to the application’s characteristics. Inparticular, dynamic analysis and tuning tools are necessaryfor applications that vary their behaviour atexecution time. MATE is a tool, based on performancemo<strong>de</strong>ls, which can automatically and dynamicallytune parallel applications. This work presentsthe integration of a theoretical performance mo<strong>de</strong>l ofMaster/Worker applications into MATE. This mo<strong>de</strong>ltakes into account the main performance problemsof Master/Worker applications: load balancing andusing an appropriate number of workers. This knowledgeis encapsulated in MATE in a component calleda tunlet. It implements the specific logic necessaryto overcome these performance problems in terms ofmeasurement points, performance functions, and tuningpoints/actions. The experimentation shows theeffectiveness of using performance mo<strong>de</strong>ls for dynamicallytuning parallel applications. However, theanalysis process inclu<strong>de</strong>d in MATE presents seriousscalability problems that must be addressed to makeit efficient in large scale systems.Keywords— dynamic performance analysis; dynamicand automatic tuning; performance mo<strong>de</strong>ls; parallel/distributedcomputingI. IntroductionCURRENTLY , software applications are used tosolve complex problems in a number of differentareas of science and engineering. Many of these problemshave very high computing requirements thatcan only be addressed through parallel/distributedprocessing. Therefore, performance is usually themost important issue related to parallel applications.In this work, we apply a methodology, based on performancemo<strong>de</strong>ls, for automatically and dynamicallytuning the performance of parallel applications. Inparticular, we focus on the implementation and integrationof a performance mo<strong>de</strong>l for Master/Workerapplications in MATE.When a programmer <strong>de</strong>velops a parallel application,he or she wishes to achieve a level of performanceclose to the expected theoretical performance.Unfortunately, this is not usually the case becausethe <strong>de</strong>velopment of this type of applications is a complexand difficult task that involves knowledge of parallelprogramming mo<strong>de</strong>ls, communication librariesand/or operating system features.With the aim of increasing the performance oftheir applications, <strong>de</strong>velopers must un<strong>de</strong>rtake a per-1 Computer Architecture and Operating Systems Department,CampusBellaterra (08193) Barcelona, Spain,e-mail: amartinez@caos.uab.es, ania.morajko@uab.es,eduardo.cesar@uab.es, joan.sorribes@uab.esformance improvement process. This process inclu<strong>de</strong>s3 successive phases: monitoring, analysis andtuning. First, during the monitoring phase, informationabout the application behaviour is captured.Then, by studying this information, the analysisphase involves looking for bottlenecks, <strong>de</strong>ducing theircauses, and tries to <strong>de</strong>termining what the correct actionsto eliminate the problems are. Finally, in tuningphase these actions are applied to the applicationto solve the problems and improve performance.As a result, <strong>de</strong>velopers must be familiar with the application,the software layers involved, and the behaviourof the system on which it is executed.Various approaches and tools have been <strong>de</strong>velopedto support the performance improvement process [1][2]. In particular, one of these approaches is the automaticand dynamic tuning of the application withoutstopping, recompiling, or rerunning it. This typeof performance tuning approach is especially recommen<strong>de</strong>dfor applications that behave differently <strong>de</strong>pendingon input data, or may even change theirbehaviour during each execution. In such cases, it isnot worth carrying out a post-mortem performanceanalysis and tuning because conclusions based on oneexecution may be invalid for another. An automaticand dynamic performance tuning process must consi<strong>de</strong>rseveral aspects to be useful and efficient. First,it requires an efficient analysis to make <strong>de</strong>cisions ina short period of time. Second, the overhead causedby the whole process must be minimised to avoi<strong>de</strong>xcessive application intrusion.MATE (Monitoring Analysis and Tuning Environment)is a tool that implements this approach. It isable to automatically and dynamically tune a parallel/distributedapplication using the knowledge provi<strong>de</strong>dby a performance mo<strong>de</strong>l. The remain<strong>de</strong>r of thiswork is organised as follows. Section 2 briefly <strong>de</strong>scribesMATE. In Section 3, we present an overviewof the performance mo<strong>de</strong>l <strong>de</strong>veloped for dynamicallytuning Master/Worker applications. Section 4 explainsthe integration of the performance mo<strong>de</strong>l intoMATE. In Section 5 we present the results of theexperiments conducted using MATE to improve theperformance of a Master/Worker application. Section6 presents the related work in automatic anddynamic tuning. And finally, Section 7 <strong>de</strong>tails theconclusions of this study.II. MATEMATE [3] is a tool that performs monitoring, analysis,and tuning of MPI parallel applications. Itsobjective is to improve the performance of a parallelapplication at run-time, by adapting it to the<strong>JP2011</strong>-613


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011variable conditions of the system. First, at runtimeMATE instruments the application to gatherinformation about its behaviour. During the analysisphase MATE receives events, searches for bottlenecksand specifies solutions for solving the performanceproblems encountered. Finally, the applicationis dynamically modified by applying the givensolutions. MATE uses dynamic instrumentation [4]to modify the application at run-time, so it does notneed to be recompiled or restarted.MATE is composed of the following modules whichcooperate to control and improve the application’sperformance [5]:• The Application Controller (AC) is a daemonthat controls the execution and the dynamic instrumentationof each individual MPI task.• The Analyzer is a centralised process that carriesout the application performance analysis,and <strong>de</strong>ci<strong>de</strong>s on monitoring and tuning. It automatically<strong>de</strong>tects existing performance problemson the fly and requests appropriate changes toimprove the application’s performance.• The Dynamic Monitoring Library (DMLib) is ashared library that is dynamically loa<strong>de</strong>d by theAC in the application tasks to facilitate collectingdata and <strong>de</strong>livering it to the Analyzer.Performance mo<strong>de</strong>ls constitute the knowledge usedby MATE to conduct the performance analysis process.Each performance mo<strong>de</strong>l is encapsulated inMATE in a piece of software called a tunlet. Eachtunlet implements the logic to overcome a particularperformance problem by encapsulating informationabout it in the following terms:• Measurement points, which are the places inthe application co<strong>de</strong> where the instrumentationmust be inserted to gather information aboutthe application’s performance.• Performance functions, which are a set of expressionsthat mo<strong>de</strong>l the application’s behaviour.• Tuning points,which are the points of the applicationsthat can be changed by a tuning actionto improve its performance.III. Master/Worker Performance Mo<strong>de</strong>lThe goal of performance analysis is to i<strong>de</strong>ntify andsolve the application performance problems. Thisprocess may be supported by a performance mo<strong>de</strong>lthat can be a combination of analytical expressionsand heuristics. The parameters nee<strong>de</strong>d for evaluatingthe mo<strong>de</strong>l correspond to the measurements gatheredduring the application execution. We haveimplemented and integrated into MATE a tunletwith the Master/Worker performance mo<strong>de</strong>l <strong>de</strong>scribedin [6]. It is <strong>de</strong>signed for Master/Worker iterativeapplications, where all process repeatedly performsall operations. In every iteration, the masterdistributes tasks to a specific number of workersand then waits for the results before the next iteration.Workers processes calculate the results andsend them back to the master. The condition ofthe iteration-based application behaviour implies theexistence of a significant number of iterations andpersistent performance problems between iterations.This performance mo<strong>de</strong>l inclu<strong>de</strong>s two phases tosolve Master/Worker application performance problems:a load balancing strategy, and an analyticalmo<strong>de</strong>l to evaluate and predict the appropriate numberof workers for the application. In the followingsubsections we summarise both phases, and how torepresent them in terms of the knowledge organisationrequired by MATE.A. Load BalancingLoad balancing techniques try to avoid that someprocesses complete their processing before others.Some of these techniques are based on distributingthe tasks in portions of <strong>de</strong>creasing size called batches.In particular, we have implemented the strategycalled Dynamic Adjusting Factoring (DAF) [7]. Thistechnique divi<strong>de</strong>s the task set into different sizedbatches using a partition factor x i whose value isdynamically adapted to the current load conditionsof the application through expressions (1) and (2).This factor <strong>de</strong>pends on the mean µ C and standard<strong>de</strong>viation σ C of task processing C, and the numberof workers N. Table I shows the Dynamic AdjustingFactoring strategy <strong>de</strong>finition, represented accordingto the MATE knowledge requirements.TABLE IDefinition of the load balancing strategyParametersPerformancefunctionsTuningpoints/actions- N, number of workers- C, task processing time, msPartition factor of the first batch of theiteration:√ )x 0 = 1 +(σ C N/2 /µ C (1)Partition factor of the remainingbatches of the iteration:√ )x i = 2 +(σ C N/2 /µ C (2)Partition factor. Its value can bemodified throughout the iteration.B. Adapting the Number of WorkersFor <strong>de</strong>termining the appropriate number of workersof the application, we have used the performancein<strong>de</strong>x Pi proposed in [6]. This in<strong>de</strong>x relates the executiontime to the efficient use of resources in or<strong>de</strong>rto maximise the performance without wastingresources. Following the requirements of knowledgerepresentation in MATE, the <strong>de</strong>finition of this tuningstrategy is presented in Table II.The parameters m 0 and λ are statically configuredtaking into account the characteristics of the computingplatform . The total communication volume,V , is calculated as the sum of task sizes sent/receiveto/from workers, and finally the total computationtime, T c , is obtained by adding the computation timeof workers in an iteration.IV. Tunlet ImplementationTo dynamically tune the performance of Master/Workerapplications, we have <strong>de</strong>veloped a tun-<strong>JP2011</strong>-614


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLE IIDefinition of the adjust number of workers strategyParametersPerformancefunctionsTuningpoints/actions- m 0 , start up time per message, in ms- λ, communication cost per byte, inms/byte.- V , total communication volume, in bytes.- T c, total computation time,in ms.Performance in<strong>de</strong>x for different number ofworkers x:P i(x) = xT t(x) 2T c/µ C (3)At the execution time of one iteration forx workers:⌊((x−1)α+1)λV Tc⌋T t(x) = 2m 0 + /µ x C (4)The number of workers. Its value can bemodified at the beginning of each iteration.let that integrates the tuning strategies presented inSection III.Technically, a tunlet is a library that encapsulatesthe information about a performance problem, implementinga particular tuning technique. Its implementationmust use the Dynamic Tuning API [3]provi<strong>de</strong>d by the MATE’s Analyzer module.Earlier works featuring MATE show applying separatetuning techniques to load balancing [8] or toadapting the number of workers [9]. It is worth notingthe complexity of the <strong>de</strong>veloped tunlet as it encapsulatestwo tuning phases, taking into account theinteractions between them. In particular, the phasefor adapting the number of worker consi<strong>de</strong>rs that theapplication is balanced.For the proper <strong>de</strong>velopment of the tunlet, its <strong>de</strong>finitionshould inclu<strong>de</strong> the i<strong>de</strong>ntification and interpretationof a set of elements related to the performancemo<strong>de</strong>l and the type of the applications un<strong>de</strong>rstudy. From the point of view of the performancemo<strong>de</strong>l, the following must be <strong>de</strong>fined: measurementpoints, analytic performance functions and tuningpoints/actions. With respect to the application, inour work we have taken into consi<strong>de</strong>ration:• The programming mo<strong>de</strong>l followed by the applications.• The variables or values that can be manipulated,with the aim of locating variables to tune.• The functions whose execution must be <strong>de</strong>tectedto gather behavioural information.In or<strong>de</strong>r to implement the tunlet based on the presentedMaster/Worker performance mo<strong>de</strong>l, we havefollowed a tunlet <strong>de</strong>sign and <strong>de</strong>velopment process [10]consisting of four steps which are explained in the followingsubsections.A. I<strong>de</strong>ntify Application ActorsThe <strong>de</strong>signed tunlet needs information about thedifferent types of application processes that cooperateto solve a concrete problem. This knowledge isrequired because each type of process should be instrumented<strong>de</strong>pending on the role that it plays in theapplication. The application to be tuned follows aMaster/Worker paradigm, so, two types of processcan be i<strong>de</strong>ntified: the master and N workers.B. I<strong>de</strong>ntify Measurement PointsTo evaluate the performance mo<strong>de</strong>l it is necessaryto <strong>de</strong>termine which points in the application execution- measurement points - must be monitored withthe aim of collecting behavioural information aboutthe application to calculate the parameters of themo<strong>de</strong>l’s analytical expressions, which are shown inTables I and II.The measurement points are located in either theentry to or exit from a function. One value is extractedof each of these points. However some parametersrequire multiple values and therefore multiplemeasurement points in or<strong>de</strong>r to be calculated.C. I<strong>de</strong>ntify EventsEvents are messages in which the values extractedat the measurement point are sent to MATE’s Analyzermodule. These events are explicitly <strong>de</strong>finedwithin the tunlet. Multiple values obtained at thesame measurement point can be encapsulated in asingle event and these values will be used by the Analyzermodule in or<strong>de</strong>r to calculate the parameters forevaluating the performance mo<strong>de</strong>l.Table III presents the relationship between eventsand measurement points required by the analysisprocess. For each measurement point the table showsthe actor, the function where it is situated, whetherit is the entry to or exit from this function and thevalue which will be obtained.D. I<strong>de</strong>ntify the Tuning Points and ActionsThe last step consists of i<strong>de</strong>ntifying the specificvariables that will be modified by MATE at runtime.Consequently, a Master/Worker application mustinclu<strong>de</strong> a variable indicating the partition factor tobe applied to the set of tasks for the load balancingstrategy, and a variable indicating the currentnumber of workers. Once MATE has taken all measurementsto calculate the parameters of the analyticalexpressions, the performance mo<strong>de</strong>l can beevaluated, and <strong>de</strong>pending on the results of this evaluation,the a<strong>de</strong>quate point to modify the associatedvariable should be <strong>de</strong>termined.For the load balancing strategy, the evaluation ofthe expressions is triggered when two separate eventsare received by the Analyzer:• Start iteration, because at the beginning of theiteration, the tunlet has gathered all the informationfor calculating the mean µ C and standard<strong>de</strong>viation σ C of the task processing timefor the previous iteration. This allows the calculationof the partition factor values for thefirst and second batch of the current iteration.• End computing worker, because then, the tunletcan verify if the information about the processingtime of each worker that has participated inthe computation of a particular batch has beencollected. If so, the tunlet can calculate the partitionfactor for the following batches taking intoaccount the current load balancing conditions.<strong>JP2011</strong>-615


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLE IIIRelationship between events and the required measurement point by the analysis processParametersMeasurement PointsActor Function Location Value obtainedEventsNumber ofGlobal sendMasterworkers Nto workersEntry #workers Start iterationReceive tasksClock time,WorkerEntryTask processing from master #tasks from masterStart computingtime, CSend tasksWorkerto masterExit Clock time End computingSend toMaster sendsMasterEntry #tasks to worker iTotal communication worker i to workervolume, VReceive tasksMaster receivesMasterExit #tasks from worker ifrom worker ifrom workerReceive tasksWorkerTotal computationfrom masterEntry Clock time Start computingtime, T cSend tasksWorkerto masterExit Clock time End computingThen, the tuning action can be invoked and thepartition factor modified at any time during the iteration.On the other hand, for adjusting the numberof workers, the evaluation of the expressions is triggeredwhen the Start iteration event arrives to theAnalyzer. At this moment, the tunlet has all the requiredinformation from the previous iteration (T c ,V , λ, and m 0 ). If the number of workers calculatedby the Analyzer differs from the current number ofworkers, the tuning action is invoked between twoiterations, and the predicted number of workers willbe used in the next iteration.V. Experimental ResultsIn this section, we present the experimental resultsobtained to validate the efficiency of the <strong>de</strong>velopedtunlet when it is integrated into MATE fordynamically tuning of Master/Worker applications.To conduct the experiments, we selected a computationallyintensive Forest Fire Propagation parallelapplication called Xfire [11]. It is a Master/WorkerMPI application that simulates fire line propagationfollowing the Andre-Viegas mo<strong>de</strong>l [12]. It iterativelycalculates the next position of the fire line consi<strong>de</strong>ringthe current fire line position and environmentaspects, such as weather, wind, vegetation, topology,etc. In each iteration, the master distributesthe fire line among the workers and waits for the results.Then, it composes the new fire line and startsthe next iteration. Workers calculate the evolution ofthe received fire line and send it back to the master.The application presents computational imbalance,with processing time differences between 20% and100% among workers.Experiments were conducted on a 33 no<strong>de</strong> homogenouscluster running 3.00 GHz Intel Xeon Dual-Core processors, SuSE Linux 10, and connected bydual Gigabit Ethernet. The experiments were performedusing 2, 4, 8, 16 and 31 workers. In eachexperiment, each worker, the master, and the Analyzerwere executed on a <strong>de</strong>dicated no<strong>de</strong>. We haveconducted our experiments using four scenarios:1. Xfire was executed for different numbers of workerswithout tuning.2. Xfire was executed with MATE, but only tuningthe load balancing following the DAF algorithm.The initial partition factor was 0.5, andduring the execution this value was adjusted tothe load balancing conditions.3. Xfire was executed with MATE, but only tuningthe number of workers. The applicationstarted with two workers, and during the executionthis number was changed according to themo<strong>de</strong>l <strong>de</strong>scribed in Section III.4. Xfire was executed with MATE applying theentire <strong>de</strong>veloped tunlet, i.e., Xfire was tunedusing the load balancing strategy and adjustingthe number of workers.Table IV summarises the results obtained. Thecomparison of the execution times obtained for scenario1 and 2 shows that dynamic tuning of the partitionfactor improves Xfire performance only for 4workers. For a greater number of processes the tuningprocess loses effectiveness due to two main reasons:• Centralised performance analysis carried out byMATE’s Analyzer module.• Frequent partition factor tuning.Regarding the first reason, when the number ofprocesses increases, the number of events received bythe Analyzer also increases. It is related to the factthat the applied load balancing strategy is quite conservative,which means low partition factors around[0.2-0.4]. This leads to a finer grained distributionof tasks, increasing the number of events generatedby worker processes. This behaviour causes the processessending events to the Analyzer to block untilthe Analyzer is able to receive the event.To measure the overhead introduced by MATE anew experiment was conducted with two new scenarios.In the first, Xfire was executed for three differentcases: a) without workload fragmentation, b) with astatic partition factor of 0.5 and c) with a static partitionfactor of 0.2. The cases b and c have been executedto analyse the behaviour of Xfire with a finergrained distribution of tasks. In the second scenario,Xfire was executed with MATE but without tuningthe application, using the same static partition factorsas in the first scenario. This means that eventsare generated and sent to the Analyzer, but the partitionfactor and the number of workers are not tuned<strong>JP2011</strong>-616


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLE IVExecution time of Xfire in the different scenariosScenario#Workers2 4 8 16 311 48.08s 24.38s 13.67s 8.75s 6.08s2 40.69s 20.17s 14.89s 20.27s 20.69s3 Starting with two workers 8.49s4 Starting with two workers 25.01sduring the application execution.The results shown in Figure 1 indicate that forlow partition factors, when increasing the number ofworkers, the number of events generated by themincrease significantly. In this situation, MATE isnot able to handle all received events and introducesa large overhead. Therefore, it can be <strong>de</strong>ducedthat MATE presents a bottleneck as the applicationgrows, due to the centralised analysis process [13].The second cause that leads to problems in the tuningprocess is related to the implemented load balancingstrategy in the tunlet. It is characterised byapplying a technique that tries to adapt the partitionfactor to the current conditions of the application.Figure 2 shows the partition factor variation overfive iterations of Xfire execution. According to theload balancing strategy, it is observed that the partitionfactor used for the iterations’ first batch is significantlyhigher than the remaining factors along theiteration. This happens because the remaining partitionfactors are calculated following a more conservativeestimation that compensates for workers that arebusy when the corresponding tasks are distributed.This continuous adaptation during the iterationimplies changes of the the partition factor valuein the application using dynamic instrumentation,which means intrusion into the master process, generatingoverhead in application execution.Regarding scenario 3, starting with two workers,MATE receives the data for each iteration, evaluatesthe performance mo<strong>de</strong>l, and <strong>de</strong>tects the need foradding or removing workers. Figure 3 shows howcomputational load variations cause changes in thenumber of workers in the application. These variationsare due to varying condition in the weather,wind, vegetation or topology as the fire line progresses,and consequently the calculation of the newfire front may have a greater or lesser complexity. Itcan be observed that the execution time of Xfire withMATE is close to the best execution time obtainedby different fixed number of workers, even taking intoFig. 2.Partition factor over five iterations of Xfire executionaccount the overhead introduced by MATE.When all the functionality implemented in the tunletis applied to Xfire, in scenario 4, the effect of theoverhead introduced by the tuning tool is once againnoticeable, especially due to the characteristics of theload balancing strategy.Taking into account the results obtained, the currentcentralised version of MATE would be usefulfor applications which have data <strong>de</strong>pen<strong>de</strong>nt behaviouror change during each execution, beingcomputationally expensive and presenting long runtimes.Thus the overhead that centralised performanceanalysis can generate (management of eventsand instrumentation) may be offset by the cost ofre-run the applicationVI. Related WorkMATE presents an approach that automaticallyand dynamically improves the performance of parallelapplications. This approach is based on the useof dynamic instrumentation and performance mo<strong>de</strong>lsas the intelligence engine of the analysis process. Currently,there are other tools which perform dynamictuning processes.Autopilot [14] is a project for dynamic performancetuning in heterogeneous environments. It isbased on the use of real-time techniques, which dynamicallyadapt the system to different <strong>de</strong>mands andresource availability. Similar to MATE, Autopilotmonitoring process is based on dynamic integrationof sensors, which extract information about the application.The information analysis and <strong>de</strong>cision proceduresare performed using fuzzy logic. The applicationtuning is done by dynamically inserting actua-Fig. 1. Execution time of the conducted experiments in or<strong>de</strong>rto study the MATE overheadFig. 3. Evolution of the number of workers with a variablecomputational load<strong>JP2011</strong>-617


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011tor processes that adjust the application behaviour.This requires knowledge about the application.Active Harmony [15] is a framework, which allowsdynamic adaptation of an application to the networkand available resources using automatic adjustmentof algorithms, data distribution and load balancing.Its structure is based on a client-server mo<strong>de</strong>l. Theclient is the harmonised application, which sends performanceinformation to the server. The server performsthe tuning based on this information. In thistool, the monitoring process gathers measures forvarious libraries with the same functionality. Then,it uses heuristic techniques to explore the applicationoptimisation space and to adjust the tuning values.Thetuning process is based on choosing the bestimplementation among the libraries.PerCo [16] is a framework for performance monitoringin heterogeneous environments. It is ableto manage the distributed execution of applicationsusing migrations, for example, in response to changesin the runtime environment. PerCo monitors executiontimes and reacts according to a control strategyto adapt the performance when significant changesoccur in the application behaviour. The performanceanalysis and tuning process is performed using historicaldata, and combining time series and data adjustmentmethods.The main difference between MATE and presentedtools is in the analysis phase. In MATE, the analysisis based on performance mo<strong>de</strong>ls, whereas Autopilot,Active Harmony and PerCo use fuzzy logic, heuristictechniques, and historical data and time seriesrespectively.VII. Conclusions and future workAchieving high performance for parallel applicationsis a complicated task that requires a high <strong>de</strong>greeof experience, especially when <strong>de</strong>aling with applicationswith dynamic behaviour, or those runningon heterogeneous systems. In these cases, the automaticand dynamic tuning performance is the mosta<strong>de</strong>quate approach. MATE is a tool that implementsthis approach for tuning applications’ performance.In this work, the implementation of a theoreticalperformance mo<strong>de</strong>l for Master/Worker applicationsand its integration into MATE has been presented.MATE has been exten<strong>de</strong>d to improve applicationperformance by balancing the load and <strong>de</strong>terminingthe appropriate number of workers. The performancemo<strong>de</strong>l has been encapsulated in a MATEcomponent called a tunlet. To correctly <strong>de</strong>sign and<strong>de</strong>velop the tunlet, it has been necessary to i<strong>de</strong>ntifyand interpret the relation between the performancemo<strong>de</strong>l, the type of tuned application, and the tuningtool. The <strong>de</strong>veloped tunlet can be used to tune otherapplications based, as in the case of Xfire, on iterationsand a Master/Worker paradigm. It would onlybe necessary to adapt the application to the tuningprocess, adjusting the names of certain functions andtuning variables.The experimental results show the effectivenessof the use of performance mo<strong>de</strong>ls for dynamicallytuning parallel applications. However, the experimentsalso show that MATE has scalability problems,which are related to the volume of data collectedand the centralised performance analysis. Ourcurrent work [17] is focused on studying how to distributethe performance analysis and implement anew version of MATE with architecture capable ofovercoming the current scalability barriers.AcknowledgmentThis research has been supported by the MICINN-Spainun<strong>de</strong>r contract TIN2007-64974.References[1] M. Geimer, F. Wolf, B. Wylie, E. Ábrahám, D. Becker,and B. Mohr, “The SCALASCA Performance ToolsetArchitecture,” in Int. Workshop on Scalable Tools forHigh-End Computing, Kos, Greece, 2008, pp. 51–65.[2] S. Benedict, V. Petkov, and M. Gerndt, “PERISCOPE:An Online-based Distributed Performance AnalysisTool,” in Int. Workshop on Parallel Tools for HPC,2009.[3] Morajko A., Dynamic Tuning of Parallel/DistributedApplications, Ph.D. thesis, Universitat Autònoma <strong>de</strong>Barcelona, 2003.[4] B. Buck and J.K Hollingsworth, “An API for RuntimeCo<strong>de</strong> Patching,” The Int. Journal of High PerformanceComputing Applications, vol. 14, pp. 317–329, 2000.[5] A. Morajko, T. Margalef, and E. Luque, “Design andImplementation of a Dynamic Tuning Environment,” J.Parallel Distrib. Comput., vol. 67, pp. 474–490, 2007.[6] E. Cesar, A. Moreno, J. Sorribes, and E. Luque, “Mo<strong>de</strong>lingMaster/Worker Applications for Automatic PerformanceTuning,” Parallel Comput., vol. 32, no. 7, pp.568–589, 2006.[7] I. Banicescu and V. Velusamy, “Load Balancing HighlyIrregular Computations with the Adaptive Factoring,” inProc. of IPDPS Conference, 2002.[8] A. Morajko, P Caymes-Scutari, T. Margalef, andE. Luque, “Automatic Tuning of Data Distribution UsingFactoring in Master/Worker Applications,” in Int. Conferenceon Computational Science, 2005, pp. 132–139.[9] A. Morajko, E. César, P. Caymes-Scutari, T. Margalef,J. Sorribes, and E. Luque, “Automatic Tuning of Master/WorkerApplications,” in Euro-Par, 2005, pp. 95–103.[10] P. Caymes-Scutari, A. Morajko, T. Margalef, andE. Luque, “A Methodology for Transparent KnowledgeSpecification in a Dynamic Tuning Environment,” Software:Practice and Experience, 2011.[11] J. Jorba, T. Margalef, E. Luque, J. Andre, and D. Viegas,“Application of Parallel Processing to the Simulation ofForest Fire Propagation,” in Proc. of ICFFR, Coimbra,Portugal, 1998, vol. II.[12] J.C.S. André and D.X. Viegas, “A Strategy to Mo<strong>de</strong>l theAverage Fireline Movement of a light-to-medium IntensitySurface Forest Fire,” in Proc. of ICFFR, Coimbra,Portugal, 1994, pp. 221–242.[13] P. Caymes-Scutari, A. Morajko, T. Margalef, andE. Luque, “Scalable Dynamic Monitoring, Analysis andTuning Environment for Parallel Applications,” J. ParallelDistrib. Comput., vol. 70, no. 4, pp. 330–337, 2010.[14] R. Ribler, J. Vetter, H. Simitci, Huseyin Simitci, andDaniel A. Reed, “Autopilot: Adaptive Control of DistributedApplications,” in Proc. of IEEE Symposium onHPDC, 1998, pp. 172–179.[15] C Tapus, I-Hsin Chung, and J.K Hollingsworth, “ActiveHarmony: Towards Automated Performance Tuning,” inProc. from the Conference on High Performance Networkingand Computing, 2003, pp. 1–11.[16] K.R Mayes, M. Luján, G. D. Riley, J. Chin, P. V.Coveney, and J. R. Gurd, “Towards Performance Controlon the Grid,” Philosophical Transactions: Mathematical,Physical and Engineering Sciences, vol. 363, no. 1833,pp. 1793–1805, 2005.[17] A. Morajko, A. Martinez, E. Cesar, and J. Sorribes,“MATE: Towards Scalable Automated and Dynamic PerformanceTuning Environment,” in Proc. PARA 2010,Reykjavik, 2010.<strong>JP2011</strong>-618


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Análisis <strong>de</strong> un sistema Android comoplataforma para juegos <strong>de</strong> realidad aumentada.Andrés L. Sarmiento, Margarita Amor, Carlos V. Regueiro y E. J. Padrón 1Resumen— En este trabajo analizamos las capacida<strong>de</strong>s<strong>de</strong> un smartphone con Android. El objetivo es<strong>de</strong>terminar las facilida<strong>de</strong>s y limitaciones que ofrecela plataforma para <strong>de</strong>sarrollar juegos <strong>de</strong> realidad aumentadaque integren imágenes virtuales con el mundoreal usando la información obtenida mediante lacámara y los sensores <strong>de</strong> posicionamiento. El análisisque se presenta cubre tres campos: las capacida<strong>de</strong>s <strong>de</strong>posicionamiento <strong>de</strong> los dispositivos móviles actuales,la información obtenida mediante la cámara y las facilida<strong>de</strong>s<strong>de</strong> síntesis <strong>de</strong> gráficos. El rendimiento, medidoen términos <strong>de</strong> fotogramas por segundo y latencia, hasido probado en diferentes dispositivos. Se ha <strong>de</strong>sarrolladoun juego <strong>de</strong> realidad aumentada como ejemplo<strong>de</strong> aplicación, tratando <strong>de</strong> combinar calidad, rendimientoy velocidad <strong>de</strong> respuesta.Palabras clave— Realidad aumentada, Android, posicionamiento,visión artificial.I. IntroducciónLOS teléfonos inteligentes (smartphones) reúnencaracterísticas tales como teléfono móvil, agendaelectrónica, navegador GPS, cámara <strong>de</strong> fotos oconsola <strong>de</strong> vi<strong>de</strong>ojuegos. Existen cuatro o cinco sistemasoperativos para estos teléfonos inteligentes. Elsistema Android [1] presenta un contexto opensourcecon un entorno <strong>de</strong> <strong>de</strong>sarrollo multiplataforma.<strong>La</strong> realidad aumentada (RA) es una <strong>de</strong> las aplicacionesque se ha implantado sobre los dispositivosmóviles [2]. <strong>La</strong>s propuestas disponibles sobre la plataformaAndroid se pue<strong>de</strong>n clasificar en tres tipos.Por una parte aplicaciones que geoposicionan objetosvirtuales en el mundo real usando los sensores<strong>de</strong> orientación y el GPS [3–5]. <strong>La</strong> información <strong>de</strong> losobjetos a posicionar se encuentra precalculada y nose requiere excesiva precisión en el posicionamientoy orientación <strong>de</strong>l smartphone.En un segundo tipo <strong>de</strong> aplicaciones los elementosse generan en una escena virtual que se muestra enla pantalla <strong>de</strong>l móvil [6,7]. Se utilizan los movimientos<strong>de</strong>l dispositivo y su orientación respecto al campomagnético terrestre y al centro <strong>de</strong> la Tierra (gravedad)para establecer o actualizar el punto <strong>de</strong> vista<strong>de</strong> la escena que se muestra en la pantalla.Una tercera aproximación utiliza la visión artificial[8–10]. Procesan la imagen percibida y utilizanesta información para situar mo<strong>de</strong>los virtuales. Habitualmenteusan marcadores (tags) para interpretarmejor la imagen. Existen muy pocas aplicaciones <strong>de</strong>este tipo en Android y las pocas que existen no sonmás que meras <strong>de</strong>mostraciones técnicas.En este trabajo preten<strong>de</strong>mos avanzar en ésta últimalínea, ya que en un entorno dinámico y comple-1 Grupo <strong>de</strong> Arquitectura <strong>de</strong> Computadores, <strong>Universidad</strong>eda Coruña, e-mails: margamor@udc.es, cvazquez@udc.es,emilioj@udc.esjo, parece que la mejor manera <strong>de</strong> integrar la informaciónsintética con el entorno inmediato es utilizartanto los datos <strong>de</strong> la cámara como los datos <strong>de</strong>posicionamiento <strong>de</strong>l dispositivo (GPS, brújula, acelerómetros).Obviamente, ello implicará mayor cargacomputacional y mayor complejidad <strong>de</strong> la aplicación.Dado que Android es relativamente nuevo, hacerun análisis <strong>de</strong> viabilidad <strong>de</strong> la aplicación que se quiere<strong>de</strong>sarrollar es obligatorio.II. Análisis <strong>de</strong> las capacida<strong>de</strong>s <strong>de</strong> unsistema Android con OpenGL ESEn esta sección se presenta el análisis <strong>de</strong> la plataformaAndroid. Los dispositivos usados (tabla I)cubren la mayor parte <strong>de</strong> las posibilida<strong>de</strong>s <strong>de</strong>l mercadoactual. En primer lugar, se realiza un análisis<strong>de</strong> la información que se pue<strong>de</strong> extraer <strong>de</strong>l entorno apartir <strong>de</strong> los datos <strong>de</strong> la cámara. En segundo lugar,se presenta un estudio <strong>de</strong> las posibilida<strong>de</strong>s <strong>de</strong> posicionamientoy seguimiento <strong>de</strong>l dispositivo móvil ensu entorno. En tercer lugar, se comprueban las posibilida<strong>de</strong>s<strong>de</strong> ren<strong>de</strong>ring en tiempo real <strong>de</strong> mo<strong>de</strong>losrealistas.A. Captura y procesado <strong>de</strong> la imagenEn el caso <strong>de</strong> que solo se quiera visualizar la imagenobtenida mediante la cámara, ésta se aña<strong>de</strong> alas capas mostradas por la aplicación, cosa que Androidhace <strong>de</strong> forma muy eficiente. En caso <strong>de</strong> que se<strong>de</strong>seen procesar los datos obtenidos, las imágenes aprocesar se obtendrán en el formato especificado alconfigurar la cámara. En el caso <strong>de</strong> los dispositivos<strong>de</strong> prueba solo es aceptado el formato YUV.Procesar imágenes es muy costoso computacionalmentecon lo que es imprescindible realizarlo en unhilo distinto al que ejecuta la interfaz gráfica paraevitar que ésta se congele y <strong>de</strong>je la aplicación en unestado <strong>de</strong> no respuesta. Por otra parte, también esrecomendable programar tal procedimiento en códigosnativos como C o C++ e integrarlo usando elNDK [11] proporcionado en Android, ya que se consiguenmejoras en la velocidad <strong>de</strong> ejecución, <strong>de</strong> hastael 400 %.Como primer paso <strong>de</strong> nuestro análisis hemos estudiadola frecuencia máxima a la que se pue<strong>de</strong>n capturarimágenes para comprobar el límite superior <strong>de</strong>lrendimiento. El resultado en el Motorola Milestonecon la versión 2.1 <strong>de</strong> Android ha sido 9,3 fps configurandola cámara a 30 fps <strong>de</strong> frecuencia máxima y8,8 fps configurando la cámara a 10 fps <strong>de</strong> frecuenciamáxima. Estos resultados no son excesivamentebuenos para nuestros objetivos.<strong>JP2011</strong>-619


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA I: Características técnicas <strong>de</strong> los smartphones usados en los experimentos.Motorola Milestone GeeksPhone One Samsung Galaxy SAndroid 2.1 Eclair 2.2 Froyo 2.2 FroyoCPU ARM Cortex A8 ARM11 Samsung550 MHz 528 MHz Hummingbird 1 GHzGPU PowerVR SGX 530 integrado CPU PowerVR SGX 540Memoria 256 MB 256 MB 512 MBPantalla 3.7” 854x480 3.2” 400x240 4” 800x480GPS Si Si SiAcelerómetros Si Si SiBrújula Si No SiCámara Si Si SiTABLA II: Fotogramas por segundo para captura <strong>de</strong>imagen, <strong>de</strong>codificación y visualización.Max. FPSTamaño imagen Milestone-30 Milestone-10560×320 3,25 3,90280×320 3,90 4,45280×160 4,50 4,95140×160 4,60 5,1015×15 4,65 5,15TABLA III: Fotogramas por segundo para captura<strong>de</strong> imagen, <strong>de</strong>codificación y visualización en dispositivoscon Android 2.2.GeeksPhoneGalaxy STamaño Max. FPS Tamaño Max. FPS400×240 3,9 800×480 5,70200×240 4,5 400×480 7,10200×120 5 400×240 8100×120 5,50 200×240 8,7515×15 5,80 15×15 9,20Como segundo paso, hemos extendido nuestro estudioa la visualización <strong>de</strong> imágenes en pantalla. Paraello, en Android, la imagen tiene que estar codificadaen RGB. Como los dispositivos <strong>de</strong> prueba solo entregabanlas imágenes codificadas en formato YUV, espreciso recodificarlas. En la tabla II se muestran losresultados obtenidos en un Milestone. El tamaño <strong>de</strong>la imagen que otorga la cámara <strong>de</strong>l Milestone no esigual al <strong>de</strong> la pantalla, por lo que el SO la escala automáticamente.Como se pue<strong>de</strong> comprobar el valormáximo es <strong>de</strong> 5,15 fps, lo que imposibilita mostrar enpantalla una secuencia fluida <strong>de</strong> imágenes. A<strong>de</strong>másse ha observado que las imágenes se visualizan conuna latencia aproximada <strong>de</strong> 2 segundos. Los mejoresresultados se obtienen configurando la cámara a10 fps, lo cual es razonable porque se evita saturar laaplicación con imágenes que no es capaz <strong>de</strong> procesar.Aunque existe una apreciable mejora en la capturareduciendo el tamaño <strong>de</strong> la imagen (25 % fps con 1/4<strong>de</strong> la imagen) el resultado es inferior a 5 fps.En una tercera fase hemos segmentado la imagenpor colores. Los resultados obtenidos son muy similaresa los <strong>de</strong> la tabla II lo cual indica que el mayorcoste se centra en la captura y posterior recodificación<strong>de</strong> las imágenes para su visualización.De los resultados se pue<strong>de</strong> concluir que la frecuencia<strong>de</strong> procesamiento es baja, aún implementandotodas las mejoras propuestas para ganar eficiencia,tales como procesar la imagen en un hilo aparte yusando la herramienta NDK. Parece que este comportamientoes <strong>de</strong>bido a la ineficiencia <strong>de</strong>l sistemaoperativo para tratar imágenes. Por cada imagencapturada se reserva la memoria necesaria, se guarda,se procesa y se elimina la referencia a dicha porción<strong>de</strong> memoria [12]. En Java no se libera la memoriaautomáticamente, sino que el recolector <strong>de</strong> basura oGC (Garbage Collector) se encarga <strong>de</strong> hacerlo. Esteproceso es muy costoso y poco eficiente. En Androidconsume entre 100 y 300 milisegundos. Al no reutilizarla memoria asignada a cada imagen el recolector<strong>de</strong> basura <strong>de</strong>be activarse muy a menudo.<strong>La</strong> versión 2.2 <strong>de</strong> Android incluye nuevos métodosque permiten especificar el buffer al que se copiala imagen, eliminando así la necesidad <strong>de</strong> reservar yliberar memoria para cada imagen capturada.Los resultados <strong>de</strong> las pruebas se muestran en latabla III.En el Galaxy S la mejora es <strong>de</strong> 50 % (<strong>de</strong>3,90 a 5,70) teniendo en cuenta un aumento <strong>de</strong>l 50 %en el tamaño <strong>de</strong> las imágenes a procesar. El retardo<strong>de</strong> visualización <strong>de</strong> las imágenes también ha bajadoa aproximadamente 1 segundo. Sin embargo, siguesiendo imposible trabajar en tiempo real únicamentecon las imágenes obtenidas por la cámara. Es necesariala ayuda <strong>de</strong> otros sensores para conocer el estado<strong>de</strong>l smartphone en el mundo que lo ro<strong>de</strong>a.B. Sensores <strong>de</strong> posicionamiento integradosEn esta sección se analizan las posibilida<strong>de</strong>s <strong>de</strong> posicionamiento<strong>de</strong> un smartphone mediante el uso <strong>de</strong>acelerómetros, brújulas, GPS y triangulación <strong>de</strong> red<strong>de</strong> telefonía. Se <strong>de</strong>scribe cada sensor y los resultadosobtenidos en un Milestone, siendo similares en elresto <strong>de</strong> dispositivos.Un acelerómetro mi<strong>de</strong> la aceleración a la que se vesometido, es <strong>de</strong>cir, el cambio en su velocidad. Nor-<strong>JP2011</strong>-620


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 3: Mo<strong>de</strong>lo <strong>de</strong> prueba en OpenGL ES.Fig. 1: Valores obtenidos por los acelerómetros <strong>de</strong>lMotorola Milestone mientras el usuario camina.Fig. 2: Valores obtenidos por las brújulas <strong>de</strong>l MotorolaMilestone.malmente un dispositivo contiene tres acelerómetros,uno en cada eje. Los acelerómetros se pue<strong>de</strong>n utilizarpara saber la posición relativa <strong>de</strong>l dispositivo conrespecto al suelo, suponiendo que la fuerza <strong>de</strong> la graveda<strong>de</strong>s la fuerza dominante. <strong>La</strong> precisión no es muyalta, pero es aceptable para la mayoría <strong>de</strong> las aplicaciones.En la figura 1 se muestran los datos cuandoel usuario coge el móvil en vertical y avanza en línearecta. El eje Z es el <strong>de</strong> avance, el Y es el perpendicularal suelo y el X es el lateral. En la figura 1 sereconoce un patrón regular <strong>de</strong> casi un paso cada segundo(crestas en el eje Y ). En el eje X se observa elmovimiento lateral según cada pisada. Movimientosalgo más complejos serían difíciles <strong>de</strong> reconocer.Una brújula digital mi<strong>de</strong> la dirección <strong>de</strong> los camposmagnéticos presentes en su entorno, especialmente elcampo magnético <strong>de</strong> la Tierra. Normalmente en losdispositivos móviles se integran tres brújulas colocadasen cada eje <strong>de</strong>l espacio [13]. En la figura 2 semuestran los resultados obtenidos en un giro bruscoen un sentido y volver a la posición inicial con un giromucho mucho más suave, durante unos 3 segundos.Se pue<strong>de</strong> observar que la brújula se adapta lentamenteante cambios bruscos, generando medidas incorrectas.Ante giros suaves la brújula es mucho másfiable.Para calcular la orientación <strong>de</strong>l dispositivo en An-droid se recomienda recoger la información <strong>de</strong> losacelerómetros y las brújulas. Un aspecto interesante<strong>de</strong> este método es que se le pue<strong>de</strong> indicar que posicióntendrá por <strong>de</strong>fecto el móvil durante el uso <strong>de</strong> nuestraaplicación, es <strong>de</strong>cir, la posición relativa <strong>de</strong> sus tresejes con respecto al mundo real, lo que permitirá obtenermedidas más precisas para esa configuraciónespecífica. Como hemos visto, ante cambios suavesel cálculo <strong>de</strong> la orientación <strong>de</strong>l dispositivo en su entornoes relativamente fiable. Sin embargo, <strong>de</strong>terminarel <strong>de</strong>splazamiento (cambio <strong>de</strong> posición y orientación)es mucho más complicado y sensible a errores,ya que es necesario integrar dos veces la aceleraciónmedida <strong>de</strong>spués <strong>de</strong> eliminar la fuerza <strong>de</strong> la gravedad(según la orientación calculada por la brújula).El GPS es un sistema <strong>de</strong> posicionamiento portriangulación vía satélite. Pue<strong>de</strong> ser usado en todoel mundo siempre que haya el suficiente número <strong>de</strong>satélites visibles. Dentro <strong>de</strong> un edificio las medidasson poco precisas y mayoritariamente no hay cobertura.<strong>La</strong>s medidas obtenidas indican la posición <strong>de</strong>ldispositivo en la esfera terrestre, contando con unaprecisión <strong>de</strong> unos pocos metros. A<strong>de</strong>más no proporcionainformación fiable sobre la orientación o inclinación<strong>de</strong>l dispositivo. Por otra parte, se ha observadoque los datos se generan con un retraso <strong>de</strong> entre 1y 2 segundos. <strong>La</strong> precisión <strong>de</strong>l sistema es <strong>de</strong> 10 metrosen exteriores. Por todo ello, no es posible posicionary mover con realismo objetos virtuales próximos aldispositivo.El posicionamiento por red calcula la posición portriangulación usando la cobertura <strong>de</strong> la red <strong>de</strong> telefoníamóvil. Este sistema tiene aun menos precisiónque el GPS. A su favor cuenta con que tiene un tiempo<strong>de</strong> inicialización mucho menor y consume menosbatería, ya que no utiliza ninguna otra señal que la<strong>de</strong> telefonía. Otra <strong>de</strong> sus ventajas es que pue<strong>de</strong> serusado en interiores, lugares don<strong>de</strong> el GPS no tieneun buen funcionamiento. De cualquier modo, ambossistemas no son excluyentes.C. Síntesis <strong>de</strong> gráficos en AndroidEl API para la síntesis <strong>de</strong> gráficos incluido en Androi<strong>de</strong>s OpenGL ES [14]. Una <strong>de</strong> las principales características<strong>de</strong> la versión para sistemas empotrados<strong>de</strong> OpenGL es que solo existe un tipo <strong>de</strong> primitivas<strong>JP2011</strong>-621


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA IV: Análisis <strong>de</strong>l rendimiento <strong>de</strong> OpenGL ES en un sistema Android.Frecuencia (fps)Puntos GeeksPhone Milestone Galaxy SC1 C2 C3 C4 C1 C2 C3 C4 C1 C2 C3 C43 K 35 35 35 33 30 30 30 30 55 55 55 559 K 18 19 19 15 30 29 29 28 55 55 55 5515 K 12 10 10 10 29 26 26 25 55 55 55 5530 K 8 - - - 25 22 22 19 55 55 55 5575 K - - - - 18 15 15 12 55 53 53 50100 K - - - - - - - - 55 44 44 41que es el triángulo. Con el objetivo <strong>de</strong> analizar el rendimientoobtenido en la síntesis <strong>de</strong> gráficos, se hanrealizado distintos experimentos con los dispositivos<strong>de</strong> la tabla I.<strong>La</strong> primera prueba consistió en comprobar el rendimientoa medida que se iban aumentando el número<strong>de</strong> primitivas a sintetizar. Los resultados para elmo<strong>de</strong>lo <strong>de</strong> la figura 3 se muestran en la columna C1<strong>de</strong> la tabla IV. Se pue<strong>de</strong> observar que efectivamenteel rendimiento empeora a medida que aumenta elnúmero <strong>de</strong> polígonos que se sintetiza salvo para elGalaxy S, en el que se percibe una pérdida <strong>de</strong> rendimientoa partir <strong>de</strong> los 300K puntos.En la columna C2 <strong>de</strong> la tabla IV se ven los resultados<strong>de</strong> añadir una textura a los mo<strong>de</strong>los. <strong>La</strong> inclusión<strong>de</strong> texturas mejora notablemente el aspecto visual<strong>de</strong>l entorno virtual a costa <strong>de</strong> suponer una pérdidamínima <strong>de</strong> eficiencia, como mucho <strong>de</strong> un 17 % cuandose utiliza un mo<strong>de</strong>lo <strong>de</strong> 75.000 puntos en el Milestone.En la columna C3 <strong>de</strong> la tabla IV se presentan losresultados <strong>de</strong> las pruebas <strong>de</strong> inclusión <strong>de</strong> transparencias.Su presencia apenas tiene influencia con respectoa la síntesis con texturas.En la columna C4 <strong>de</strong> la tabla IV se muestran losdatos al incluir iluminación. En este caso el rendimientollega a <strong>de</strong>crecer un 24 % para el Milestone enuna escena con 30K puntos. Esta pérdida <strong>de</strong> rendimientoes <strong>de</strong>bida a los cálculos adicionales para <strong>de</strong>terminarel color <strong>de</strong> cada píxel <strong>de</strong> la escena. Hay que<strong>de</strong>finir las luces presentes en la escena, indicando suposición, tipo, color e intensidad y se <strong>de</strong>be dotar <strong>de</strong>normales a cada vértice <strong>de</strong>l mo<strong>de</strong>lo.De los posibles métodos <strong>de</strong> animación hemos analizadola inclusión <strong>de</strong> morphing [15]. Esta técnica consisteen, disponiendo <strong>de</strong> un mo<strong>de</strong>lo inicial y <strong>de</strong> unmo<strong>de</strong>lo final, calcular mediante interpolación los estadosintermedios <strong>de</strong> los puntos que componen dichomo<strong>de</strong>lo en una metamorfosis entre ambos mo<strong>de</strong>los.<strong>La</strong> técnica tiene un gran coste computacional, ya quepara cada fotograma se <strong>de</strong>be calcular la posición <strong>de</strong>cada uno <strong>de</strong> los puntos que componen el mo<strong>de</strong>lo.Para probar el rendimiento <strong>de</strong>spués <strong>de</strong> incluir estaopción se utilizó el mo<strong>de</strong>lo, <strong>de</strong> unos 800 puntos y 300polígonos, que se muestra en la figura 4, con texturase iluminación. <strong>La</strong> tabla V muestra los fps para variasescenas con el mo<strong>de</strong>lo <strong>de</strong> la figura 4 replicado variasveces. Sin embargo, los resultados obtenidos aplican-TABLA V: Comparativa <strong>de</strong> escenas con mo<strong>de</strong>losestáticos contra escenas con mo<strong>de</strong>los dinámicos.Puntos GeeksPhone Milestone Galaxy Sest anim est anim est anim800 40 21 30 30 55 551,6 K 32 14 30 25 55 552,4 K 27 10 30 18 55 554 K 21 6 30 10 55 518 K - - 27 5 55 2912 K - - - - 55 2016 K - - - - 55 15Fig. 4: Animación mediante técnicas <strong>de</strong> morphing. Ala izquierda el estado inicial y a la <strong>de</strong>recha el estadofinal.do morphing gozan <strong>de</strong> gran calidad, por lo que sepue<strong>de</strong> optar por incluirlo con mo<strong>de</strong>los <strong>de</strong> 1.6K enel Milestone y <strong>de</strong> 8K en el Galaxy S para dotar <strong>de</strong>mayor realismo a la escena creada.D. DiscusiónUna vez realizado este primer análisis <strong>de</strong> la plataformase obtienen varias conclusiones. Por una parte,se ha comprobado el funcionamiento <strong>de</strong> los sensores<strong>de</strong> posicionamiento integrados. Los acelerómetros yla brújula obtienen resultados relativamente fiablescon errores no <strong>de</strong>masiado gran<strong>de</strong>s. El GPS presentaun error <strong>de</strong>masiado gran<strong>de</strong> para usarlo en una aplicacióncomo la que se propone en este trabajo, quenecesitaría conocer <strong>de</strong>splazamientos <strong>de</strong>, como máximo,un metro.Por otra parte, se ha <strong>de</strong>scubierto una gran carenciaen cuanto al tratamiento <strong>de</strong> imagen en la plataforma,principalmente en cuanto a la latencia. <strong>La</strong>saplicaciones <strong>de</strong> realidad aumentada más habitualesen otros entornos hacen un análisis complejo <strong>de</strong> la<strong>JP2011</strong>-622


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA VI: Frecuencia en fps <strong>de</strong> la aplicación en susdistintos estados.(a) BatGhost(b) HulkGhostMilestone GeekPhone Galaxy SEstado Cám Ogl Cám Ogl Cám OglImagen +síntesis 3,25 15 2,75 8 4,1 35Imagen +morphing 2,75 8 2,5 3 3,6 23Síntesis 30 21 44Morphing 28 17 41(c) EmGhostFig. 5: Mo<strong>de</strong>los tridimensionales.(d) SuperGhostFig. 6: Detección <strong>de</strong> eventos en el juego.información obtenida <strong>de</strong> la cámara y ubican los objetosvirtuales usando principalmente esa fuente <strong>de</strong>información. En vista <strong>de</strong> los resultados obtenidos ennuestro análisis, este tipo <strong>de</strong> aplicaciones se hacen actualmenteinviables en los dispositivos Android probados.Por último, en cuanto a la síntesis <strong>de</strong> gráficos, seha observado que existen limitaciones <strong>de</strong> tamaño yen la complejidad <strong>de</strong>l mo<strong>de</strong>lo que se pue<strong>de</strong> visualizar.Por los resultados obtenidos en las pruebas realizadas,se ha comprobado que el hardware gráficoresulta lo suficientemente potente como para representarmo<strong>de</strong>los no muy complejos usando texturase iluminación. Por ello, para la aplicación se usarántodas las capacida<strong>de</strong>s estudiadas para intentar crearunos mo<strong>de</strong>los gráficos atractivos pero limitando lacomplejidad <strong>de</strong>l mo<strong>de</strong>lo para obtener tiempo real.III. Juego <strong>de</strong> RA en un sistema Android<strong>La</strong> aplicación que se preten<strong>de</strong> crear es un juegoque, analizando la imagen tomada por la cámara entiempo real, <strong>de</strong>termine la presencia <strong>de</strong> enemigos queel jugador <strong>de</strong>berá cazar. Para buscar un enemigo se<strong>de</strong>be encontrar un objeto real <strong>de</strong> un color <strong>de</strong>terminado.Cada tipo <strong>de</strong> enemigo aparece ante un tipo <strong>de</strong>evento distinto. Con ese objetivo <strong>de</strong>l juego, un primerrequisito será mostrar elementos virtuales sobrela imagen obtenida <strong>de</strong> la cámara. Dichos elementos<strong>de</strong>berán simular encontrarse en el mundo real, por loque ante un movimiento <strong>de</strong> la cámara ellos <strong>de</strong>beránmoverse también. Se preten<strong>de</strong> cazar los enemigos,que reaccionan <strong>de</strong> manera distinta ante cada disparo.Cuando se da caza a un enemigo, se obtiene unarecompensa en forma <strong>de</strong> puntos y <strong>de</strong> un número aleatorio<strong>de</strong> disparos extra. Por otra parte, si un enemigonos golpea per<strong>de</strong>remos una vida. Cuando nuestronúmero <strong>de</strong> vidas sea cero se per<strong>de</strong>rá la partida.Existirán varios tipos <strong>de</strong> enemigos, con distintosmovimientos y características <strong>de</strong> ren<strong>de</strong>ring cada uno<strong>de</strong> ellos: BatGhost (figura 5a), fue diseñado comoejemplo <strong>de</strong> animación por partes. Sus alas se muevenin<strong>de</strong>pendientemente dando sensación <strong>de</strong> aleteo,HulkGhost (figura 5b) fue diseñado como ejemplo<strong>de</strong> animación mediante técnicas <strong>de</strong> morphing consistenteen un parpa<strong>de</strong>o, abriendo y cerrando su ojo,EmGhost (figura 5c) se diseñó pensando en crear unenemigo que rebotase, saltando por encima <strong>de</strong>l jugadory SuperGhost (figura 5d) se diseñó con el objetivo<strong>de</strong> crear un enemigo que se moviese en torno al jugador,mientras se acerca cada vez más a él.A la hora <strong>de</strong> ejecutar la síntesis <strong>de</strong> gráficos medianteOpenGL ES, el sistema operativo se encargaautomáticamente <strong>de</strong> hacerlo en un hilo distinto alprincipal, permitiendo <strong>de</strong> este modo <strong>de</strong>sacoplar suejecución. Siguiendo las recomendaciones dadas porlos <strong>de</strong>sarrolladores <strong>de</strong> Android [16], se ha evitado lallamada a métodos a través <strong>de</strong> una interfaz, eliminandolas interfaces incluidas por motivos <strong>de</strong> facilitarla reusabilidad <strong>de</strong>l código, por necesitar más tiempopara realizarse. A<strong>de</strong>más se ha intentado en la mayormedida posible las reservas <strong>de</strong> memoria, evitandocrear objetos nuevos y utilizando en la medida <strong>de</strong> loposible tipos <strong>de</strong> datos primitivos.IV. Resultados experimentalesEn esta sección se presenta el rendimiento obtenidocon la aplicación en términos <strong>de</strong> fotogramas porsegundo. En la tabla VI se muestran los resultadosobtenidos calculando el rendimiento <strong>de</strong> los aspectoscríticos <strong>de</strong> la aplicación durante una serie <strong>de</strong> ejecucionestípicas.En el Motorola Milestone la frecuencia <strong>de</strong> procesado<strong>de</strong> imágenes <strong>de</strong> la cámara varía <strong>de</strong> los 3,25 fpscuando no se encuentran enemigos visibles a los 2,75fps cuando hay un enemigo animado con morphing.Por otra parte, la síntesis <strong>de</strong> gráficos presenta una<strong>JP2011</strong>-623


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011frecuencia <strong>de</strong> refresco <strong>de</strong> unos 15 fps, cayendo hastalos 8 fps con un solo mo<strong>de</strong>lo animado presente en laescena.En el GeeksPhone One la frecuencia <strong>de</strong> procesado<strong>de</strong> imágenes es algo menor, situándose en un máximo<strong>de</strong> 2,75 fps. Como se observa, la mayor pérdida en elrendimiento se nota en el apartado gráfico. Mientrasse está procesando la imagen tomada <strong>de</strong> la cámara,los valores <strong>de</strong> síntesis <strong>de</strong> gráficos son un 50 % menosque los valores obtenidos con el Motorola Milestone.En el Galaxy S los resultados son mejores, obteniendouna frecuencia <strong>de</strong> procesado <strong>de</strong> imagen entre3,6 y 4,1 fps junto con una frecuencia <strong>de</strong> síntesis <strong>de</strong>gráficos <strong>de</strong> 35 fps en síntesis <strong>de</strong> mo<strong>de</strong>los estáticos y23 con un mo<strong>de</strong>lo animado, siendo en este apartadográfico en don<strong>de</strong> más se percibe la mejoría.Por otra parte, y <strong>de</strong>bido también a la pérdida <strong>de</strong>rendimiento en el procesado <strong>de</strong> la imagen, el retardo<strong>de</strong> las imágenes obtenidas <strong>de</strong>s<strong>de</strong> la cámara ha aumentado,situándose en esta aplicación en valores cercanosa los 2 segundos.Como se ha comentado anteriormente, se ha <strong>de</strong>cididootorgar movimiento propio a los enemigos, nopermaneciendo anclados a la posición en la que sehan <strong>de</strong>tectado. Teniendo esto en cuenta, y que solose permite un único enemigo simultáneamente, sepue<strong>de</strong> evitar el procesado <strong>de</strong> la imagen cuando existeun enemigo activo. Con esto se ha conseguido unamejora notable en cuanto al rendimiento <strong>de</strong> la síntesis<strong>de</strong> gráficos, consiguiendo unos 30 fps en el Milestone,unos 21 fps en el GeeksPhone y unos 44 fps en elGalaxy S, unos números suficientemente altos comopara conseguir una flui<strong>de</strong>z muy aceptable en el juego.V. conclusionesEn este trabajo se presenta un estudio <strong>de</strong> las capacida<strong>de</strong>s<strong>de</strong> los smartphones que incluye un análisis<strong>de</strong> sus posibilida<strong>de</strong>s <strong>de</strong> posicionamiento en su entorno.Po<strong>de</strong>mos concluir que obtener la orientación<strong>de</strong>l dispositivo es relativamente sencillo y fiable, peroconocer el <strong>de</strong>splazamiento <strong>de</strong>l dispositivo se hacemuy complicado. Calcularlo mediante los valores obtenidospor los acelerómetros es poco fiable (por loserrores cometidos en la doble integración) y, por otraparte, los sistemas <strong>de</strong> geolocalización tienen un margen<strong>de</strong> error <strong>de</strong>masiado gran<strong>de</strong> (unos 10 metros) paranuestros requisitos.Otro punto <strong>de</strong>l estudio ha sido comprobar qué informaciónse pue<strong>de</strong> extraer <strong>de</strong> la cámara y con qué limitaciones.El número <strong>de</strong> fotogramas que se pue<strong>de</strong>nvisualizar es <strong>de</strong> menos <strong>de</strong> 6 por segundo. Incluir otrosprocesamientos (como la segmentación por colores)no tiene un impacto apreciable. <strong>La</strong> principal limitaciónes la latencia con la que se visualiza la imagen:cerca <strong>de</strong> un segundo en el mejor <strong>de</strong> los casos.Con respecto a la síntesis <strong>de</strong> imágenes con la libreríaOpenGL ES, se ha probado la inclusión <strong>de</strong>texturas, iluminación y transparencias, observandoun rendimiento aceptable en escenas <strong>de</strong> hasta 15Kpuntos en un móvil <strong>de</strong> gama media como el MotorolaMilestone. <strong>La</strong> utilización <strong>de</strong> morphing implica unapérdida <strong>de</strong> rendimiento <strong>de</strong> más <strong>de</strong>l 20 % cada vez quese dobla la cantidad <strong>de</strong> puntos.Para mostrar las posibilida<strong>de</strong>s <strong>de</strong> los smartphonesutilizados se ha implementado un juego sencillo <strong>de</strong>realidad aumentada. El rendimiento final obtenido<strong>de</strong>l juego es <strong>de</strong> 3,25 imágenes extraídas <strong>de</strong> la cámarapor segundo y <strong>de</strong> 28 fps en la síntesis <strong>de</strong> gráficos enun dispositivo <strong>de</strong> gama media-alta como el MotorolaMilestone. Estos resultados mejoran en un móvil conmás potencia como el Samsung Galaxy S (con 4,1imágenes procesadas por segundo y 35 fps <strong>de</strong> síntesis)y empeoran notablemente en uno menos potentecomo el GeeksPhone One (2,75 imágenes procesadaspor segundo y síntesis a 8 fps).Agra<strong>de</strong>cimientosDeseamos agra<strong>de</strong>cer a la Xunta <strong>de</strong> Galicia por lafinanciación <strong>de</strong> los proyectos 08TIC001206PR, INCI-TE08PXIB105161PR e INCITE08PXIB262202PR yal Ministerio <strong>de</strong> Ciencia e Innovación, cofinanciadopor fondos FEDER <strong>de</strong> la Unión Europea, por losproyectos TIN2010-16735 y TIN2009-07737.Referencias[1] Marko Gargenta, Learning Android, O’Reilly, first edition,2011.[2] Daniel Wagner and Dieter Schmalstieg, “Making augmentedreality practical on mobile phones,” IEEE ComputerGraphics and Applications, vol. 29, no. 3, 2009.[3] Google Inc., “Google navigation for mobile,”http://www.google.com/mobile/navigation, Última visita:05/01/2011.[4] <strong>La</strong>yar, “<strong>La</strong>yar reality browser,” http://www.layar.com,Última visita: 05/01/2011.[5] “Spectrek,” http://www.spectrekking.com, Última visita:05/01/2011.[6] MADfirm, “Sky siege,” http://madfirm.com, Última visita:14/01/2011.[7] Quest-Com, “Droidshooting,”http://www.quest-com.co.jp, Última visita: 14/01/2011.[8] Hirokazu Kato, “Artoolkit,” http://www.hitl.washington.edu/artoolkit,Adaptado a Android por Igarashi, Atsuoen 2010, Ultima visita: 05/01/2011.[9] Novarama SL., “Invizimals,”http://www.invizimals.com, Última visita: 05/01/2011.[10] Parrot SA., “Ardrone,” http://ardrone.parrot.com, Últimavisita: 05/01/2011.[11] “Android NDK,” http://<strong>de</strong>veloper.android.com/sdk/ndk,Última visita: 25/05/2011.[12] “Android Google Co<strong>de</strong>. Issue 2794: Camera previewcallback memory issue,”http://co<strong>de</strong>.google.com/p/android/issues/<strong>de</strong>tail?id=2794,Última visita: 10/01/2011.[13] “Asahi Kasei Micro<strong>de</strong>vices. 3-axis electronic compass,”http://www.asahi-kasei.co.jp/akm/en/in<strong>de</strong>x.html, Últimavisita: 10/01/2011.[14] Dave Astle and Dave Durnil, OpenGL ES Game Development,Thomson Course Technology, first edition,2004.[15] Tomas Akenine-Möller, Eric Haines, and Naty Hoffman,Real-Time Ren<strong>de</strong>ring, A K Peters, third edition, 2008.[16] Chris Pruett, “Writing real time games for android,”http://www.google.com/events/io/2009/sessions/WritingRealTimeGamesAndroid.html,May 2009, Últimavisita: 05/01/2011.<strong>JP2011</strong>-624


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Un mo<strong>de</strong>lo analítico mejorado para laarquitectura CUDAM. Viñas 1 B.B Fraguela 1 M. Amor 1 y R. Doallo 1Resumen— Este artículo presenta la implementación<strong>de</strong> un mo<strong>de</strong>lo analítico para la estimación <strong>de</strong>l tiempo<strong>de</strong> ejecución <strong>de</strong> aplicaciones CUDA sobre una GPU.Este trabajo se basa en un mo<strong>de</strong>lo previo <strong>de</strong> una arquitecturaTesla que trata <strong>de</strong> estimar los ciclos <strong>de</strong> ejecución<strong>de</strong> una aplicación basándose en un análisis <strong>de</strong>lcódigo. El mo<strong>de</strong>lo pue<strong>de</strong> servir al programador comouna guía <strong>de</strong> las mejores opciones <strong>de</strong> implementaciónpara un <strong>de</strong>terminado problema. En este trabajo sehan confrontado los tiempos estimados por el mo<strong>de</strong>locon las mediciones sobre una tarjeta concreta y se<strong>de</strong>scriben algunas <strong>de</strong>ficiencias <strong>de</strong>tectadas en el mo<strong>de</strong>looriginal. Por otra parte, y esto constituye la principalaportación <strong>de</strong> este trabajo, se ha extendido el mo<strong>de</strong>loa casos que no fueron contemplados originalmente,como la gestión <strong>de</strong>l ancho <strong>de</strong> banda consumido en losaccesos a memoria o el grado <strong>de</strong> coalescencia en losaccesos a memoria global.Palabras clave— GPU, CUDA, GPGPU, mo<strong>de</strong>loanalítico, kernelI. IntroducciónLOS procesadores gráficos o GPUs (Graphics ProcessingUnits) hoy en día se utilizan para ejecutartareas computacionales genéricas, conociéndoseeste uso como GPGPU (o GPU <strong>de</strong> computaciónpropósito general) gracias al soporte que ofrecen alenguajes <strong>de</strong> programación como CUDA [1] <strong>de</strong> Nvidia,u OpenCL [2].Si bien aparecen constantemente nuevos lenguajes<strong>de</strong> programación que buscan reducir el tiempoque <strong>de</strong>dican los programadores a escribir programasparalelos, aún se necesita emplear mucho tiempo yesfuerzo en optimizar estos programas. Por otra parte,las especificaciones <strong>de</strong>talladas <strong>de</strong>l hardware y losestudios <strong>de</strong>l rendimiento teórico proporcionan informaciónque pue<strong>de</strong> ser usada por el programador parala optimización <strong>de</strong> aplicaciones. En esta línea se hanpropuesto trabajos <strong>de</strong> elaboración <strong>de</strong> mo<strong>de</strong>los parael análisis <strong>de</strong>l rendimiento <strong>de</strong> las GPUs [3], medianteel análisis <strong>de</strong> programas [4] o mediante el empleo <strong>de</strong>micro-benchmarks [5], [6], [7].Una herramienta muy útil para ayudar a los <strong>de</strong>sarrolladoresa i<strong>de</strong>ntificar los cuellos <strong>de</strong> botella <strong>de</strong>l rendimientoen un sistema computacional son los mo<strong>de</strong>losanalíticos. Éste es el caso <strong>de</strong>l mo<strong>de</strong>lo que inspiraeste trabajo [8] y que se <strong>de</strong>tallará en la Sección II. Elmo<strong>de</strong>lo original se aplicó a pequeños códigos <strong>de</strong> pruebas,sin embargo su utilización en códigos reales haproporcionado estimaciones bastante alejadas <strong>de</strong> losciclos reales <strong>de</strong> ejecución. En este artículo se proponeun conjunto <strong>de</strong> correcciones <strong>de</strong> las <strong>de</strong>ficiencias <strong>de</strong>lmo<strong>de</strong>lo original y extensiones al mismo, que logran1 Grupo <strong>de</strong> arquitectura <strong>de</strong> computadores (GAC), Univ. <strong>de</strong> ACoruña (UDC), e-mails: {moises.vinas, basilio.fraguela,margamor, ramon.doallo}@udc.esuna aproximación mucho más ajustada <strong>de</strong>l mo<strong>de</strong>loresultante a los tiempos reales <strong>de</strong> ejecución tal comose verá en la Sección IV.El contenido <strong>de</strong> este artículo se distribuye <strong>de</strong> lasiguiente forma: en la Sección II se explica el mo<strong>de</strong>loanalítico original; la Sección III presenta las <strong>de</strong>ficienciasencontradas en el mo<strong>de</strong>lo original, sus correccionesy las extensiones aportadas. En la Sección IV sepresentan y valoran los resultados obtenidos. Finalmente,en la Sección V se exponen y argumentan lasprincipales conclusiones.II. Mo<strong>de</strong>lo analítico basado en elparalelismo <strong>de</strong> warps<strong>La</strong> arquitectura CUDA es una arquitectura multihilo,en la que el trabajo asociado a un kernel esllevado a cabo por un conjunto <strong>de</strong> hilos. Este conjunto<strong>de</strong> hilos, se estructura siguiendo una jerarquía<strong>de</strong> tres niveles lógicos. En la cima <strong>de</strong> esta jerarquíase encuentra el grid, que representa a todo el trabajoa realizar. Un grid se divi<strong>de</strong> en bloques <strong>de</strong> hilosque son ejecutados en paralelo. Cada uno <strong>de</strong> estosbloques está formado por múltiples hilos don<strong>de</strong> cadauno <strong>de</strong> ellos calcula un resultado final. Existe unconcepto que se situaría entre el nivel <strong>de</strong> los hilosindividuales y el bloque <strong>de</strong> hilos, el warp. El warp esun subconjunto <strong>de</strong> hilos <strong>de</strong>l bloque que comparten algunaspropieda<strong>de</strong>s que no comparten con el resto <strong>de</strong>hilos <strong>de</strong>l bloque, como por ejemplo el contador <strong>de</strong> instrucción,<strong>de</strong> tal forma que todos los hilos <strong>de</strong> un warpejecutan una única instrucción al mismo tiempo. Estajerarquía <strong>de</strong> hilos está soportada en la GPU porun conjunto <strong>de</strong> múltiples procesadores. Cada procesador,en a<strong>de</strong>lante SM (Streaming Multiprocessor),pue<strong>de</strong> ejecutar varios warps alternándose en el tiempomientras uno o más warps está esperando porvalores <strong>de</strong> memoria. Esto permite ocultar el coste <strong>de</strong>ejecución <strong>de</strong> los warps que se están ejecutando concurrentemente.El mo<strong>de</strong>lo presentado en [8] se basa en conocercuántas peticiones <strong>de</strong> memoria pue<strong>de</strong>n ser servidasjuntas (Memory Warp Parallelism o MWP),y cuántos warps pue<strong>de</strong>n ser ejecutados juntos mientrasun warp está esperando por valores <strong>de</strong> memoria(Computation Warp Parallelism o CWP). El mo<strong>de</strong>lousa estos dos conceptos para estimar las distintassituaciones que pue<strong>de</strong>n darse en la ejecución <strong>de</strong> uncódigo en GPU. Para ello, se <strong>de</strong>fine tramo <strong>de</strong> computacióncomo el período <strong>de</strong> tiempo durante el cual seejecutan instrucciones <strong>de</strong> un warp en un SM. Análogamente,se <strong>de</strong>fine tramo <strong>de</strong> espera <strong>de</strong> memoria comoel período <strong>de</strong> tiempo durante el cual las peticiones amemoria <strong>de</strong> un warp están siendo servidas.<strong>JP2011</strong>-625


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Así pues, MWP será el número máximo <strong>de</strong> warpspor SM que pue<strong>de</strong>n acce<strong>de</strong>r a memoria global simultáneamentedurante el período <strong>de</strong> tiempo <strong>de</strong>s<strong>de</strong>que un SM ejecuta una instrucción <strong>de</strong> memoria paraun warp, hasta que todas las peticiones <strong>de</strong> memoriapara ese mismo warp sean servidas. MWP está <strong>de</strong>terminadopor el ancho <strong>de</strong> banda <strong>de</strong> memoria, porel paralelismo a nivel <strong>de</strong> bancos <strong>de</strong> memoria y por elnúmero <strong>de</strong> warps ejecutándose en un momento dado.Por otra parte CWP se <strong>de</strong>finirá como el número <strong>de</strong>warps que el SM pue<strong>de</strong> ejecutar durante un tramo <strong>de</strong>espera <strong>de</strong> memoria más uno. Este uno es añadido paracontabilizar al propio warp que estaba esperandopor valores <strong>de</strong> memoria.Fig. 1: Ejemplo para 8 warps activos con CWP mayorque MWPA. Casos <strong>de</strong> ejecuciónEn este subapartado se explica el método <strong>de</strong> estimación<strong>de</strong>l mo<strong>de</strong>lo empleando los conceptos <strong>de</strong>MWP y CWP. Dada una ejecución en una GPU,pue<strong>de</strong>n darse las siguientes situaciones: que CWP seamayor que MWP, que MWP sea mayor que CWP oque MWP sea igual al número <strong>de</strong> warps activos.A.1 CWP es mayor que MWPLos ciclos <strong>de</strong> ejecución en este caso pue<strong>de</strong>n calcularseusando la siguiente ecuación:#A W SMExec cycles = Mem cycles× +Comp p×MW P (1)MW Pdon<strong>de</strong> Comp p es el número <strong>de</strong> ciclos <strong>de</strong> cada tramo<strong>de</strong> computación y se obtiene como:Comp cyclesComp p = (2)#Mem instsdon<strong>de</strong> Comp cycles es el número <strong>de</strong> ciclos <strong>de</strong> computaciónpor cada warp (véase la Ecuación 19 en [8] parasu cálculo), y #Mem insts es el número <strong>de</strong> instrucciones<strong>de</strong> memoria que ejecuta un thread. #A W SMse <strong>de</strong>fine como el número <strong>de</strong> warps activos por SM(#Active warps per SM en el texto original). Esteparámetro <strong>de</strong>pen<strong>de</strong> <strong>de</strong> las características <strong>de</strong>l dispositivohardware tales como el número <strong>de</strong> registrosusados por SM, cantidad máxima <strong>de</strong> bloques activospor SM o el tamaño máximo <strong>de</strong> memoria compartidaque se pue<strong>de</strong> usar por SM. Finalmente, Mem cycleses el número <strong>de</strong> ciclos <strong>de</strong> espera <strong>de</strong> memoria <strong>de</strong> cadawarp, y se halla pon<strong>de</strong>rando los ciclos <strong>de</strong> espera<strong>de</strong> memoria <strong>de</strong> cada tipo <strong>de</strong> acceso (coalescente o nocoalescente) por el número <strong>de</strong> accesos <strong>de</strong> cada tipo.En la Figura 1, se muestra un ejemplo con CWPmayor que MWP para 8 warps en ejecución y contodos los tramos <strong>de</strong> computación y tramos <strong>de</strong> espera<strong>de</strong> memoria <strong>de</strong> warps diferentes. En este ejemplo elsistema pue<strong>de</strong> recibir <strong>de</strong> memoria los datos <strong>de</strong> doswarps simultáneamente, y un tramo <strong>de</strong> computaciónes aproximadamente un tercio <strong>de</strong> uno <strong>de</strong> espera <strong>de</strong>memoria. Así, el SM pue<strong>de</strong> terminar los tramos <strong>de</strong>computación <strong>de</strong> 3 warps durante un tramo <strong>de</strong> espera<strong>de</strong> memoria <strong>de</strong> un warp (esto es, MWP es 2y CWP es 4 en este caso). Como resultado, 6 tramos<strong>de</strong> computación están completamente solapadosFig. 2: Ejemplo para 8 warps activos con MWP mayorque CWPcon dos tramos <strong>de</strong> espera <strong>de</strong> memoria. Por ello, sólo2 computaciones y 4 tramos <strong>de</strong> espera <strong>de</strong> memoriacontribuyen a los ciclos totales <strong>de</strong> ejecución.A.2 MWP es mayor que CWPLos ciclos totales <strong>de</strong> ejecución, en este caso, pue<strong>de</strong>nser calculados usando la siguiente expresión:Exec cycles = Mem L + Comp cycles × #A W SM (3)don<strong>de</strong> Mem L son los ciclos <strong>de</strong> ejecución por cadatramo <strong>de</strong> espera <strong>de</strong> memoria.Este caso se ilustra con CWP=4 y MWP=8, en laFigura 2. Al igual que en la Figura 1 no existe ninguna<strong>de</strong>pen<strong>de</strong>ncia entre los distintos warps, por loque se pue<strong>de</strong>n ejecutar sin ninguna restricción. Lostramos <strong>de</strong> espera <strong>de</strong> memoria están todos completamentesolapados con otros tramos <strong>de</strong> computación y<strong>de</strong> espera <strong>de</strong> memoria <strong>de</strong> otros warps excepto el últimowarp. Los ciclos <strong>de</strong> ejecución totales son la suma<strong>de</strong> 8 tramos <strong>de</strong> computación más un único tramo <strong>de</strong>espera <strong>de</strong> memoria.A.3 MWP igual al número <strong>de</strong> warps activosSi una aplicación no tiene suficiente número <strong>de</strong>warps, el sistema no pue<strong>de</strong> aprovechar el paralelismo<strong>de</strong> warps disponible. MWP y CWP no pue<strong>de</strong>n sermayores que el número <strong>de</strong> warps activos en un SM.En este caso, los ciclos <strong>de</strong> ejecución pue<strong>de</strong>n sercalculados usando la siguiente ecuación:Exec cycles = Mem cycles+Comp cycles+Comp p×(MW P − 1)(4)<strong>JP2011</strong>-626


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 3: Ejemplo <strong>de</strong> la evolución <strong>de</strong>l sistema cuandoMWP es igual al número <strong>de</strong> warps activos: (a) 1 warp(b) 2 warpsEn la Figura 3(a) se muestra un ejemplo en el quese ejecuta un único warp activo por SM (CWP yMWP son 1). Todas las ejecuciones se efectúan <strong>de</strong>forma secuencial. Así, los ciclos <strong>de</strong> ejecución totalesson la suma <strong>de</strong> los tramos <strong>de</strong> computación y <strong>de</strong> memoria.En la Figura 3(b) se muestra la ejecución <strong>de</strong>dos warps con MWP = CWP = 2. Debido al bajonúmero <strong>de</strong> warps activos, en este ejemplo los SMsestán inactivos dos tercios <strong>de</strong>l tramo <strong>de</strong> espera <strong>de</strong>memoria. El tiempo <strong>de</strong> ejecución total es aproximadamentela mitad <strong>de</strong> la suma <strong>de</strong> todos los tramos <strong>de</strong>computación y <strong>de</strong> espera <strong>de</strong> memoria.III. Extensiones al mo<strong>de</strong>lo originalPo<strong>de</strong>mos clasificar las mejoras propuestas sobre elmo<strong>de</strong>lo presentado en [8] en dos grupos. Por un lado,está la corrección <strong>de</strong> partes <strong>de</strong>l mo<strong>de</strong>lo que no seajustaban a la arquitectura CUDA: tratamiento <strong>de</strong>los accesos por halfwarp y <strong>de</strong> los accesos no coalescentes;y por otro lado las extensiones a fin <strong>de</strong> consi<strong>de</strong>raraspectos <strong>de</strong> dicha arquitectura no contemplados enel mo<strong>de</strong>lo original: pon<strong>de</strong>ración <strong>de</strong> lecturas y escrituras,tratamiento <strong>de</strong> las sentencias condicionales o eltratamiento <strong>de</strong>l acceso a memoria <strong>de</strong> texturas y constante.También se incluyen en este apartado algunas<strong>de</strong>ficiencias encontradas en el mo<strong>de</strong>lo original paralas cuales nos limitaremos sólamente a <strong>de</strong>scribirlasya que su mo<strong>de</strong>lado no sería trivial.A. Tratamiento <strong>de</strong> los accesos por halfwarpEl parámetro #Coal per mw se <strong>de</strong>fine en [8] comoel número <strong>de</strong> transacciones <strong>de</strong> memoria que necesitaun warp para acce<strong>de</strong>r a sus datos en memoria cuandose trate <strong>de</strong> un acceso coalescente. Este parámetro,toma siempre el valor uno. Según el algoritmo <strong>de</strong>cálculo <strong>de</strong> la coalescencia expuesto en [9], el número<strong>de</strong> transacciones necesarias para cubrir un warp (32hilos) son dos y no una como afirman los autores <strong>de</strong>lmo<strong>de</strong>lo. En consecuencia se cambió el nombre y elconcepto <strong>de</strong> esta variable por el <strong>de</strong> #Coal per mhw<strong>de</strong> tal forma que ahora sí pue<strong>de</strong> tomar valor igual auno como mínimo, pues cuenta las transacciones porhalfwarp.El mo<strong>de</strong>lo <strong>de</strong>fine la variable #Uncoal per mw comoel número <strong>de</strong> transacciones necesarias para cubrirun tramo <strong>de</strong> espera <strong>de</strong> memoria originado por un accesono coalescente. Para mantener la coherencia entrelas variables #Coal per mw y #Uncoal per mw,y dado que ahora la primera variable está consi<strong>de</strong>randoaccesos las transacciones por halfwarp, se <strong>de</strong>cidiócambiar el rango <strong>de</strong> la segunda variable quedandolimitado inferiormente por 2 y superiormentepor 16 (2 y 16 transacciones por halfwarp, respectivamente).Por tanto se <strong>de</strong>cidió cambiar también elnombre y significado <strong>de</strong> #Uncoal per mw por el <strong>de</strong>#Uncoal per mhw.B. Accesos no coalescentesEl parámetro L B W (Load bytes per warp en elmo<strong>de</strong>lo original) es una media <strong>de</strong>l número <strong>de</strong> bytesa los que acce<strong>de</strong> un warp. Este valor se usa en elmo<strong>de</strong>lo para conocer el MWP máximo limitado porel ancho <strong>de</strong> banda consumido por cada warp. Losautores <strong>de</strong>scriben este parámetro como “número <strong>de</strong>bytes por cada warp” y se obtiene como:L B W = Datasize(typically. 4B) × #T W (5)don<strong>de</strong> #T W es el número <strong>de</strong> hilos por warp.<strong>La</strong> ecuación anterior simplifica algunos aspectos<strong>de</strong> la arquitectura CUDA. En primer lugar, esteparámetro <strong>de</strong>pen<strong>de</strong> <strong>de</strong>l número <strong>de</strong> transacciones necesariopara cubrir un <strong>de</strong>terminado warp. En segundolugar, también se <strong>de</strong>bería tener en cuenta el tamaño<strong>de</strong> esas transacciones, pues no es lo mismo quesean transacciones <strong>de</strong> 32 bytes que <strong>de</strong> 128 bytes. Finalmente,como cada tramo <strong>de</strong> espera <strong>de</strong> memoriatendrá propieda<strong>de</strong>s distintas (grado <strong>de</strong> coalescenciao tamaño <strong>de</strong> segmentos), se <strong>de</strong>berá tener en cuentatambién el número <strong>de</strong> accesos a memoria. <strong>La</strong> correcciónse refleja en la siguiente expresión:L B W =#A M∑i=1((#T 0∑j=1T S ij)+#A M(#T 1∑j=1T S ij))En primer lugar, se trata <strong>de</strong> una media a nivel <strong>de</strong>warp con lo que es necesario conocer el número <strong>de</strong>accesos a memoria que ocurren por cada warp. Paraello, el sumatorio principal itera por los accesosa memoria (#A M) y se divi<strong>de</strong> la cantidad <strong>de</strong> bytesaccedidos por todo el warp entre el número <strong>de</strong> accesos.Se obtiene así una media <strong>de</strong>l ancho <strong>de</strong> bandaconsumido por cada tramo <strong>de</strong> espera <strong>de</strong> memoria. Ensegundo lugar, #T refleja el número <strong>de</strong> transaccionesnecesario por cada acceso a memoria medidas paracada halfwarp. Es un factor importante, ya que noes lo mismo accesos con 16 transacciones <strong>de</strong> 32 bytespor halfwarp, que accesos con 2 transacciones <strong>de</strong> 32bytes por transacción. Finalmente, T S ij se refiereal tamaño <strong>de</strong>l segmento j en el acceso a memoria i.Los tamaños <strong>de</strong> segmento se hallan también con elalgoritmo <strong>de</strong> coalescencia [9].(6)<strong>JP2011</strong>-627


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011C. Pon<strong>de</strong>ración <strong>de</strong> lecturas y escriturasSe ha comprobado que existe una diferencia <strong>de</strong> rendimientoentre los accesos <strong>de</strong> lectura y <strong>de</strong> escritura.Para llegar a la conclusión anterior, se realizaronpruebas cuyo código era básicamente una o variasescrituras y se confrontaron los tiempos obtenidoscon los hallados en otras pruebas con igual estructurapero sustituyendo las escrituras por lecturas. Esteestudio concluyó que la sustitución <strong>de</strong> una lecturapor una escritura significaba un notable aumento <strong>de</strong>ltiempo <strong>de</strong> ejecución.Con el objetivo <strong>de</strong> pon<strong>de</strong>rar el ancho <strong>de</strong> bandaconsumido por los distintos accesos a memoria segúnse trate <strong>de</strong> escrituras y lecturas, se <strong>de</strong>cidió gravar elancho <strong>de</strong> banda teórico en función <strong>de</strong>l tipo <strong>de</strong> acceso.<strong>La</strong> ecuación que pon<strong>de</strong>ra el ancho <strong>de</strong> banda es:AB avg = AB teórico ×w read+peso×AB teórico ×w write (7)don<strong>de</strong>#Mem inst readw read =#Mem insts#Mem inst writew write =#Mem instsy el valor <strong>de</strong> la variable peso fue hallado comparandoresultados <strong>de</strong> pruebas que contenían lecturas con losresultados <strong>de</strong> esas mismas pruebas tras sustituir esaslecturas por escrituras.D. Sentencias condicionalesEl concepto <strong>de</strong> divergencia aparece ligado a la ejecución<strong>de</strong> sentencias condicionales en una GPU. Sitodos los hilos <strong>de</strong> un warp tienen el mismo resultadoal evaluar la condición <strong>de</strong>l salto, no habrá efectoalguno sobre el rendimiento normal, esto es, el SMejecutará una única instrucción para los 32 hilos. Sino es así, cada uno <strong>de</strong> los posibles caminos que tengaese salto, será serializado <strong>de</strong>sactivando los hilosque no estén en el camino que se esté ejecutando enese momento. Cuando todos los caminos alternativosse hayan completado, los hilos convergerán a unúnico camino <strong>de</strong> ejecución. <strong>La</strong> ejecución secuencial<strong>de</strong> instrucciones ligado a la aparición <strong>de</strong> divergenciasupone un importante impacto en el rendimiento.Los autores <strong>de</strong>l mo<strong>de</strong>lo original advertían que elcoste <strong>de</strong> ejecutar instrucciones <strong>de</strong> salto condicionalno era mo<strong>de</strong>lado en <strong>de</strong>talle. Se sugería que se contasenlas instrucciones <strong>de</strong> las dos ramas <strong>de</strong>l salto tantosi se cumplía la condición <strong>de</strong> salto como si no, conel fin <strong>de</strong> obtener un límite superior en los ciclos <strong>de</strong>ejecución.En este trabajo se siguieron las siguientes reglascuando se encontraba un bloque <strong>de</strong> código condicionalen un código:Condición no trivial (<strong>de</strong>pendiente <strong>de</strong> datoso <strong>de</strong> cálculos): se proce<strong>de</strong> <strong>de</strong> la forma habitual,separando las que sean <strong>de</strong> computación, accesoa memoria o sincronización para cada una <strong>de</strong> lasdos ramas. Se asume pues, la ejecución <strong>de</strong> ambasramas por todos los hilos.(8)(9)Condición trivial (<strong>de</strong>pendiente <strong>de</strong>l i<strong>de</strong>ntificador<strong>de</strong> hilo): Se proce<strong>de</strong> como en el caso anteriorpero multiplicando el conteo <strong>de</strong> instruccionespor un factor que indique el porcentaje <strong>de</strong>hilos <strong>de</strong> un bloque que ejecutan dicha rama <strong>de</strong>código. Los bloques <strong>de</strong> código condicionales paralos cuales se produzca divergencia <strong>de</strong>ntro <strong>de</strong> loshilos <strong>de</strong> un warp se tratarán igual que los casos<strong>de</strong> condición no trivial.E. Acceso a memoria <strong>de</strong> texturas y constanteEl mo<strong>de</strong>lo explicado en la Sección II, no consi<strong>de</strong>raestos tipos <strong>de</strong> acceso a memoria. Debido a su importancia,en este trabajo se ha optado por abordarestos tipos <strong>de</strong> acceso.Para conseguir un buen rendimiento <strong>de</strong> la arquitecturaCUDA es clave hacer un uso a<strong>de</strong>cuado <strong>de</strong> lajerarquía <strong>de</strong> memoria. Esto implica tratar <strong>de</strong> aprovecharal máximo la memoria on-chip (memoria compartida,constante y caché <strong>de</strong> texturas) en <strong>de</strong>trimento<strong>de</strong> la memoria off-chip (memoria global, memorialocal y memoria <strong>de</strong> texturas). Por tanto las memoriason-chip serán muy utilizadas, a pesar <strong>de</strong> lo cual en[8] no se contemplan ni se proporcionan guías paramo<strong>de</strong>lar los accesos a las mismas. Con las siguientesconsi<strong>de</strong>raciones se consigue aproximar, o al menosgeneralizar el mo<strong>de</strong>lo, para abordar casi toda la jerarquía<strong>de</strong> memorias.En primer lugar, los accesos a memoria <strong>de</strong> texturascercanos (localidad espacial) en tiempos cercanos(localidad temporal) van a repercutir en mejorestiempos gracias al uso <strong>de</strong> la caché <strong>de</strong> texturas. Nvidiarecomienda el uso <strong>de</strong> memoria <strong>de</strong> texturas cuando losaccesos a memoria global son no coalescentes y pue<strong>de</strong>nmejorar su rendimiento si dichos accesos cumplenla localidad espacial <strong>de</strong> la que se beneficia lamemoria <strong>de</strong> texturas. Para el caso <strong>de</strong> accesos coalescenteslas diferencias <strong>de</strong> tiempo entre usar memoriaglobal o usar memoria <strong>de</strong> texturas se ha mantenidoen la mayoría <strong>de</strong> las pruebas realizadas por <strong>de</strong>bajo<strong>de</strong>l 10 %, sólo superando ligeramente esta cifra parael caso <strong>de</strong> accesos “espacialmente cercanos”. Desafortunadamente,el hecho <strong>de</strong> <strong>de</strong>terminar si se trata <strong>de</strong>accesos cercanos en momentos cercanos es <strong>de</strong>masiadocomplejo a partir <strong>de</strong> un código fuente. En este estudiose consi<strong>de</strong>ró la misma latencia para los accesos amemoria <strong>de</strong> texturas que para los accesos coalescentesa memoria global, aún siendo conocedores <strong>de</strong> laimprecisión cometida.En segundo lugar, dadas las características <strong>de</strong> lamemoria constante, la cual es cacheable y tan rápidacomo la utilización <strong>de</strong> registros si todos los hilos <strong>de</strong>un halfwarp leen la misma dirección, se consi<strong>de</strong>raráneste tipo <strong>de</strong> accesos como instrucciones <strong>de</strong> computación<strong>de</strong> cara al mo<strong>de</strong>lo.F. Deficiencias <strong>de</strong>l mo<strong>de</strong>lo originalA continuación presentamos las <strong>de</strong>ficiencias encontradasen el mo<strong>de</strong>lo original. Se trata <strong>de</strong> dos imprecisiones<strong>de</strong>tectadas en la metodología <strong>de</strong>l mo<strong>de</strong>loanalítico, que influirán en el ajuste <strong>de</strong> los resultados<strong>JP2011</strong>-628


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 4: Retrasos adicionales <strong>de</strong>bidos a la sincronización<strong>de</strong> threads tras cada acceso a memoria<strong>de</strong>l mo<strong>de</strong>lo respecto a los tiempos <strong>de</strong> ejecución reales.F.1 Barrera <strong>de</strong> sincronizaciónUna instrucción <strong>de</strong> sincronizaciónsyncthreads() provoca que todos los warps<strong>de</strong> un bloque activo se <strong>de</strong>tengan hasta que todos loswarps <strong>de</strong> ese mismo bloque alcancen esa instrucción.<strong>La</strong> Figura 4 muestra el mo<strong>de</strong>lado <strong>de</strong> sincronizaciónconsi<strong>de</strong>rado en [8]. Los warps que aparecen en lafigura son los warps activos, los cuales componenlos bloques activos. Por lo tanto, son warps que nonecesariamente pertenecen al mismo bloque, si bienserá así en la mayoría <strong>de</strong> los casos. A la hora <strong>de</strong>estimar los ciclos <strong>de</strong> ejecución se dijo, y así se pue<strong>de</strong>ver en la imagen, que la instrucción <strong>de</strong> sincronizaciónprovocaba el retraso <strong>de</strong> todos los warps activos. Estoes cierto si sólo hay un único bloque activo. En casocontrario, esa barrera <strong>de</strong> sincronización no <strong>de</strong>bieraretrasar a todos los warps activos sino sólo a los quepertenecen al bloque cuyos warps hayan ejecutadouna instrucción <strong>de</strong> sincronización.F.2 Tramos <strong>de</strong> computación <strong>de</strong>sbalanceadosTodos los escenarios <strong>de</strong> ejecución <strong>de</strong> warps activospresentados en [8] para explicar las ecuaciones <strong>de</strong>contabilización <strong>de</strong> los ciclos <strong>de</strong> ejecución en el mo<strong>de</strong>lo,se basan en tramos <strong>de</strong> computación aproximadamenteiguales. Es <strong>de</strong>cir, cuando se tienen dos tramos<strong>de</strong> computación por warp, el segundo tramo es igualal primero. Esto no ocurre en la realidad por lo queesta simplificación pue<strong>de</strong> conducir a la obtención <strong>de</strong>resultados incorrectos.IV. Resultados experimentales<strong>La</strong> GPU utilizada en este trabajo ha sido la NVI-DIA GTX 295. Esta GPU está constituida en realidadpor dos GPUs con 240 núcleos cada una, haciendoun total <strong>de</strong> 480 núcleos. Otros parámetrosrelevantes <strong>de</strong> este dispositivo, en particular <strong>de</strong> caraal mo<strong>de</strong>lo, son: 1,242 GHz <strong>de</strong> frecuencia <strong>de</strong> reloj,223,8 GB/s <strong>de</strong> ancho <strong>de</strong> banda a memoria para todoel dispositivo, y 111,9 GB/s para cada una <strong>de</strong> lasdos GPUs (son dos espacios <strong>de</strong> memoria totalmentein<strong>de</strong>pendientes). <strong>La</strong> GPU NVIDIA GTX 295 esun dispositivo <strong>de</strong> capacidad <strong>de</strong> computación 1.3. Estedato será tenido en cuenta en varios puntos <strong>de</strong>lmo<strong>de</strong>lo tales como el número <strong>de</strong> hilos máximo porSM, el tamaño máximo <strong>de</strong> memoria compartida o elmáximo número <strong>de</strong> registros usados por cada bloque<strong>de</strong> hilos.Familia <strong>de</strong> pruebasDesviaciónmo<strong>de</strong>lo extendidosumavectores 13,64 %saxpy 6,97 %simplePitchLinearTexture 0,95 %matrixMul 54,25 %sepia 23 %reduction 27,6 %FDTD 5,73 %Dct8x8 1,8 %BlackScholes 41 %Fractal 41,95 %TABLA I: Diferencias entre el tiempo estimado conel mo<strong>de</strong>lo extendido y el tiempo real para las distintasfamilias <strong>de</strong> pruebasPor otra parte, hay tres parámetros <strong>de</strong>l mo<strong>de</strong>lomuy ligados a la arquitectura concreta a mo<strong>de</strong>larque se obtienen mediante experimentación en [8]:Mem LD, Departure <strong>de</strong>l coal y Departure <strong>de</strong>l uncoal.Los autores <strong>de</strong>l mo<strong>de</strong>lo calcularon estos valores paralos dispositivos con los que realizaron sus pruebas,entre ellos, la GPU NVIDIA GTX 280. Para este trabajose han tomado los datos <strong>de</strong> esta tarjeta, pues esun dispositivo muy semejante a la GTX 295.En lo que resta <strong>de</strong> sección se va a validar el mo<strong>de</strong>locon un conjunto <strong>de</strong> 111 pruebas agrupadas enfamilias haciendo, cada una <strong>de</strong> ellas, énfasis en losdistintos componentes <strong>de</strong>l mo<strong>de</strong>lo. <strong>La</strong> Tabla I muestraen su primera columna, el nombre <strong>de</strong> las familias<strong>de</strong> pruebas realizadas. <strong>La</strong> segunda columna muestrala <strong>de</strong>sviación entre el tiempo real y el tiempo estimadopor el mo<strong>de</strong>lo extendido para cada familia <strong>de</strong>pruebas. Estos resultados se obtuvieron tras haberleaplicado al mo<strong>de</strong>lo las extensiones y correcciones propuestasen este trabajo. Pese a que la <strong>de</strong>sviación enalgunos casos es consi<strong>de</strong>rable, <strong>de</strong>be tenerse en cuentaque el error pronosticado (13.3 %) por los autores <strong>de</strong>lmo<strong>de</strong>lo original sobre códigos <strong>de</strong> prueba mucho mássencillos supera <strong>de</strong> forma notable este error mediopara nuestros códigos tal y como se pue<strong>de</strong> ver en lastablas mostradas a continuación.En las Tablas II y III se muestra la <strong>de</strong>sviación<strong>de</strong> una serie <strong>de</strong> pruebas para el mo<strong>de</strong>lo extendidoy se confronta con la <strong>de</strong>sviación obtenidapara esas mismas pruebas con el mo<strong>de</strong>lo originaltal y como fue propuesto en [8]. <strong>La</strong> pruebasumavectores2Lecturas suma dos vectores en untercero, sumavectores3Lecturas suma 3 vectores enun cuarto vector y sumavectoresEscritura escribedatos en un único vector sin ser necesaria ningunalectura <strong>de</strong> memoria global. Análogamente laspruebas saxpyUncoal se distinguen entre ellas por elnúmero <strong>de</strong> accesos y/o el tipo <strong>de</strong> accesos. Se pue<strong>de</strong>apreciar que aunque en error se que<strong>de</strong> fuera <strong>de</strong>l rangoanunciado, en el mo<strong>de</strong>lo extendido se comete unerror mucho menor que en el mo<strong>de</strong>lo original.En resumen, las pruebas realizadas en este trabajocon el mo<strong>de</strong>lo original arrojaron una <strong>de</strong>sviación<strong>JP2011</strong>-629


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Prueba Mo<strong>de</strong>lo Mo<strong>de</strong>loNombre stri<strong>de</strong> original extendidosumavectores2Lecturas 3 13,97 % 8,14 %sumavectores2Lecturas 5 13,82 % 8,96 %sumavectores3Lecturas 3 13,75 % 8,73 %sumavectores3Lecturas 5 14,34 % 9,17 %sumavectoresEscritura 3 29,21 % 18,74 %sumavectoresEscritura 5 47,05 % 20,98 %TABLA II: Desviaciones <strong>de</strong>l mo<strong>de</strong>lo original y extendidopara pruebas <strong>de</strong> la familia sumavectoresPrueba Mo<strong>de</strong>lo Mo<strong>de</strong>loNombre stri<strong>de</strong> original extendidosaxpyUncoal 3 31,32 % 6,94 %saxpyUncoal 5 42,11 % 7,13 %saxpyUncoal 7 41,93 % 6,83 %saxpyUncoal2 3 6,82 % 4,02 %saxpyUncoal2 5 26,28 % 3,24 %saxpyUncoal2 7 26,2 % 3,13 %saxpyUncoal4 1 127,03 % 13,6 %saxpyUncoal5 1 91,77 % 3,5 %saxpyUncoal6 1 82,84 % 7,69 %TABLA III: Desviaciones <strong>de</strong>l mo<strong>de</strong>lo original y extendidopara pruebas <strong>de</strong> la familia saxpymedia cercana al 35 % (un 21.7 % más que la <strong>de</strong>sviaciónpronosticada por los autores) mientras quela <strong>de</strong>sviación media obtenida para un total <strong>de</strong> 111pruebas realizadas con el mo<strong>de</strong>lo extendido ha sido<strong>de</strong> 19,31 %.Finalmente, la Tabla IV muestra la aplicaciónpráctica <strong>de</strong> los resultados <strong>de</strong> este trabajo mediantetres configuraciones <strong>de</strong> la prueba saxpyUncoal correspondientesa tres estrategias <strong>de</strong> implementación<strong>de</strong>l mismo código. Vemos cómo el mo<strong>de</strong>lo extendidono sólo se acerca más al tiempo real, sino que a<strong>de</strong>máses capaz <strong>de</strong> <strong>de</strong>terminar cuál será la versión más eficiente<strong>de</strong> las tres configuraciones, en este caso, la <strong>de</strong>stri<strong>de</strong> = 3. Es <strong>de</strong>cir, el mo<strong>de</strong>lo permite seleccionarcon éxito entre varias alternativas para la realización<strong>de</strong> una computación más eficiente, siendo por tantoútil para guiar optimizaciones automáticas efectuadaspor un compilador, o para ayudar al programadora seleccionar el mejor código para su aplicación.En la tabla po<strong>de</strong>mos ver que sin embargo, el mo<strong>de</strong>looriginal no tiene la suficiente precisión como parapo<strong>de</strong>r <strong>de</strong>sempeñar este papel con éste código <strong>de</strong>ejemplo.V. ConclusionesTras un análisis <strong>de</strong>l mo<strong>de</strong>lo propuesto en [8] se observóque sus predicciones se alejaban en ocasionessignificativamente <strong>de</strong>l tiempo <strong>de</strong> ejecución real. Sehan propuesto varias mejoras al mo<strong>de</strong>lo, cambiandola unidad <strong>de</strong> transacciones <strong>de</strong> memoria <strong>de</strong> warp porhalfwarp, y modificando el cálculo <strong>de</strong>l tráfico en bytesque origina un acceso no coalescente, así comostri<strong>de</strong> GPU Mo<strong>de</strong>lo Desviación Mo<strong>de</strong>lo Desviación(µs) original original extendido final(µs)(µs)3 219,584 150,82 45,6 % 204,35 6,94 %5 260,544 150,82 72,75 % 241,97 7,13 %7 259,712 150,82 72,19 % 241,97 6,83 %TABLA IV: Tiempos y <strong>de</strong>sviaciones para tres configuraciones<strong>de</strong> saxpyUncoal en el mo<strong>de</strong>lo original yel mo<strong>de</strong>lo extendidoel ancho <strong>de</strong> banda teórico en función <strong>de</strong>l número <strong>de</strong>escrituras que exista en el programa y la contabilización<strong>de</strong>l número <strong>de</strong> instrucciones en los bloquescondicionales; y por último, el tratamiento <strong>de</strong> los accesosa memoria <strong>de</strong> texturas y constantes tambiénha sido incluido en el mo<strong>de</strong>lo extendido. El error <strong>de</strong>lmo<strong>de</strong>lo original, en torno al 35 %, exce<strong>de</strong> notablementeel error cometido por la versión extendida <strong>de</strong>lmo<strong>de</strong>lo <strong>de</strong>sarrollado en este trabajo, que se sitúa enel 19,31 %.Si bien a veces la predicción <strong>de</strong>l mo<strong>de</strong>lo se aleja <strong>de</strong>ltiempo real <strong>de</strong> ejecución medido, la evolución comparativa<strong>de</strong> sus predicciones ha sido siempre análogaa la <strong>de</strong> los tiempos <strong>de</strong> ejecución reales en los casosanalizados. Por ello, este mo<strong>de</strong>lo ha probado ser fiablea la hora <strong>de</strong> ayudar a <strong>de</strong>cidir qué estrategias <strong>de</strong>codificación CUDA son las más apropiadas para un<strong>de</strong>terminado código.Agra<strong>de</strong>cimientosEste trabajo ha sido financiado por la Xunta <strong>de</strong>Galicia bajo los proyectos INCITE08PXIB105161PRy 08TIC001206PR, y por el Ministerio <strong>de</strong> Ciencia eInnovación con fondos FEDER <strong>de</strong> la Unión Europea(proyecto TIN2010-16735).Referencias[1] NVIDIA. CUDA Compute Unified Device Architecture,v3.0 edition, 2010.[2] Khronos OpenCL Working Group. The OpenCL Specification,2009.[3] S.S Baghsorkhi, M. Delahaye, S.J. Patel, W.D. Gropp andW.W. Hwu. An adaptative performance mo<strong>de</strong>ling tool forgpu architectures. In Proceedings of the 15 th ACM SIG-PLAN Symposium of Principles and Practice of ParallelProgramming (PPoPP 2010), pages 105–114, 2010.[4] A. Singh J. W. Choi and R. W. Vuduc. Mo<strong>de</strong>l-drivenautotuning of sparse matrix-vector multiply on GPUs. InProceedings of the 15th ACM SIGPLAN symposium onPrinciples and practice of parallel programming (PPoPP2010), volume 45, pages 115–126, 2010.[5] H. Wong, M.-M. Papadopoulou, M. Sadooghi-Alvandi, A.Moshovos. Desmystifying GPU microarchitecture throughmicrobenchmarking. In 2010 IEEE int. symp. on performanceanalysis of systems software (ISPASS), pages 235–246, 2010.[6] R. Taylor and X. Li. A micro-benchmark suite for AMDGPUs. In 2010 39th international conference on parallelprocessing workshops (ICPPW), pages 387–396, 2010.[7] Y. Zhang and J.D. Owens. A quantitative performanceanalysis mo<strong>de</strong>l for GPU architectures. In Proc. of the17th IEEE Int. Symposium on High-Performance ComputerArchitecture (HPCA 17), 2011.[8] S. Hong and H. Kim. An analytical mo<strong>de</strong>l for a GPUarchitecture with memory-level and thread-level parallelismawareness. In Proc. of the 36th Int. Symposium onComputer Architecture (ISCA ’09), 2009.[9] Nvidia. CUDA programming gui<strong>de</strong>, 2010.<strong>JP2011</strong>-630


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Análisis <strong>de</strong> Escalabilidad en AplicacionesParalelas con Carga <strong>de</strong> Trabajo No EquilibradaJose Luis Bosque 1 , Oscar D. Robles 2 , Pablo Toharia 2 , y Luis Pastor 2Resumen En los sistemas paralelos actuales y futuroscon un gran número <strong>de</strong> nodos <strong>de</strong> cómputo la escalabilida<strong>de</strong>s una propiedad <strong>de</strong>l sistema (arquitecturamás aplicación) tan importante como el rendimiento.Por otro lado es ampliamente conocido el impacto<strong>de</strong>l equilibrio <strong>de</strong> carga <strong>de</strong> trabajo en el rendimiento<strong>de</strong> una aplicación paralela. Este artículo estudia larelación entre la escalabilidad <strong>de</strong> un sistema paraleloy el equilibrio en su carga <strong>de</strong> trabajo. Se proponey valida un mo<strong>de</strong>lo teórico, evolución <strong>de</strong> la función<strong>de</strong> isoeciencia, que permite mo<strong>de</strong>lar y pre<strong>de</strong>cir conprecisión esta relación. Finalmente, se presentan unaevaluación empírica <strong>de</strong>l mo<strong>de</strong>lo así como una serie <strong>de</strong>conclusiones obtenidas <strong>de</strong> dicha validación.Palabras clave Escalabilidad, Mo<strong>de</strong>los Teóricos,Equilibrio <strong>de</strong> carga.I. IntroducciónEN los últimos años, gracias a la arquitecturamulti-core el número <strong>de</strong> cores en los supercomputadoresse ha visto incrementado drásticamente.En la última lista <strong>de</strong>l top500 (Noviembre 2010 [1])aparecen ya 12 máquinas con más <strong>de</strong> 100.000 cores.Esto ha hecho que la escalabilidad <strong>de</strong> las aplicacionesparalelas sea un factor que ha ganado gran importanciaen su diseño e implementación, por encimaincluso <strong>de</strong>l rendimiento.Por otro lado, está ampliamente reconocido que elequilibrio <strong>de</strong> carga <strong>de</strong> trabajo tiene un fuerte impactosobre el rendimiento <strong>de</strong> un sistema paralelo y por lotanto sobre su eciencia [2]. Según la función <strong>de</strong>isoeciencia [3] la escalabilidad <strong>de</strong> un sistema paralelo(computador+aplicación) se <strong>de</strong>ne en términos<strong>de</strong>l incremento necesario <strong>de</strong> carga <strong>de</strong> trabajo que setiene que producir, al aumentar el número <strong>de</strong> procesadores,para que la eciencia se mantenga constante.Por lo tanto, si la escalabilidad se <strong>de</strong>ne en función<strong>de</strong>l tamaño <strong>de</strong>l problema, es <strong>de</strong>cir <strong>de</strong>l número <strong>de</strong> operacionesque hay que realizar, po<strong>de</strong>mos preguntarnoscuál será el impacto <strong>de</strong> un <strong>de</strong>sequilibrio <strong>de</strong> carga <strong>de</strong>trabajo en una aplicación sobre su escalabilidad.En todos los trabajos presentados hasta la fecha[3], [4], [5], [6], [7] para mo<strong>de</strong>lar y evaluar la escalabilidad<strong>de</strong> sistemas paralelos se consi<strong>de</strong>ra, ya sea <strong>de</strong>forma implícita o explícita, que la carga <strong>de</strong> trabajoestá perfectamente equilibrada entre los nodos <strong>de</strong>lsistema. Esta hipótesis es poco realista porque, enprimer lugar, obliga a que la carga <strong>de</strong> trabajo sea continuae innitamente divisible y por otro lado, existenmúltiples fuentes <strong>de</strong> <strong>de</strong>sequilibrio en sistemas paralelos,como pue<strong>de</strong>n ser una mala distribución inicial,1 Dpto. <strong>de</strong> Electrónica y Computadores, <strong>Universidad</strong> <strong>de</strong>Cantabria, e-mail: joseluis.bosque@unican.es.2 Departamento <strong>de</strong> ATC y CCIA, <strong>Universidad</strong>Rey Juan Carlos, e-mail:{oscardavid.robles,pablo.toharia,luis.pastor}@urjc.es.la existencia <strong>de</strong> sistemas no <strong>de</strong>dicados, en los que lasprestaciones <strong>de</strong> los nodos pue<strong>de</strong>n variar a lo largo<strong>de</strong>l tiempo <strong>de</strong> ejecución <strong>de</strong> la aplicación, o bien laexistencia <strong>de</strong> sistemas heterogéneos.Este artículo presenta una nueva expresión parala función <strong>de</strong> isoeciencia que permite mo<strong>de</strong>lar lacarga <strong>de</strong> trabajo <strong>de</strong>sequilibrada, es <strong>de</strong>cir una función<strong>de</strong> isoeciencia más general que pueda aplicarsea sistemas paralelos en los que la carga <strong>de</strong> trabajopueda estar equilibrada o <strong>de</strong>sequilibrada. Hastadon<strong>de</strong> conocen los autores este es el primer trabajoque pone <strong>de</strong> maniesto este problema y que, por lotanto, propone una solución a<strong>de</strong>cuada. A pesar <strong>de</strong>ser eminentemente teórico, este resultado tiene ungran impacto en el diseño e implementación <strong>de</strong> aplicacionesparalelas.A partir <strong>de</strong> la nueva versión <strong>de</strong> la función <strong>de</strong> isoecienciase plantean una serie <strong>de</strong> estudios teóricos, <strong>de</strong>los que se obtienen ciertas propieda<strong>de</strong>s <strong>de</strong> escalabilidad<strong>de</strong> los sistemas paralelos, consi<strong>de</strong>rando tanto lasobrecarga <strong>de</strong> comunicación como la <strong>de</strong>bida al equilibrio<strong>de</strong> carga. Finalmente se ha llevado a cabo unaevaluación experimental para validar y vericar lavali<strong>de</strong>z y corrección <strong>de</strong> los mo<strong>de</strong>los propuestos.II. Escalabilidad <strong>de</strong> sistemas paralelos con<strong>de</strong>sequilibrio <strong>de</strong> carga <strong>de</strong> trabajoA. Mo<strong>de</strong>lo <strong>de</strong>l Desequilibrio <strong>de</strong> carga <strong>de</strong> trabajoPartimos <strong>de</strong> un mo<strong>de</strong>lo <strong>de</strong> sistema compuestopor un conjunto <strong>de</strong> m nodos, <strong>de</strong>notados por N =n 1 , · · · , n m interconectados entre sí. Todos los nodosson idénticos y tienen las mismas prestaciones. <strong>La</strong>carga <strong>de</strong> trabajo que se va a ejecutar en una aplicaciónviene <strong>de</strong>terminada por un conjunto <strong>de</strong> operacionesbásicas que se pue<strong>de</strong>n realizar en paralelo.Dicha carga <strong>de</strong> trabajo viene caracterizada por sutamaño, que <strong>de</strong>nominaremos W , y se pue<strong>de</strong> <strong>de</strong>scomponeren una serie <strong>de</strong> unida<strong>de</strong>s <strong>de</strong> cómputo.Para parametrizar su rendimiento <strong>de</strong>nimos la potencia<strong>de</strong> cómputo (p) <strong>de</strong> cada uno <strong>de</strong> estos nodoscomo la cantidad <strong>de</strong> operaciones básicas por unidad<strong>de</strong> tiempo que es capaz <strong>de</strong> ejecutar.Si la carga <strong>de</strong> trabajo es continua e innitamentedivisible, el sistema estaría completamente equilibradoasignando a cada nodo la misma carga <strong>de</strong>trabajo, es <strong>de</strong>cir w i = W m. En ese caso, asumiendoque no existen otras sobrecargas <strong>de</strong>bido a la comunicaciónentre procesos, el tiempo <strong>de</strong> ejecución <strong>de</strong> todoslos nodos <strong>de</strong>be ser el mismo, y viene dado por lasiguiente expresión: T CP U = Wp·m ∀ n i con i ∈ 1...mSin embargo, en aplicaciones reales la carga <strong>de</strong> trabajono se pue<strong>de</strong> dividir innitamente, por lo que la<strong>JP2011</strong>-631


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011asignación <strong>de</strong> carga <strong>de</strong> trabajo a cada nodo <strong>de</strong>be serun número entero. Esto da lugar a una asignación<strong>de</strong> carga <strong>de</strong> trabajo que no cumple por completo laexpresión anterior y que por lo tanto hace que lostiempos <strong>de</strong> ejecución sean diferentes en los distintosnodos. Existen aplicaciones en las que la unidad <strong>de</strong>asignación es una estructura <strong>de</strong> datos compleja y porlo tanto estas diferencias pue<strong>de</strong>n ser gran<strong>de</strong>s.Por lo tanto, en el caso <strong>de</strong>sequilibrado habrá nodosque ejecutarán menos carga <strong>de</strong> la que les correspon<strong>de</strong>ríaen una asignación óptima y otros a los que lestocará más. Denotamos ∆w i (pue<strong>de</strong> ser positivo onegativo, para indicar más o menos carga que la óptima)la diferencia <strong>de</strong> carga <strong>de</strong> trabajo que tiene queprocesar un nodo con respecto a la carga <strong>de</strong> trabajoque se le asignaría si el equilibrio fuera perfecto. Eneste caso, la carga <strong>de</strong> trabajo asignada a cada nodoes w i = W m + ∆w i Y por lo tanto el tiempo <strong>de</strong> ejecución<strong>de</strong> un nodo, sin tener en cuenta las sobrecargas<strong>de</strong> comunicación (es <strong>de</strong>cir el tiempo <strong>de</strong> CPU) vendríadado por la expresión:T CP U =Wm + ∆w i⇒ T CP U =Wpm · p + ∆w ip(1)Denotemos ahora T qi al tiempo empleado por elprocesador N i para procesar su carga <strong>de</strong> trabajo adicionalrespecto a la carga óptima, es <strong>de</strong>cir T qi = ∆wip .Sea T q = max m i=1 { ∆wip} el tiempo empleado por elnodo que más tiempo invierte en procesar su exceso<strong>de</strong> carga respecto a la distribución óptima, y que porlo tanto termina el último su trabajo (sin tener encuenta las sobrecargas <strong>de</strong>bidas a comunicación). <strong>La</strong>sobrecarga pue<strong>de</strong> ser un valor constante, pue<strong>de</strong> <strong>de</strong>pen<strong>de</strong>r<strong>de</strong> la carga <strong>de</strong> trabajo total W , o bien <strong>de</strong>lnúmero <strong>de</strong> procesadores m, por lo que la <strong>de</strong>niremoscomo T q (W, m). Consi<strong>de</strong>rando a<strong>de</strong>más un tiempo <strong>de</strong>sobrecarga T o (m), su tiempo <strong>de</strong> respuesta será:T R =Wp · m + T q(W, m) + T o (W, m) (2)Es importante hacer notar que así como T o aumentacon el número <strong>de</strong> procesadores en todos loscasos (a lo sumo permanece constante), T q pue<strong>de</strong> disminuiral aumentar m. Esto es posible ya que po<strong>de</strong>mospartir <strong>de</strong> un sistema con pocos procesadores ymuy <strong>de</strong>sequilibrado, con lo que tiene un gran impactoen el tiempo <strong>de</strong> respuesta, y a medida que seincrementa el número <strong>de</strong> nodos se pue<strong>de</strong> equilibraral po<strong>de</strong>r hacerse un reparto mejor <strong>de</strong> los datos.B. Función <strong>de</strong> isoecienciaPara obtener la función <strong>de</strong> isoeciencia <strong>de</strong>bemosen primer lugar calcular la expresión <strong>de</strong> la eciencia,que <strong>de</strong>pen<strong>de</strong> <strong>de</strong>l tiempo secuencial y <strong>de</strong>l paralelo.El tiempo secuencial necesario para resolver unproblema <strong>de</strong> tamaño W en el sistema propuesto esT S = W p, es <strong>de</strong>cir toda la carga <strong>de</strong> trabajo ejecutadaen un único procesador con potencia <strong>de</strong> cómputo p.El tiempo paralelo es el presentado en la Ecuación2. Sustituyendo estos valores en la <strong>de</strong>nición <strong>de</strong> eciencia,se obtiene:E =T ST R · m = 11 + m·p·(To+Tq)WPor lo tanto, para sistemas paralelos escalables laeciencia se pue<strong>de</strong> mantener estable si el cocientem·(T q+T o)W, mantiene a su vez un valor constante en laexpresión anterior. A partir <strong>de</strong> ahí po<strong>de</strong>mos obteneruna expresión que <strong>de</strong>termine cómo <strong>de</strong>be evolucionarla carga <strong>de</strong> trabajo al escalar el sistema para que laeciencia se mantenga constante:m · p · (T q + T o )W= 1 − EE ⇒ W = E1 − E ·m·p·(T q+T o )ESea K = p ·1−Euna constante que <strong>de</strong>pen<strong>de</strong> <strong>de</strong>lvalor <strong>de</strong> eciencia inicial. Entonces la función <strong>de</strong>isoeciencia que mo<strong>de</strong>la el <strong>de</strong>sequilibrio en la carga<strong>de</strong> trabajo se pue<strong>de</strong> expresar <strong>de</strong> la siguiente forma:W = K · m · (T q + T o ) (3)Es <strong>de</strong>cir, el <strong>de</strong>sequilibrio <strong>de</strong> carga se pue<strong>de</strong> mo<strong>de</strong>larcomo una sobrecarga más <strong>de</strong>l sistema, <strong>de</strong> formaequivalente a como se consi<strong>de</strong>ran los tiempos <strong>de</strong> comunicación.En este caso el factor T q = ∆wmpes eltiempo adicional que tarda el procesador que tienemayor tiempo <strong>de</strong> ejecución, sobre el tiempo que emplearíasi estuviera equilibrado. Este factor, multiplicadopor la potencia <strong>de</strong> cómputo <strong>de</strong>l sistema, <strong>de</strong>terminael tiempo global <strong>de</strong>saprovechado en todo elsistema y por lo tanto su eciencia.Finalmente, una cuestión importante que hay queremarcar es que en un sistema paralelo, incluso sinsobrecarga <strong>de</strong> comunicación, el <strong>de</strong>sequilibrio <strong>de</strong> carga<strong>de</strong> trabajo implica que el sistema no sea perfectamenteescalable. Por otro lado, aunque se mo<strong>de</strong>lacomo un tiempo <strong>de</strong> sobrecarga adicional que <strong>de</strong>besumarse a los tiempos <strong>de</strong> comunicación tiene una peculiaridadimportante. Mientras que la sobrecargasiempre crece al escalar el sistema, el <strong>de</strong>sequilibriopue<strong>de</strong> variar <strong>de</strong> forma inversamente proporcional alnúmero <strong>de</strong> nodos. Es <strong>de</strong>cir, un sistema inicialmentemuy <strong>de</strong>sequilibrado pue<strong>de</strong> variar a uno menos <strong>de</strong>sequilibradocuando se escala.III. Influencia <strong>de</strong>l Desequilibrio <strong>de</strong> Carga<strong>de</strong> Trabajo en la EscalabilidadDe la expresión anterior (Ecuación 3) se pue<strong>de</strong>n<strong>de</strong>ducir una serie <strong>de</strong> propieda<strong>de</strong>s que relacionan laescalabilidad <strong>de</strong> un sistema paralelo con la evolución<strong>de</strong>l <strong>de</strong>sequilibrio, al escalar el sistema. Un sistemasería perfectamente escalable si T q = T o = 0. Estoes, si no existe sobrecarga <strong>de</strong> comunicación ni <strong>de</strong>sequilibrio<strong>de</strong> carga <strong>de</strong> trabajo, el sistema escala perfectamentey no es necesario aumentar el tamaño <strong>de</strong>lproblema con el número <strong>de</strong> procesadores (siempreque todo procesador tenga asignada una parte <strong>de</strong>carga <strong>de</strong> trabajo, es <strong>de</strong>cir w i > 0 ∀ i ∈ 1 . . . m).En esta sección se presentan una serie <strong>de</strong> propieda<strong>de</strong>s<strong>JP2011</strong>-632


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>de</strong> escalabilidad <strong>de</strong> sistemas paralelos en función <strong>de</strong>la variación <strong>de</strong> T q y consi<strong>de</strong>rando T o = 0. Es <strong>de</strong>cir,se estudia cómo afecta la evolución <strong>de</strong>l <strong>de</strong>sequilibrio<strong>de</strong> carga <strong>de</strong> trabajo a medida que el sistema escalasu tamaño. <strong>La</strong> hipótesis <strong>de</strong> que T o = 0 no es realistaen la mayor parte <strong>de</strong> las aplicaciones, pero nos sirvepara aislar el efecto <strong>de</strong>l <strong>de</strong>sequilibrio en estos estudiosteóricos. En todos los casos consi<strong>de</strong>ramos unsistema paralelo <strong>de</strong> partida <strong>de</strong>nido por S(m, W ) yun sistema escalado S ′ (m ′ , W ′ ), ambos con T o = 0.Si la carga <strong>de</strong> trabajo en S y S ′ se reparte entre losprocesadores, con un <strong>de</strong>sequilibrio T q = c, es <strong>de</strong>circonstante e in<strong>de</strong>pendiente <strong>de</strong> m y W , entonces elsistema es escalable sii la carga <strong>de</strong> trabajo crece <strong>de</strong>forma proporcional al número <strong>de</strong> procesadores en elsistema, es <strong>de</strong>cir W es O(m).Sea T q = c ∈ R, constante para todo m y W . <strong>La</strong>función <strong>de</strong> isoeciencia para este caso es:W = K·m·T q ⇒ W = K ′·m, con K ′ = K·c (4)Por lo tanto W= K ′ ·m, es <strong>de</strong>cir W <strong>de</strong>be crecer <strong>de</strong>forma lineal con la potencia <strong>de</strong> cómputo <strong>de</strong>l sistema,in<strong>de</strong>pendientemente <strong>de</strong>l <strong>de</strong>sequilibrio <strong>de</strong>l mismo.Por otro lado, si el <strong>de</strong>sequilibrio <strong>de</strong>pen<strong>de</strong> <strong>de</strong> formalineal <strong>de</strong>l número <strong>de</strong> procesadores T q = c 1·m+c 2 , conc 1 , c 2 ∈ R, y no hay ninguna sobrecarga adicional,entonces el sistema será escalable sii el tamaño <strong>de</strong>lproblema crece como una función O(m 2 ). <strong>La</strong> prueba<strong>de</strong> esta armación es trivial y se obtiene reemplazandoT q en la Ecuación 3.Si la carga <strong>de</strong> trabajo en ambos sistemas se repartecon un <strong>de</strong>sequilibrio que <strong>de</strong>pen<strong>de</strong> <strong>de</strong> forma inversamenteproporcional <strong>de</strong>l número <strong>de</strong> procesadores, es<strong>de</strong>cir, T q = c1 m , con c 1 ∈ R, entonces el sistema seráperfectamente escalable ya que la función <strong>de</strong> isoecienciaes constante in<strong>de</strong>pendientemente <strong>de</strong>l tamaño<strong>de</strong>l sistema, es <strong>de</strong>cir W es O(K). Es necesario remarcarque si W > m, esta situación contradice lacota inferior estimada por [3] para la función <strong>de</strong> isoeciencia.Si la carga <strong>de</strong> trabajo en ambos sistemas se repartecon un <strong>de</strong>sequilibrio que <strong>de</strong>pen<strong>de</strong> <strong>de</strong> forma lineal <strong>de</strong>ltamaño <strong>de</strong>l problema T q = c 1 · W , con c 1 ∈ R, entoncesel sistema es no escalable ya que al aumentarla carga <strong>de</strong> trabajo se incrementa el <strong>de</strong>sequilibrio yla eciencia nunca se pue<strong>de</strong> mantener constante.Finalmente, si el <strong>de</strong>sequilibrio <strong>de</strong>pen<strong>de</strong> <strong>de</strong> formainversamente proporcional al tamaño <strong>de</strong>l problemaT q = c1W , con c 1 ∈ R, entonces es trivial <strong>de</strong>mostrarque el sistema será escalable sii el tamaño <strong>de</strong>l problemacrece como una función <strong>de</strong> O( √ m). De nuevoen este caso el crecimiento es inferior al lineal, quees el límite inferior para los sistemas perfectamenteequilibrados, establecido por [3].IV. Combinando Sobrecarga yDesequilibrioFinalmente, en esta sección se propone un estudioteórico sobre el impacto que estos dos factores,comunicación y <strong>de</strong>sequilibrio, tienen <strong>de</strong> forma combinadaen la escalabilidad <strong>de</strong> las aplicaciones paralelas.Sea un sistema paralelo S(m, W ) y un sistema escaladoS ′ (m ′ , W ′ ). <strong>La</strong> carga <strong>de</strong> trabajo se reparte entodos los casos <strong>de</strong> forma proporcional al número <strong>de</strong>procesadores con un <strong>de</strong>sequilibrio <strong>de</strong>terminado porT q . Para analizar su escalabilidad según el mo<strong>de</strong>lopropuesto se <strong>de</strong>be mo<strong>de</strong>lar tanto su sobrecarga <strong>de</strong>comunicación como el comportamiento <strong>de</strong>l <strong>de</strong>sequilibrioa medida que se escala el sistema. Por ejemplo,si al escalar el sistema <strong>de</strong> S a S ′ , tanto el <strong>de</strong>sequilibriocomo la sobrecarga son constantes e in<strong>de</strong>pendientes<strong>de</strong> m y W , es <strong>de</strong>cir T q = c 1 , y T o = c 2 , con c 1 , c 2 ∈ R,el sistema es escalable sii el tamaño <strong>de</strong>l problema Wcrece <strong>de</strong> forma linealmente proporcional al número<strong>de</strong> procesadores, es <strong>de</strong>cir W es O(m).<strong>La</strong> <strong>de</strong>mostración es sencilla a partir <strong>de</strong> la función<strong>de</strong> isoeciencia presentada en la sección anterior.W = K ·m·(T q +T o ) = K ·m·(c 1 +c 2 ) ⇒ W = K ′·mdon<strong>de</strong>K ′ = K · (c 1 + c 2 )Por lo tanto W es O(m), es <strong>de</strong>cir <strong>de</strong>be crecer <strong>de</strong>forma lineal con el número <strong>de</strong> procesadores, in<strong>de</strong>pendientemente<strong>de</strong>l <strong>de</strong>sequilibrio <strong>de</strong> la aplicación. Engeneral, en sistemas con una sobrecarga <strong>de</strong>bida a lacomunicación entre procesos y un <strong>de</strong>sequilibrio constante,entonces el <strong>de</strong>sequilibrio no tiene ningún efectoen la escalabilidad <strong>de</strong>l sistema. Sólo afecta a la ecienciamáxima que se pue<strong>de</strong> alcanzar pero no a suevolución respecto al número <strong>de</strong> nodos, por lo que noafecta a la escalabilidad.Finalmente, un último ejemplo que pue<strong>de</strong> resultar<strong>de</strong> interés consi<strong>de</strong>rando un sistema en el que el<strong>de</strong>sequilibrio crece <strong>de</strong> forma inversamente proporcionalal número <strong>de</strong> procesadores (T q = c1 m), mientrasque la sobrecarga <strong>de</strong> comunicación crece <strong>de</strong> formalineal también respecto al número <strong>de</strong> procesadores(T o = c 2 · m, siendo c 1 y c 2 ∈ R). En este caso pue<strong>de</strong><strong>de</strong>mostrarse que W <strong>de</strong>be crecer también <strong>de</strong> formacuadrática respecto al número <strong>de</strong> procesadores, es<strong>de</strong>cir W es O(m 2 ).V. Evaluación ExperimentalEn esta sección se presentan una serie <strong>de</strong> experimentoscon el objetivo <strong>de</strong> conrmar empíricamentela hipótesis planteada en este artículo sobre la in-uencia <strong>de</strong>l <strong>de</strong>sequilibrio <strong>de</strong> carga en la escalabilidad<strong>de</strong> sistemas paralelos. Por otro lado, se tratará<strong>de</strong> validar el mo<strong>de</strong>lo <strong>de</strong> escalabilidad propuesto enpresencia <strong>de</strong> situaciones <strong>de</strong> <strong>de</strong>sequilibrio <strong>de</strong> carga <strong>de</strong>trabajo, así como las propieda<strong>de</strong>s enunciadas en lassecciones anteriores. El sistema sobre el que se realizanlos experimentos es un cluster <strong>de</strong> la <strong>Universidad</strong><strong>de</strong> Cantabria <strong>de</strong>nominado Altamira. Está compuestopor 256 nodos biprocesador conectados mediante unared Myrinet a 1 Gbps. Para cada uno <strong>de</strong> los casospresentados se realizarán una serie <strong>de</strong> experimentosvariando el tamaño <strong>de</strong>l sistema y la carga <strong>de</strong> trabajoa resolver, realizando varias muestras por caso y midiendoen cada uno los tiempos <strong>de</strong> respuesta y comunicación.A continuación se obtienen los valores <strong>de</strong>eciencia para cada sistema y carga <strong>de</strong> trabajo. De<strong>JP2011</strong>-633


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 201110.90.82.5e+062e+06Linear IsoefficiencyIsoefficiency O(m^2)0.7Efficiency0.60.5Efficiency = 0.830.4m=20.3m=4m=80.2m=16m=320.1m=64m=12800 500000 1e+06 1.5e+06 2e+06 2.5e+06Workload (W)Workload (W)1.5e+061e+0650000000 20 40 60 80 100 120 140Number of Processors (m)(a) Evolución <strong>de</strong> la Eciencia.(b) Función <strong>de</strong> isoecienciaFig. 1.Función <strong>de</strong> isoeciencia para el benchmark Proporcional_mesta forma obtenemos una curva <strong>de</strong> evolución <strong>de</strong> laeciencia con la carga <strong>de</strong> trabajo, para cada tamaño<strong>de</strong>l sistema.A. Validación <strong>de</strong>l Mo<strong>de</strong>lo <strong>de</strong> DesequilibrioPara validar el mo<strong>de</strong>lo <strong>de</strong> escalabilidad en presencia<strong>de</strong> <strong>de</strong>sequilibrio <strong>de</strong> carga <strong>de</strong> trabajo se han <strong>de</strong>sarrolladouna serie <strong>de</strong> benchmarks ad hoc en los que noexiste sobrecarga <strong>de</strong> comunicación y por lo tanto sonperfectamente escalables, es <strong>de</strong>cir tienen su función<strong>de</strong> isoeciencia constante O(K), con K ∈ R. Esto escierto siempre que la carga <strong>de</strong> trabajo esté perfectamenteequilibrada. Por lo tanto, partimos <strong>de</strong> la ecienciaque obtiene el benchmark en 2 nodos, y vemoscuál es su evolución a medida que el sistema se escala.En una situación <strong>de</strong> carga <strong>de</strong> trabajo equilibrada laeciencia <strong>de</strong>bería mantenerse constante para todaslas conguraciones. Sin embargo veremos en estecaso que la función <strong>de</strong> isoeciencia cambia a medidaque se introducen distintos niveles <strong>de</strong> <strong>de</strong>sequilibrioen el sistema y se vericará el mo<strong>de</strong>lo propuesto. Elvalor <strong>de</strong> todas las constantes utilizadas en los experimentos<strong>de</strong>pen<strong>de</strong> tanto <strong>de</strong> las prestaciones <strong>de</strong> losnodos como <strong>de</strong> la naturaleza <strong>de</strong>l problema, y todoslos valores se han medido sobre la implementaciónsecuencial <strong>de</strong> los distintos benchmarks.Se consi<strong>de</strong>ran cuatro variaciones distintas <strong>de</strong> la distribución<strong>de</strong> carga <strong>de</strong> trabajo que serán las siguientes:• Proporcional_m: Desequilibrio <strong>de</strong> carga proporcionalal número <strong>de</strong> procesadores, T q = c · m.• Inverso_m: Desequilibrio inversamente proporcionalal número <strong>de</strong> procesadores, T q = c m .• Proporcional_w: Desequilibrio <strong>de</strong> carga proporcionala la carga <strong>de</strong> trabajo, T q = c · W .• Inverso_w: Desequilibrio inversamente proporcionala la carga <strong>de</strong> trabajo, T q = c W .<strong>La</strong> gura 1(a) presenta la evolución <strong>de</strong> la ecienciaa medida que aumenta la carga <strong>de</strong> trabajo paradiferentes tamaños <strong>de</strong>l sistema para el test Proporcional_m.Como se pue<strong>de</strong> observar todos alcanzanla eciencia <strong>de</strong> partida (0.83) por lo que el sistema esescalable. <strong>La</strong> gura 1(b) muestra la función <strong>de</strong> isoecienciaobtenida respecto a una función lineal. ComoEfficiency10.90.80.70.60.5m=20.4m=4m=80.3m=16m=320.2m=64m=1280.10 10000 20000 30000 40000 50000 60000 70000Workload (W)Fig. 2. Evolución <strong>de</strong> la Eciencia con la carga <strong>de</strong> trabajo parasistemas con diferente número <strong>de</strong> nodosse pue<strong>de</strong> apreciar la función <strong>de</strong> isoeciencia sigue unacurva parabólica, <strong>de</strong> forma que el tamaño <strong>de</strong>l problema<strong>de</strong>be crecer cuadráticamente con la carga <strong>de</strong>trabajo. Esta situación correspon<strong>de</strong> a la predicciónrealizada por el mo<strong>de</strong>lo teórico presentado en la secciónIII.<strong>La</strong> tabla I muestra los resultados obtenidos parala evolución <strong>de</strong> la eciencia en el test Inverso_m.<strong>La</strong> eciencia permanece prácticamente constante, entorno a 0.50, in<strong>de</strong>pendientemente <strong>de</strong>l tamaño <strong>de</strong>lproblema y <strong>de</strong>l número <strong>de</strong> nodos. Por lo tanto, lafunción <strong>de</strong> isoeciencia asociada a esta situación <strong>de</strong>beser constante y el sistema es perfectamente escalable,tal y como predice el mo<strong>de</strong>lo.<strong>La</strong> gura 2 presenta la evolución <strong>de</strong> la ecienciaen función <strong>de</strong> la carga, para el benchmark Proporcional_w.Se observa que dado un tamaño concretola eciencia permanece prácticamente constante alaumentar la carga <strong>de</strong> trabajo. Por otro lado, al aumentarel tamaño <strong>de</strong>l sistema no se pue<strong>de</strong> mantenerla eciencia constante, sea cual sea la carga <strong>de</strong> trabajo.Así pues, por la propia <strong>de</strong>nición <strong>de</strong> la función<strong>de</strong> isoeciencia el sistema no es escalable.Por último, la gura 3 presenta la evolución <strong>de</strong> laeciencia (g. 3(a)) y la función <strong>de</strong> isoeciencia (g.3(b)) para un <strong>de</strong>sequilibrio que varía <strong>de</strong> forma inver-<strong>JP2011</strong>-634


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA IEvolución <strong>de</strong> la eficiencia para el benchmarks (Inverso_m).W 2 Nodos 4 Nodos 8 Nodos 16 Nodos 32 Nodos 64 Nodos 128 Nodos1024 0.500 0.503 0.499 0.496 0.497 0.495 0.4854096 0.500 0.503 0.502 0.499 0.498 0.498 0.49816384 0.500 0.501 0.499 0.501 0.502 0.499 0.49665536 0.500 0.498 0.499 0.501 0.498 0.500 0.502262144 0.500 0.501 0.502 0.500 0.500 0.503 0.500samente proporcional a la carga <strong>de</strong> trabajo, respectoa una función <strong>de</strong> isoeciencia lineal. Todos los nodosalcanzan la eciencia <strong>de</strong> partida por lo que se pue<strong>de</strong>armar que el sistema es escalable. <strong>La</strong> función <strong>de</strong>isoeciencia obtenida es O( √ m), muy por <strong>de</strong>bajo <strong>de</strong>lo que sería un crecimiento lineal.De estas cuatro situaciones se pue<strong>de</strong>n obtener unaserie <strong>de</strong> importantes conclusiones. En primer lugarqueda claro el gran impacto que tiene el <strong>de</strong>sequilibrio<strong>de</strong> carga <strong>de</strong> trabajo en la escalabilidad <strong>de</strong> un sistemaparalelo. Efectivamente, <strong>de</strong> los resultados presentadosse <strong>de</strong>spren<strong>de</strong> que el mismo sistema paralelo pue<strong>de</strong>tener comportamientos <strong>de</strong> escalabilidad muy distintosen función <strong>de</strong>l reparto <strong>de</strong> la carga <strong>de</strong> trabajo quese realice, llegando incluso a po<strong>de</strong>r convertirse en unsistema no escalable, aunque no tenga ninguna sobrecarga<strong>de</strong> comunicación. Por otro lado, los cuatro casospresentados sirven para validar la corrección <strong>de</strong>lmo<strong>de</strong>lo propuesto en este artículo. Todos los casoshan sido analizados <strong>de</strong> forma teórica en la sección IIIy los resultados obtenidos coinci<strong>de</strong>n perfectamentecon las predicciones teóricas efectuadas.B. Inuencia <strong>de</strong>l Desequilibrio en un Sistema conSobrecarga <strong>de</strong> ComunicaciónFinalmente en esta sección se verica la precisión<strong>de</strong>l mo<strong>de</strong>lo teórico en un benchmark que introducetanto <strong>de</strong>sequilibrio <strong>de</strong> carga como sobrecarga <strong>de</strong> comunicación.<strong>La</strong> comunicación es 1 a m, por lotanto proporcional al número <strong>de</strong> procesadores, es <strong>de</strong>cirT o = c 2 · m. Por lo tanto, la función <strong>de</strong> isoecienciaclásica, sin tener en cuenta el <strong>de</strong>sequilibrio<strong>de</strong> carga, es O(m). Se presentan, a modo <strong>de</strong>ejemplo, dos situaciones <strong>de</strong> <strong>de</strong>sequilibrio: <strong>de</strong>sequilibrio<strong>de</strong> carga constante, (T q = c 1 ) y <strong>de</strong>sequilibrio <strong>de</strong>carga inversamente proporcional al número <strong>de</strong> procesadores(T q = c1 m). Por lo tanto, si tenemos en cuentalas dos fuentes <strong>de</strong> sobrecarga el mo<strong>de</strong>lo <strong>de</strong> escalabilidadpresentado predice una función <strong>de</strong> isoeciencia<strong>de</strong> O(m 2 ). <strong>La</strong> gura 4 presenta los resultadosobtenidos experimentalmente, mostrando en amboscasos la función <strong>de</strong> isoeciencia obtenida.<strong>La</strong> gura 4(a) muestra dos resultados que se hanobtenido para la función <strong>de</strong> isoeciencia en función<strong>de</strong> la relación existente entre los valores <strong>de</strong> T o y T q .Estos resultados muestran el impacto que tienen enla escalabilidad <strong>de</strong>l sistema los valores <strong>de</strong> las constantesc 1 y c 2 . Si estos valores son similares, comunicacióny <strong>de</strong>sequilibrio tienen el mismo impacto en laescalabilidad y por lo tanto la función <strong>de</strong> isoecienciaes cuadrática respecto al número <strong>de</strong> procesadores, es<strong>de</strong>cir O(m 2 ) como indica el mo<strong>de</strong>lo propuesto. Sinembargo, si c 1 ≫ c 2 la inuencia <strong>de</strong> la comunicaciónes prácticamente <strong>de</strong>spreciable y no tiene apenas in-uencia en la función <strong>de</strong> isoeciencia. Por ello, el resultadoobtenido es una función <strong>de</strong> isoeciencia constante,aunque con una pendiente ligeramente mayorque 0 que sería el caso <strong>de</strong> escalabilidad i<strong>de</strong>al. Estecomportamiento se <strong>de</strong>be a que al ser T q ≫ T o elefecto <strong>de</strong>l crecimiento lineal <strong>de</strong> T o es prácticamente<strong>de</strong>spreciable respecto a T q y en consecuencia no tieneapenas inuencia en la eciencia, siendo el valor <strong>de</strong>T q el que domina el comportamiento <strong>de</strong> la eciencia.Un efecto similar po<strong>de</strong>mos observar en la gura 4(b)para el caso <strong>de</strong> T q = c m . Cundo c 1 y c 2 tienen valoressimilares, la función <strong>de</strong> isoeciencia pasa a sercuadrática, como predice el mo<strong>de</strong>lo.VI. Conclusiones y Trabajos FuturosEs bien conocido el fuerte impacto que el equilibrio<strong>de</strong> carga tiene en el rendimiento <strong>de</strong> aplicacionesparalelas. Este artículo <strong>de</strong>muestra por primera vezque esto también es cierto en relación a la escalabilidad.Efectivamente, la primera y mayor aportaciónque se realiza en este artículo es que si no se tiene encuenta el <strong>de</strong>sequilibrio <strong>de</strong> carga <strong>de</strong> trabajo a la hora<strong>de</strong> evaluar la escalabilidad <strong>de</strong> un sistema paralelolas predicciones pue<strong>de</strong>n ser completamente erróneas.Muchos autores han propuesto mo<strong>de</strong>los <strong>de</strong> escalabilidad,como ha quedado recogido en la introducción,pero ninguno <strong>de</strong> ellos contempla esta situación.Este comportamiento hay que incorporarlo a lasherramientas <strong>de</strong> trabajo. En este artículo se ha propuestouna sencilla mo<strong>de</strong>lización matemática <strong>de</strong>l <strong>de</strong>sequilibrioentre los nodos <strong>de</strong> un sistema paralelo. Elmo<strong>de</strong>lo permite tratar el <strong>de</strong>sequilibrio <strong>de</strong> carga comouna sobrecarga más <strong>de</strong>l sistema, similar en su concepcióna la sobrecarga <strong>de</strong> comunicación. De estaforma es muy sencillo incorporar este factor en lafunción <strong>de</strong> isoeciencia, para pre<strong>de</strong>cir la escalabilidad<strong>de</strong> sistemas paralelos <strong>de</strong>sequilibrados.Con la nueva versión <strong>de</strong> la función <strong>de</strong> isoecienciaes posible analizar la inuencia que tiene el <strong>de</strong>sequilibrioen la escalabilidad <strong>de</strong> sistemas paralelos, yver su relación con la sobrecarga <strong>de</strong> comunicación.Se han presentado, a modo <strong>de</strong> ejemplo, una serie <strong>de</strong>análisis teóricos <strong>de</strong> los cuales se obtiene al menosun resultado <strong>de</strong>stacable: en sistemas <strong>de</strong>sequilibradossi la variación <strong>de</strong>l <strong>de</strong>sequilibrio es inversamenteproporcional a la carga <strong>de</strong> trabajo o al número <strong>de</strong>procesadores, la escalabilidad <strong>de</strong>l sistema pue<strong>de</strong> sersub-lineal. Este resultado contradice la cota inferiorpropuesta por Grama et al. [3] que proponen comolímite inferior para la función <strong>de</strong> isoeciencia Θ(m).<strong>JP2011</strong>-635


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 201110.8700006000050000Linear growthIsoefficiency O(m^1/2)Efficiency0.6Eficiency = 0.800.4m=2m=4m=80.2m=16m=32m=64m=12800 1000 2000 3000 4000 5000 6000 7000 8000Workload (W)Workload (W)4000030000200001000000 20 40 60 80 100 120 140Number of Processors (m)(a) Evolución <strong>de</strong> la Eciencia.(b) Función <strong>de</strong> isoecienciaFig. 3.Función <strong>de</strong> isoeciencia para el benchmark Inverso_w1.2e+061e+06c1 >> c2c1 ~ c21.2e+061e+06c1 >> c2c1 ~ c2Workload (W)800000600000400000Workload (W)80000060000040000020000020000000 20 40 60 80 100 120 140Number of Processors (m)(a) Desequilibrio constante (T q = c 1 )00 20 40 60 80 100 120 140Number of Processors (m)(b) Desequilibrio inversamente proporcional al número <strong>de</strong>procesadores (T q = c 1m)Fig. 4.Isoeciencia: benchmark con sobrecarga <strong>de</strong> comunicación y <strong>de</strong>sequilibrio <strong>de</strong> carga <strong>de</strong> trabajoEl mo<strong>de</strong>lo se ha validado experimentalmente medianteuna serie <strong>de</strong> benchmarks sintéticos. En todoslos experimentos realizados la correlación entrelas predicciones teóricas y los resultados empíricoses excelente. Por lo tanto, se pue<strong>de</strong> armar que elmo<strong>de</strong>lo presentado queda validado y vericado porestos experimentos. Otro aspecto importante que se<strong>de</strong>spren<strong>de</strong> <strong>de</strong> los experimentos es la importancia <strong>de</strong>lvalor relativo <strong>de</strong> las dos sobrecargas (comunicacióny <strong>de</strong>sequilibrio). Al ser la función <strong>de</strong> isoeciencia unanálisis <strong>de</strong> complejidad sólo se queda con la ten<strong>de</strong>ncia<strong>de</strong> la función al aumentar el número <strong>de</strong> procesadores.Esto es válido si todas las fuentes <strong>de</strong> sobrecarga sonhomogéneas y presentan constantes similares. Peroen los resultados presentados se ha visto que si una<strong>de</strong> las sobrecargas tiene un valor mucho mayor quela otra entonces una <strong>de</strong> ellas pue<strong>de</strong> dominar el comportamiento<strong>de</strong>l sistema en los rangos <strong>de</strong> número <strong>de</strong>nodos que nos movemos en la actualidad.El trabajo futuro se centra en analizar aplicacionesreales y obtener una metodología <strong>de</strong> trabajo que permita,la mo<strong>de</strong>lización <strong>de</strong>l <strong>de</strong>sequilibrio <strong>de</strong> carga <strong>de</strong>trabajo propuesto en este artículo. Asimismo, setratará <strong>de</strong> exten<strong>de</strong>r este resultado a sistemas paralelosheterogéneos don<strong>de</strong> los problemas <strong>de</strong> equilibrio<strong>de</strong> carga <strong>de</strong> trabajo son más frecuentes y complejos.Agra<strong>de</strong>cimientosEste trabajo ha sido parcialmente nanciado porel Ministerio <strong>de</strong> Educación y Ciencia (proyectosTIN2010-21289, TIN2010-21291-C02-02, Consoli<strong>de</strong>rCSD2007-00050 y Cajal Blue Brain project) así comopor la Red Europea <strong>de</strong> Excelencia HiPEAC.Referencias[1] The top500 project, November 2010,http://www.top500.org.[2] Ananth Grama, Anshul Gupta, George Karypis, and VipinKumar., Introduction to Parallel Computing (Second Edition),PEARSON - Addison-Wesley, 2003.[3] Ananth Y. Grama, Anshul Gupta, and Vipin Kumar, Isoeciency:measuring the scalability of parallel algorithmsand architectures, IEEE parallel and distributed technology:systems and applications, vol. 1, no. 3, pp. 1221,Aug. 1993.[4] J. Chen and V. Taylor, Mesh partitioning for distributedsystems, Proceedings of Seventh IEEE Int. Symposiumon High Performance Distributed Computing, July 1998.[5] Luis Pastor and Jose L. Bosque, Eciency and scalabilitymo<strong>de</strong>ls for heterogeneous clusters, in Third IEEE Int.Conference on Cluster Computing,, Los Angeles, California,Octubre 2001, pp. 427434.[6] A. Ya. Kalinov, Scalability of heterogeneous parallel systems,Programming and Computer Software, vol. 32, no.1, pp. 17, 2006.[7] Y., X.-H. Sun, and M. Wu, Algorithm-system scalabilityof heterogeneous computing, Journal of Parallel and DistributedComputing, vol. 68, no. 11, pp. 14031412, 2008.<strong>JP2011</strong>-636


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Mejorando las aplicaciones <strong>de</strong> red enarquitecturas multinúcleo heterogéneasAndrés Ortíz 1 ; Pablo Cascón 2 ; Julio Ortega 2 ; Antonio F. Díaz 2 ; Alberto Prieto 2Resumen— Los nodos con varios procesadores,posiblemente heterogéneos y/o multinúcleo, suponennuevos <strong>de</strong>safíos y oportunida<strong>de</strong>s para acelerar lasaplicaciones que requieren comunicaciones connecesida<strong>de</strong>s <strong>de</strong> anchos <strong>de</strong> banda elevados. Muchas <strong>de</strong> lasmejoras posibles para incrementar el ancho <strong>de</strong> bandaestán relacionadas con la explotación <strong>de</strong>l paralelismodisponible en los nodos, gracias a la presencia <strong>de</strong> variosnúcleos <strong>de</strong> procesamiento. Dicho paralelismo no sólopue<strong>de</strong> aprovecharse para mejorar las prestaciones <strong>de</strong> laaplicación sino también para reducir la sobrecargaasociada a la interfaz <strong>de</strong> red. Este trabajo analiza algunasalternativas para distribuir la interfaz <strong>de</strong> red en losdiferentes núcleos <strong>de</strong> procesador disponibles en el nodo.Dichas alternativas incluyen el uso <strong>de</strong> procesadoresmultinúcleo heterogéneos así como el uso <strong>de</strong>procesadores <strong>de</strong> red y la explotación <strong>de</strong> la afinidad entrela ubicación interfaz <strong>de</strong> red (proximidad a la memoriadon<strong>de</strong> se almacenan las diferentes estructuras <strong>de</strong> datos) ylas características específicas <strong>de</strong> la arquitectura <strong>de</strong>l nodo.LA interfaz <strong>de</strong> red distribuida que proponemosproporciona mejoras en el ancho <strong>de</strong> banda y en lalatencia. Esta propuesta ha sido evaluadaexperimentalmente mediante la implementación <strong>de</strong> unsistema <strong>de</strong> prevención contra intrusos (IPS).Palabras clave— Afinidad <strong>de</strong> interrupción, Sistema <strong>de</strong>prevención contra intrusos, Interfaz <strong>de</strong> red, Afinidad <strong>de</strong>procesador, Simics.EI. INTRODUCCIÓNN los últimos años, ha sido más difícil reducir eltiempo por ciclo <strong>de</strong> reloj y a la vez incrementar elnúmero medio <strong>de</strong> instrucciones por segundo (IPC) que seejecutan en un núcleo <strong>de</strong> procesamiento, con el fin <strong>de</strong>aprovechar (<strong>de</strong> acuerdo con la ley <strong>de</strong> Moore) el aumento <strong>de</strong>lnúmero <strong>de</strong> transistores que pue<strong>de</strong>n incluirse <strong>de</strong>ntro <strong>de</strong> uncircuito integrado. De esta forma, la mejora limitada quepue<strong>de</strong> obtenerse en el número <strong>de</strong> instrucciones completadaspor unidad <strong>de</strong> tiempo y les restricciones <strong>de</strong> potencia han<strong>de</strong>terminado una ten<strong>de</strong>ncia hacia arquitecturas con múltiplesnúcleos en un chip [1]. A<strong>de</strong>más, teniendo en cuenta la ley <strong>de</strong>Amdalh, también es interesante el uso <strong>de</strong> chips multinúcleoheterogéneas que incluyen núcleos con arquitecturasdiferentes para proporcionar la aceleración <strong>de</strong> partes <strong>de</strong> laaplicación que presentan diferentes tipos <strong>de</strong> paralelismo. Almismo tiempo, dichas arquitecturas permiten aprovecharmejor el área disponible en el chip y mejorar la eficienciaenergética [2,3].1 Departamento <strong>de</strong> Ingeniería <strong>de</strong> Comunicaciones, <strong>Universidad</strong> <strong>de</strong>Málaga, e-mail: aortiz@ic.uma.es.2 Departemanto <strong>de</strong> Arquitectura y Tecnologia <strong>de</strong> Computadores,<strong>Universidad</strong> <strong>de</strong> Granada, e-mail: julio@atc.ugr.es,afdiaz@atc.ugr.es, aprieto@ugr.es.Precisamente, la interfaz <strong>de</strong> red (los elementoshardware/software utilizados para conectar el computador ala red) <strong>de</strong>termina las prestaciones <strong>de</strong> los servidores <strong>de</strong> red ylas aplicaciones distribuidas que requieren gran<strong>de</strong>s anchos <strong>de</strong>banda a la vez que bajas latencias. Por ejemplo, paraaprovechar todo su potencial, las técnicas <strong>de</strong> virtualizaciónrequieren arquitecturas <strong>de</strong> red virtualizadas eficientes que<strong>de</strong>scansan sobre interfaces <strong>de</strong> red <strong>de</strong> altas prestaciones talescomo las interfaces <strong>de</strong> red multicola (CDNA) [4], propuestaspara aprovechar los procesadores multinúcleo [5]. A<strong>de</strong>más,la disponibilidad <strong>de</strong> enlaces <strong>de</strong> red con gran ancho <strong>de</strong> banda(multigigabit Ethernet, Infiniband, etc.) [6] han <strong>de</strong>splazado elcuello <strong>de</strong> botella en el camino <strong>de</strong> comunicación <strong>de</strong> la red alos nodos, <strong>de</strong>bido a la sobrecarga <strong>de</strong> comunicación porcambios <strong>de</strong> contexto, procesamiento <strong>de</strong> la pila <strong>de</strong> protocolos,múltiples copias <strong>de</strong> datos, e interrupciones.<strong>La</strong> presencia <strong>de</strong> múltiples procesadores (homogéneos oheterogéneos) en los nodos, incluyendo arquitecturasmultinúcleo con diferentes perfiles <strong>de</strong> cache y buses <strong>de</strong> E/Smejorados, proporcionan nuevas posibilida<strong>de</strong>s para escalar lainterfaz <strong>de</strong> red. De hecho, el uso <strong>de</strong> varios procesares en elcomputador para reducir la sobrecarga <strong>de</strong> comunicación enlas CPU que ejecutan la aplicación ha sido propuesto ennumerosos trabajo. Así, la externalización <strong>de</strong> protocolosmediante offloading u onloading [7, 8] son técnicas bienconocidas. Mientras la técnica <strong>de</strong> offloading utilizaprocesadores incluidos en la tarjeta <strong>de</strong> red (NIC) para elprocesamiento <strong>de</strong> los protocolos <strong>de</strong> red, el onloading utilizaprocesadores <strong>de</strong> propósito general en un procesadormultinúcleo o en un SMP. Ambas alternativas contribuyen aliberar ciclos en los procesadores que ejecutan la aplicación,dado que <strong>de</strong>splazan la sobrecarga <strong>de</strong> comunicación a otroprocesador. Sin embargo, cada alternativa tiene sus pros ysus contras. Por ejemplo, el offloading sólo proporcionamejoras cuando la velocidad <strong>de</strong>l procesador principal essimilar a la <strong>de</strong>l procesador incluido en la NIC (que procesa elprotocolo <strong>de</strong> red). Por otro lado, la API para comunicar laNIC con la CPU principal pue<strong>de</strong> ser <strong>de</strong>masiado compleja,especialmente con la pila <strong>de</strong> protocolos TCP. A<strong>de</strong>más,aunque el onloading explota la ten<strong>de</strong>ncia actual a lasarquitecturas multinúcleo o a los nodos multiprocesador, eluso <strong>de</strong> núcleos más simples y eficientes en cuanto a potenciay área, añadidos a una CPU <strong>de</strong> propósito general, tambiénpue<strong>de</strong> acelerar las funciones <strong>de</strong> red pero con menor coste enárea y una mayor eficiencia en potencia [9]. Este sería elcaso <strong>de</strong> los procesadores <strong>de</strong> red, normalmente basados enmicroarquitecturas heterogéneas.De esta forma, hay varias propuestas [10, 11] que intentancombinar los beneficios <strong>de</strong>l offloading y <strong>de</strong>l onloading paraacelerar el procesamiento <strong>de</strong> la red aprovechando laexistencia <strong>de</strong> varios procesadores en el nodo (no sólo en laNIC).<strong>La</strong> paralelización <strong>de</strong> los protocolos <strong>de</strong> red y la explotación<strong>de</strong>l paralelismo presente en las interfaces <strong>de</strong> redprogramables también han sido analizadas [12, 13]. <strong>La</strong>sdiferentes estrategias que pue<strong>de</strong>n utilizarse para paralelizarprotocolos se han consi<strong>de</strong>rado en [12], don<strong>de</strong> se muestraque, aunque el paralelismo a nivel <strong>de</strong> paquete que se pue<strong>de</strong>conseguir en una conexión TCP es limitado, las<strong>JP2011</strong>-637


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011oportunida<strong>de</strong>s <strong>de</strong> paralelizar el procesamiento pue<strong>de</strong>nincrementarse en el caso <strong>de</strong> múltiples conexiones. En [13],se evalúan las prestaciones obtenidas con elparticionalmiento <strong>de</strong> tareas estáticas para aprovechar lapresencia <strong>de</strong> dos procesadores incluidos en una NICespecífica, utilizando la mejora proporcionada por elservidor web httpd con diferentes cargas <strong>de</strong> trabajo. Otroesquema <strong>de</strong> particionamiento estático se presenta en [14],don<strong>de</strong> se <strong>de</strong>scribe una versión paralela <strong>de</strong> protocolo <strong>de</strong> paso<strong>de</strong> mensajes (EMP). En [15], se <strong>de</strong>muestra que una mapeoa<strong>de</strong>cuado <strong>de</strong> los procesos <strong>de</strong> una aplicación entre losdiferentes núcleos y la NIC pue<strong>de</strong> corregir el <strong>de</strong>sequilíbriocreado por el procesamiento <strong>de</strong> los protocolos <strong>de</strong> red,minimizando los fallos <strong>de</strong> cache y mejorando lasprestaciones globales. Esta i<strong>de</strong>a <strong>de</strong> crear afinidad <strong>de</strong>procesos y <strong>de</strong> interrupciones a procesadores específicos se haconsi<strong>de</strong>rado en [16-18]. Los experimentos realizados en[16], relacionados con las ventajas <strong>de</strong> utilizar arquitecturasque tienen en cuenta la localidad <strong>de</strong> los datos y la afinidad <strong>de</strong>los procesadores han puesto <strong>de</strong> manifiesto que estaspropuestas mejoran las prestaciones proporcionadas por lastécnicas <strong>de</strong> offloading y onloading. A<strong>de</strong>más, en aplicacionesque utilizan varias hebras [17, 18] pue<strong>de</strong>n obtenerseimportantes mejoras con esquemas <strong>de</strong> planificación conafinidad. El trabajo [17] muestra mejoras no sólo en elnúmero <strong>de</strong> conexiones que pue<strong>de</strong>n ser procesadasconcurrentemente sino también en el ancho <strong>de</strong> banda <strong>de</strong> lasconexiones individuales. En [18] se presenta un esquema <strong>de</strong>planificación <strong>de</strong> los procesos <strong>de</strong> red para <strong>de</strong>cidir elprocesador óptimo <strong>de</strong>pendiendo <strong>de</strong> la carga <strong>de</strong> losprocesadores, la distribución <strong>de</strong> cache y los perfiles <strong>de</strong>comunicación <strong>de</strong> las aplicaciones. El problema <strong>de</strong> la latencia<strong>de</strong> memoria en el contexto <strong>de</strong> las interfaces <strong>de</strong> red ha sidotambién consi<strong>de</strong>rado en trabajos como [19, 20]. En [19] seconcluye que en la mayoría <strong>de</strong> los escenarios, incluso parapaquetes pequeños e interfaces que implementan cerocopias,tamaños <strong>de</strong> cache gran<strong>de</strong>s y niveles <strong>de</strong> asociatividadmayores pue<strong>de</strong>n mejorar las prestaciones <strong>de</strong> lascomunicaciones (principalmente en el caso <strong>de</strong> TCP). En [20]se analizan los mecanismos utilizados por los procesadores<strong>de</strong> red para superar los cuellos <strong>de</strong> botella <strong>de</strong> memoria y seconcluye que las caches <strong>de</strong> datos y las estrategias multihebrapue<strong>de</strong>n cooperar para alcanzar gran<strong>de</strong>s anchos <strong>de</strong> banda entarjetas <strong>de</strong> red programables.En este trabajo, se evalúan diferentes configuraciones paradistribuir las aplicaciones <strong>de</strong> red entre los procesadoresdisponibles en el nodo. Dichas configuraciones secorrespon<strong>de</strong>n con alternativas para implementar la interfaz<strong>de</strong> red utilizando procesadores multinúcleo, en el nodo o enla NIC, incluyendo microarquitecturas multinúcleoheterogéneas tales como los procesadores <strong>de</strong> red. Así,<strong>de</strong>spués <strong>de</strong> esta introducción, la Sección 2 <strong>de</strong>scribe lasconfiguraciones propuestas para nuestra interfaz distribuiday basada en afinidad. Después, en la Sección 3 se presentanlas principales características <strong>de</strong> los sistemas <strong>de</strong> prevencióncontra intrusos (IPS) utilizados para evaluar lasconfiguraciones y la Sección 4 proporciona loscorrespondientes resultados experimentales. Finalmente, laSección 5 muestra las conclusiones y las líneas futuras <strong>de</strong>investigación <strong>de</strong> este trabajo.II. CONFIGURACIONES DE LAS INTERFACES DE REDEn esta sección, se <strong>de</strong>scriben las configuracionespropuestas para distribuir la aplicación y la interfaz <strong>de</strong> redcon el fin <strong>de</strong> aprovechar los diferentes procesadorespresentes en el nodo.ApplicationbufferUser MemoryApplicationbufferUser MemorySpace65577NICSystem CPUCPU0sk_buff4DMA areaSystem MemorySpace(a)CPU2sk_buffNICIRQIRQCPU1 3CPU032NICMemoryNICRing BufferNICmemory21NetworkData transferHardware interrupt (IRQ)Software interrupt (SoftIrq)CPU0 controls the transference1Network46 Data transferHardware interrupt (IRQ)DMA areaSoftware interrupt (SoftIrq)CPU1 controls the transferenceSystem MemorySpace(b)Fig. 1. Recepción <strong>de</strong> paquete por la interfaz <strong>de</strong> red base (a); y porla interfaz <strong>de</strong> red distribuida propuesta (b)<strong>La</strong> Figura 1 muestra los principales pasos para la recepcíón<strong>de</strong> un paquete en el sistema base tomado como referenciapara <strong>de</strong>terminar las mejoras alcanzadas por las diferentesconfiguraciones que se han analizado. En la Figura 1a,<strong>de</strong>spués <strong>de</strong> que un nuevo paquete llegue a la NIC 1, éstacopia el paquete <strong>de</strong>s<strong>de</strong> la memoria <strong>de</strong> la NIC al área <strong>de</strong>DMA localizada en la memoria principal, 2, don<strong>de</strong> laCPU0 almacena el paquete en estructuras sk_buff. <strong>La</strong>transferencia 2 se realiza una vez que el anillo <strong>de</strong> DMA <strong>de</strong>la NIC está lleno. En otras palabras, estamos utilizandocoalescencia <strong>de</strong> interrupciones [9] en el sistema base parareducir el número <strong>de</strong> interrupciones. Después <strong>de</strong> 2, se envíauna interrupción hardware a la CPU principal par informar<strong>de</strong> que hay disponibles nuevos paquetes para ser procesados3, y el driver copia los datos en estructuras sk_buff 4.Después, el sistema operativo planifica una softirq para elprocesamiento <strong>de</strong> paquetes TCP 5. El mecanismo softirq,disponible <strong>de</strong>s<strong>de</strong> el Kernel 2.4 <strong>de</strong> Linux, permite laejecución <strong>de</strong> tareas prorrogables hasta el correspondienteevento software [21]. Dado que pue<strong>de</strong>n enviarse diferentessoftirq a los distintos procesadores <strong>de</strong>l nodo, varias hebras <strong>de</strong>procesamiento TCP/IP pue<strong>de</strong>n ejecutarse en paralelo envarios procesadores. Cuando la softirq ha procesado elprotocolo, la CPU0 almacena los datos, 7, en los buffers <strong>de</strong>aplicación localizados en el espacio <strong>de</strong> memoria <strong>de</strong> usuario,6.<strong>La</strong> Figura 1b muestra la forma en que se lleva a cabo larecepción <strong>de</strong> paquetes en nuestra interfaz <strong>de</strong> red híbrida (i.e.,implementa elementos <strong>de</strong> las técnicas <strong>de</strong> onloading yoffloading). Aquí, el procesador CPU2 está incluido en laNIC y ejecuta los protocolos <strong>de</strong> red. El procesador CPU1recibe las interrupciones y ejecuta el driver <strong>de</strong> la mismaforma que lo hace la interfaz <strong>de</strong> red con onloading. A<strong>de</strong>más,la CPU1 es capaz <strong>de</strong> ejecutar otras tareas como las llamadas<strong>JP2011</strong>-638


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011al sistema para copiar los datos <strong>de</strong>s<strong>de</strong> los sockets TCP a losbuffers <strong>de</strong> la aplicación. Así, en el mo<strong>de</strong>lo híbrido no semolesta a la CPU0 mientras se está recibiendo datos. Portanto, como la CPU0 ejecuta la aplicación (y está únicamentecentrada en ser el consumidor <strong>de</strong> datos), el ancho <strong>de</strong> bandaalcanzado podría ser mayor que el ancho <strong>de</strong> banda alcanzadocon las interfaces <strong>de</strong> red con offloading u onloading.Así, en la Figura 1b, <strong>de</strong>spués <strong>de</strong> recibir un paquete 1, laNIC lo almacena en su buffer en anillo. Cuando dicho bufferestá lleno o la transferencia <strong>de</strong>l paquete ha finalizado, lospaquetes se copian <strong>de</strong>s<strong>de</strong> el buffer en anillo a la memoria <strong>de</strong>la NIC. Entonces, la NIC realiza una transferencia <strong>de</strong> DMAal área <strong>de</strong> DMA en la memoria principal, 2, y envía unainterrupción hardware a la CPU1, 3. Esta interrupción causala ejecución <strong>de</strong> la función do_irq() [21], que llama a lacorrespondiente rutina <strong>de</strong> interrupción <strong>de</strong>finida en el driver<strong>de</strong>l dispositivo para copiar los datos en las estructurassk_buff , 4, [21]. Entonces, el driver ejecuta una softirq [21]en la CPU2, 5, para procesar los paquetes <strong>de</strong> acuerdo conlos parámetros <strong>de</strong> las estructuras sk_buff.Los parámetros en las estructuras sk_buff correspon<strong>de</strong>n alos protocolos utilizados en las capas altas (en este casoTCP). Una vez que se ha procesado la pila <strong>de</strong> protocolos, losdatos se copian al Socket TCP. Entonces, la CPU1 copia, 7,los datos <strong>de</strong>s<strong>de</strong> el Socket TCP a los buffers <strong>de</strong> la aplicación,a través <strong>de</strong> la correspondiente llamada al sistema, 6.Una alternativa que ha sido consi<strong>de</strong>rada para la CPU2, enla Figura 1b, es una microarquitectura multinúcleo usual enprocesadores <strong>de</strong> red. Los procesadores <strong>de</strong> red (NP) soncircuitos programables que proporcionan recursos rápidos yflexibles para las funciones <strong>de</strong> comunicación a altavelocidad. Dichos procesadores incluyen múltiples núcleoscon características multihebra que hacen posible aprovecharel procesamiento paralelo en las interfaces <strong>de</strong> red. En estetrabajo, hemos utilizado el procesador <strong>de</strong> red Intel IXP2855[22, 23] que incluye 16 coprocesadores (llamadosMicroEngines) optimizados para el procesamiento <strong>de</strong>paquetes, y un núcleo <strong>de</strong> propósito general (Intel XScale quepresenta una arquitectura RISC compatible con laarquitectura ARM).En una interfaz <strong>de</strong> red distribuida, es muy importante teneren cuenta el problema <strong>de</strong>l muro <strong>de</strong> memoria. En las técnicasque asocian la mayoría <strong>de</strong>l trabajo <strong>de</strong> procesamiento <strong>de</strong>lprotocolo TCP/IP a un núcleo mientras los procesos <strong>de</strong> laaplicación se ejecutan en otras CPU o núcleos disponibles enel sistema, pue<strong>de</strong> suce<strong>de</strong>r que los datos que tenga queprocesar el la pila <strong>de</strong> protocolos se encuentren en una cacheL1 o L2 diferente a la que almacena el código <strong>de</strong>l protocolo.Esta situación produce fallos <strong>de</strong> cache que <strong>de</strong>gradan elrendimiento global <strong>de</strong>l servidor [12]. Para resolver esteproblema, en este trabajo proponemos el uso <strong>de</strong> diferentesperfiles <strong>de</strong> cache así como <strong>de</strong> distribución <strong>de</strong> procesos einterrupciones <strong>de</strong> acuerdo con su afinidad.Para ejecutar el driver <strong>de</strong> la NIC en una CPU específica,hemos forzado la petición <strong>de</strong> interrupciones a dicha CPU.Esto se ha implementado utilizando la característica <strong>de</strong>afinidad <strong>de</strong> interrupciones proporcionada por el kernel 2.6 <strong>de</strong>Linux mediante smp_affinity [25], que contiene la máscara<strong>de</strong> interrupciones para la programación <strong>de</strong>l APIC (AdvancedProgrammable Interrupt Controller). Es posible solicitar unaIRQ a un procesador específico, que pue<strong>de</strong> ejecutar el driver<strong>de</strong> la NIC y la pila <strong>de</strong> protocolos. Aunque hay otraspropuestas para la distribución dinámica <strong>de</strong> lasinterrupciones, tales como irqbalance [21], lo que se buscaes que se soliciten las IRQ a la misma CPU don<strong>de</strong> lacorrespondiente softirq se va a encolar.<strong>La</strong> Figura 2 muestra los perfiles <strong>de</strong> procesador y cachepara las diferentes configuraciones <strong>de</strong> interfaz <strong>de</strong> redconsi<strong>de</strong>radas. En la Figura 2a, los procesos <strong>de</strong> aplicación hansido distribuidos para equilibrar la carga entre las diferentesCPU. En esta configuración, llamada hybrid(1), CPU0 yCPU1 comparten la cache L2 mientras que la CPU2 procesala pila <strong>de</strong> protocolos y tiene su propia memoria cache. Porotro lado, los procesos <strong>de</strong> aplicación pue<strong>de</strong>n ser ejecutadospor cada una <strong>de</strong> las CPU presentes en el nodo, y ladistribución <strong>de</strong> esos procesos la <strong>de</strong>ci<strong>de</strong> el planificador <strong>de</strong>lsistema operativo. Al mismo tiempo, las interrupciones seredirigen a la CPU1, que ejecuta el driver <strong>de</strong> la NIC. Estapropuesta podría ser potencialmente causa <strong>de</strong> fallos <strong>de</strong> cachey, por tanto, <strong>de</strong> un gran número <strong>de</strong> ciclos <strong>de</strong> CPU perdidos alcargar datos <strong>de</strong>s<strong>de</strong> la memoria principal, especialmentecuando el servidor se encuentre bajo una gran carga <strong>de</strong>trabajo. De esta forma, hybrid (2) en la Figura 2b, utiliza unperfil <strong>de</strong> cache diferente para las CPU que procesan elsistema operativo y los procesos <strong>de</strong> la aplicación <strong>de</strong>lservidor, respectivamente. A<strong>de</strong>más, las interrupciones se hanredirigido a la CPU2 para evitar que la interfaz <strong>de</strong> redinterrumpa a la CPU que ejecuta los procesos <strong>de</strong>l servidor.Por otro lado, los procesos <strong>de</strong> red relacionados con lasaplicaciones <strong>de</strong> usuario se han asignado a la CPU1. Así, estaCPU no se interrumpe, ni por la interfaz <strong>de</strong> red, ni por otrasfuentes <strong>de</strong> interrupción.Al mismo tiempo, se ha consi<strong>de</strong>rado una cache L2unificada. Esta propuesta resuelve el problema <strong>de</strong> lalocalidad <strong>de</strong> cache, dado que la cache utilizada por la CPU2,la cual procesa la pila <strong>de</strong> protocolos, se comparte con laCPU1, la cual ejecuta los procesos <strong>de</strong> la aplicación,resultando en una disminución <strong>de</strong> los fallos <strong>de</strong> cache. Estadistribución <strong>de</strong>l hardware se podría correspon<strong>de</strong>r con unaNIC integrada en un microprocesador multinúcleo [27].Finalmente, la Figura 2c muestra la configuración npNICque utiliza una NIC basada en un procesador <strong>de</strong> red. En estecaso, las funciones <strong>de</strong> red se procesan aprovechando lasventajas <strong>de</strong> tener múltiples núcleos, optimizados para elprocesamiento <strong>de</strong> paquetes, que están incluidos en lamicroarquitectura <strong>de</strong>l procesador <strong>de</strong> red.OS +User processesCPU0 CPU1 CPU2L1OS +User processesCPU0 CPU1 CPU2L1L2User +Networkprocesses +NIC driverL1User +networkprocessesL1L2TCP/IPNICTCP/IP +NIC driverL1NICmem.NICmem.(a)Network(b)NetworkOS +User processes +NIC driverCPU0L1L2TCP/IP +NetworkProcessesNICNICmem.Fig. 2. Configuraciones para las interfaces <strong>de</strong> red propuestas (a)hybrid(1); (b) hybrid(2); (c) npNICNP(c)NetworkIII. IMPLEMENTACIONES EN EL NODO DE SISTEMAS DEPREVENCIÓN DE INTRUSOSPara comparar las prestaciones <strong>de</strong> las diferentesconfiguraciones <strong>de</strong> interfaces <strong>de</strong> red distribuidas que hemosanalizado, se ha consi<strong>de</strong>rado un sistema <strong>de</strong> prevención <strong>de</strong>intrusiones (IPS). Un IPS necesita analizar la cabecera y elcontenido <strong>de</strong>l paquete para <strong>de</strong>tectar comportamientos no<strong>de</strong>seados. También se requiere que la función implementadapor el sistema <strong>de</strong> prevención <strong>de</strong> intrusiones se actualice connuevos procedimientos <strong>de</strong> <strong>de</strong>tección <strong>de</strong>bido a la evolución <strong>de</strong>los ataques <strong>de</strong> red. Dado que esta aplicación requiere altasprestaciones <strong>de</strong> procesamiento y flexibilidad, un buencandidato para implementar dicho sistema es un procesador<strong>de</strong> red. <strong>La</strong> configuración más común <strong>de</strong> los sistemas IPSconsiste en monitorizar todo el tráfico entrante a la red <strong>de</strong>una organización, mediante un computador que ejecute el<strong>JP2011</strong>-639


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011software IPS conectado a la conexión principal a Internet <strong>de</strong>dicha organización. Los paquetes que provienen <strong>de</strong> Internetson analizados por el sistema IPS, y se procesan antes <strong>de</strong> quealcancen la red y los sistemas <strong>de</strong> la organización.Normalmente, los paquetes se reciben mediante una NICestándar, son procesados en la CPU que <strong>de</strong>ci<strong>de</strong> si el paquete<strong>de</strong>be continuar hacia la red <strong>de</strong> la organización o <strong>de</strong>be ser<strong>de</strong>scartado. Esta implementación tiene la <strong>de</strong>sventaja <strong>de</strong> quetodos los paquetes <strong>de</strong>ben ser procesados por la CPU. Esteprocesamiento pue<strong>de</strong> llegar a consumir <strong>de</strong>masiados recursos<strong>de</strong> la CPU y en el caso <strong>de</strong> que la tasa <strong>de</strong> paquetes sea muyalta, el IPS pue<strong>de</strong> verse forzado a <strong>de</strong>scartar paquetes yafectar el rendimiento <strong>de</strong> la organización. Nuestra propuestaconsiste en mover el IPS, parcial o totalmente, <strong>de</strong>s<strong>de</strong> elnúcleo <strong>de</strong>dicado a las aplicaciones, a otro núcleo en un nodomultinúcleo o en la NIC.Así, en el caso <strong>de</strong> utilizar una interfaz <strong>de</strong> red distribuida,teniendo en cuenta la Figura 1b, la implementación <strong>de</strong>lsistema IPS funciona como se indica a continuación.Después <strong>de</strong> recibir un paquete, 1, la NIC lo almacena en unbuffer en anillo. Entonces los paquetes se copian a lamemoria <strong>de</strong> la NIC, y <strong>de</strong>spués, al área <strong>de</strong> DMA en lamemoria principal, 2. Una vez que el paquete está en el área<strong>de</strong> DMA, la NIC envía una interrupción hardware (IRQ) a laCPU1, 3, causando la ejecución <strong>de</strong> la rutina <strong>de</strong> atención a lainterrupción (ISR). Dicha rutina copia el paquete recibido auna estructura sk_buff , 4, [26]. Entonces, <strong>de</strong>spués <strong>de</strong>ejecutar la función netif_rx(), que encola una softirq, seejecuta el código <strong>de</strong>l IPS en la CPU1. Este código examinano sólo la cabecera <strong>de</strong>l paquete sino también el contenido y<strong>de</strong>ci<strong>de</strong> si el paquete pue<strong>de</strong> ser aceptado y enviado a las capassuperiores <strong>de</strong>l protocolo, o no. Si el IPS <strong>de</strong>ci<strong>de</strong> <strong>de</strong>jar que elpaquete siga viajando, se encola una softirq [26] en la CPU2,5, para procesar el paquete <strong>de</strong> acuerdo con los parámetros<strong>de</strong> las estructuras sk_buff, y utilizando las rutinas ip_rcv(), ytcp_rcv() o udp_rcv().Una vez que la pila <strong>de</strong> protocolos ha sido procesada, losdatos se copian a un Socket INET (dado que hemos trabajadocon TCP/IP) [26] y la CPU1 copia, 7, los datos <strong>de</strong>s<strong>de</strong> elINET Socket a un Socket BSD don<strong>de</strong> la aplicación pue<strong>de</strong>acce<strong>de</strong>r a los datos a través <strong>de</strong> la correspondiente llamada alsistema, 6. Así, el código <strong>de</strong>l IPS se ejecuta en el espacio <strong>de</strong>kernel, capturando los paquetes entrantes en una etapa muytemprana <strong>de</strong>l proceso <strong>de</strong> recepción <strong>de</strong> paquetes, evitando laejecución <strong>de</strong> rutinas <strong>de</strong> más alto nivel para la comprobación<strong>de</strong> las reglas <strong>de</strong>l IPS.Cuando la NIC basada en el procesador <strong>de</strong> red IXP2855 seutiliza para implementar el IPS (Figura 2c), un MicroEnginese <strong>de</strong>dica a la recepción <strong>de</strong> paquetes mientras que otro seencarga <strong>de</strong> la transmisión (con la ayuda <strong>de</strong> otros dos), dosMicroEngines gestionan la comunicación con el nodo através <strong>de</strong>l bus PCIe y otro MicroEngine se utiliza para elprocesamiento <strong>de</strong> los paquetes. Este MicroEngineprecisamente, ejecuta el código <strong>de</strong>l IPS y <strong>de</strong>scarta aquellospaquetes que no cumplan con las reglas establecidas, <strong>de</strong>forma que no alcancen la CPU principal <strong>de</strong>l nodo. No hay,en este caso, estructuras <strong>de</strong> datos compartidas, dado que lasreglas <strong>de</strong>l IPS están escritas en el propio código, y no hayuna estructura <strong>de</strong> memoria compartida por las hebras (8 ennuestro prototipo).operativo, como las aplicaciones comerciales. Para ello, seha simulado una arquitectura [10] que contiene procesadores<strong>de</strong> propósito general así como dos niveles <strong>de</strong> memoria cache.Más específicamente, la cache L1 ha sido dividida en cache<strong>de</strong> instrucciones y <strong>de</strong> datos, cada una con 256 líneas <strong>de</strong> 64bytes, y una política write-through. <strong>La</strong> cache L2 utiliza 8192líneas <strong>de</strong> 128 bytes. <strong>La</strong> asociatividad implementada en lacache L1 <strong>de</strong> instrucciones, L1 <strong>de</strong> datos y L2 es <strong>de</strong> 2, 4 y 8líneas respectivamente. En todos los casos, se utiliza unapolítica LRU <strong>de</strong> reemplazo y un protocolo <strong>de</strong> coherencia <strong>de</strong>cache MESI.<strong>La</strong> implementación <strong>de</strong>l IPS que se ha simulado en Simicsutiliza un kernel 2.6 <strong>de</strong> Linux [24] y está basada en elmódulo netfilter [25, 26]. Sin embargo, las reglas han sidoescritas en el código y el cambio <strong>de</strong> las mismas requiere lamodificación <strong>de</strong>l mismo. <strong>La</strong> implementación se ha realizadoen un módulo para el kernel 2.6 <strong>de</strong> Linux que pue<strong>de</strong> sercargado y <strong>de</strong>scargado en tiempo <strong>de</strong> ejecución.Throughput improvement (%)<strong>La</strong>tency improvement (%)20001800160014001200100080060040020010090807060504030201000IPS on Hybrid (1)IPS on Hybrid (2)IPS on npNIC1 10 100 1000 10000 100000 1+e06Packet size (bytes)(a)1 10 100 1000 10000 100000 1e+06Packet size (bytes)(b)IPS on Hybrid (1)IPS on Hybrid (2)IPS on npNICFigura 3. Comparación <strong>de</strong> mejoras en ancho <strong>de</strong> banda (a) y latencia (b)IV. CONFIGURACIÓN EXPERIMENTAL Y RESULTADOSLos resultados experimentales han sido obtenidos mediantesimulación, y mediante la ejecución <strong>de</strong>l código IPS en unsistema que incluye una NIC NFE-i800 basada en elprocesador <strong>de</strong> red IXP2855. El mo<strong>de</strong>lo <strong>de</strong> simulacióncorrespondiente a la interfaz <strong>de</strong> red distribuida ha sidoconstruido utilizando el simulador <strong>de</strong> sistema completoSimics [10], <strong>de</strong> forma que se simula no sólo el hardware,sino también el software, que compren<strong>de</strong> tanto el sistema<strong>JP2011</strong>-640


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011npNIC-based IPS 1000 MbpsHybrid(1) IPS 1000 MbpsHybrid(2) IPS 1000 MbpsBase IPS 600 MbpsBase IPS 700 MbpsBase IPS 1000 Mbps4 10810 0 10610 102npNIC-based IPS 1000 MbpsHybrid(1) IPS 1000 MbpsHybrid(2) IPS 1000 MbpsBase IPS 600 MbpsBase IPS 700 MbpsBase IPS 1000 MbpsPacket Size(bytes)Packet Size (bytes)0 10 0 10 2 10 4 10 6 10 8Figura 4. Comparación <strong>de</strong> la latencia para tráfico corrupto (a); ycomparación <strong>de</strong>l ancho <strong>de</strong> banda para tráfico corrupto (b)Como se muestra en la Figura 3, la implementación <strong>de</strong>lIPS utilizando npNIC proporciona mejores valores <strong>de</strong> ancho<strong>de</strong> banda y latencia, con respecto al sistema base, parapaquetes <strong>de</strong> tamaño pequeño. Este comportamiento pue<strong>de</strong>explicarse dado que la npNIC permite una interacción másdirecta con la red y pue<strong>de</strong> reaccionar a los paquetes entrantessin la intervención <strong>de</strong>l sistema operativo. De esta forma, laactual implementación <strong>de</strong> npNIC está recomendada parapaquetes <strong>de</strong> tamaño pequeño, los cuales suelen ser losresponsables <strong>de</strong> altas latencias si tiene que viajar por losbuses <strong>de</strong>l sistema hasta llegar a la CPU principal.00Both (Legitime+Corrupt)LegitimeBoth (Legitime+Corrupt)LegitimePacket Size (bytes)0.40.2001.41.210.80.6100080060040020010 0 10 2 10 4 10 6 10 8Packet Size (bytes)0100080060040020010 0 10 2 10 4 10 6 10 8Figura 5. (a) <strong>La</strong>tencia para tráfico legítimo y corrupto+legítimocon sistema base. (b) <strong>La</strong>tencia para tráfico legítimo ycorrupto+legítimo con npNIC01000800600400200<strong>La</strong>tency (s)Throughput (Mbps)Throughput (Mbps)Throughput (Mbps)Cuando el tamaño <strong>de</strong> los paquetes se incrementa, lasalternativas híbridas proporcionan mejores resultados, dadoque dichas alternativas asignan recursos según el perfil <strong>de</strong> laaplicación, <strong>de</strong>terminado por la sobrecarga <strong>de</strong> computación,el tamaño <strong>de</strong>l paquete y la cantidad <strong>de</strong> tráfico entrantecorrupto. A<strong>de</strong>más, la alternativa hybrid(2), la cual utilizatécnicas basadas en afinidad, proporciona incluso mayorganancia. Por otro lado, para tamaños <strong>de</strong> paquete muygran<strong>de</strong>s (>2Mbits), las tres alternativas proporcionanresultados similares aunque la implementación npNIC ofreceresultados ligeramente mejores que las alternativas híbridas.Aunque el IPS se comporta <strong>de</strong> forma similar en ambos casos,las diferencias entre las prestaciones proporcionadas pornpNIC y las interfaces híbridas pue<strong>de</strong>n explicarse por lascaracterísticas específicas <strong>de</strong> la npNIC en la ejecución <strong>de</strong>lcorrespondiente código IPS paralelo.<strong>La</strong> Figura 4 proporciona comparaciones en latencia (Figura4a) y ancho <strong>de</strong> banda (Figura 4b) cuando se inyecta tráficocorrupto a diferentes tasas. Como pue<strong>de</strong> verse, lasimplementaciones npNIC e híbridas claramente mejoran elsistema base, ofreciendo mejores prestaciones para 1Gpbs <strong>de</strong>tráfico corrupto que el sistema base para 700 Mbps <strong>de</strong> tráficocorrupto. <strong>La</strong> Figura 5 compara las latencias obtenidas contráfico corrupto y con tráfico no corrupto en la configuraciónnpNIC. Por otro lado, en la configuración base, cuando haytráfico corrupto y no corrupto, la latencia se <strong>de</strong>gradaseriamente respecto a la latencia que se obtiene cuando sólohay tráfico legítimo (Figura 5b).V. CONCLUSIONES Y TRABAJO FUTUROEn este trabajo se ha utilizado un sistema <strong>de</strong> prevención <strong>de</strong>intrusiones para comparar algunas interfaces <strong>de</strong> reddistribuidas que aprovechan los múltiples procesadoresdisponibles en el nodo, incluyendo un procesador <strong>de</strong>dicadoen la NIC que pue<strong>de</strong> correspon<strong>de</strong>r con un procesador <strong>de</strong> red(una arquitectura heterogénea multinúcleo), así como unesquema <strong>de</strong> afinidad <strong>de</strong> interrupciones para conseguir unadistribución eficiente <strong>de</strong> la carga <strong>de</strong> trabajo.Se han analizado tres configuraciones diferentes,hybrid(1), hybrid(2) y npNIC, que aprovechan el paralelismopresente en el nodo y que tienen en cuenta la localización <strong>de</strong>los datos <strong>de</strong> las correspondientes aplicaciones <strong>de</strong> red. Losresultados proporcionados en la Sección 4 muestran cómo laconfiguración npNIC es más eficiente para paquetespequeños mientras que las interfaces híbridas se comportanmejor con paquetes gran<strong>de</strong>s (>10000 bytes). A<strong>de</strong>más, laconfiguración npNIC proporciona mejores prestaciones bajoaltas cargas <strong>de</strong> trabajo (i.e.: altas tasas <strong>de</strong> tráfico corrupto),ya que es posible aprovechar el paralelismo presente en elprocesador <strong>de</strong> red, evitando que paquetes corruptos <strong>de</strong> grantamaño viajen a través <strong>de</strong> los buses <strong>de</strong>l sistema.Hay diferentes situaciones experimentales que podrían seranalizadas para proporcionar una mejor caracterización <strong>de</strong>lcomportamiento, y <strong>de</strong>sarrollar nuevas mejoras para lasalternativas <strong>de</strong>scritas. Por ejemplo, cuando se inyectanpaquetes corruptos a una tasa baja, el procesamiento <strong>de</strong> losprotocolos <strong>de</strong> red podría realizarse <strong>de</strong> forma concurrente conla ejecución <strong>de</strong>l IPS. A<strong>de</strong>más, nuevas mejoras en el núcleo<strong>de</strong> Linux podrían mejorar nuestras interfaces <strong>de</strong> red híbridas.De esta forma, el planificador podría ser modificado paracontrolar dinámicamente las colas <strong>de</strong> softirq <strong>de</strong> acuerdo conla carga <strong>de</strong> las CPU. Por otro lado, la implementación <strong>de</strong>lIPS podría mejorarse utilizando un sistema <strong>de</strong> predicción <strong>de</strong>patrones corruptos o atacantes, lo cual proporcionaría unprocesamiento especulativo <strong>de</strong> los eventos y, comoconsecuencia, una reacción más rápida <strong>de</strong>l IPS, al aceptar o<strong>de</strong>scartar paquetes, o simplemente para clasificar lospaquetes según una escala <strong>de</strong> sospecha.<strong>JP2011</strong>-641


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011AGRADECIMIENTOSEl presente trabajo ha sido financiado mediante elproyecto DSIPA-BIO , SAF2010-20558 (Ministerio <strong>de</strong>Ciencia e Innovación).REFERENCIAS[1] Catanzaro, B.; et al.:”Ubiquitous parallel computing fromBerkeley, Illinois, and Stanford”. IEEE Micro, pp.41-55.March/April, 2010.[2] Kumar, R.; et al.:”Heterogeneous Chip Multiprocessors”. IEEEComputer, vol. 38, pp.32-38. November, 2005[3] Hill, M.; Marty, M.:”Amdahl’s law in the Multicore Era”. IEEEComputer, Vol.41, pp.33-38. July, 2008.[4] Willmann, P.; Shafer, J.; Carr, D.; Menon, A.; Rixner, S.; Cox,A.L.; Zwaenepoel, W.:”Concurrent Direct Network Access forVirtual Machine Monitors”. Proc. Intl. Symposium on High-Performance Computer Architecture, February, 2007.[5] Rixner, S.:”Network virtualization: breaking the performancebarrier”. ACM Queue, pp.36-52. January/February, 2008.[6] Balaji, P.; Feng, W.; Panda, D.K.:”Bridging the Ethernet-Ethernotperformance gap”. IEEE Micro, pp.24-40. May-June, 2006.[7] Shivam, P.: Chase, J.S.:”On the elusive benefits of protocoloffload”. SIGCOMM’03 Workshop on Network-I/O convergence:Experience, Lesons, Implications (NICELI). August, 2003.[8] Regnier, G. et al.:”TCP onloading for data center servers”. IEEEComputer, pp.48-58. November2004.[9] Wun, B.; Crowley, P.:”Network I/O Acceleration inHeterogeneous Multicore Processors”. In Proceedings of the 14thAnnual Symposium on High Performance Interconnects (HotInterconnects). August, 2006.[10] Ortiz, A.; Ortega, J.; Díaz, A. F.; Prieto, A.:”A newoffloa<strong>de</strong>d/onloa<strong>de</strong>d network interface for high performancecommunication”. 17 th Euromicro Intenational Conference onParalell, Distributed and Network-based Processing. PDP 2009,February 2008.[11] Shalev, L.; Marhervaks, V.; Machulsky, Z.; Biran, G.; Satran, J.;Ben-Yehuda, M.; Shimony, I.: “Loosely Coupled TCPAcceleration Architecture”. Proceedings of the 14 th IEEESymposium on High-Performance Interconnects (HOTI). 2006.[12] Nahum, E.M.; Yates, D.J. ; Kurose, J.F.; Towsley,D.:”Performance issues in parallelized network protocols”. Proc.Of the Operating Systems Design and Implementation, pp. 125-137, 1994.[13] Kim, H.; Pai, V.S.; Rixner, S.: ”Exploiting task-level concurrencyin a programmable network interface”. Proc. of the ACMPPoPP’03, 2003.[14] Shivam, P.; Wyckoff, P.; Panda, D.:”Can user-level protocols takeadvantage of Multi-CPU NICs?”. Proc. Intl. Parallel andDistributed Processing Symp. (IPDPS’02), pp.64-69. April, 2002.[15] Narayanaswamy, G.; Balaji, P.; Feng, W.:”An Analysis of 10-Gigabit Ethernet Protocol Staks in Multicore Environments”. 15 thIEEE Symp. On High-Performance Interconects (HOTI’07),pp.109-116, 2007.[16] Foong, A.; Fung, J.; Newell, D.: “An in-<strong>de</strong>pth analysis of theimpact of processor affinity on network performance”.Proceedings of the 12 th IEEE International Conference onNetworks. 2004.[17] Salehi, J.; Kurose, J.; Towsley, D.: “The efectiveness of Affinitybasedscheduling in multiprocessor network protocol processing”.IEEE/ACM transactions on networking. Vol 4, nº4. pp. 516-530.1996.[18] Jan, H.; Jin, H.-W.: “MiAMI: Multi-Core Aware ProcessorAffinity for TCP/IP over Multiple Network Interfaces”. 17 th IEEESymposium on High Performance Interconnects. HOTI 2009.[19] Bruijn, W. <strong>de</strong>; Bos, H.:”Mo<strong>de</strong>l-T: “Rethinking the OS for terabitsspeeds”. Workshop on High-Speed Networks (HSN2008),INFOCOM’2008, 2008.[20] Mudigonda, J.; Vin, H.M.; Yavatkar, R.:”Overcoming thememory wall in packet processing: hammers or lad<strong>de</strong>rs?”. Proc. ofthe ACM ANCS’05, 2005[21] Irqbalance daemon. GNU General Public License (GPL) version2. http://irqbalance.org/[22] Johnson, E.J.; Kunze, A.R.: ”IXP2400/2800 Programming. TheComplete Microengine Coding Gui<strong>de</strong>”. Intel Press, 2003.[23] Netronome: “NFE-i800 Network Acceleration Card”, 2006.www.netronome.com/pages/acceleration-cards[24] Love, R.: “Linux kernel <strong>de</strong>velopment”. Novell Press. Secon<strong>de</strong>dition. 2005.[25] Netfilter framework. www.netfilter.org[26] Benvenuti, C.: “Un<strong>de</strong>rstanding linux network internals”. O’Reillymedia. First edition. 2006.[27] Binkert, N.; et al.:”Integrated network interfaces for highbandwidthTCP/IP”. Proc. Of the 2006 ASPLOS Conference.December, 2006.<strong>JP2011</strong>-642


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Estimación <strong>de</strong>l efecto <strong>de</strong> los fallos cache en elrendimiento <strong>de</strong> aplicaciones paralelasD. R. Martínez 1 , V. Blanco 2 , J. C. Cabaleiro 1 , T. F. Pena 1 y F. F. Rivera 1Resumen— Este artículo presenta una metodologíapara caracterizar la influencia <strong>de</strong> los fallos cache enel rendimiento <strong>de</strong> aplicaciones paralelas, que está basadaen los mo<strong>de</strong>los analíticos proporcionados por elentono TIA, obtenidos mediante técnicas <strong>de</strong> selección<strong>de</strong> mo<strong>de</strong>los. En particular, esta metodología proporcionauna estimación <strong>de</strong> la influencia <strong>de</strong> los fallos cacheen el rendimiento <strong>de</strong> una aplicación, a partir <strong>de</strong> mo<strong>de</strong>losanalíticos <strong>de</strong>l tiempo <strong>de</strong> ejecución y <strong>de</strong>l número<strong>de</strong> fallos cache. Como caso <strong>de</strong> estudio, esta metodologíaha sido aplicada en dos versiones <strong>de</strong>l productoparalelo <strong>de</strong> matrices.Palabras clave— Rendimiento, selección <strong>de</strong> mo<strong>de</strong>los,fallos cache, aplicaciones paralelas.LOS fallos cache tienen una influencia significativaen el rendimiento <strong>de</strong> las aplicaciones. Sinembargo, es difícil <strong>de</strong>terminar su influencia real enel rendimiento <strong>de</strong> una aplicación concreta, porquesu efecto se solapa con otros elementos. El objetivo<strong>de</strong> este trabajo es la presentación <strong>de</strong> una metodologíaautomática para caracterizar, utilizando mecanismos<strong>de</strong> selección <strong>de</strong> mo<strong>de</strong>los, la influencia <strong>de</strong> losfallos cache en el rendimiento <strong>de</strong> aplicaciones paralelas.<strong>La</strong>s diferentes aproximaciones existentes paramo<strong>de</strong>lar los fallos cache se basan en mo<strong>de</strong>los analíticos[1] o en simulaciones [2]. Sin embargo, estas aproximacionesmo<strong>de</strong>lan el número <strong>de</strong> fallos cache <strong>de</strong>s<strong>de</strong>un punto <strong>de</strong> vista cuantitativo, pero no proporcionaninformación <strong>de</strong> la influencia real <strong>de</strong> los fallos cacheen el rendimiento <strong>de</strong> las aplicaciones.<strong>La</strong> estructura <strong>de</strong> este artículo se <strong>de</strong>scribe a continuación.En la sección I se presentan las bases teóricasen las que se fundamenta el mecanismo <strong>de</strong> selección<strong>de</strong> mo<strong>de</strong>los utilizado. El entorno <strong>de</strong> análisis TIAy el mecanismo <strong>de</strong> selección <strong>de</strong> mo<strong>de</strong>los, basado enel criterio <strong>de</strong> información <strong>de</strong> Akaike, se <strong>de</strong>scriben enla sección II. <strong>La</strong> metodología para la caracterización<strong>de</strong> la influencia <strong>de</strong> los fallos cache en el rendimiento<strong>de</strong> una aplicación se <strong>de</strong>scribe en la sección III.En la sección IV se muestra un caso <strong>de</strong> estudio y seanalizan los resultados. Finalmente, se presentan lasprincipales conclusiones <strong>de</strong> este trabajo.I. Selección <strong>de</strong> mo<strong>de</strong>los con AICEl criterio <strong>de</strong> información <strong>de</strong> Akaike (An InformationCriterion, AIC) [3] proporciona un método simpley objetivo para <strong>de</strong>terminar el mo<strong>de</strong>lo que mejorcaracteriza los datos experimentales. Este criterio se<strong>de</strong>fine como:AIC = −2 log(L(̂θ)) + 2K (1)1 Dpto. <strong>de</strong> Electrónica y Computación, Univ. Santiago<strong>de</strong> Compostela, e-mail: {diego.rodriguez, jc.cabaleiro,tf.pena, ff.rivera}@usc.es2 Dpto. <strong>de</strong> Estadística e Investigación Operativa, Univ. <strong>La</strong><strong>La</strong>guna, e-mail: Vicente.Blanco@ull.esdon<strong>de</strong> log(L(̂θ)) es el logaritmo <strong>de</strong> la máxima verosimilitud,que permite <strong>de</strong>terminar los valores <strong>de</strong> losparámetros libres <strong>de</strong> un mo<strong>de</strong>lo estadístico, y K es elnúmero <strong>de</strong> parámetros libres <strong>de</strong>l mo<strong>de</strong>lo. Aunque nojustifica las bases teóricas en las que se fundamenta,es posible hacer una interpretación heurística <strong>de</strong> (1).Esta interpretación consi<strong>de</strong>ra el primer término <strong>de</strong>esta ecuación como una medida <strong>de</strong> la calidad con laque el mo<strong>de</strong>lo se ajusta a los datos experimentales,mientras que el segundo sería una penalización quese incrementa con la complejidad <strong>de</strong>l mo<strong>de</strong>lo. Por lotanto, este criterio ofrece un valor objetivo que, <strong>de</strong>manera relativa, cuantifica simultáneamente la precisióny sencillez <strong>de</strong>l mo<strong>de</strong>lo.El criterio <strong>de</strong> información <strong>de</strong> Akaike formula elproblema <strong>de</strong> selección <strong>de</strong> mo<strong>de</strong>los como una búsqueda<strong>de</strong>l mo<strong>de</strong>lo que presente un menor valor AIC, entreun conjunto <strong>de</strong> mo<strong>de</strong>los candidatos. Los pesos<strong>de</strong> Akaike (ω AIC ) proporcionan un mecanismo paracuantificar la calidad <strong>de</strong> la selección <strong>de</strong> mo<strong>de</strong>los medianteAIC. Estos pesos se basan en las diferenciasAIC (∆ AIC ), que permiten or<strong>de</strong>nar los mo<strong>de</strong>los segúnsu calidad. <strong>La</strong> diferencia AIC <strong>de</strong> un mo<strong>de</strong>lo i se <strong>de</strong>finecomo:∆ AICi = AIC i − AIC min (2)don<strong>de</strong> AIC min es el menor valor AIC <strong>de</strong>ntro <strong>de</strong>l conjunto<strong>de</strong> mo<strong>de</strong>los candidatos. <strong>La</strong>s diferencias or<strong>de</strong>nanlos mo<strong>de</strong>los según su distancia con el mejor mo<strong>de</strong>lo,pero no aportan información acerca <strong>de</strong> la calidad<strong>de</strong>l mejor mo<strong>de</strong>lo. Los pesos <strong>de</strong> Akaike proporcionanuna estimación <strong>de</strong> la calidad <strong>de</strong> un mo<strong>de</strong>lo. En particular,dado un conjunto <strong>de</strong> mo<strong>de</strong>los candidatos <strong>de</strong>tamaño R, el peso <strong>de</strong> Akaike <strong>de</strong>l mo<strong>de</strong>lo i es:ω AICi )i = exp (− 1 2 ∆AICR∑exp (− 1 2 ∆AIC r )r=1(3)Este valor pue<strong>de</strong> ser interpretado como la probabilidad<strong>de</strong> que el mo<strong>de</strong>lo i sea realmente el mejor mo<strong>de</strong>loen el conjunto escogido, suponiendo que uno <strong>de</strong> losmo<strong>de</strong>los consi<strong>de</strong>rados es el mejor mo<strong>de</strong>lo.II. Entorno <strong>de</strong> AnálisisEl entorno <strong>de</strong> análisis TIA (Tools for Instrumentacionand Analysis) [4] consta <strong>de</strong> dos fases. En laprimera fase, <strong>de</strong>nominada fase <strong>de</strong> instrumentación,el usuario instrumenta el código fuente <strong>de</strong> una aplicacióny la información acerca <strong>de</strong>l rendimiento, obtenidadurante la ejecución <strong>de</strong> la aplicación, es almacenadaen ficheros XML. <strong>La</strong> segunda fase, <strong>de</strong>nominadafase <strong>de</strong> análisis, utiliza la información proce<strong>de</strong>nte<strong>de</strong> múltiples ejecuciones instrumentadas para<strong>JP2011</strong>-643


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011generar un mo<strong>de</strong>lo analítico <strong>de</strong>l rendimiento <strong>de</strong> laaplicación bajo estudio mediante análisis estadísticosexhaustivos [5].El proceso <strong>de</strong> obtención <strong>de</strong> mo<strong>de</strong>los estadísticos<strong>de</strong> aplicaciones paralelas implementado en la fase <strong>de</strong>análisis <strong>de</strong>l entorno TIA está basado en la selección<strong>de</strong> mo<strong>de</strong>los mediante AIC [6]. Este proceso realiza unanálisis AIC sobre un conjunto finito <strong>de</strong> mo<strong>de</strong>los candidatos,generados a partir <strong>de</strong> información suministradapor el usuario. El resultado final es el mo<strong>de</strong>loque presente el AIC más bajo, así como informaciónacerca <strong>de</strong>l análisis que permita al usuario hacer unavaloración <strong>de</strong>l resultado obtenido.El conjunto <strong>de</strong> mo<strong>de</strong>los candidatos (MC) es el elementofundamental para garantizar la calidad <strong>de</strong>lproceso <strong>de</strong> selección AIC. <strong>La</strong> responsabilidad <strong>de</strong> estatarea recae inicialmente sobre el usuario, que <strong>de</strong>beproporcionar un conjunto <strong>de</strong> mo<strong>de</strong>los a<strong>de</strong>cuado.En particular, se ha diseñado un mecanismo <strong>de</strong> <strong>de</strong>scripciónpara representar un conjunto <strong>de</strong> mo<strong>de</strong>losmediante una estructura <strong>de</strong> dos niveles. Esta <strong>de</strong>scripción<strong>de</strong>fine un mo<strong>de</strong>lo global y consi<strong>de</strong>ra comoelementos <strong>de</strong>l conjunto <strong>de</strong> mo<strong>de</strong>los todos los posiblesmo<strong>de</strong>los anidados <strong>de</strong>rivados <strong>de</strong>l mo<strong>de</strong>lo global.Los elementos constitutivos <strong>de</strong>l nivel más interno <strong>de</strong>lanidamiento son las diferentes variables (métricas oparámetros) que a priori tienen influencia en el comportamiento<strong>de</strong>l experimento. El nivel más externo<strong>de</strong>l anidamiento está formado por conjuntos disjuntos<strong>de</strong> estas variables.Este agrupamiento <strong>de</strong> las variables permite <strong>de</strong>finir,<strong>de</strong> manera implícita, una nueva lista <strong>de</strong> variables<strong>de</strong>rivadas formada por todos los posibles productos(<strong>de</strong>nominados términos) <strong>de</strong> variables pertenecientesa diferentes conjuntos. En esta lista también se consi<strong>de</strong>raque cada grupo contiene implícitamente el elementoi<strong>de</strong>ntidad. El mo<strong>de</strong>lo global que <strong>de</strong>fine el conjunto<strong>de</strong> mo<strong>de</strong>los está formado por la suma <strong>de</strong> todoslos términos, con sus correspondientes coeficientes.Para una <strong>de</strong>scripción que genere N términos, el mo<strong>de</strong>loglobal tendrá la siguiente estructura, que no representamás que la combinación lineal <strong>de</strong> todos lostérminos consi<strong>de</strong>rados:M global = ∑ iC i T i ,i = 1, 2, . . . , Ndon<strong>de</strong> T i representa el término i-ésimo y C i su correspondientecoeficiente <strong>de</strong> pon<strong>de</strong>ración. En cualquiercaso, una vez <strong>de</strong>finidos los diferentes conjuntos<strong>de</strong> variables primarias, la construcción <strong>de</strong>l mo<strong>de</strong>loglobal, incluyendo la generación <strong>de</strong> términos, esautomática. En este proceso, el usuario únicamentenecesita <strong>de</strong>terminar los conjuntos <strong>de</strong> variables primarias.En un entorno R, esta estructura <strong>de</strong> conjuntosse pue<strong>de</strong> implementar mediante una lista <strong>de</strong> listas,que <strong>de</strong>nominamos Lista Inicial (LI), en la que cadalista interior contiene las variables asociadas a cadaconjunto. Para complementar este mecanismo, seha consi<strong>de</strong>rado una extensión que permite al usuariocontemplar otros términos aparte <strong>de</strong> los generadosautomáticamente a través <strong>de</strong> los grupos <strong>de</strong> variablesprimarias.Una vez <strong>de</strong>terminado el conjunto <strong>de</strong> mo<strong>de</strong>los candidatos,se realiza la selección <strong>de</strong> mo<strong>de</strong>los con AIC.En primer lugar, se ajustan todos los mo<strong>de</strong>los a losdatos experimentales y se obtiene, para cada mo<strong>de</strong>lo,una aproximación <strong>de</strong> segundo or<strong>de</strong>n <strong>de</strong> AIC [7]. Elmo<strong>de</strong>lo que presente un menor valor <strong>de</strong> AIC se propondrácomo mejor mo<strong>de</strong>lo. A partir <strong>de</strong> los valoresAIC <strong>de</strong> todos los mo<strong>de</strong>los candidato, se calculan lospesos <strong>de</strong> Akaike (ω AIC ), pero también se proporcionala importancia relativa <strong>de</strong> cada uno <strong>de</strong> los términosconsi<strong>de</strong>rados (ω+ AIC ). <strong>La</strong> importancia relativa <strong>de</strong> unavariable predictora j será la suma <strong>de</strong> los pesos <strong>de</strong>Akaike <strong>de</strong> todos los mo<strong>de</strong>los que contengan j comovariable predictora. Con esta información, el usuariotendrá la capacidad <strong>de</strong> valorar si el mo<strong>de</strong>lo propuestoes a<strong>de</strong>cuado para caracterizar el comportamiento<strong>de</strong> la aplicación bajo estudio.III. Estimación <strong>de</strong> la influencia <strong>de</strong> losfallos cacheAunque la métrica más habitual, en términos <strong>de</strong>análisis <strong>de</strong>l rendimiento, es el tiempo <strong>de</strong> ejecución,el entorno TIA proporciona al usuario la capacidad<strong>de</strong> obtener mo<strong>de</strong>los estadísticos <strong>de</strong> rendimiento <strong>de</strong>cualquier métrica disponible a través <strong>de</strong> los drivers<strong>de</strong> TIA. En concreto, el driver PAPI proporciona elmecanismo apropiado para medir diferentes aspectos<strong>de</strong>l rendimiento <strong>de</strong> la memoria cache en los microprocesadoresactuales como, por ejemplo, el número<strong>de</strong> fallos cache <strong>de</strong> lectura/escritura en los diferentesniveles [8].Los fallos cache no se pue<strong>de</strong>n utilizar para pre<strong>de</strong>cirel tiempo <strong>de</strong> ejecución, ya que esta métrica es<strong>de</strong>sconocida antes <strong>de</strong> ejecutar la aplicación. Sin embargo,utilizando el entorno TIA, es posible obtenerun mo<strong>de</strong>lo <strong>de</strong> los fallos cache que pueda utilizarse entareas <strong>de</strong> predicción. Por otro lado, si se i<strong>de</strong>ntifica lacontribución <strong>de</strong> los fallos cache al mo<strong>de</strong>lo <strong>de</strong>l tiempo<strong>de</strong> ejecución, se pue<strong>de</strong> <strong>de</strong>terminar la influencia<strong>de</strong> estos en el rendimiento <strong>de</strong> la aplicación. Utilizandoel entorno TIA, se ha diseñado una metodologíapara mo<strong>de</strong>lar la influencia <strong>de</strong> los fallos cache en eltiempo <strong>de</strong> ejecución <strong>de</strong> una aplicación paralela. Encualquier caso, esta metodología no está restringidaúnicamente a la caracterización <strong>de</strong> los fallos cache,sino que podría aplicarse a cualquier otro parámetroarquitectural cuyo valor no se conozca antes <strong>de</strong> laejecución <strong>de</strong> una aplicación.En primer lugar, el tiempo <strong>de</strong> ejecución y el número<strong>de</strong> fallos cache son medidos a través <strong>de</strong> los drivers<strong>de</strong> TIA, así como otros parámetros <strong>de</strong> ejecución <strong>de</strong> laaplicación paralela como, por ejemplo, el número <strong>de</strong>procesos o el tamaño <strong>de</strong> problema. Una vez conocidoslos valores experimentales <strong>de</strong> las diferentes métricasy parámetros <strong>de</strong> rendimiento, se obtienen los mo<strong>de</strong>losestadísticos <strong>de</strong>l tiempo <strong>de</strong> ejecución y <strong>de</strong> losfallos cache mediante el método <strong>de</strong> selección <strong>de</strong> mo<strong>de</strong>losimplementado en la fase <strong>de</strong> análisis <strong>de</strong>l entornoTIA. Por un lado, el mo<strong>de</strong>lo <strong>de</strong> los fallos cache se obtienecomo una función <strong>de</strong> los diferentes parámetros<strong>de</strong> ejecución medidos. Por otro lado, se construye el<strong>JP2011</strong>-644


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011mo<strong>de</strong>lo <strong>de</strong>l tiempo <strong>de</strong> ejecución como una función <strong>de</strong>los parámetros <strong>de</strong> ejecución y <strong>de</strong> los fallos cache. Es<strong>de</strong>cir, los fallos cache se consi<strong>de</strong>ran como un nuevoparámetro <strong>de</strong> ejecución in<strong>de</strong>pendiente. <strong>La</strong> variableque caracteriza los fallos cache en la expresión <strong>de</strong>lmo<strong>de</strong>lo <strong>de</strong>l tiempo <strong>de</strong> ejecución podrá ser sustituidapor el correspondiente mo<strong>de</strong>lo. Por lo tanto, la expresiónfinal <strong>de</strong>l tiempo <strong>de</strong> ejecución <strong>de</strong> la aplicaciónsólo <strong>de</strong>pen<strong>de</strong>rá <strong>de</strong> los parámetros <strong>de</strong> ejecución. Porlo tanto, estas expresiones pue<strong>de</strong>n evaluarse antes <strong>de</strong>ejecutar la aplicación, proporcionando un mecanismoa<strong>de</strong>cuado para la predicción <strong>de</strong>l rendimiento <strong>de</strong>la aplicación.IV. Caso <strong>de</strong> estudio<strong>La</strong> estimación <strong>de</strong> la influencia <strong>de</strong> los fallos cache enla ejecución <strong>de</strong> aplicaciones paralelas ha sido evaluadaen dos versiones diferentes <strong>de</strong>l producto paralelo<strong>de</strong> matrices. En particular, estas dos versiones utilizannúmeros en punto flotante <strong>de</strong> simple precisióny las comunicaciones entre los diferentes procesos serealiza a través <strong>de</strong> funciones MPI. <strong>La</strong> figura 1 muestrael pseudo-código <strong>de</strong> estas dos versiones, don<strong>de</strong> eltamaño <strong>de</strong> las matrices es N × N, siendo P el número<strong>de</strong> procesos. En ambos casos, se ha supuesto quela distribución <strong>de</strong> las matrices X e Y se ha realizadoen un paso previo y que el reparto <strong>de</strong> la matriz X hasido realizado por bloques, <strong>de</strong> forma equitativa, entrelos diferentes procesos implicados. Por un lado, elcaso A, representado en la figura 1(a), muestra unasituación en la que todo el trabajo computacional serealiza intensivamente antes <strong>de</strong> iniciar el envío <strong>de</strong> losresultados parciales, mediante una única comunicacióncolectiva. Por otro lado, el caso B, representadoen la figura 1(b), muestra una situación en la que elnúmero <strong>de</strong> comunicaciones es muy elevado, ya quecada fila <strong>de</strong> la matriz Z es enviada al proceso raízinmediatamente <strong>de</strong>spués <strong>de</strong> calcularse en el procesocorrespondiente. Por lo tanto, las diferencias entre losdos casos están en el número y tamaño <strong>de</strong> las funcionesglobales <strong>de</strong> comunicación (MPI_Gather), queenvían los resultados parciales <strong>de</strong> la matriz resultadoal proceso raíz. El caso A realiza una única comunicaciónglobal en la que envía la matriz completa,mientras que en el caso B, se realizan N/P comunicacionesglobales y en cada una <strong>de</strong> ellas se envían P filas<strong>de</strong> la matriz resultado. Se han incluido las funcionesMPI_Barrier, antes y <strong>de</strong>spués <strong>de</strong> cada función <strong>de</strong> comunicación,para reducir los posibles solapamientosentre la comunicación y la computación.Ambos códigos han sido instrumentados utilizandolos drivers PAPI, MPI y NWS <strong>de</strong>l entorno TIA.El driver PAPI ha sido utilizado para obtener losfallos cache registrados durante las distintas ejecuciones.Asimismo, para obtener una mayor precisión,el tiempo <strong>de</strong> ejecución ha sido medido utilizando elobservable PAPI_REAL_USEC <strong>de</strong>l driver PAPI. El driverMPI es necesario para la correcta gestión <strong>de</strong> losobservables obtenidos con PAPI. El driver NWS seha utilizado para obtener el estado <strong>de</strong> la red <strong>de</strong> comunicación,proporcionando el ancho <strong>de</strong> banda y laFOR i in 1:(N/P) /* Parallel loop */FOR j in 1:NZ i,j =0FOR k in 1:NZ i,j +=X i,k *Y k,jEND FOREND FOREND FORMPI BarrierMPI Gather(Z)MPI Barriera) Caso A, cómputo intensivoFOR i in 1:(N/P) /* Parallel loop */FOR j in 1:NZ i,j =0FOR k in 1:NZ i,j +=X i,k *Y k,jEND FOREND FORMPI BarrierMPI Gather(Z i,∗ )MPI BarrierEND FORb) Caso B, comunicación intensivaFig. 1. Pseudo-códigos <strong>de</strong>l producto paralelo <strong>de</strong> matricesTABLA IValores numéricos <strong>de</strong> los parámetros experimentalesParámetroValoresNúmero <strong>de</strong> procesadores 2, 3, 4, 5, y 6Dimensión <strong>de</strong> la matrices 300, 400 y 500Velocidad <strong>de</strong> la red 10, 100 y 1000 Mbpslatencia efectiva <strong>de</strong> la red justo antes <strong>de</strong> la ejecución<strong>de</strong> los códigos.Los códigos instrumentados han sido ejecutados enun cluster <strong>de</strong> seis nodos conectados a través <strong>de</strong> unared Gigabit Ethernet. El controlador <strong>de</strong> la interfaz<strong>de</strong> red <strong>de</strong> los nodos permite al usuario modificar lavelocidad <strong>de</strong> la red, por lo que se han consi<strong>de</strong>radotres situaciones <strong>de</strong> red diferentes, utilizando diferentesparámetros en la configuración <strong>de</strong> este controlador.Los nodos <strong>de</strong>l cluster están equipados con procesadoresIntel R○ Pentium R○ 4. Este procesador dispone<strong>de</strong> 2 niveles <strong>de</strong> cache: L1 <strong>de</strong> 32 KB (16 KB <strong>de</strong>datos) y L2 <strong>de</strong> 1 MB. <strong>La</strong> latencia asociada a un falloen el nivel L2 es, aproximadamente, un or<strong>de</strong>n <strong>de</strong>magnitud mayor que la latencia <strong>de</strong>l nivel L1 [9], porlo que sólo consi<strong>de</strong>raremos los fallos <strong>de</strong> nivel L2 eneste estudio. Cada aplicación ha sido ejecutada contres tamaños <strong>de</strong> matriz diferentes para cada configuración<strong>de</strong> velocidad <strong>de</strong> la red <strong>de</strong> interconexión ynúmero <strong>de</strong> procesos. <strong>La</strong> tabla I muestra, para cadaparámetro experimental, los valores utilizados en esteestudio. Para cada configuración experimental sehan realizado cuatro ejecuciones in<strong>de</strong>pendientes <strong>de</strong>la aplicación instrumentada.A. Mo<strong>de</strong>lo <strong>de</strong>l número <strong>de</strong> fallos cache L2Teniendo en cuenta que la principal causa <strong>de</strong> falloscache L2 es el volumen <strong>de</strong> operaciones MAC (multiplicary acumular), los límites <strong>de</strong> los diferentes lazos<strong>de</strong>berían ser los factores fundamentales a tener en<strong>JP2011</strong>-645


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011cuenta para la construcción <strong>de</strong> la lista inicial (LI) <strong>de</strong>lmétodo <strong>de</strong> selección <strong>de</strong> mo<strong>de</strong>los <strong>de</strong>l entorno TIA. Comola estructura <strong>de</strong> lazos es similar en los dos casos,la lista inicial propuesta para ambos casos es:{ } N {N 2 , N }PEl primer elemento <strong>de</strong> la lista, { N P}, se correspon<strong>de</strong>con el tamaño <strong>de</strong> lazo más externo. El segundoelemento, {N 2 , N}, representa el número <strong>de</strong> instruccionesMAC que se ejecutan en cada instancia <strong>de</strong> losdos lazos internos. El mo<strong>de</strong>lo <strong>de</strong>l número <strong>de</strong> falloscache <strong>de</strong> nivel L2, que <strong>de</strong>nominamos Φ, obtenido automáticamentemediante la selección <strong>de</strong> mo<strong>de</strong>los implementadaen TIA, se muestra en la tabla II paralos dos casos consi<strong>de</strong>rados.Los elevados pesos <strong>de</strong> Akaike indican que, <strong>de</strong>ntro<strong>de</strong>l conjunto <strong>de</strong> mo<strong>de</strong>los candidatos seleccionado, estosmo<strong>de</strong>los son una buena aproximación <strong>de</strong>l comportamientoreal <strong>de</strong> los fallos cache <strong>de</strong> nivel L2. Encualquier caso, existe una notable similitud entre lasexpresiones <strong>de</strong> los dos mo<strong>de</strong>los ya que los coeficientes<strong>de</strong> los términos dominantes en las expresiones ( N 3N 2Py N PP ,) son similares. Este hecho indica <strong>de</strong> que lasuposición inicial, al respecto <strong>de</strong> que el número <strong>de</strong>fallos cache <strong>de</strong> nivel L2 es in<strong>de</strong>pendiente <strong>de</strong> las comunicaciones,es correcta.B. Mo<strong>de</strong>lo <strong>de</strong>l tiempo <strong>de</strong> ejecuciónPara construir la lista inicial (LI) <strong>de</strong>l proceso <strong>de</strong> selección,en ambos casos, se han analizado <strong>de</strong> manerain<strong>de</strong>pendiente las secciones <strong>de</strong> cómputo y comunicación,porque el solape entre ambas es prácticamentenulo por el uso <strong>de</strong> las funciones MPI_Barrier.Por un lado, al análisis <strong>de</strong> los factores <strong>de</strong> cómputoen ambos casos es similar, ya que ambas aplicacionesejecutan el mismo número ( N 3P) <strong>de</strong> operacionesMAC. A<strong>de</strong>más, po<strong>de</strong>mos consi<strong>de</strong>rar que el coste <strong>de</strong>la gestión <strong>de</strong> los lazos es <strong>de</strong>spreciable. <strong>La</strong> influencia<strong>de</strong> los fallos cache también <strong>de</strong>ber ser tenida en cuentaen el tiempo <strong>de</strong> ejecución en esta sección <strong>de</strong> cómputo,ya que, <strong>de</strong> acuerdo con la suposición consi<strong>de</strong>radaen la obtención <strong>de</strong> los mo<strong>de</strong>los Φ, los fallos cacheestán correlacionados con la ejecución <strong>de</strong> las instruccionesMAC. Se supondrá que la influencia <strong>de</strong> losfallos cache <strong>de</strong> nivel L2 es directamente proporcionalal número total <strong>de</strong> fallos cache, que es un dato experimentalproporcionado por el driver PAPI (variablePAPI_L2_TCM). En este análisis se utilizará el símboloφ para referirse al número total <strong>de</strong> fallos cache <strong>de</strong>nivel L2 medidos a través <strong>de</strong> este driver.Por otro lado, la contribución <strong>de</strong> las comunicacionesal rendimiento <strong>de</strong> los distintos códigos merece unanálisis <strong>de</strong>tallado, porque las principales diferenciasentre ambos códigos resi<strong>de</strong> precisamente en el númeroy tamaño <strong>de</strong> las comunicaciones. En concreto, losparámetros relacionados con el número <strong>de</strong> llamadas alas funciones <strong>de</strong> comunicación y los parámetros relacionadoscon el coste <strong>de</strong> cada comunicación han sidoconsi<strong>de</strong>rados <strong>de</strong> manera in<strong>de</strong>pendiente. El númerototal <strong>de</strong> comunicaciones colectivas (MPI_Gather) esigual al producto <strong>de</strong> los límites <strong>de</strong> los lazos externosa la propia función. En el caso A no hay ningúnlazo exterior, mientras que en el caso B la funcióncolectiva está <strong>de</strong>ntro <strong>de</strong> un lazo cuyo límite es N P .El análisis <strong>de</strong>l coste asociado a cada funciónMPI_Gather no es inmediato, ya que el rendimientoreal <strong>de</strong>pen<strong>de</strong> <strong>de</strong> las características <strong>de</strong> la red <strong>de</strong> interconexióny <strong>de</strong>l algoritmo <strong>de</strong> comunicación, es <strong>de</strong>cir,<strong>de</strong> la topología <strong>de</strong> las comunicaciones punto a puntoimplementadas internamente en la función colectiva.El rendimiento <strong>de</strong> las comunicaciones punto a puntopue<strong>de</strong> mo<strong>de</strong>larse mediante los parámetros <strong>de</strong> latencia(α) y ancho <strong>de</strong> banda (1/β), <strong>de</strong> acuerdo con elmo<strong>de</strong>lo <strong>de</strong> Hockney [10]. Sin embargo, el algoritmo<strong>de</strong> comunicación colectiva es, a priori, <strong>de</strong>sconocido eincluso podría cambiar dinámicamente según el tamaño<strong>de</strong> mensaje. En este caso, para cubrir varias posibilida<strong>de</strong>s,se consi<strong>de</strong>ran los caminos críticos <strong>de</strong> losalgoritmos lineal y binomial (⌈log 2 P ⌉ y P , respectivamente),que <strong>de</strong>terminan el tiempo teórico máximo<strong>de</strong> la función <strong>de</strong> comunicación. <strong>La</strong> conexión entre elmo<strong>de</strong>lo <strong>de</strong> Hockney y los distintos algoritmos se realizasiguiendo la misma aproximación que Pjěsivac-Grbovíc et ál. [11]: la latencia multiplica el caminocrítico <strong>de</strong>l algoritmo y el ancho <strong>de</strong> banda divi<strong>de</strong> eltamaño <strong>de</strong> mensaje global <strong>de</strong> la función colectiva,esto es, el tamaño <strong>de</strong> la matriz Z. El tamaño global<strong>de</strong> cada comunicación colectiva es N 2 en el caso A yN en el caso B. A<strong>de</strong>más, tanto los caminos críticos<strong>de</strong> los dos algoritmos consi<strong>de</strong>rados como el tamañoglobal <strong>de</strong> la función colectiva han sido consi<strong>de</strong>radoscomo variables individuales y, <strong>de</strong> este modo, se tieneen cuenta la posibilidad <strong>de</strong> que los parámetros <strong>de</strong>lmo<strong>de</strong>lo <strong>de</strong> Hockney no influyan significativamente enel rendimiento <strong>de</strong> los códigos.Teniendo en cuenta las consi<strong>de</strong>raciones previas, lalista inicial utilizada en el caso A es:{N 2 , N 2} { } N3 ∗β , ⌈log 2 P ⌉, α⌈log 2 P ⌉, P, αPP , φmientras que para el caso B sería:{ } { NN, N } { } N3 ∗P β , ⌈log 2 P ⌉, α⌈log 2 P ⌉, P, αPP , φEl asterisco{que aparece } en el último elemento <strong>de</strong>Nestas listas,3P , φ en ambos casos, indica que estasvariables <strong>de</strong>ben ser consi<strong>de</strong>readas directamente comotérminos en el proceso <strong>de</strong> selección <strong>de</strong> mo<strong>de</strong>los.<strong>La</strong> tabla III muestra los mo<strong>de</strong>los seleccionados entreel conjunto <strong>de</strong> mo<strong>de</strong>los candidatos correspondiente,obtenidos automáticamente mediante el método<strong>de</strong> selección <strong>de</strong> mo<strong>de</strong>los <strong>de</strong> TIA.Los términos asociados al número <strong>de</strong> operacionesMAC y al número <strong>de</strong> fallos cache son muy similaresen ambos casos, aunque ligeramente menores enT B respecto <strong>de</strong> T A . Esta pequeña diferencia es consecuenciadirecta <strong>de</strong> la menor influencia <strong>de</strong> estos factoresen el tiempo <strong>de</strong> ejecución <strong>de</strong>l caso B. El coste <strong>de</strong>las comunicaciones colectivas es mayor que el costeasociado al cálculo <strong>de</strong> una fila <strong>de</strong> la matriz resulta-<strong>JP2011</strong>-646


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLA IIMo<strong>de</strong>lo <strong>de</strong>l número <strong>de</strong> fallos cache <strong>de</strong> nivel L2, obtenido automáticamente con el entorno TIACaso Mo<strong>de</strong>lo Error ω CMA Φ A = 0,144 N 3B Φ B = 0,154 N 3P −98 N 2P −0,39N 2 +16400 N P +130N 37.4 0.999P −102 N 2P +0,9N 2 +17000 N P −230N 26.7 0.981TABLA IIIMo<strong>de</strong>los <strong>de</strong>l tiempo <strong>de</strong> ejecución, obtenidos automáticamente mediante con el entorno TIACaso Mo<strong>de</strong>lo Error ω CMA T A (µs) = 18,7 N 2β + 0,18N 2 − 4000⌈log 2 P ⌉ + 40000α⌈log 2 P ⌉ − 27000αP + 0,0154 N 3P + 0,19φ 4.4 % 0.418BT B (µs) = 21 N 2P β + 970 N β + 14000⌈log 2 P ⌉ − 130000α⌈log 2 P ⌉ + 100 N P ⌈log 2 P ⌉++ 800 N P α⌈log 2 P ⌉ + 0,0142 N 33.5 % 0.0246P + 0,13φdo y, por lo tanto, la función colectiva es el factordominante en cada iteración <strong>de</strong>l lazo más externo.A diferencia <strong>de</strong> los mo<strong>de</strong>los Φ A y Φ B , estos mo<strong>de</strong>lospresentan unos pesos <strong>de</strong> Akaike relativamentebajos que indican, a priori, una calidad pobre <strong>de</strong> losresultados. En cualquier caso, la importancia relativa<strong>de</strong> los diferentes términos consi<strong>de</strong>rados, proporcionadapor el entorno TIA, permite que el usuario analicela calidad <strong>de</strong> estas expresiones y las modifique consecuentemente.<strong>La</strong> tabla IV muestra la importanciarelativa <strong>de</strong> los diferentes términos consi<strong>de</strong>rados en laobtención <strong>de</strong> los mo<strong>de</strong>los <strong>de</strong>l tiempo <strong>de</strong> ejecución enlos casos A y B. Únicamente se muestran los términoscon una importancia relativa mayor que 0,5. Enel caso A, seis <strong>de</strong> los siete términos que aparecen enel mo<strong>de</strong>lo comparten el valor máximo <strong>de</strong> importanciarelativa, lo que evi<strong>de</strong>ncia que el mo<strong>de</strong>lo T A esrealmente una aproximación a<strong>de</strong>cuada <strong>de</strong>l comportamientoreal <strong>de</strong> la aplicación. En el caso B, aunqueel mo<strong>de</strong>lo es muy preciso para caracterizar los datosexperimentales, el peso <strong>de</strong> Akaike es muy pequeño eneste caso. Es posible que, en este caso, los mo<strong>de</strong>losconsi<strong>de</strong>rados en el conjunto <strong>de</strong> candidatos no reflejena<strong>de</strong>cuadamente el comportamiento <strong>de</strong>l caso B,aunque la mejor aproximación sea el mo<strong>de</strong>lo T B .C. Influencia <strong>de</strong> los fallos cache en el tiempo <strong>de</strong> ejecuciónEn los casos consi<strong>de</strong>rados, la influencia <strong>de</strong> los falloscache L2 en el tiempo <strong>de</strong> ejecución se pue<strong>de</strong> estimarcombinando los mo<strong>de</strong>los obtenidos para los fallos cache(tabla II) y los mo<strong>de</strong>los <strong>de</strong>l tiempo <strong>de</strong> ejecución(tabla III). Tanto en el caso A como en el caso B,la contribución <strong>de</strong> los fallos cache L2 en el tiempo<strong>de</strong> ejecución total <strong>de</strong> la aplicación se i<strong>de</strong>ntifica en elsumando correspondiente al término φ. Por lo tanto,el coeficiente <strong>de</strong> estos términos proporciona el costeTABLA IVImportancia relativa <strong>de</strong> los mo<strong>de</strong>los T A y T BCaso ACaso Bω+ M término ω+ M términoN0.91872N0.9003β βN0.91873N0.90032P P β0.9187 φ 0.8800 φ0.9187 N 2 N0.87763P0.9187 α⌈log 2 P ⌉ 0.8667 α⌈log 2 P ⌉N0.9187 αP 0.8246 P α⌈log 2 P ⌉0.5615 ⌈log 2 P ⌉ 0.7728 ⌈log 2 P ⌉N0.5003 P 0.5424 P ⌈log 2 P ⌉efectivo por cada fallo en la cache <strong>de</strong> nivel L2: 0,19µs/fallo y 0,13 µs/fallo en los casos A y B, respectivamente.<strong>La</strong> figura 3 muestra la estimación <strong>de</strong>l porcentaje<strong>de</strong> tiempo <strong>de</strong> ejecución asociado a los falloscache L2, en ambos casos. Estos datos han sido obtenidosutilizando los mo<strong>de</strong>los T y Φ para caracterizar,respectivamente, el tiempo <strong>de</strong> ejecución y los falloscache L2. Por lo tanto, estas estimaciones han sidocalculadas a partir <strong>de</strong> los parámetros <strong>de</strong> ejecución N,P , α y β.En el caso A, la influencia <strong>de</strong> los fallos cache L2es prácticamente insignificante cuando la dimensión<strong>de</strong> la matriz es 300 o 400, pero alcanza un 10 % <strong>de</strong>ltiempo <strong>de</strong> ejecución cuando la dimensión <strong>de</strong> la matrizes 500. En el caso B se pue<strong>de</strong> observar un comportamientosimilar, aunque la contribución es mayorcuando la dimensión <strong>de</strong> la matriz es 400. Aunque lainfluencia <strong>de</strong> los fallos cache disminuye con el número<strong>de</strong> procesos, el ritmo <strong>de</strong> <strong>de</strong>crecimiento es menoral aumentar el ancho <strong>de</strong> banda <strong>de</strong> la red. A<strong>de</strong>más,en ambos casos, la importancia <strong>de</strong> los fallos cachees prácticamente constante cuando la velocidad <strong>de</strong>la red es 1000 Mbps. Ambos efectos están asociados<strong>JP2011</strong>-647


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20112 3 4 5 610 Mbps100 Mbps1000 Mbps% of execution time105matrix size30040050002 3 4 5 6Number of processors2 3 4 5 6Fig. 2. Estimación <strong>de</strong>l porcentaje <strong>de</strong> tiempo <strong>de</strong> ejecución asociado a los fallos cache L2 en el caso A2 3 4 5 610 Mbps100 Mbps1000 Mbps% of execution time105matrix size30040050002 3 4 5 6Number of processors2 3 4 5 6Fig. 3. Estimación <strong>de</strong>l porcentaje <strong>de</strong> tiempo <strong>de</strong> ejecución asociado a los fallos cache L2 en el caso Bal hecho <strong>de</strong> que el coste individual <strong>de</strong> cada comunicacióndisminuye al aumentar el ancho <strong>de</strong> banda <strong>de</strong>la red y, por lo tanto, la importancia <strong>de</strong> las comunicacionesen el coste total <strong>de</strong> la aplicación se reduceconsecuentemente.V. ConclusionesEn este artículo se propone una nueva metodologíapara obtener una estimación <strong>de</strong> la influencia <strong>de</strong> losfallos cache en el rendimiento <strong>de</strong> una aplicación. Estametodología está basada en los mo<strong>de</strong>los analíticosproporcionados por mecanismo <strong>de</strong> selección <strong>de</strong> mo<strong>de</strong>los,basado en el criterio <strong>de</strong> información <strong>de</strong> Akaike,que ha sido implementado en el entorno TIA. Comocaso <strong>de</strong> estudio, en este artículo se presentan losresultados obtenidos con esta metodología para diferentesversiones <strong>de</strong>l producto paralelo <strong>de</strong> matrices.Agra<strong>de</strong>cimientosEste trabajo ha sido financiado por fondos FEDERy por el Ministerio <strong>de</strong> Educación y Ciencia (proyectosTIN2008-06570-C04-03 y TIN2010-17541), por laXunta <strong>de</strong> Galicia (proyecto 2010/28) y por las re<strong>de</strong>sHiPEAC, CAPAP-H y GHPC.Referencias[1] D. Andra<strong>de</strong>, M. Arenaz, B.B. Fraguela, J. Touriño, andR. Doallo, “Automated and accurate cache behavioranalysis for co<strong>de</strong>s with irregular access patterns,” Concurrencyand Computation: Practice and Experience, vol.19, no. 18, pp. 2407–2423, 2007.[2] R. A. Uhlig and T. N. Mudge, “Trace-driven memorysimulation: A survey,” ACM Computing Surveys, vol.29, no. 2, pp. 128–170, 1997.[3] H. Akaike, “A new look at the statistical mo<strong>de</strong>l i<strong>de</strong>ntification,”IEEE Transactions on Automatic Control, vol.19, pp. 716–723, 1974.[4] Diego R. Martínez, Vicente Blanco, Marcos Boullón,José Carlos Cabaleiro, Casiano Rodríguez, and FranciscoF. Rivera, “Software tools for performance mo<strong>de</strong>ling ofparallel programs,” in IEEE International Parallel andDistributed Processing Symposium, 2007, IPDPS.[5] Diego R. Martínez, Vicente Blanco, Marcos Boullón,José Carlos Cabaleiro, and Tomás F. Pena, “Analyticalperformance mo<strong>de</strong>ls of parallel programs in clusters,” inParallel Computing: Architectures, Algorithms and Applications,2007, ParCo.[6] Diego R. Martínez, Julio L. Albín, José Carlos Cabaleiro,Tomás F. Pena, Francisco F. Rivera, and Vicente Blanco,“El criterio <strong>de</strong> información <strong>de</strong> Akaike en la obtención <strong>de</strong>mo<strong>de</strong>los estadísticos <strong>de</strong> rendimiento,” in XX Jornadas<strong>de</strong> Paralelismo, 2009.[7] Kenneth P. Burnham and David R. An<strong>de</strong>rson, Mo<strong>de</strong>lSelection and Multimo<strong>de</strong>l Inference. A PracticalInformation-Theoretic Approach, Spring Science + BussinessMedia, LLC, 2002.[8] S. Browne, J. Dongarra, N. Garner, G. Ho, and P. Mucci,“A portable programming interface for performance evaluationon mo<strong>de</strong>rn processors,” International Journal ofHigh-Performance Computing Applications, vol. 14, no.3, pp. 189–204, 2000.[9] J. C. Pichel, D. B. Heras, J. C. Cabaleiro, and F. F.Rivera, “Increasing data reuse of sparse algebra co<strong>de</strong>son simultaneous multithreading architectures,” Concurrencyand Computation: Practice and Experience, vol.21, no. 15, pp. 1838–1856, 2009.[10] R. Hockney, “The communication challenge for MPP:Intel Paragon and Meiko CS-2,” Parallel Computing,vol. 20, pp. 389–398, 1994.[11] J. Pjěsivac-Grbovíc, Towards Automatic and AdaptiveOptimizations of MPI Collective Operations, Ph.D. thesis,University of Tennessee, 2007.<strong>JP2011</strong>-648


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Metodología para la sintonización <strong>de</strong>aplicaciones OpenMP en sistemas multicoreCésar Allan<strong>de</strong> 1 , Josep Jorba 2 , Eduardo César 1 y Anna Morajko 1Resumen—<strong>La</strong>s aplicaciones científicas en entornos HPC han<strong>de</strong> ser capaces <strong>de</strong> utilizar los procesadores multicore<strong>de</strong> forma eficiente. Surge la duda <strong>de</strong> cómo explotarlos recursos evitando ineficiencias <strong>de</strong>bidas principalmentea la compartición <strong>de</strong> recursos por parte <strong>de</strong>lprocesador. Es necesario proporcionar herramientascapaces <strong>de</strong> minimizar los problemas <strong>de</strong> rendimiento,mediante la <strong>de</strong>tección, medición y predicción <strong>de</strong>factores <strong>de</strong> rendimiento. Usando técnicas <strong>de</strong> sintonizacióndinámica se pue<strong>de</strong> proporcionar transparenciay a<strong>de</strong>más obtener mejoras <strong>de</strong> rendimientogeneral <strong>de</strong> la aplicación.En este trabajo se propone una metodología parael análisis y sintonización <strong>de</strong> aplicaciones OpenMP enentornos multicore. <strong>La</strong> sintonización dinámica se produceen base a la predicción <strong>de</strong> comportamiento proporcionadapor mo<strong>de</strong>los <strong>de</strong> rendimiento, provistos <strong>de</strong>información obtenida en la caracterización <strong>de</strong>l sistemay durante la monitorización <strong>de</strong> factores dinámicos <strong>de</strong>rendimiento.Palabras clave— OpenMP, análisis <strong>de</strong> rendimiento,mo<strong>de</strong>lo <strong>de</strong> rendimiento, multicore, paralelismo <strong>de</strong>datos, paralelismo <strong>de</strong> tareasI. Introducción<strong>La</strong> limitación en la capacidad <strong>de</strong> integración <strong>de</strong>transistores ha generado la necesidad <strong>de</strong> aumentarlas prestaciones mediante la agregación <strong>de</strong> másunida<strong>de</strong>s <strong>de</strong> proceso, <strong>de</strong>sembocando en la era multicore.<strong>La</strong> ten<strong>de</strong>ncia parece indicar que la evolución<strong>de</strong> las nuevas generaciones <strong>de</strong> procesadores pasará,en gran medida, por un aumento ingente <strong>de</strong> núcleosen el chip. Los fabricantes estudian la viabilidad <strong>de</strong>diseños <strong>de</strong> 48 [1], o hasta 100 cores[2]. Por no mencionarlos sistemas GPU [3] o APU [4], con cifras<strong>de</strong>l or<strong>de</strong>n <strong>de</strong> cientos <strong>de</strong> núcleos por procesador. <strong>La</strong>aparición <strong>de</strong> estos procesadores genera cierta controversiarespecto a si ¿será posible utilizar <strong>de</strong> formaeficiente estos recursos?. Es cierto que existen importantesproblemas a resolver en el diseño <strong>de</strong> estosprocesadores, como el cuello <strong>de</strong> botella que representala memoria. Una barrera que hasta el momentose ha intentado minimizar mediante jerarquías<strong>de</strong> memorias multinivel. Sin embargo, a nivel <strong>de</strong> softwarees muy costoso ajustar la aplicación a nivel <strong>de</strong>cache para maximizar el rendimiento. A<strong>de</strong>más, estosajustes son difícilmente portables entre plataformascon distintos procesadores.Sea como fuere, los sistemas multicore ya estándisponibles. Más <strong>de</strong>l 99% <strong>de</strong> los 500 mejores sistemas<strong>de</strong> computación <strong>de</strong> altas prestaciones [5] disponen <strong>de</strong>1 Departamento <strong>de</strong> Arquitectura <strong>de</strong> Computadores y SistemasOperativos, Universitat Autònoma <strong>de</strong> Barcelona,e-mail: callan<strong>de</strong>@caos.uab.es, eduardo.cesar@uab.es,anna.morajko@uab.es2 Estudis d’Informàtica, Multimèdia i Telecomunicacions,Universitat Oberta <strong>de</strong> Catalunya, e-mail: jjorbae@uoc.eduprocesadores multinúcleo. Sin embargo, ¿en qué medidase utilizan <strong>de</strong> forma eficiente los recursos multicoreen los centros <strong>de</strong> HPC?Por una parte, los mo<strong>de</strong>los multicore han aumentadonotablemente el rendimiento potencial <strong>de</strong> lossistemas, pero para po<strong>de</strong>r utilizar estos recursos, lasaplicaciones <strong>de</strong>ben ejecutarse en paralelo. Los mo<strong>de</strong>los<strong>de</strong> programación nos permiten expresar en ciertogrado el paralelismo <strong>de</strong> las aplicaciones. Sin embargo,<strong>de</strong>pendiendo <strong>de</strong>l tipo <strong>de</strong> aplicación, no siempreva a ser posible extraer el mismo nivel <strong>de</strong> paralelismoentre la aplicación y el sistema hardware.<strong>La</strong> aplicación pue<strong>de</strong> tener restricciones en el grado<strong>de</strong> paralelismo que limiten la eficiencia. Asimismo,el mo<strong>de</strong>lo <strong>de</strong> programación, encargado <strong>de</strong> la gestión<strong>de</strong> recursos, y que proporciona a la aplicación unnivel <strong>de</strong> abstración <strong>de</strong> estos dispositivos, pue<strong>de</strong> noaprovechar <strong>de</strong> forma eficiente los recursos multicore<strong>de</strong>bido a una gestión ina<strong>de</strong>cuada. Uno <strong>de</strong> los mo<strong>de</strong>los<strong>de</strong> programación más extendidos y que a<strong>de</strong>máspermite explotar los recursos multicore es OpenMP.Por tanto, en el estudio <strong>de</strong> la metodología parala sintonización <strong>de</strong> aplicaciones se <strong>de</strong>berán analizarfactores <strong>de</strong> rendimiento en base a las aplicaciones,aquellos generados por el mo<strong>de</strong>lo <strong>de</strong> programación ylos originados a nivel <strong>de</strong>l sistema hardware.Este trabajo se estructura en las siguientes secciones,un análisis general <strong>de</strong>l rendimiento en entornosmulticore se presenta en la sección II. <strong>La</strong>metodología propuesta se <strong>de</strong>scribe en la sección III.En la sección IV se analizan dos casos <strong>de</strong> uso parala metodología propuesta, que ha <strong>de</strong>sembocado en la<strong>de</strong>tección <strong>de</strong> dos factores <strong>de</strong> rendimiento candidatos.<strong>La</strong> experimentación para la evaluación <strong>de</strong>l impacto<strong>de</strong> los factores <strong>de</strong> rendimiento candidatos se <strong>de</strong>tallanen la sección V. Finalmente, en la sección VI sereflejan las conclusiones y el trabajo futuro.II. Análisis <strong>de</strong> rendimientoDes<strong>de</strong> el punto <strong>de</strong> vista <strong>de</strong> la arquitectura, una característicacomún <strong>de</strong> los sistemas multicore, es queestán <strong>de</strong>finidos como sistemas <strong>de</strong> memoria compartida.Eso significa que los recursos tienen una visióncomún <strong>de</strong> la memoria principal. Diferentes recursos<strong>de</strong> cómputo pue<strong>de</strong>n acce<strong>de</strong>r a los mismos datos <strong>de</strong>memoria. Por tanto, <strong>de</strong>ben aplicar políticas <strong>de</strong> accesoconcurrente. A<strong>de</strong>más, en los sistemas multicoreexisten problemas <strong>de</strong>bidos a la interconexión entrecores <strong>de</strong>ntro <strong>de</strong>l chip. <strong>La</strong> compartición <strong>de</strong> recursos<strong>de</strong>l procesador, como son los niveles jerárquicos <strong>de</strong>memoria cache, precisan <strong>de</strong> un ajuste en cuanto sepretenda obtener el mejor rendimiento posible. Unaaproximación a un mo<strong>de</strong>lo <strong>de</strong> rendimiento en base<strong>JP2011</strong>-649


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011a la caracterización <strong>de</strong>l sistema <strong>de</strong> memoria es presentadaen [6], que presenta una caracterización <strong>de</strong>lsistema hardware mediante microbenchmarks para<strong>de</strong>terminar el ancho <strong>de</strong> banda <strong>de</strong> acceso a memoriaprincipal y así, po<strong>de</strong>r pre<strong>de</strong>cir qué sistema hardwarees más apropiado para la ejecución <strong>de</strong> una aplicaciónespecífica.Por otra parte, a nivel <strong>de</strong> software, las aplicacionescientíficas <strong>de</strong>l entorno <strong>de</strong> HPC son aquellas que <strong>de</strong>bidoa su complejidad requieren un gran tiempo<strong>de</strong> ejecución sobre las arquitecturas <strong>de</strong> los or<strong>de</strong>nadoresactuales. <strong>La</strong>s aplicaciones son ejecutadas enentornos paralelos para obtener su ejecución en elmenor tiempo posible. Estas aplicaciones, <strong>de</strong> formageneral, presentan patrones <strong>de</strong> comportamiento comuneso paradigmas <strong>de</strong> programación paralela. Debidoa su propia naturaleza, cada paradigma <strong>de</strong> programaciónparalela presenta sus propios problemas<strong>de</strong> rendimiento. Por tanto, los patrones <strong>de</strong> la aplicación<strong>de</strong>ben ser caracterizados para po<strong>de</strong>r ajustar elsistema en la medida <strong>de</strong> lo posible. De los paradigmas<strong>de</strong> programación paralela más utilizados en entornosHPC po<strong>de</strong>mos i<strong>de</strong>ntificar los tipos Master-Worker, Pipeline, SPMD (Single Program MultipleData) y Divi<strong>de</strong>&Conquer.Finalmente <strong>de</strong>stacar que, no únicamente van aexistir problemas <strong>de</strong> rendimiento a nivel <strong>de</strong> aplicacióncientífica y arquitectura hardware. El encargado<strong>de</strong> gestionar la ejecución <strong>de</strong> la aplicaciónparalela y la asignación a los recursos es la libreríadinámica <strong>de</strong>l mo<strong>de</strong>lo <strong>de</strong> programación. A este nivel,existen problemas generados en el <strong>de</strong>sajuste <strong>de</strong> losrequisitos <strong>de</strong> la aplicación y los recursos multicore.Existe cierta diversidad <strong>de</strong> mo<strong>de</strong>los <strong>de</strong> programaciónque explotan las arquitecturas <strong>de</strong> memoria compartida.Entre los más extendidos están OpenMP, Cilk,Intel TBB.En este trabajo vamos a analizar algunos problemas<strong>de</strong> rendimiento en el mo<strong>de</strong>lo <strong>de</strong> programaciónOpenMP.A. Mo<strong>de</strong>lo <strong>de</strong> programación OpenMPEl mo<strong>de</strong>lo <strong>de</strong> programación OpenMP es unestándar que permite abstraer la utilización <strong>de</strong>threads. Cabe <strong>de</strong>stacar que es un mo<strong>de</strong>lo <strong>de</strong> programaciónmuy utilizado en los entornos HPC. A<strong>de</strong>más,favorece su análisis el hecho <strong>de</strong> existir implementaciones<strong>de</strong> código abierto.Los factores <strong>de</strong> rendimiento conocidos a nivel <strong>de</strong>ineficiencias <strong>de</strong> la gestión <strong>de</strong> la librería, vienen <strong>de</strong>terminadospor las primitivas <strong>de</strong>l mo<strong>de</strong>lo y por lagestión <strong>de</strong>l propio paradigma <strong>de</strong> aplicación. <strong>La</strong>sprimitivas <strong>de</strong> OpenMP pue<strong>de</strong>n hacer referencia a unmo<strong>de</strong>lo <strong>de</strong> paralelismo <strong>de</strong> datos o a un mo<strong>de</strong>lo <strong>de</strong>paralelismo <strong>de</strong> tareas.En la reciente <strong>de</strong>finición <strong>de</strong>l estándar OpenMPversión 3.0, se agrega el paradigma <strong>de</strong> tareas, queamplia las posibilida<strong>de</strong>s <strong>de</strong> paralelismo con OpenMP.Este es un paradigma concurrente, que en entornosmulticore permite la ejecución paralela <strong>de</strong> tareas. Sia<strong>de</strong>más, las tareas son in<strong>de</strong>pendientes, el mo<strong>de</strong>lo permitela ejecución <strong>de</strong> tareas fuera <strong>de</strong> or<strong>de</strong>n, permitiendola finalización previa <strong>de</strong> tareas instanciadas<strong>de</strong>spués <strong>de</strong> otras, generando un balanceo <strong>de</strong> la aplicación.Habiendo <strong>de</strong>scrito algunas características <strong>de</strong>l mo<strong>de</strong>lo<strong>de</strong> programación, será necesario evaluar el verda<strong>de</strong>roimpacto en ejecuciones reales. Por tanto, esnecesario <strong>de</strong>finir las herramientas <strong>de</strong>l estado <strong>de</strong>l arteque van a permitir la obtención <strong>de</strong> la informaciónpara el análisis <strong>de</strong> los factores <strong>de</strong> rendimiento.B. Estudio <strong>de</strong>l sistemaEn el estado <strong>de</strong>l arte, existen diferentes kernels <strong>de</strong>aplicaciones científicas representativas <strong>de</strong>l entorno <strong>de</strong>HPC. Entre ellas se han consi<strong>de</strong>rado aquellas expresadascon el mo<strong>de</strong>lo OpenMP, o aquellas que permitenanalizar aspectos referentes a OpenMP.• Caracterizar aplicaciones científicas; lasbenchmark suites seleccionadas representan alas aplicaciones científicas representativas <strong>de</strong>lentorno <strong>de</strong> HPC. Pertenecen a núcleos <strong>de</strong> aplicacionescientíficas reales.1. BOTS (Barcelona OpenMP Tasks Suite)[7];conjunto <strong>de</strong> benchmark basados en el mo<strong>de</strong>lo<strong>de</strong> tareas: uts, strassen, sparselu, sort,nqueens, health, floorplan, fft, alignment2. Parsec (Princeton Application Repository forShared-Memory Computers)[8]; suite para elanálisis <strong>de</strong> aplicacionse basadas en OpenMP,pthreads y TBB. De las cuales blackscholes,bodytrack, freqmine, y ferret contienen referenciasa OpenMP.3. NPB (NASA Parallel Benchmark Suite)[9];suite <strong>de</strong> la NASA con núcleos <strong>de</strong> aplicacionescientíficas, <strong>de</strong> las que contienen <strong>de</strong>finiciónexclusiva OpenMP: IS (Integer Sort) y DC(Data Cube).4. MRI segmentation [10]; núcleo <strong>de</strong> unaaplicación científica para la segmentación <strong>de</strong>imágenes <strong>de</strong> resonancia magnética. Benchmark<strong>de</strong>sarrollado <strong>de</strong>ntro <strong>de</strong>l <strong>de</strong>partamentoCAOS (UAB).• Caracterizar el mo<strong>de</strong>lo <strong>de</strong> programación;mediante pruebas <strong>de</strong> estrés sobre las primitivas<strong>de</strong> la librería, es posible obtener medidas paradiferentes parámetros <strong>de</strong> configuración <strong>de</strong>l mo<strong>de</strong>lo<strong>de</strong> programación OpenMP.1. UTS (Unbalanced Tree Search)[11]; benchmarkpara la búsqueda exhaustiva en unárbol altamente <strong>de</strong>sbalanceado. Expresadoen un paradigma <strong>de</strong> programación Divi<strong>de</strong>&Conquer.Permite la emulación <strong>de</strong> unmo<strong>de</strong>lo <strong>de</strong> tareas con varias configuracionespara la gestión <strong>de</strong> tareas..2. ASC Sequoia; <strong>de</strong>l LLNL (<strong>La</strong>wrence LivermoreNational <strong>La</strong>boratory); benchmark utilizadoen la caracterización <strong>de</strong>l supercomputadorSequoia. De esta suite es posible utilizarel benchmark CLOMP [12] para la caracterización<strong>de</strong> la librería <strong>de</strong> OpenMP, y medir overheadsy rendimiento.<strong>JP2011</strong>-650


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20113. Sphinx (Integrated parallel microbenchmarksuite); <strong>de</strong>l LLNL. Test <strong>de</strong> rendimientoOpenMP mediante sphinx omp.4. EPCC (Edimburgh Parallel Computing Center)[13];microbenchmarks para la evalución<strong>de</strong> rendimiento OpenMP para la versión <strong>de</strong>lestándar 2.5 .• Caracterización <strong>de</strong> hardware; para la <strong>de</strong>scripción<strong>de</strong>l sistema hardware mediante pruebas<strong>de</strong> estrés dinámico.1. ASC Sequoia; <strong>de</strong>l LLNL (<strong>La</strong>wrence LivermoreNational <strong>La</strong>boratory); realiza pruebas<strong>de</strong> estrés <strong>de</strong>l sistema <strong>de</strong> memoria accediendoa diferentes tamaños <strong>de</strong> datos y con diferentedistribución para la obtención <strong>de</strong> anchos <strong>de</strong>banda: STREAM, STRIDE y AMGmk.C. Herramientas para el análisis <strong>de</strong> OpenMP<strong>La</strong>s siguientes herramientas permiten instrumentaraplicaciones OpenMP, generar resúmenes otrazas, visualizar trazas y generar análisis postmortem.1. Instrumentación; Para la instrumentación<strong>de</strong> OpenMP es posible utilizar herramientascomo Extrae (Barcelona Supercomputing Center)que permite generar trazas para la herramientaParaver. A<strong>de</strong>más, Papi (PerformanceApplication Programming Interface) [14]permite obtener información <strong>de</strong>l hardware <strong>de</strong>forma dinámica. Opari[15] (OpenMP PragmaAnd Region Instrumentator) proporciona informacióndinámica <strong>de</strong> las estructuras y primitivasOpenMP.2. Tracing/Profile; <strong>La</strong> aplicación instrumentadaproporciona información a las herramientasOmpp[16] (Basado en instrumentacion <strong>de</strong>Opari), TAU[17] y Extrae.3. Visualización y análisis; Para la visualización<strong>de</strong> trazas Paraver (BSC), y las herramientas<strong>de</strong> analisis Scalasca [18] y Dimemas.D. Herramientas para la integración <strong>de</strong>l mo<strong>de</strong>lo <strong>de</strong>rendimientoNuestro objetivo es sintonizar dinámicamente. Portanto, son necesarias herramientas para la monitorizacióny sintonización dinámica <strong>de</strong> la librería queimplementa la gestión dinámica <strong>de</strong>l mo<strong>de</strong>lo <strong>de</strong> programación.1. libgomp; Es posible integrar la lógica <strong>de</strong> sintonización<strong>de</strong> forma manual sobre el códigofuente <strong>de</strong> la librería libgomp <strong>de</strong> GNU. Paramejorar la portabilidad, es posible utilizarherramientas <strong>de</strong> sintonización dinámica comoDyninst[19] o Intel Pin[20].2. Framework MATE (Dynamic PerformanceTuning Environment)[21]; permite la sintonizacióndinámica basada en mo<strong>de</strong>los <strong>de</strong>rendimiento. Requiere la <strong>de</strong>scripción <strong>de</strong>l elementotunlet para la integración <strong>de</strong>l mo<strong>de</strong>lo <strong>de</strong>rendimiento y las políticas <strong>de</strong> sintonización.E. Entornos <strong>de</strong> experimentación<strong>La</strong>s herramientas <strong>de</strong> simulación han <strong>de</strong> permitiranalizar la escalabildad y arquitecturas <strong>de</strong> la próximageneración <strong>de</strong> procesadores multicore.1. Graphite[22]; entorno <strong>de</strong> simulación paraleloque permite la simulación <strong>de</strong> hasta 1024 cores2. AMD SimNow/Cotson[23]; entorno <strong>de</strong> simulaciónsecuencial que permite la simulación<strong>de</strong> hasta 64 cores.III. Metodología para la <strong>de</strong>tección <strong>de</strong>ineficienciasComo se ha comentado anteriormente, OpenMPpermite cierta flexibilidad para po<strong>de</strong>r expresar diferentesparadigmas <strong>de</strong> programación paralela. Poreste motivo, existe la necesidad <strong>de</strong> evaluar a nivel <strong>de</strong>aplicación los diferentes patrones <strong>de</strong> forma aislada.Cada paradigma conlleva implícitamente cuellos <strong>de</strong>botella que <strong>de</strong>pendiendo <strong>de</strong> la arquitectura podrántener mayor o menor afectación en el rendimiento.Por otro lado, la implementación específica <strong>de</strong>l mo<strong>de</strong>lo<strong>de</strong> programación pue<strong>de</strong> contemplar alternativas<strong>de</strong> diseño. Existen <strong>de</strong>cisiones <strong>de</strong> diseño sobre aspectosno <strong>de</strong>tallados en la <strong>de</strong>finición <strong>de</strong>l estándar. <strong>La</strong>svariabilida<strong>de</strong>s en la implementación pue<strong>de</strong>n afectaral rendimiento <strong>de</strong>pendiendo <strong>de</strong> aspectos relativos ala asignación <strong>de</strong> trabajos y gestión <strong>de</strong> recursos. Porejemplo, la utilización <strong>de</strong> estrategias <strong>de</strong> gestión <strong>de</strong> tareasmediante la utilización <strong>de</strong> recursos <strong>de</strong> memoriacentralizados o estrategias <strong>de</strong> gestión <strong>de</strong>scentralizadas.<strong>La</strong> diversidad <strong>de</strong> contextos requiere un estudiopara cada configuración.Por tanto, se ha <strong>de</strong>finido una metodología parael estudio <strong>de</strong> factores <strong>de</strong> rendimiento basada en unmo<strong>de</strong>lo en espiral que ha <strong>de</strong> permitir la <strong>de</strong>finiciónanalítica <strong>de</strong> mo<strong>de</strong>los <strong>de</strong> rendimiento para factores<strong>de</strong> rendimiento, así como la propuesta y mo<strong>de</strong>lado<strong>de</strong> soluciones a factores <strong>de</strong> rendimiento <strong>de</strong>l mo<strong>de</strong>loexistente. Se ha propuesto un mo<strong>de</strong>lo en espiralpor la necesidad <strong>de</strong> evaluar <strong>de</strong> forma in<strong>de</strong>pendientecada factor <strong>de</strong> rendimiento y po<strong>de</strong>r verificar su impacto<strong>de</strong> forma aislada. <strong>La</strong>s nuevas iteraciones ala metodología nos permitiran agregar un mayor alcancey precisión a la metodología.Se <strong>de</strong>finen a continuación las etapas:1. Definir el contexto <strong>de</strong>l estudio En estaetapa se <strong>de</strong>limita el contexto <strong>de</strong> estudio. Se<strong>de</strong>fine el paradigma <strong>de</strong> programación paralelaa evaluar, las herramientas <strong>de</strong> benchmark quehan <strong>de</strong> permitir caracterizar el problema y lapreparación <strong>de</strong>l entorno <strong>de</strong> ejecución.2. I<strong>de</strong>ntificar factores <strong>de</strong> rendimiento Teniendoen cuenta que existen factores <strong>de</strong>rendimiento en los niveles <strong>de</strong> aplicación, mo<strong>de</strong>lo<strong>de</strong> programación paralela y hardware. Seanaliza una funcionalidad <strong>de</strong> OpenMP o unparadigma <strong>de</strong> programación paralela y se analizanlas ineficiencias <strong>de</strong> la aplicación para diferentesconfiguraciones. Tras la <strong>de</strong>tección <strong>de</strong>ineficiencias en base a la <strong>de</strong>finición <strong>de</strong> varias con-<strong>JP2011</strong>-651


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011figuraciones, se obtiene un factor <strong>de</strong> rendimientocandidato.3. Evaluación <strong>de</strong>l impacto <strong>de</strong> los factores<strong>de</strong> rendimiento Para la evaluación <strong>de</strong>l impactose mi<strong>de</strong> empíricamente el tiempo <strong>de</strong> ejecución<strong>de</strong> las configuraciones posibles <strong>de</strong>l factor<strong>de</strong> rendimiento, y se <strong>de</strong>termina qué configuraciónobtiene mayor speedup y eficiencia. Severifica mediante simulación que es posible reproducirel problema <strong>de</strong> rendimiento obtenidoen el entorno real. Posteriormente, se analizamediante simulación el impacto <strong>de</strong>l factor <strong>de</strong>rendimiento para arquitecturas con gran número<strong>de</strong> cores.4. Mo<strong>de</strong>lo <strong>de</strong> rendimiento o alternativa<strong>de</strong> diseño y mo<strong>de</strong>lado Mo<strong>de</strong>lar el factor<strong>de</strong> rendimiento o proponer una alternativa<strong>de</strong> diseño conjuntamente con su mo<strong>de</strong>lo <strong>de</strong>rendimiento. Este proceso requiere la recopilación<strong>de</strong> las medidas y configuraciones para elfactor <strong>de</strong> rendimiento y buscar una relación quepermita pre<strong>de</strong>cir el comportamiento en un entornodinámico.5. Verificación <strong>de</strong>l mo<strong>de</strong>lo <strong>de</strong> rendimientoIntegrar el mo<strong>de</strong>lo <strong>de</strong> rendimiento mediante lasherramientas <strong>de</strong> sitonización que permitan actuara nivel <strong>de</strong> la librería dinámica <strong>de</strong> OpenMP.Verificar mediante la sintonización dinámica sila predicción permite conseguir una mejora respectoa la ejecución sin sintonizar. Posteriormente,analizar el overhead <strong>de</strong>bido a la instrumentacióny sintonización dinámica y verificar laprecisión <strong>de</strong>l mo<strong>de</strong>lo generado. Posteriormente,se valida el mo<strong>de</strong>lo en un entorno <strong>de</strong> simulación,mediante la simulación <strong>de</strong>l mo<strong>de</strong>lo sobre una arquitecturacon alto número <strong>de</strong> cores.IV. Casos <strong>de</strong> usoEn esta sección se muestran dos casos <strong>de</strong> uso <strong>de</strong> lametodología presentada anteriormente.A. Paralelismo <strong>de</strong> datosEn el mo<strong>de</strong>lo <strong>de</strong> paralelismo <strong>de</strong> datos existen factores<strong>de</strong> rendimiento relacionados con la gestión <strong>de</strong>lreparto <strong>de</strong> iteraciones en bucles paralelizados, primitivas<strong>de</strong> acceso concurrente a memoria y la asignación<strong>de</strong> threads sobre cores en base a datos afines paraminimizar fallos <strong>de</strong> cache.Respecto al reparto <strong>de</strong> iteraciones <strong>de</strong> bucles paralelizados,para una carga <strong>de</strong> trabajo <strong>de</strong>sbalanceada,es posible en OpenMP aplicar tres estrategias <strong>de</strong> planificación:static, dynamic y gui<strong>de</strong>d.<strong>La</strong> estrategia <strong>de</strong> planificación estática reparte lasiteraciones en base al factor <strong>de</strong>nominado chunksize.Previo al cómputo, se realiza la asignación <strong>de</strong> rangos<strong>de</strong> iteraciones para cada thread. <strong>La</strong> repartición<strong>de</strong> rangos altamente <strong>de</strong>sbalanceados va a afectar alrendimiento <strong>de</strong> la aplicación.<strong>La</strong> planificación dinámica reparte iteraciones <strong>de</strong>tamaño chunksize bajo <strong>de</strong>manda. Cuando un threadfinaliza la ejecución <strong>de</strong> las iteraciones asignadas, solicitanuevas iteraciones. Esta estrategia mejorael balanceo <strong>de</strong> carga. Sin embargo, tiene unpequeño overhead en los accesos concurrentes parala <strong>de</strong>manda <strong>de</strong> nuevas iteraciones, que afectará alrendimiento si los accesos son muy frecuentes o siintervienen un gran número <strong>de</strong> threads.El método guiado reparte bajo <strong>de</strong>manda grupos <strong>de</strong>iteraciones, empezando con tamaños gran<strong>de</strong>s hastallegar a un tamaño chunksize <strong>de</strong>finido por el usuario.Esta estrategia pue<strong>de</strong> conseguir una mejora en el balanceoy preten<strong>de</strong> minimizar los problemas <strong>de</strong> las estrategiasanteriores.Por otro lado, existen factores <strong>de</strong> rendimiento enla utilización <strong>de</strong> las primitivas <strong>de</strong> acceso a memoria.<strong>La</strong>s diversas directivas OpenMP ofrecen diferentefuncionalidad y rendimiento en el acceso concurrente.Sin embargo, <strong>de</strong>pendiendo <strong>de</strong> la aplicación no siempreserá posible utilizar la directiva con menor overhead.También existe en algunas implementaciones <strong>de</strong>lmo<strong>de</strong>lo <strong>de</strong> programación, aunque fuera <strong>de</strong>l estándar<strong>de</strong> <strong>de</strong>finición <strong>de</strong> OpenMP, la posibilidad <strong>de</strong> <strong>de</strong>finirel or<strong>de</strong>n <strong>de</strong> asignación <strong>de</strong> threads sobre los coresen base a la afinidad. Mediante esta <strong>de</strong>finición, esposible asignar threads con regiones afines sobre mismosniveles <strong>de</strong> memoria para minimizar los fallos <strong>de</strong>cache. Gracias a esta <strong>de</strong>finición, también es posibleevitar problemas <strong>de</strong> falsa compartición. Éstos problemasocurren cuando threads en niveles diferentes<strong>de</strong> la jerarquía <strong>de</strong> memoria compiten por los mismosdatos, y aunque ejecutados <strong>de</strong> forma paralela, la disputaen el acceso concurrente a los datos serializa laejecución y a<strong>de</strong>más aña<strong>de</strong> un alto overhead <strong>de</strong>bido aconstantes fallos <strong>de</strong> cache y migración <strong>de</strong> datos.B. Paralelismo <strong>de</strong> tareasLos factores <strong>de</strong> rendimiento en este paradigmaestán relacionados con la gestión <strong>de</strong> tareas <strong>de</strong> la implementaciónOpenMP. Existen dos estrategias principalmente.El mo<strong>de</strong>lo centralizado dispone <strong>de</strong> unacola compartida que almacena las tareas, a dón<strong>de</strong> losthreads ociosos acce<strong>de</strong>n <strong>de</strong> forma concurrente para laobtención <strong>de</strong> tareas. El otro mo<strong>de</strong>lo, está basado encolas <strong>de</strong>scentralizadas. Cada thread cuenta con unacola local. Cuando un thread queda ocioso calculamediante una función (e.g. random) el i<strong>de</strong>ntificador<strong>de</strong> un thread sobre el que acce<strong>de</strong>r a su cola localpara iniciar el robo <strong>de</strong> tareas, este thread es llamadovíctima.En el mo<strong>de</strong>lo <strong>de</strong> gestión centralizada, se presentaun problema <strong>de</strong> rendimiento en base al acceso concurrentea la cola. Este factor pue<strong>de</strong> ser más significativocuantos más threads existan en el sistema.Por tanto, el tiempo <strong>de</strong> acceso concurrente limita elrendimiento.En la gestión <strong>de</strong>scentralizada existen dos factores<strong>de</strong> rendimiento principalmente. El primero consisteen la posible ineficiencia en i<strong>de</strong>ntificar al threadvíctima con suficiente carga <strong>de</strong> trabajo. <strong>La</strong>s diferentesimplementaciones suelen utilizar una lógica simple.Por ejemplo, mediante una función aleatoria o<strong>JP2011</strong>-652


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011seleccionando la víctima en el thread vecino. Paraminimizar la búsqueda <strong>de</strong> cargas es posible, al i<strong>de</strong>ntificaruna víctica, robar un conjunto <strong>de</strong> tareas. Existeen esta solución un factor <strong>de</strong> rendimiento a tener encuenta, la <strong>de</strong>cisión <strong>de</strong>l número <strong>de</strong> tareas que van aser migradas <strong>de</strong> una cola a otra.V. Evaluación <strong>de</strong>l impactoSe ha <strong>de</strong>sarrollado un estudio <strong>de</strong> impacto para losfactores <strong>de</strong> rendimiento candidatos presentados anteriormente.A. Paralelismo <strong>de</strong> datosEl contexto inicial se ha centrado en el análisis <strong>de</strong>la gestión <strong>de</strong> iteraciones en el paralelismo <strong>de</strong> bucles.Se ha analizado una aplicación embarazosamenteparalela, basada en la segmentación <strong>de</strong> imágenes <strong>de</strong>resonancia magnética. El algoritmo tiene la caracterísitca<strong>de</strong> segmentar cortes 2D <strong>de</strong> una imagen tridimensional.Por tanto, es posible paralelizar los cortes<strong>de</strong> forma in<strong>de</strong>pendien<strong>de</strong>. Ha sido candidato para laevaluación <strong>de</strong> las primitivas <strong>de</strong> paralelismo <strong>de</strong> bucles<strong>de</strong> OpenMP, que permite <strong>de</strong>finir tres estrategias<strong>de</strong> planificación <strong>de</strong> iteraciones. <strong>La</strong>s estrategiasse diferencian entre aquellas que favorecen un balance<strong>de</strong> carga dinámico o guiado bajo <strong>de</strong>manda, yla planificación estática que minimiza el overhead <strong>de</strong>la gestión dinámica mediante una preasignación inicial<strong>de</strong> iteraciones.Fig. 1. Caracterización <strong>de</strong> las cargas F y Z <strong>de</strong>l BenchmarkMRI SegmentationPara la evaluación <strong>de</strong>l impacto se ha realizado unaejecución en un nodo con 8 cores. Teniendo 2 procesadoresIntel Xeon E5504 <strong>de</strong> 4 cores a 2GHz y 8GBytes <strong>de</strong> memoria. Se han evaluado diferentes cargas<strong>de</strong> trabajo. En la figura 1 se pue<strong>de</strong> observar eltiempo <strong>de</strong> ejecución serie, para cada corte <strong>de</strong> la imagen,<strong>de</strong> las cargas etiquetadas en la figura como F yZ. Cada corte correspon<strong>de</strong> a una iteración <strong>de</strong>l buclegestionado con OpenMP. Se ha verificado como lasestrategias <strong>de</strong> planificación tienen una afectación enel rendimiento, y que <strong>de</strong>pen<strong>de</strong>rá <strong>de</strong> las características<strong>de</strong> carga <strong>de</strong> trabajo. En la figura 2 se presenta elspeedup <strong>de</strong> la carga etiquetada F. En esta gráficase pue<strong>de</strong> observar que el rendimiento no ha escalado<strong>de</strong> forma a<strong>de</strong>cuada, obteniendo una eficiencia para 8threads <strong>de</strong>l 56% en la estrategia estática y <strong>de</strong>l 53%en la estrategia guiada. <strong>La</strong> estrategia dinámica seha adaptado mejor a la carga <strong>de</strong>sbalanceada, obteniendopara todos los casos una eficiencia superior al90%.Por tanto, es posible mejorar el rendimiento si seobtiene una caracterización <strong>de</strong> las cargas <strong>de</strong> trabajo,o utilizando una estrategia dinámica. Para analizarel impacto <strong>de</strong> estas estrategias en entornos con altaescalabilidad se utilizará la simulacion en trabajosfuturos.Fig. 2. Speedup obtenido en las estrategias <strong>de</strong> planificaciónpara la carga <strong>de</strong> datos etiquetada FB. Paralelismo <strong>de</strong> tareasSe ha evaluado el impacto <strong>de</strong> las estrategias <strong>de</strong>planificación en el mo<strong>de</strong>lo <strong>de</strong> paralelismo <strong>de</strong> tareasmediante el benchmark UTS. Este benchmark generamediante un algoritmo recursivo un árbol <strong>de</strong>tareas altamente <strong>de</strong>sbalanceado. <strong>La</strong> implementación<strong>de</strong>l benchmark UTS permite su ejecución mediantevarios mo<strong>de</strong>los <strong>de</strong> programación.Para la evaluación <strong>de</strong>l rendimiento se ha ejecutadoel benchmark en su versión <strong>de</strong> paso <strong>de</strong> mensajesMPI que proporciona dos tipos <strong>de</strong> planificación <strong>de</strong>tareas. <strong>La</strong> centralizada (WorkSharing) y <strong>de</strong>scentralizada(WorkStealing). El nodo <strong>de</strong> cómputo dispone<strong>de</strong> dos procesadores Intel Xeon E5504 a 2GHz y 8GBytes <strong>de</strong> memoria, con un total <strong>de</strong> 8 cores pornodo.<strong>La</strong> estrategia WorkSharing o centralizada dispone<strong>de</strong> una cola compartida que genera concurrecia en laobtención <strong>de</strong> tareas. <strong>La</strong> estrategia WorkStealing o<strong>de</strong>scentralizada, don<strong>de</strong> cada proceso dispone <strong>de</strong> unacola local y en caso <strong>de</strong> inanición se acce<strong>de</strong> a los procesosvecinos para la solicitud <strong>de</strong> tareas mediante unalgoritmo <strong>de</strong> polling adaptativo. El benchmark tienepor <strong>de</strong>fecto el factor <strong>de</strong> robo <strong>de</strong> tareas <strong>de</strong>finido en 20tareas por robo.En la gráfica 3 la estrategia centralizada no consiguebalancear rápidamente la carga <strong>de</strong> trabajo paraun pequeño número <strong>de</strong> cores y, sin embargo, obtieneel mejor rendimiento para el máximo número<strong>de</strong> cores. A su vez, la estrategia <strong>de</strong>scentralizada obtieneun mejor balance <strong>de</strong> carga <strong>de</strong> forma generalpara cualquier número <strong>de</strong> procesos, pero la localización<strong>de</strong> víctimas y transferencia <strong>de</strong> tareas limitasu rendimiento. Sin embargo es necesario evaluarel algoritmo para un mayor número <strong>de</strong> procesadoresy cores para <strong>de</strong>terminar la ten<strong>de</strong>ncia general <strong>de</strong> laspolíticas. Este estudio se analizará mediante simulaciónen trabajos futuros.<strong>JP2011</strong>-653


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 3. UTS scheduling. Experimento T1L con generación <strong>de</strong>102.181.082 tareasPor otra parte, ha sido posible analizar el factor<strong>de</strong> robo <strong>de</strong> tareas <strong>de</strong> la planificación <strong>de</strong> <strong>de</strong>scentralizada.Mediante la ejecución <strong>de</strong>l benchmark UTS ensu configuración OpenMP <strong>de</strong> memoria compartida,se ha evaluado el impacto <strong>de</strong> rendimiento en el ajuste<strong>de</strong>l factor <strong>de</strong> tamaño <strong>de</strong> robo <strong>de</strong> tareas. Se ha realizadouna ejecución con tamaños <strong>de</strong> número <strong>de</strong> robos<strong>de</strong> 1 a 50. En la figura 4 se muestra un <strong>de</strong>talle <strong>de</strong>lárbol T1 con la localización <strong>de</strong>l mínimo. Este valoróptimo se encuentra entre 10 y 25 para el conjunto<strong>de</strong> árboles evaluado.Fig. 4. Ejecución exhaustiva <strong>de</strong>l benchmark UTS para lai<strong>de</strong>ntificación <strong>de</strong>l tamaño óptimo <strong>de</strong> robo <strong>de</strong> tareasSin embargo, este valor <strong>de</strong> robo <strong>de</strong> tareas viene<strong>de</strong>terminado por un sistema don<strong>de</strong> las tareas tienenel mismo peso <strong>de</strong> cómputo. En trabajos futuros seevaluará un sistema don<strong>de</strong> las tareas tengan heterogeneida<strong>de</strong>n el cómputo para analizar la variabilidad<strong>de</strong>l tamaño óptimo <strong>de</strong> robo <strong>de</strong> tareas.VI. ConclusionesEn este artículo se ha propuesto una metodologíabasada en el análisis <strong>de</strong> cuellos <strong>de</strong> botella en aplicacionesOpenMP, mediante la <strong>de</strong>tección <strong>de</strong> factores <strong>de</strong>rendimiento, evaluación <strong>de</strong>l impacto y generación <strong>de</strong>un mo<strong>de</strong>lo predictivo. Se ha iniciado la metodologíaanalizando los factores <strong>de</strong> rendimiento basados en lasestrategias <strong>de</strong> planificación <strong>de</strong> iteraciones <strong>de</strong> buclesparalelos y planificación <strong>de</strong> tareas. Se ha evaluado elimpacto para las arquitecturas disponbles mediantela experimentación y se ha <strong>de</strong>terminado la necesidad<strong>de</strong> utilizar herramientas <strong>de</strong> simulación que permitiránevaular el impacto <strong>de</strong> estos factores en arquitecturasmulticore <strong>de</strong> próxima generación.Agra<strong>de</strong>cimientosEste estudio <strong>de</strong> investigación está enmarcado enel Proyecto Computación <strong>de</strong> Altas Prestaciones y suAplicación a la Ciencia e Ingeniera Computacional,financiado por el MEC (Ministerio <strong>de</strong> Educación yCiencia) con referencia TIN2007-64974.Referencias[1] Intel, “Single chip-cloud computer project,” .[2] “Tilera,” http://www.tilera.com.[3] “Next generation cuda architecture,”http://www.nvidia.com/object/fermi architecture.html.[4] “The amd fusion family of apus,” http://fusion.amd.com.[5] “Top 500 list, november 2010,”http://www.top500.org/lists/2010/11.[6] Samuel Williams et al., “Roofline: an insightful visualperformance mo<strong>de</strong>l for multicore architectures,” Commun.ACM, vol. 52, pp. 65–76, April 2009.[7] A. Duran et al., “Barcelona openmp tasks suite: A set ofbenchmarks targeting the exploitation of task parallelismin openmp,” in Parallel Processing, 2009. ICPP ’09. Int.Conf. on, sept. 2009, pp. 124 –131.[8] Christian Bienia et al., “The parsec benchmark suite:characterization and architectural implications,” in Proceedingsof the 17th Int. Conf. on Parallel architecturesand compilation techniques, USA, 2008, PACT ’08, pp.72–81, ACM.[9] D. H. Bailey et al., “The nas parallel benchmarks,” Tech.Rep., The Int. Journal of Supercomputer Applications,1991.[10] John Ashburner and Karl J. Friston, “Voxel-basedmorphometry–the methods,” NeuroImage, vol. 11, no.6, pp. 805 – 821, 2000.[11] Stephen Olivier et al., “Uts: An unbalanced tree searchbenchmark,” in <strong>La</strong>nguages and Compilers for ParallelComputing, George Almási, Calin Cascaval, and PengWu, Eds., vol. 4382 of Lecture Notes in Computer Science,pp. 235–250. Springer Berlin / Hei<strong>de</strong>lberg, 2007.[12] Greg Bronevetsky et al., “Clomp: Accurately characterizingopenmp application overheads,” in OpenMP in aNew Era of Parallelism, Rudolf Eigenmann and Bronis<strong>de</strong> Supinski, Eds., vol. 5004 of Lecture Notes in ComputerScience, pp. 13–25. Springer Berlin / Hei<strong>de</strong>lberg,2008.[13] “The epcc microbenchmarks page,”http://www.epcc.ed.ac.uk/research/openmpbench/.[14] J. Dongarra et al., “A portable programming interfacefor performance evaluation on mo<strong>de</strong>rn processors,” Int.Journal of High Performance Computing Applications14: 189, 2000.[15] Bernd Mohr et al., “Design and prototype of a performancetool interface for openmp,” The Journal of Supercomputing,vol. 23, pp. 105–128, 2001.[16] Karl Fürlinger and Michael Gerndt, “A profiling tool foropenmp,” in OpenMP Shared Memory Parallel Programming,2008, pp. 15–23.[17] Sameer S. Shen<strong>de</strong> et al., “The tau parallel performancesystem,” The Int. Journal of High Performance ComputingApplications, vol. 20, pp. 287–331, 2006.[18] Markus Geimer et al., “The scalasca performance toolsetarchitecture,” in Concurrency and Computation: Practiceand Experience, 2010, pp. 702–719.[19] Gregory Lee et al., “Dynamic binary instrumentation anddata aggregation on large scale systems,” Int. Journal ofParallel Programming, vol. 35, pp. 207–232, 2007.[20] Chi-Keung Luk et al., “Pin: building customized programanalysis tools with dynamic instrumentation,” inProcs. of the 2005 ACM SIGPLAN conf. on Programminglanguage <strong>de</strong>sign and implementation, USA, 2005,PLDI ’05, pp. 190–200, ACM.[21] Anna Morajko et al., “Mate: Dynamic performance tuningenvironment,” Euro-Par 2004 Parallel Processing,pp. 98–107, 2004.[22] J.E. Miller et al., “Graphite: A distributed parallel simulatorfor multicores,” in High Performance ComputerArchitecture (HPCA), 2010 IEEE 16th Int. Symposiumon, jan. 2010, pp. 1 –12.[23] Eduardo Argollo et al., “Cotson: infrastructure for fullsystem simulation,” SIGOPS Oper. Syst. Rev., vol. 43,pp. 52–61, January 2009.<strong>JP2011</strong>-654


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Herramientas para la monitorización <strong>de</strong> losaccesos a memoria <strong>de</strong> códigos paralelosmediante contadores hardwareOscar G. Lorenzo, Juan A. Lorenzo, Dora B. Heras, Juan C. Pichel y Francisco F. Rivera 1Resumen— En este trabajo se presenta el <strong>de</strong>sarrollo<strong>de</strong> una serie <strong>de</strong> herramientas que facilitan, especialmenteen códigos paralelos, tanto la programación <strong>de</strong>los contadores EARs (Event Address Registers) <strong>de</strong> losprocesadores Itanium 2 como el acceso y lectura <strong>de</strong> lainformación ofrecida por ellos. En concreto, se han<strong>de</strong>sarrollado las siguientes herramientas:Una herramienta que permite la inserción en unprograma paralelo <strong>de</strong>l código <strong>de</strong> monitorización y programación<strong>de</strong> los contadores hardware <strong>de</strong> una formasencilla e intuitiva. Se han realizado dos versiones,una ejecutable <strong>de</strong>s<strong>de</strong> la línea <strong>de</strong> comandos, que tomacomo entrada un programa paralelo y <strong>de</strong>vuelve comosalida el programa paralelo con el código <strong>de</strong> monitorizaciónañadido, y otra con una interfaz gráfica queaña<strong>de</strong> el código <strong>de</strong> monitorización <strong>de</strong> forma gradualsegún lo requiera el usuario.Otra herramienta que toma como entrada la informaciónobtenida por el código paralelo monitorizado,y muestra la información obtenida por los contadoreshardware <strong>de</strong> forma amigable y clara, pero a la vez exhaustivay <strong>de</strong>tallada. Esta herramienta permite ajustarel nivel <strong>de</strong> <strong>de</strong>talle, <strong>de</strong> modo que se pue<strong>de</strong> elegir<strong>de</strong>s<strong>de</strong> una vista global <strong>de</strong> los accesos a memoria, hastauna muestra <strong>de</strong>tallada evento a evento.Se ha realizado un estudio <strong>de</strong> estos <strong>de</strong>sarrollos sobrediversos problemas paralelos irregulares <strong>de</strong> memoriacompartida en el supercomputador FinisTerrae,centrándose en el producto matriz dispersa vector.Aunque el trabajo se ha realizado en el entorno <strong>de</strong>lFinisTerrae, las herramientas obtenidas son <strong>de</strong> aplicacióngeneral para cualquier otro sistema basado enprocesadores Itanium 2, que disponen <strong>de</strong> contadoreshardware, tanto mono como multiprocesador.Palabras clave— Contadores hardware, códigos irregulares,monitorización.I. IntroducciónUNO <strong>de</strong> los ámbitos don<strong>de</strong> la gestión <strong>de</strong> la memoriay el aprovechamiento <strong>de</strong> los ciclos <strong>de</strong> la CPUes más importante es el <strong>de</strong> la supercomputación.Para que un código paralelo se ejecute <strong>de</strong> forma correctay eficiente, su programación ha <strong>de</strong> ser muycuidadosa, teniendo en cuenta las características arquitectónicas,y en particular el comportamiento <strong>de</strong>los accesos a la memoria.El hecho <strong>de</strong> que el paradigma <strong>de</strong> computación enmemoria compartida esté presente extensivamente,<strong>de</strong>s<strong>de</strong> plataformas como teléfonos móviles hasta PCs,ha <strong>de</strong>terminado que librerías como OpenMP [1], quenacieron junto con los gran<strong>de</strong>s supercomputadoresmultiprocesador, sean hoy estándar en cualquier distribución.Pese a todo el cambio <strong>de</strong> paradigma <strong>de</strong>s<strong>de</strong>la programación secuencial a la paralela no es simple,y aún queda mucho por hacer.1 Grupo <strong>de</strong> Arquitectura <strong>de</strong> Computadores, Departamento<strong>de</strong> Electrónica y Computación, Univ. <strong>de</strong> Santiago <strong>de</strong>Compostela, e-mail: {oscar.garcia,juanangel.lorenzo,dora.blanco,juancarlos.pichel,ff.rivera}@usc.es,Es por todo esto que los fabricantes <strong>de</strong> microprocesadoresintegran en sus diseños <strong>de</strong> alta gama contadoreshardware (CH) [2] en aplicaciones que son utilizadaspor programadores no solamente restringidasa la caracterización <strong>de</strong>l rendimiento <strong>de</strong> los procesos.Por ejemplo, son <strong>de</strong> gran utilidad en la <strong>de</strong>puración<strong>de</strong> códigos paralelos, para encontrar aquellos puntos<strong>de</strong>l código don<strong>de</strong> el programa sobrecarga ciertasCPUs o <strong>de</strong>ja sin trabajo a otras, etc. Incluso pue<strong>de</strong>nser usados para modificar los programas en tiempo<strong>de</strong> ejecución <strong>de</strong> manera que sean más productivos[3][4].<strong>La</strong> familia <strong>de</strong> procesadores Itanium 2 ofrece untipo particular <strong>de</strong> CH <strong>de</strong>nominado EARs [2] que ofreceninformación sobre eventos asociados a los accesosa memoria a nivel <strong>de</strong> las direcciones virtuales, y enlos que se basan los incluidos en los procesadores másmo<strong>de</strong>rnos <strong>de</strong> Intel. Esta información incluye, entreotros, la presencia <strong>de</strong> fallos <strong>de</strong> TLB, fallos a diferentesniveles <strong>de</strong> memoria caché, latencias <strong>de</strong> acceso, etc,para cada dirección virtual. Esta información pue<strong>de</strong>resultar muy valiosa al programador, pero acce<strong>de</strong>ra ella resulta complejo y tedioso. En este trabajomostramos diversas herramientas que facilitan el uso<strong>de</strong> estos CH.II. Los contadores hardware en elFinisterraeEl supercomputador FinisTerrae [5] es un sistemaintegrado por nodos <strong>de</strong> memoria compartidacon una arquitectura SMP NUMA. Está compuestopor 142 nodos <strong>de</strong> computación HP Integrityrx7640 [6] con 16 núcleos Itanium Montvale y 128GB <strong>de</strong> memoria cada nodo, 1 nodo HP IntegritySuperdome, con 128 núcleos Itanium Montvale y1.024 GB <strong>de</strong> memoria, y 1 nodo HP IntegritySuperdome, con 128 núcleos Itanium 2 y 384 GB<strong>de</strong> memoria. <strong>La</strong> memoria <strong>de</strong> estos procesadoresestá compuesta por tres niveles <strong>de</strong> memoria caché.A<strong>de</strong>más, las diferentes velocida<strong>de</strong>s <strong>de</strong> acceso a lamemoria principal local frente a la remota hacen queel tiempo <strong>de</strong> acceso a los datos sea uno <strong>de</strong> los aspectosque más influye en el rendimiento <strong>de</strong> los códigosparalelos <strong>de</strong> memoria compartida, sobre todo en loscódigos que presenten accesos irregulares.El procesador Itanium2 Montvale tiene una jerarquía<strong>de</strong> memoria en tres niveles. En cada core, elprimer nivel consta <strong>de</strong> dos memorias <strong>de</strong> 16KB, unapara datos y otra para instrucciones. El nivel 2 presentauna caché L2 <strong>de</strong> 256KB <strong>de</strong>dicada únicamentea los datos, y una caché L2 <strong>de</strong> 1MB para instruc-<strong>JP2011</strong>-655


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 1.El procesador Itanium 2 Montvale.ciones. El tamaño <strong>de</strong> la caché <strong>de</strong>l tercer nivel varía<strong>de</strong>ntro <strong>de</strong> cada familia entre 1,5 MB y 24 MB. Eneste trabajo nos centramos en el nivel 1 <strong>de</strong> caché <strong>de</strong>datos, ya que en ella se producirán la mayoría <strong>de</strong> losfallos caché <strong>de</strong> datos para su posterior <strong>de</strong>tección porlos CH. <strong>La</strong> latencia mínima <strong>de</strong> un fallo en la L1 es<strong>de</strong> 5 ciclos, que se produce cuando el dato está enla L2 <strong>de</strong> caché. Mientras que si está en el nivel 3 lalatencia pasa a ser <strong>de</strong>, al menos, 14 ciclos. Los datosen punto flotante se guardan directamente en el nivel2 <strong>de</strong> caché, por lo que su lectura siempre provoca unfallo en le nivel 1. Los EAR utilizados para capturarfallos caché permiten <strong>de</strong>tectar éstos con latencias <strong>de</strong>al menos 4 ciclos, por lo que con su lectura se podrán<strong>de</strong>tectar potencialmente todos ellos.<strong>La</strong> TLB consta <strong>de</strong> dos niveles y se divi<strong>de</strong> en TLB<strong>de</strong> instrucciones y <strong>de</strong> datos. Cada TLB <strong>de</strong> nivel 2soporta 32 registros <strong>de</strong> traducción por cada procesador.<strong>La</strong> familia Itanium dispone <strong>de</strong> una PMU (PerformanceMonitoring Unit). Esencialmente consiste enuna serie <strong>de</strong> registros y contadores hardware que contieneninformación sobre lo que ocurre en la CPU durantela ejecución <strong>de</strong> instrucciones. Estos se divi<strong>de</strong>nprincipalmente en registros <strong>de</strong> configuración (PMC),que son programables y guardan información sobrelo que almacenan los otros registros, y los registros<strong>de</strong> datos o PMD, que pue<strong>de</strong>n ser leídos para obtenerinformación sobre la ejecución <strong>de</strong> las instrucciones.<strong>La</strong> PMU es un subsistema sincronizado con estadoglobal, don<strong>de</strong> todos los contadores se pue<strong>de</strong>n iniciaro <strong>de</strong>tener al mismo tiempo.<strong>La</strong> PMU pue<strong>de</strong> filtrar los eventos que captura <strong>de</strong>múltiples maneras, por ejemplo, por nivel <strong>de</strong> privilegio,por el código <strong>de</strong> la instrucción o por direcciones<strong>de</strong> memoria virtual.Los Event Address Registers (EAR) son un tipo especial<strong>de</strong> estos contadores hardware presentes en lafamilia Itanium. Obtienen información sobre las direcciones<strong>de</strong> memoria accedidas y sus latencias. LosEARs ofrecen una manera <strong>de</strong> obtener información<strong>de</strong>tallada <strong>de</strong> los fallos <strong>de</strong> caché, TLB y ALAT cuandose producen. Por cada evento capturado se guarda enlos registros <strong>de</strong> la PMU la dirección <strong>de</strong> la instrucciónque provocó el acceso a memoria, la dirección <strong>de</strong> lamemoria virtual que provocó el fallo y la latencia <strong>de</strong>la recuperación <strong>de</strong> la dirección en los fallos <strong>de</strong> L1. Elfallo en niveles superiores se <strong>de</strong>duce <strong>de</strong> su latencia<strong>de</strong> resolución. También pue<strong>de</strong> obtenerse el nivel <strong>de</strong>TLB don<strong>de</strong> se resolvió la traducción. Dentro <strong>de</strong> losfallos <strong>de</strong> TLB se pue<strong>de</strong>n <strong>de</strong>tectar fallos en cada uno<strong>de</strong> sus niveles.Los registros <strong>de</strong> la PMU pue<strong>de</strong>n configurarse manualmente.De esta manera los EARs pue<strong>de</strong>n serconfigurados para capturar tan solo los eventos <strong>de</strong>interés. Para eventos <strong>de</strong> fallo caché se pue<strong>de</strong> <strong>de</strong>finirtanto la latencia mínima <strong>de</strong> resolución <strong>de</strong>l fallo, convalores fijos <strong>de</strong>s<strong>de</strong> 4 a 4096, como el tipo <strong>de</strong> caché,si datos o instrucciones. En este trabajo nos hemoscentrado en los fallos en la caché <strong>de</strong> datos, generalmente<strong>de</strong> latencias bajas. En la práctica se <strong>de</strong>beguardar la latencia en un registro PMC e indicar alprocesador el tipo <strong>de</strong> evento consi<strong>de</strong>rado en otro diferente(entre fallos en la caché <strong>de</strong> instrucciones, falloen la caché <strong>de</strong> datos, fallo en la TLB o fallo en laALAT). Los EARs no pue<strong>de</strong>n capturan los accesos acaché que no provoquen fallo, así como los accesos <strong>de</strong>escritura. Debe tenerse en cuenta <strong>de</strong> que funcionana través <strong>de</strong> un proceso <strong>de</strong> muestreo, lo que significaque no es posible capturar sistemáticamente todoslos eventos que se producen. Es necesario indicar ala PMU el período <strong>de</strong> muestreo <strong>de</strong>seado.Para realizar la programación <strong>de</strong> las PMUs yobtener los resultados <strong>de</strong> la ejecución <strong>de</strong> los códigosse ha usado la librería libpfm2[7] y la interfaz <strong>de</strong> comunicaciónperfmon2[7]. Libpfm es una librería <strong>de</strong>ayuda que pue<strong>de</strong> ser usada para la creación <strong>de</strong> herramientas<strong>de</strong> monitorización <strong>de</strong> CPUs. <strong>La</strong> librería contienetoda la información sobre las PMU específicas<strong>de</strong> cada mo<strong>de</strong>lo <strong>de</strong> procesador, por ejemplo los nombresy códigos <strong>de</strong> los eventos y <strong>de</strong> las diferentes variables<strong>de</strong> estos. El programador tan solo tiene que indicaren las funciones lo que se quiere medir y estas<strong>de</strong>terminan el modo <strong>de</strong> programar la PMU. <strong>La</strong> in-<strong>JP2011</strong>-656


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011terfaz perfmon2 es un subsistema <strong>de</strong> monitorización<strong>de</strong>l rendimiento para Linux para obtener acceso a loscontadores, programarlos y leerlos.Esta librería soporta tanto a la familia <strong>de</strong> procesadoresItanium como las familias X86-64 y P6, asícomo a procesadores <strong>de</strong> otras marcas (AMD o ARM).<strong>La</strong> interfaz <strong>de</strong> la librería manipula eventos usando<strong>de</strong>scriptores opacos, por ejemplo enteros simples.III. Herramienta <strong>de</strong> instrumentaciónPreparar un programa paralelo para que realice lamonitorización <strong>de</strong> los EAR requiere el uso <strong>de</strong> diversasfunciones <strong>de</strong> la libpfm para encontrar los contadoresespecíficos, así como sus valores requeridos. Utilizarlos contadores hardware en un sistema paralelo presentadiversos inconvenientes, uno <strong>de</strong> los cuales es lanecesidad <strong>de</strong> trabajar con contadores presentes enlos procesadores individuales en arquitecturas quepue<strong>de</strong>n tener un gran número <strong>de</strong> ellos, lo que implicala programación <strong>de</strong> todos. Realizar las lecturasexactas que requerimos pue<strong>de</strong> ser complicado y costoso.Al ejecutar en paralelo varios hilos o procesosresulta complicado i<strong>de</strong>ntificar en qué procesador seubicarán, o incluso si no serán migrados durante laejecución.En principio el hecho <strong>de</strong> que todos los procesadoressean iguales (como ocurre en el FinisTerrae), y portanto con la misma programación, simplifica el procesoen cierta medida, ya que se pue<strong>de</strong>n programarlos EARs <strong>de</strong> la misma manera <strong>de</strong>s<strong>de</strong> cada hilo. <strong>La</strong>monitorización en sí <strong>de</strong> los otros procesadores pue<strong>de</strong>ser llevada a cabo por otro hilo. Esto complica laprogramación y seguimiento, ya que dificulta saberdon<strong>de</strong> se está ejecutando cada parte <strong>de</strong>l código. Resultamás sencillo que cada hilo se monitorice a símismo, así se pue<strong>de</strong> comprobar fácilmente qué CPUy qué hilo que realizó cada operación. Pese a todoesta auto-monitorización no está exenta <strong>de</strong> problemas.El más obvio es que el rendimiento <strong>de</strong> la aplicaciónbaja, ya que el hilo ocupa parte <strong>de</strong> su tiempoen la monitorización; sin embargo este tiempo sueleser <strong>de</strong> escasa relevancia.<strong>La</strong> herramienta <strong>de</strong>sarrollada resuelve el problema<strong>de</strong> añadir el código <strong>de</strong> monitorización necesario paratrabajar con los EAR <strong>de</strong> forma lo más automáticaposible en un programa paralelo. <strong>La</strong> automatizaciónno pue<strong>de</strong> ser total, pues el usuario <strong>de</strong>be po<strong>de</strong>r indicarel evento a capturar o el punto <strong>de</strong> inicio <strong>de</strong> lamedición en el código, pero simplifica en gran medidaesta tarea. Para cada evento se guarda la dirección<strong>de</strong> memoria cuyo acceso lo provocó, la dirección enmemoria <strong>de</strong> la instrucción cuya ejecución lo provocó,la CPU don<strong>de</strong> se produjo y el dato medido (latencia<strong>de</strong> la operación en casos <strong>de</strong> fallo caché o nivel<strong>de</strong> resolución en fallos <strong>de</strong> TLB). El código <strong>de</strong>be serañadido en unos puntos concretos <strong>de</strong>l programa amonitorizar. Esta inserción pue<strong>de</strong> dividirse en trespartes (Figura 2):• Código Previo: Este código prece<strong>de</strong> tanto a laprogramación <strong>de</strong> los contadores como a su lectura.Incluye las librerías usadas y la <strong>de</strong>finición<strong>de</strong> diversas constantes necesarias para el funcionamiento<strong>de</strong>l código en general, así como las<strong>de</strong>claraciones <strong>de</strong> variables y funciones globales(principalmente <strong>de</strong> lectura <strong>de</strong> los D-EARs) queson usadas posteriormente.• Código <strong>de</strong> Inicio: Este código prece<strong>de</strong> exactamenteal inicio <strong>de</strong> la monitorización, y <strong>de</strong>be encuadrarseen la misma sección paralela. Incluyetanto la inicialización <strong>de</strong> la librería libpfm comola programación <strong>de</strong> los contadores <strong>de</strong> cada PMU,y acaba con la or<strong>de</strong>n <strong>de</strong> inicio <strong>de</strong>l muestreo.• Código <strong>de</strong> Finalización: Este código se encarga<strong>de</strong> finalizar el muestreo, es <strong>de</strong>cir que sigue al final<strong>de</strong> la parte <strong>de</strong>l programa que se <strong>de</strong>sea medir.Se encarga también <strong>de</strong> procesar la informaciónque pueda faltar. <strong>La</strong> herramienta <strong>de</strong> instrumentalizaciónusa esta caracterización en su diseño.Fig. 2.Programa paralelo instrumentado.Se ha <strong>de</strong>sarrollado una interfaz gráfica que insertael código <strong>de</strong> monitorización <strong>de</strong>ntro <strong>de</strong>l código fuente<strong>de</strong>l programa a medir. <strong>La</strong>s razones para crear unaversión gráfica para esta herramienta son esencialmentedos. Por un lado la funcionalidad <strong>de</strong> la herramientagráfica facilita su uso por usuarios poco especializados.Por otro lado la interfaz gráfica reduce lasposibilida<strong>de</strong>s <strong>de</strong> que el usuario cometa errores. Conesta versión ya no es necesario editar el fichero fuentea modificar, pues la propia herramienta incluye uneditor <strong>de</strong> textos, pudiéndose indicar directamente enel programa los puntos don<strong>de</strong> insertar el código, yvisualizar los efectos <strong>de</strong> esa inserción.También limitala posibilidad <strong>de</strong> que el usuario introduzca argumentosinválidos para el código <strong>de</strong> libpfm, ya que estosson controlados automáticamente por la interfaz.<strong>JP2011</strong>-657


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 3.Herramienta <strong>de</strong> visualización. Histograma Detallado.<strong>La</strong> herramienta gráfica permite realizar la inserción<strong>de</strong> cada sección <strong>de</strong> código <strong>de</strong> monitorización<strong>de</strong> manera separada. De este modo cada inserción esun caso <strong>de</strong> uso, y la inserción <strong>de</strong>l código <strong>de</strong> inicio incluyela selección <strong>de</strong> argumentos. El usuario tambiénpue<strong>de</strong> abrir un fichero fuente, guardar el código resultantetras todas las modificaciones y elegir el idiomaen que funcionará la aplicación.IV. Herramienta <strong>de</strong> visualización <strong>de</strong>resultadosLos datos obtenidos por el código <strong>de</strong> monitorizaciónno resultan prácticos <strong>de</strong> estudiar directamente.En primer lugar <strong>de</strong>bido a la gran cantidad <strong>de</strong>eventos que pue<strong>de</strong>n ser capturados en una sola ejecución<strong>de</strong> un programa, y en segundo lugar porquelo realmente interesante es el conjunto <strong>de</strong> datos ensu totalidad, no cada evento en particular; <strong>de</strong> estemodo es necesario procesar la información obtenida.Los datos que se guardan <strong>de</strong> cada evento son los <strong>de</strong>dirección <strong>de</strong> memoria <strong>de</strong>l dato accedido, dirección <strong>de</strong>memoria <strong>de</strong> la instrucción, CPU en la que ocurreel evento y dato <strong>de</strong> latencia o tipo <strong>de</strong> fallo TLB.Adicionalmente, se guarda en un archivo separado elnombre <strong>de</strong>l evento estudiado, el rango <strong>de</strong> memoriadon<strong>de</strong> se capturó y el número <strong>de</strong> hilos <strong>de</strong> ejecución<strong>de</strong>l código medido. Con estos datos se pue<strong>de</strong> hacerun estudio completo <strong>de</strong> los accesos a la memoria.Para estudiarlos se pue<strong>de</strong> usar herramientas <strong>de</strong> monitorizacióny visualización y <strong>de</strong> análisis matemáticoy estadístico [8][9][10][11], como Matlab, Octave oR. Sin embargo es preferible usar una herramientamás sencilla y con menos opciones, pero más especializadaen el problema, que permita obtener unavista rápida y general <strong>de</strong> éste, a la vez que permiteentrar en más nivel <strong>de</strong> <strong>de</strong>talle. Una herramientaasí evita el uso <strong>de</strong> programas complejos y potencialmentedifíciles <strong>de</strong> manejar, mientras que su especializaciónpermite adaptar todas sus funcionalida<strong>de</strong>s alproblema en cuestión, facilitando su uso. Por ello hasido <strong>de</strong>sarrollada una herramienta <strong>de</strong> visualización<strong>de</strong> resultados.<strong>La</strong> funcionalidad principal <strong>de</strong> la herramienta es la<strong>de</strong> or<strong>de</strong>nar los eventos capturados en grupos según ladirección <strong>de</strong> memoria que los provoca, y mostrarlosconjuntamente en un histograma <strong>de</strong>limitado por lasdirecciones inicial y final <strong>de</strong>l rango <strong>de</strong> memorias estudiado.De este modo se permite al usuario obteneruna visión general y gráfica <strong>de</strong> los accesos a memoria<strong>de</strong> su programa.El histograma pue<strong>de</strong> ser refinado apetición <strong>de</strong>l usuario, por ejemplo, utilizando para sucreación tan solo los eventos provocados por cierta instruccióno CPU, o modificando el número y tamaño<strong>de</strong> los grupos, para aumentar o reducir el nivel <strong>de</strong><strong>de</strong>talle. En el caso <strong>de</strong> los eventos <strong>de</strong> fallo caché el histogramapue<strong>de</strong> mostrar las latencias medias <strong>de</strong> cadagrupo <strong>de</strong> direcciones. <strong>La</strong> herramienta lee <strong>de</strong>s<strong>de</strong> losficheros <strong>de</strong> datos los eventos procesados, y los guardaen memoria.Los histogramas que se pue<strong>de</strong>n visualizar son lossiguientes:• Histograma <strong>de</strong> Ocurrencias: Muestra el número<strong>de</strong> eventos individuales agrupados según la dirección<strong>de</strong> memoria a que hagan referencia. Enel caso <strong>de</strong> los eventos TLB se utilizan distintoscolores para cada tipo <strong>de</strong> fallo.• Histograma <strong>de</strong> <strong>La</strong>tencias: Muestra la latenciamedia <strong>de</strong> cada clase <strong>de</strong> direcciones <strong>de</strong> memoria.• Histograma General: Pue<strong>de</strong> ser <strong>de</strong> latencias o <strong>de</strong>número <strong>de</strong> ocurrencias. Muestra todo el rango<strong>de</strong> memoria, ajustando el histograma <strong>de</strong> modoque se vea entero en la ventana <strong>de</strong> la aplicación.Se pue<strong>de</strong> modificar el número <strong>de</strong> clases para hacerlomás o menos ajustado.• Histograma Detallado: Pue<strong>de</strong> ser <strong>de</strong> latenciaso <strong>de</strong> número <strong>de</strong> ocurrencias. Muestra todo el<strong>JP2011</strong>-658


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011rango <strong>de</strong> memoria, ajustando el número <strong>de</strong> direcciones<strong>de</strong> memoria por grupo. Cuando existenmuchos datos se muestra un histograma generalpequeño para mejorar la navegación (Figura3).V. Caso <strong>de</strong> estudio: Producto matrizdispersa vectorEl producto matriz dispersa vector (SpMxV), es unaoperación básica <strong>de</strong>l álgebra matricial, <strong>de</strong> especialrelevancia en aplicaciones prácticas. En métodos iterativos<strong>de</strong> resolución <strong>de</strong> gran<strong>de</strong>s sistemas <strong>de</strong> ecuaciones,el SpMxV se ejecuta en un lazo con un ciertonúmero <strong>de</strong> iteraciones, <strong>de</strong> manera que caracterizar elcomportamiento <strong>de</strong>l acceso a los datos es importantepara enten<strong>de</strong>r el rendimiento en su ejecución. <strong>La</strong>paralelización <strong>de</strong>l SpMxV es relativamente sencilla, sepue<strong>de</strong>n distribuir las filas y/o columnas <strong>de</strong> la matrizentre los procesadores. De este modo cada procesadortendrá a su cargo el cálculo <strong>de</strong> una parte <strong>de</strong>lvector resultado (Figura 4). Al trabajar con matricesdispersas las irregularida<strong>de</strong>s <strong>de</strong> los datos hacenque el reparto no resulte equitativo en cuandoal número <strong>de</strong> columnas o filas, que es el mismo paracada procesador. De este modo las CPUs con mayorcarga <strong>de</strong> trabajo provocan un mayor número <strong>de</strong> falloscaché, y se pue<strong>de</strong> caracterizar el comportamiento<strong>de</strong>l FinisTerrae usando diferentes matrices.esta manera no se capturan eventos que tengan lugaren la inicialización <strong>de</strong> los vectores o en la lectura<strong>de</strong> la matriz, por ejemplo. En este estudio se pue<strong>de</strong>ver como OpenMP reparte el trabajo entre los hilos,como la dispersión <strong>de</strong> los datos <strong>de</strong> la matriz dispersaafecta a las operaciones y como la PMU <strong>de</strong>l procesadorcaptura los eventos.Para la realización <strong>de</strong> este estudio se seleccionóun conjunto <strong>de</strong> matrices dispersas <strong>de</strong>l repositorio<strong>de</strong> MatrixMarket [12]. <strong>La</strong> selección <strong>de</strong> matrices sellevó a cabo <strong>de</strong> modo que se obtuviera un conjuntolo más variado posible. En primer lugar se limitóla selección a matrices cuadradas por simplicidad,y se <strong>de</strong>cidió escoger tres gran<strong>de</strong>s grupos en función<strong>de</strong> su tamaño. Dentro <strong>de</strong> cada uno <strong>de</strong> estos gruposse eligieron matrices tanto simétricas y asimétricas,así como matrices en banda y no en banda. Se encontrarondos matrices con distinta <strong>de</strong>nsidad <strong>de</strong> entradasdistintas <strong>de</strong> cero <strong>de</strong> cada tipo <strong>de</strong>ntro <strong>de</strong> esteespectro <strong>de</strong> posibilida<strong>de</strong>s. Dada la cantidad <strong>de</strong> datosobtenidos tan solo se mostrará aquí el estudio <strong>de</strong>talladopara dos <strong>de</strong> estas matrices.En la familia Itanium 2 las lecturas <strong>de</strong> datos enpunto flotante no pasan por el nivel 1 <strong>de</strong> las caché<strong>de</strong> datos, sino que se leen directamente <strong>de</strong>l nivel 2.De este modo, ya que el vector V (ver Figura 4)<strong>de</strong>l problema está formado por números reales, todaslas lecturas a V provocan un fallo caché con unalatencia mayor <strong>de</strong> 4 ciclos, y pue<strong>de</strong>n ser capturadaspor los EARs, estando limitado el número <strong>de</strong> accesos<strong>de</strong>tectados únicamente por el procedimiento <strong>de</strong>muestreo necesario para la lectura y escritura <strong>de</strong> estoscontadores. Nótese que los accesos al vector Vestán regidos por la indirección dada por el patrón<strong>de</strong> la matriz dispersa A, ya que en el SpMxV tan solose acce<strong>de</strong> a las posiciones <strong>de</strong> V que coincidan conelementos distintos <strong>de</strong> cero <strong>de</strong> A.Fig. 4.Reparto <strong>de</strong> la matriz dispersa entre hilos.El objetivo principal <strong>de</strong> este estudio es comprobarcómo con el uso <strong>de</strong> los contadores EAR y las herramientas<strong>de</strong>sarrolladas se pue<strong>de</strong> obtener una imagenútil <strong>de</strong>l comportamiento <strong>de</strong> los accesos a memoriacompartida <strong>de</strong> un programa paralelo. El estudioconsiste en la ejecución <strong>de</strong>l programa SpMxV con diferentenúmero <strong>de</strong> hilos y capturando en cada ejecucióneventos EAR, utilizando el código <strong>de</strong> monitorización.Nótese que no se ha pretendido sacar conclusiones<strong>de</strong>l estudio <strong>de</strong>l comportamiento obtenido, sinomostrar las capacida<strong>de</strong>s <strong>de</strong> las herramientas <strong>de</strong>sarrolladas.<strong>La</strong> captura <strong>de</strong> eventos comienza en cada casojusto antes <strong>de</strong> la operación matricial principal <strong>de</strong>lprograma, y finaliza justo en su terminación. DeEn las Figuras 5 y 6 se pue<strong>de</strong>n observar los accesos<strong>de</strong> lectura al vector V realizadas por cadahilo, mostrados con la herramienta <strong>de</strong> visualización.Cada histograma muestra el rango total <strong>de</strong> direcciones<strong>de</strong> V y cada barra el número <strong>de</strong> lecturas capturadas(ocurrencias <strong>de</strong>l evento data cache lat 4,es <strong>de</strong>cir, evento <strong>de</strong> fallo caché con latencia <strong>de</strong> resoluciónmayor <strong>de</strong> 4 ciclos) en cada clase. Estos datoshan sido obtenidos mediante la instrumentación <strong>de</strong>lcódigo SpMxV con la herramienta <strong>de</strong> instrumentalización,con un periodo <strong>de</strong> muestreo <strong>de</strong> 50. Se pu<strong>de</strong>comprobar fácilmente cómo la estructura <strong>de</strong> la matrizinfluye en la dispersión <strong>de</strong> los accesos. Ya que lamatriz bcsstk18 (Figura 5(a)) presenta un patrón enbanda, los accesos al vector V <strong>de</strong> los 4 hilos involucradosestán concentrados en posiciones diferentes. Sinembargo para la matriz psmigr 1 (Figura 6(a)), quepresenta un patrón más distribuido, se observa unreparto más uniforme entre los hilos, aunque existeuna ligera componente en banda como se aprecia enun auge <strong>de</strong> accesos en esa zona para cada hilo.<strong>JP2011</strong>-659


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011(a) Matriz bcsstk18(a) Matriz psmigr 1(b) Hilo 1 (c) Hilo 2(b) Hilo 1 (c) Hilo 2(d) Hilo 3 (e) Hilo 4Fig. 5. Fallos caché por dirección, el eje x representa el rango<strong>de</strong> memoria <strong>de</strong> V . Reparto <strong>de</strong> la matriz bcsstk18.(d) Hilo 3 (e) Hilo 4Fig. 6. Fallos caché por dirección, el eje x representa el rango<strong>de</strong> memoria <strong>de</strong> V . Reparto <strong>de</strong> la matriz psmigr 1.VI. Conclusiones<strong>La</strong>s herramientas <strong>de</strong>sarrolladas facilitan la obtencióny estudio <strong>de</strong> datos ofrecidos por los contadoresEAR <strong>de</strong> los procesadores Itanium 2. Con lainformación ofrecida por los EAR se pue<strong>de</strong>n caracterizarlos accesos a memoria durante la ejecución <strong>de</strong>un programa paralelo. El uso <strong>de</strong> las herramientas<strong>de</strong>sarrolladas exige un cierto grado <strong>de</strong> familiaridadcon el estudio <strong>de</strong> los contadores PMU para su uso,pero facilita la inserción <strong>de</strong> código, y ya que estecódigo es completamente modificable por el usuariose pue<strong>de</strong> adaptar a un buen número <strong>de</strong> sistemas, arquitecturaso problemas. <strong>La</strong> herramienta <strong>de</strong> muestra<strong>de</strong> datos simplifica el estudio estadístico <strong>de</strong> los eventoscapturados, al ofrecer las funcionalida<strong>de</strong>s más importantesrelativas al tratamiento <strong>de</strong> la informaciónobtenida por los contadores. Mediante el estudio <strong>de</strong>lSpMxV, se ha comprobado que los datos obtenidosmediante el uso <strong>de</strong> los EAR sirven para mo<strong>de</strong>lar laejecución <strong>de</strong> un programa paralelo gracias al estudio<strong>de</strong> sus accesos a memoria. Esta información esvaliosa para que el programador pueda mejorar elrendimiento <strong>de</strong> sus aplicaciones.Agra<strong>de</strong>cimientosEste trabajo ha sido parcialmente financiado por elproyecto <strong>de</strong>l MEC TIN 2010-17541, y por los proyectos<strong>de</strong> la Xunta <strong>de</strong> Galicia 2010/28 y 09TIC002CT.Así mismo, los autores agra<strong>de</strong>cen el soporte ofrecidopor el CESGA.Referencias[1] The OpenMP API specification for parallel programming,http://openmp.org.[2] download.intel.com/<strong>de</strong>sign/Itanium2/manuals/30806501.pdf,Dual-Core Update to the Intel Itanium 2 Processor ReferenceManual.[3] J. C. Pichel, D. B. Heras, J. C. Cabaleiro, and F. F.Rivera, “Increasing data reuse of sparse algebra co<strong>de</strong>son simultaneous multithreading architectures,” Concurrencyand Computation: Practice and Experience, vol.21, no. 15, pp. 1838–1856, 2009.[4] J. C. Pichel, D. E. Singh, and J. Carretero, “Reor<strong>de</strong>ringalgorithms for increasing locality on multicore processors,”in Proc. of the IEEE Int. Conf. on High PerformanceComputing and Communications, 2008, pp. 123–130.[5] Galicia Supercomputing Center, http://www.cesga.es.[6] HP Integrity rx7640 Server Quick Specs, http://h18000.www1.hp.com/products/quickspecs/12470div/12470 div.pdf.[7] Perfmon2 monitoring interface, http://perfmon2.sourceforge.net.[8] Sameer S. Shen<strong>de</strong> and Allen D. Malony, “The Tau parallelperformance system,” International Journal of HighPerformance Computing Applications, vol. 20, no. 2, pp.287–311, Summer 2006.[9] W. E. Nagel, A. Arnold, M. Weber, H.-Ch. Hoppe, andK. Solchenbach, “VAMPIR: Visualization and analysis ofmpi resources,” Supercomputer, vol. 12, pp. 69–80, 1996.[10] Jesus <strong>La</strong>barta, Sergi Girona, Vincent Pillet, Toni Cortes,and Luis Gregoris, “Dip: A parallel program <strong>de</strong>velopmentenvironment,” in Euro-Par’96 Parallel Processing,Luc Bougé, Pierre Fraigniaud, Anne Mignotte, and YvesRobert, Eds., vol. 1124 of Lecture Notes in ComputerScience, pp. 665–674. Springer Berlin / Hei<strong>de</strong>lberg, 1996,10.1007/BFb0024763.[11] Performance Application Programming Interface(PAPI), http://icl.cs.utk.edu/papi/.[12] Matrix Market, http://math.nist.gov/MatrixMarket/.<strong>JP2011</strong>-660


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Evaluación <strong>de</strong>l Benchmark Rodinia en lossistemas <strong>de</strong>l SAIILuis Cerrudo, Antonio J. Dorta, Juan J. Fumero, Carlos González, Lucas Grillo,Iván López, Francisco <strong>de</strong> San<strong>de</strong> 1Resumen— Cada vez es más frecuente el concurso <strong>de</strong>aceleradores hardware en sistemas <strong>de</strong> computación <strong>de</strong>altas prestaciones <strong>de</strong> coste medio/bajo. Para algunosproblemas el incremento <strong>de</strong> prestaciones en estetipo <strong>de</strong> sistemas heterogéneos resulta espectacular.Utilizando como base el benchmark Rodinia, eneste trabajo realizamos una amplia experienciacomputacional utilizando los sistemas <strong>de</strong> cómputo <strong>de</strong>alto rendimiento disponibles en el Servicio <strong>de</strong> ApoyoInformático a la Investigación <strong>de</strong> la ULL.Palabras clave— Rendimiento, Evaluación, Rodinia,CUDA, OpenMP, Sistemas heterogéneos, multi-coreI. Introducción<strong>La</strong> Computación <strong>de</strong> Altas Prestaciones (CAP) seencuentra en la actualidad inmersa en un rápidoproceso <strong>de</strong> cambio. El rango <strong>de</strong> arquitecturasdisponibles para altas prestaciones se ha ampliadoconsi<strong>de</strong>rablemente con la irrupción en escena <strong>de</strong>los aceleradores hardware. Aunque las GPUsson capaces hoy en día <strong>de</strong> alcanzar muy altosrendimientos y la computación <strong>de</strong> propósito generalsobre GPUs (GPGPU) está siendo estudiada <strong>de</strong>forma muy activa en la actualidad, el <strong>de</strong>sarrollo <strong>de</strong>aplicaciones para GPGPU sigue resultando una laboraltamente especializada, <strong>de</strong>bido fundamentalmentea la carencia <strong>de</strong> herramientas a<strong>de</strong>cuadas paraprogramar este tipo <strong>de</strong> arquitecturas heterogéneas.OpenCL [1] es un nuevo estándar que representaun esfuerzo para crear una interfaz común <strong>de</strong>programación para dispositivos heterogéneos. En elmomento <strong>de</strong> escribir este trabajo, el estándar aúnno ha sido ampliamente adoptado por fabricantes ni<strong>de</strong>sarrolladores.CUDA [2] es una alternativa más madura yextendida, aunque solamente soporta dispositivos<strong>de</strong> NVIDIA. CUDA permite a los <strong>de</strong>sarrolladores<strong>de</strong> aplicaciones para CAP reimplementar suscódigos utilizando GPUs. A pesar <strong>de</strong> la relativasimplicidad <strong>de</strong>l <strong>de</strong>sarrollo <strong>de</strong> aplicaciones CUDA,es difícil alcanzar el máximo rendimiento <strong>de</strong> laarquitectura <strong>de</strong>bido a los gran<strong>de</strong>s esfuerzos encodificación, <strong>de</strong>puración y optimización necesariosen este entorno.También Intel ha introducido su propio lenguaje<strong>de</strong>stinado a programar aceleradores hardware, ArBB[3]. El lenguaje permite rápidos <strong>de</strong>sarrollos SIMDy la reescritura <strong>de</strong> códigos preexistentes no resultacompleja.En el grupo <strong>de</strong> Computación <strong>de</strong> Altas Prestaciones<strong>de</strong> la ULL estamos <strong>de</strong>sarrollando yacf [?], un entorno1 Servicio <strong>de</strong> Apoyo Informático a la Investigación (SAII)<strong>Universidad</strong> <strong>de</strong> <strong>La</strong> <strong>La</strong>guna, 38271–<strong>La</strong> <strong>La</strong>guna, Spain e-mail:{saii}@ull.es<strong>de</strong> compilación fuente a fuente para el lenguaje llc[4], un lenguaje paralelo <strong>de</strong> alto nivel en el que elparalelismo se expresa mediante directivas similaresa las <strong>de</strong> OpenMP. Recientemente hemos <strong>de</strong>sarrolladoun backend para CUDA [5] en nuestro compilador yestamos trabajando en el <strong>de</strong>sarrollo <strong>de</strong> un backendpara OpenCL.Ante esta intensa actividad investigadora enla computación <strong>de</strong> altas prestaciones medianteutilización <strong>de</strong> aceleradores gráficos surgen preguntascomo: ¿qué problemas se pue<strong>de</strong>n resolver <strong>de</strong> formaeficiente y alcanzando altas prestaciones con este tipo<strong>de</strong> sistemas heterogéneos? ¿cómo han <strong>de</strong> optimizarsetanto las CPUs como los aceleradores gráficos paracolaborar <strong>de</strong> forma óptima? ¿Qué características sonnecesarias tanto en la arquitectura hardware comoen el mo<strong>de</strong>lo <strong>de</strong> programación <strong>de</strong> estos sistemas?En un intento <strong>de</strong> contribuir a clarificar estascuestiones, el grupo <strong>de</strong>l profesor Skadron <strong>de</strong> launiversidad <strong>de</strong> Virginia ha propuesto el BenchmarkRodinia [6]. En este trabajo presentamos el resultado<strong>de</strong> la evaluación <strong>de</strong> los sistemas <strong>de</strong>l SAII utilizando elbenchmark Rodinia. Los objetivos que perseguimoscon esta experimentación son varios:• Caracterizar la infraestructura computacionaldisponibles en el SAII• Hacer disponible esta información a los usuariosactuales y potenciales <strong>de</strong> los sistemas <strong>de</strong>l SAII• Incrementar nuestro conocimiento sobre lasaplicaciones que componen el benchmarkEl resto <strong>de</strong> este trabajo se organiza comosigue: la sección II presenta la suite Rodinia, conuna explicación <strong>de</strong> los códigos que componen elbenchmark. <strong>La</strong> sección III contiene una <strong>de</strong>scripción<strong>de</strong> los recursos computacionales usados, así como<strong>de</strong> la metodología que hemos seguido al realizarlos experimentos. Los resultados experimentalesobtenidos en nuestra evaluación se muestran en lasección IV. Finalmente en la seccion V presentamoslas conclusiones <strong>de</strong>l trabajo.II. El benchmark RodiniaNo es difícil encontrar benchmarks orientados aevaluar las prestaciones <strong>de</strong> aplicaciones <strong>de</strong> CAP <strong>de</strong>propósito general sobre arquitecturas basadas enCPUs. Entre los más relevantes po<strong>de</strong>mos mencionarSPEC CPU [7], EEMBC [8], SPLASH-2 [9], o Parsec[10]. El benchmark Parboil [11] representa unesfuerzo para evaluar aplicaciones sobre GPUs, perosu conjunto <strong>de</strong> tests así como su diversidad es másreducido que el <strong>de</strong> Rodinia.<strong>JP2011</strong>-661


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011En el ámbito <strong>de</strong> la evaluación <strong>de</strong> sistemasheterogéneos una característica esencial aparte<strong>de</strong> la diversidad <strong>de</strong> tests es la disponibilidad <strong>de</strong>implementaciones tanto para CPUs multi-núcleocomo para GPUs. Con estas condiciones, una <strong>de</strong>las pocas alternativas a Rodinia está representadapor el benchmark SHOC [12] que se centra en testsprogramados en OpenCL. En este trabajo hemosoptado por utilizar Rodinia <strong>de</strong>bido a que fue elprimer benchmark <strong>de</strong> estas características en estardisponible y también porque el rendimiento sobreGPUs <strong>de</strong> NVIDIA es superior utilizando CUDA queOpenCL [13], pero no <strong>de</strong>scartamos utilizar otrasalternativas en el futuro.<strong>La</strong> selección <strong>de</strong> los tests individuales quecomponen el benchmark Rodinia ha estado guiadapor la taxonomía introducida en [14], en laque el espectro <strong>de</strong> aplicaciones susceptibles <strong>de</strong>precisar CAP se caracteriza atendiendo a 13diferentes mo<strong>de</strong>los (dwarfs), cada uno <strong>de</strong> los cualesrepresenta un <strong>de</strong>terminado patrón <strong>de</strong> cómputoy comunicaciones común a toda una clase <strong>de</strong>aplicaciones relevantes. De este modo se persigueque estos 13 mo<strong>de</strong>los estén representados en elbenchmark. Aparte <strong>de</strong> la diversidad <strong>de</strong> mo<strong>de</strong>los,también se ha buscado que los tests correspondana diversos dominios <strong>de</strong> aplicación: bioinformática,minería <strong>de</strong> datos, simulaciones físicas, proceso <strong>de</strong>imágenes, reconocimiento <strong>de</strong> patrones, etc.Describimos brevemente a continuación cada uno<strong>de</strong> los tests <strong>de</strong> Rodinia que hemos utilizado ennuestros experimentos. Información adicional sobrecada uno <strong>de</strong> ellos se pue<strong>de</strong> encontrar en los propiostrabajos <strong>de</strong>l grupo <strong>de</strong>l profesor Skadron [6].Back Propagation (BP): Es un algoritmo <strong>de</strong>entrenamiento para re<strong>de</strong>s neuronales. <strong>La</strong> aplicaciónque se incorpora en el Benchmark se compone <strong>de</strong>dos etapas: la primera <strong>de</strong> ellas, Forward Phase,en la que los valores a la entrada se propaganhacia a<strong>de</strong>lante para calcular la salida y la segunda,Bacward Phase, en el que se calcula el error entre lasalida <strong>de</strong> la red y la que <strong>de</strong>bería haberse obtenido,propagándose hacia atrás.Breadth-First Search (BFS): Es un algoritmo pararecorrer o buscar elementos en un grafo, aunquefrecuentemente se usa sobre árboles. Se comienzaen la raíz (eligiendo algún nodo como elemento raízen el caso <strong>de</strong> un grafo) y se exploran todos losvecinos <strong>de</strong> este nodo. A continuación para cada uno<strong>de</strong> los vecinos se exploran sus respectivos vecinosadyacentes, y así hasta que se recorra todo el árbol.CFD: Es un algoritmo <strong>de</strong>l ámbito <strong>de</strong> la mecánica<strong>de</strong> fluidos computacional. Resuelve las ecuaciones <strong>de</strong>Euler en tres dimensiones para fluidos compresiblesen volúmenes finitos.Heartwall (HW): Es una aplicación que <strong>de</strong>tectacambios <strong>de</strong> forma <strong>de</strong> las pare<strong>de</strong>s <strong>de</strong>l corazón <strong>de</strong> unratón. Recibe como entrada un ví<strong>de</strong>o <strong>de</strong> ultrasonidos<strong>de</strong>l corazón <strong>de</strong> dicho animal y realiza múltiplesoperaciones (<strong>de</strong>tección <strong>de</strong> bor<strong>de</strong>s, transformacionesmorfológicas, filtro SRAD) para <strong>de</strong>tectar la paredinterna y externa <strong>de</strong>l corazón. Una vez <strong>de</strong>tectados,el programa sigue los cambios <strong>de</strong> las pare<strong>de</strong>s en lossucesivos frames <strong>de</strong>l ví<strong>de</strong>o.Hotspot (HS): Algoritmo que estima latemperatura en cada zona <strong>de</strong> un procesadorbasándose en su arquitectura y en medidas <strong>de</strong>potencia. <strong>La</strong> entrada <strong>de</strong>l programa son lastemperaturas y potencias iniciales y la salida es latemperatura media <strong>de</strong> cada zona <strong>de</strong>l procesador.K-means (KM): Es uno <strong>de</strong> los algoritmos nosupervisados más simples para resolver el conocidoproblema <strong>de</strong>l clustering. El objetivo es clasificar uncierto número <strong>de</strong> observaciones en un conjunto <strong>de</strong>clusters <strong>de</strong> modo que cada observación pertenezcaal cluster que tenga la media más cercana. Cada vezque se aña<strong>de</strong> un dato a un cluster se recalculan suspropieda<strong>de</strong>s y se sigue iterando hasta converger.Leukocyte (LC): Aplicación médica cuyo objetivoconsiste en <strong>de</strong>tectar y seguir la trayectoria <strong>de</strong> losleucocitos (glóbulos blancos) en un ví<strong>de</strong>o <strong>de</strong> los vasossanguíneos grabado a través <strong>de</strong> un microscopio. Enla aplicación, las células se <strong>de</strong>tectan en los primerosfotogramas <strong>de</strong>l ví<strong>de</strong>o y se siguen a través <strong>de</strong> losfotogramas posteriores.Descomposición LU (LUD): <strong>La</strong> <strong>de</strong>scomposición LUes un algoritmo para calcular las soluciones <strong>de</strong>un conjunto <strong>de</strong> ecuaciones lineales. El núcleo <strong>de</strong>lalgoritmo <strong>de</strong>scompone una matriz como producto<strong>de</strong> una matriz triangular inferior por una matriztriangular superior.Needleman-Wunsch (NW): Se trata <strong>de</strong> un método<strong>de</strong> optimización para el alineamiento <strong>de</strong> unasecuencia <strong>de</strong> ADN. Dicho alineamiento consiste enorganizar las secuencias <strong>de</strong> ADN <strong>de</strong> modo que laspartes más similares estén enfrentadas entre sí. Elalgoritmo NW es un método global (se intenta alinearla secuencia completa) basado en programacióndinámica. Se utiliza una matriz <strong>de</strong> sustituciónpara asignar puntuaciones según las coinci<strong>de</strong>nciaso diferencias entre los aminoácidos. Usando dichamatriz el algoritmo calcula el alineamiento óptimo.Particlefilter (PF): El filtro <strong>de</strong> partículas es unestimador estadístico <strong>de</strong> la posición <strong>de</strong> un objeto quese obtiene a partir <strong>de</strong> medidas <strong>de</strong> esta posición quecontienen ruido, así como <strong>de</strong> la trayectoria <strong>de</strong>l objetoen un entorno bayesiano. El PF tiene multitud <strong>de</strong>aplicaciones prácticas: seguimiento <strong>de</strong> vehículos enun ví<strong>de</strong>o o compresión <strong>de</strong> ví<strong>de</strong>o son algunas <strong>de</strong> ellas.<strong>La</strong> implementación específica que se incluye en elbenchmark está optimizada para el seguimiento <strong>de</strong>células; específicamente leucocitos y células <strong>de</strong>l tejidomiocardial.SRAD: Es un algoritmo que usando ecuaciones en<strong>de</strong>rivadas parciales trata <strong>de</strong> eliminar las manchas <strong>de</strong>una imagen tratando <strong>de</strong> preservar las característicasimportantes <strong>de</strong> la imagen. SRAD es ampliamenteutilizado en ultrasonidos y aplicaciones <strong>de</strong> imágenes<strong>de</strong> radar.Streamcluster (SC): Para un conjunto <strong>de</strong> puntos<strong>de</strong> entrada, el algoritmo genera un númeropre<strong>de</strong>terminado <strong>de</strong> grupos que cumplen que la<strong>JP2011</strong>-662


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011distancia <strong>de</strong> cada punto a su centroi<strong>de</strong> es la menor.Se trata <strong>de</strong> hacer particiones que minimicen laheterogeneidad <strong>de</strong> los datos <strong>de</strong> los que se componecada una <strong>de</strong> las particiones.En la versión original ya aparecen los tests LC,SRAD, HS, BP, NW, KM, SC, y BFS, mientras que LU, HW,CFD, y PF fueron añadidos con posterioridad [15].III. El entorno computacional<strong>La</strong> Tabla I sintetiza las características <strong>de</strong> los4 sistemas en los que se han llevado a cabo losexperimentos. tarja es un servidor Bull NovaScale4040, tajinaste es un cluster que consta <strong>de</strong>7 nodos <strong>de</strong> cómputo, cada uno <strong>de</strong> ellos con 2microprocesadores <strong>de</strong> doble núcleo, lo que haceun total <strong>de</strong> 4 núcleos por nodo, y un total <strong>de</strong> 28procesadores <strong>de</strong> cómputo. Para los experimentosen OpenMP se ha usado un único nodo <strong>de</strong>tajinaste. bejeque es un sistema <strong>de</strong> memoriacompartida con un total <strong>de</strong> 32 cores. Por últimogaroe es una estación <strong>de</strong> trabajo con 4 cores y8 threads <strong>de</strong> ejecución a la que están conectadaslas dos tarjetas gráficas cuyas características másrelevantes se muestran en la Tabla II. <strong>La</strong>s dos GPUscorrespon<strong>de</strong>n a la generación actual (Fermi) y laanterior <strong>de</strong> la línea profesional (Tesla) <strong>de</strong> NVIDIA.Para las ejecuciones en OpenMP se hanutilizado dos máquinas con procesadores Intel<strong>de</strong> 2 arquitecturas diferentes y otras dos conprocesadores AMD. Todas las ejecuciones CUDA sehan realizado en la estación garoe usando solamenteuna <strong>de</strong> las dos GPUs en cada ejecución.Característica Tesla C2050 Tesla C1060Chip T20 T10Número <strong>de</strong> núcleos 448 240Frecuencia <strong>de</strong>l núcleo 1,15 GHz 1,30 GHzMemoria 3 GB 4 GBFrecuencia <strong>de</strong> la memoria 1,5 GHz 0,8 GHzTasa <strong>de</strong> transferencia 144 GB/s 102 GB/sGFLOPs (simple) 1030 GFlop/s 933 GFlop/sGFLOPs (doble) 515 GFlop/s 78 GFlop/sConsumo 247 W 187 WTABLA IIGPUs utilizadas en los experimentosEn cuanto a los compiladores, se han utilizado lasúltimas versiones (4.3.5 y 11.0 respectivamente) <strong>de</strong>los compiladores gcc e icc en el caso <strong>de</strong> las versionessecuenciales y OpenMP <strong>de</strong> los códigos, mientras quepara la versión CUDA hemos utilizado la versión 4.0,V0.2.1221 <strong>de</strong>l compilador nvcc <strong>de</strong> NVIDIA.Para los resultados que se presentan en estetrabajo, todos los tests han sido compilados <strong>de</strong>forma uniforme utilizando las siguientes opciones <strong>de</strong>compilación:• -O3 para las versiones secuenciales <strong>de</strong> los códigos• -O3 (-fopenmp | -openmp) para las versionesOpenMP• -O3 para la versión CUDAHemos realizado experimentos adicionales probandodiferentes opciones <strong>de</strong> compilación específicas <strong>de</strong>cada arquitectura, que no se presentan en estetrabajo por razones <strong>de</strong> espacio.En cuanto a los tamaños <strong>de</strong> entrada para cadauno <strong>de</strong> los tests <strong>de</strong>l benchmark, por razones <strong>de</strong>compatibilidad <strong>de</strong> nuestros resultados con losobtenidos por los autores <strong>de</strong> Rodinia, hemosrespetado los tamaños <strong>de</strong> entrada que figuran enel benchmark tal como se <strong>de</strong>scarga <strong>de</strong> la web <strong>de</strong>Rodinia [16].IV. Resultados ExperimentalesPor razones <strong>de</strong> espacio es imposible reflejaral completo en este trabajo los resultados <strong>de</strong> laexperiencia computacional que se ha realizado. Asípues, intentaremos mostrar aquellos resultados quepuedan parecer más relevantes y que permitan sacarconclusiones sobre los experimentos.El primer tipo <strong>de</strong> experimentos que se realizaró fuela ejecución <strong>de</strong> la versión OpenMP <strong>de</strong> todos los tests<strong>de</strong>l benchmark. <strong>La</strong> Figura 1 muestra la aceleración<strong>de</strong> los tests BFS, NW, SRAD y HS compilados con gcc enbejeque. Observamos ya que nos encontramos contres patrones <strong>de</strong> comportamiento: aplicaciones comoSRAD que presentan una buena escalabilidad para elnúmero <strong>de</strong> cores seleccionado, otras como BFS que noescalan en absoluto y un tercer grupo, representadoen esta gráfica por NW y HS cuya escalabilidad eslimitada. Resultados muy similares se observaroncuando el compilador utilizado fue icc en lugar <strong>de</strong>gcc.<strong>La</strong> Figura 2 compara las aceleraciones obtenidasen tarja y tajinaste con 4 núcleos. Po<strong>de</strong>mosconcluir que las paralelizaciones en OpenMP <strong>de</strong>todos los códigos siempre resultan beneficiosas,logrando aceleraciones que en promedio po<strong>de</strong>mosestimar <strong>de</strong> un factor 1.5 para la mayoría <strong>de</strong> los tests,y alcanzando valores superiores a 3.5 para los testsmás favorables.<strong>La</strong> figura 3 muestra la aceleración obtenida concada una <strong>de</strong> las GPUs disponibles con respecto a laversión OpenMP compilada con gcc con 32 threadsejecutada en bejeque. <strong>La</strong> mejora <strong>de</strong>l rendimientoal utilizar los aceleradores hardware es para algunoscasos <strong>de</strong> un factor <strong>de</strong> 10, mientras que para otroscasos, la mejora no es tan importante. Para lamayoría <strong>de</strong> los tests, las versiones CUDA <strong>de</strong> loscódigos mejoran claramente el rendimiento. Losresultados para el compilador icc siguen un patrónsimilar, pero en este caso, el factor <strong>de</strong> mejora <strong>de</strong> lostests más beneficiados por el concurso <strong>de</strong> las GPUsllega a alcanzar un factor <strong>de</strong> 60.<strong>La</strong> Figura 4 muestra para cada uno <strong>de</strong> lostests <strong>de</strong>l benchmark y para cada una <strong>de</strong> las dosGPUs disponibles el porcentaje <strong>de</strong>l tiempo total <strong>de</strong>ejecución que se emplea en cómputo en la CPU,Entrada/Salida, transferencias <strong>de</strong> memoria entreHost y dispositivo así como el tiempo <strong>de</strong> ejecución<strong>de</strong>l kernel CUDA.En la Figura queda patente a primera vista ladiversidad <strong>de</strong> los diferentes tests. Algunos son<strong>JP2011</strong>-663


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011tarja tajinaste bejeque garoeNúmero <strong>de</strong> procesadores 4 2 8 1Núcleos por procesador 2 4 4Procesadores Intel Itanium 2 AMD OpteronProcessor 275AMD OpteronProcessor 6128Frecuencia 1.5GHz 2.2 GHz 2 GHz 2.8 GHzCaché L1 32 KB 64KB 512 KB 128 KBCaché L2 256 KB 1024MB 4096 MB 1024 MBMemoria RAM 16 GB 4 GB 129 GB 4 GBTABLA ISistemas utilizados en los experimentosIntel Core i7CPU 930Fig. 1Aceleración para 4 <strong>de</strong> los tests en su versión OpenMP compilados con gccintensivos en E/S como HS y otros en tiempo <strong>de</strong>cómputo en la GPU como LC. Esta diversidad encajacon el propósito <strong>de</strong> los autores <strong>de</strong> Rodinia a lahora <strong>de</strong> elegir los tests <strong>de</strong>l benchmark <strong>de</strong> modoque fueran representativos <strong>de</strong> una gran variedad <strong>de</strong>campos <strong>de</strong> aplicación. Sea cual sea la optimizaciónque se pretenda evaluar, habrá un test en el que,presumiblemente, ésta tendrá una gran inci<strong>de</strong>ncia.Por ejemplo, en caso <strong>de</strong> mejorarse las transferencias<strong>de</strong> memoria entre el host y la tarjeta gráfica es <strong>de</strong>esperar una mejora importante <strong>de</strong>l rendimiento <strong>de</strong>ltest HW. Sin embargo, la misma mejora apenas tendráinci<strong>de</strong>ncia en el test LUD, por ejemplo. También seobserva que el rendimiento <strong>de</strong> la nueva placa Fermies mejor que el <strong>de</strong> su antecesora en la mayoría <strong>de</strong>los tests. El porcentaje <strong>de</strong> tiempo <strong>de</strong> cómputo en laGPU se reduce en el caso <strong>de</strong> la Fermi excepto en unúnico test (SC). Sin embargo, la mejora en algunoscasos, como SRAD, PB o PF, es significativa.V. Conclusiones• Sería conveniente asegurar la posibilidad <strong>de</strong>repetición <strong>de</strong> resultados con una arquitecturaconcreta utilizando Rodinia. Para ello es precisoal menos unificar criterios en cuanto al modo enque se realiza la toma <strong>de</strong> tiempos a la hora <strong>de</strong>ejecutar un <strong>de</strong>terminado test <strong>de</strong>l benchmark.• Conectar una tarjeta gráfica a cualquier pequeñomulticomputador es una forma muy asequible<strong>de</strong> mejorar <strong>de</strong> forma sensible el rendimiento <strong>de</strong>ciertas aplicaciones paralelas. Antes <strong>de</strong> invertiresfuerzo y dinero en esta vía, es convenientecaracterizar la aplicación que preten<strong>de</strong>mosacelerar, puesto que no todas las aplicacionesson susceptibles para mejorar rendimiento eneste tipo <strong>de</strong> sistemas heterogéneos.• Un aspecto nada <strong>de</strong>s<strong>de</strong>ñable a la hora <strong>de</strong>trabajar con este tipo <strong>de</strong> sistemas heterogéneoses su falta <strong>de</strong> programabilidad. Si <strong>de</strong>sarrollarutilizando MPI u OpenMP pue<strong>de</strong>n suponer unesfuerzo para usuarios no expertos en CAP,las dificulta<strong>de</strong>s se incrementan a la hora <strong>de</strong><strong>de</strong>sarrollar, <strong>de</strong>purar y sintonizar aplicacionesprogramadas tanto en CUDA como en OpenCL.Agra<strong>de</strong>cimientosEste trabajo ha sido parcialmente subvencionadopor el la Comisión Europea a través <strong>de</strong> los fondos<strong>JP2011</strong>-664


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 2Comparativa <strong>de</strong> aceleraciones <strong>de</strong> las versiones OpenMP <strong>de</strong> cada test en tarja y tajinasteFig. 3Aceleración <strong>de</strong> las versiones CUDA en cada una <strong>de</strong> las GPUs con respecto a la versión OpenMP con 32 núcleosen bejeque<strong>JP2011</strong>-665


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Fig. 4Caracterización <strong>de</strong>l tiempo <strong>de</strong> ejecución <strong>de</strong> la versión CUDA <strong>de</strong> cada test en la Tesla C1060 (izquierda) y TeslaC2050 (<strong>de</strong>recha).FEDER y <strong>de</strong>l Plan Nacional <strong>de</strong> I+D+I <strong>de</strong>l MEC,(TIN2008-06570-C04-03).Referencias[1] Khronos Group, “OpenCL the open standard for parallelprogramming of heterogeneous systems,” 2008.[2] John Nickolls, Ian Buck, Michael Garland, and KevinSkadron, “Scalable parallel programming with CUDA,”Queue, vol. 6, no. 2, pp. 40–53, 2008.[3] Intel, “Sophisticated library for vector parallelism: Intelarray building blocks,” 2010.[4] A. J. Dorta, P. López, and F. <strong>de</strong> San<strong>de</strong>, “Basic skeletonsin llc,” Parallel Computing, vol. 32, no. 7–8, pp. 491–506, sep 2006.[5] Ruymán Reyes and F. <strong>de</strong> San<strong>de</strong>, “Automaticco<strong>de</strong> generation for gpus in llc,” The Journal ofSupercomputing, 2011.[6] Shuai Che, Michael Boyer, Jiayuan Meng, DavidTarjan, Jeremy W. Sheaffer, Sang-ha Lee, and KevinSkadron, “Rodinia: A benchmark suite for heterogeneouscomputing,” in IEEE International Symposium onWorkload Characterization, Oct. 2009.[7] The Standard Performance Evaluation Corporation(SPEC), “SPEC Home Page,” 2011,http://www.spec.org.[8] Embed<strong>de</strong>d Microprocessor Benchmark Consortium,“EEMBC Home Page,” 2011, http://www.eembc.org/.[9] Steven Cameron Woo, Moriyoshi Ohara, Evan Torrie,Jaswin<strong>de</strong>r Pal Singh, and Anoop Gupta, “The SPLASH-2 programs: characterization and methodologicalconsi<strong>de</strong>rations,” SIGARCH Comput. Archit. News, vol.23, pp. 24–36, May 1995.[10] Christian Bienia, Sanjeev Kumar, Jaswin<strong>de</strong>r Pal Singh,and Kai Li, “The PARSEC benchmark suite:characterization and architectural implications,” inProceedings of the 17th international conference onParallel architectures and compilation techniques, NewYork, NY, USA, 2008, PACT ’08, pp. 72–81, ACM.[11] “The Parboil benchmark suite Home Page,” 2011,http://impact.crhc.illinois.edu/parboil.php.[12] Anthony Danalis, Gabriel Marin, Collin McCurdy,Jeremy S. Meredith, Philip C. Roth, Kyle Spafford,Vinod Tipparaju, and Jeffrey S. Vetter, “The scalableheterogeneous computing (shoc) benchmark suite,” inArchitectural Support for Programming <strong>La</strong>nguages andOperating Systems, 2010, pp. 63–74.[13] Kazuhiko Komatsu, Katsuto Sato, Yusuke Arai, KentaroKoyama, Hiroyuki Takizawa, and Hiroaki Kobayashi,“Evaluating performance and portability of openclprograms,” in The Fifth International Workshop onAutomatic Performance Tuning, June 2010.[14] Krste Asanovic, Ras Bodik, Bryan ChristopherCatanzaro, Joseph James Gebis, Parry Husbands,Kurt Keutzer, David A. Patterson, William LesterPlishker, John Shalf, Samuel Webb Williams, andKatherine A. Yelick, “The landscape of parallelcomputing research: A view from Berkeley,” Tech. Rep.UCB/EECS-2006-183, EECS Department, University ofCalifornia, Berkeley, Dec 2006.[15] Shuai Che, Jeremy W. Sheaffer, Michael Boyer,Lukasz G. Szafaryn, Liang Wang, and Kevin Skadron,“A characterization of the rodinia benchmark suitewith comparison to contemporary cmp workloads,” inProceedings of the IEEE International Symposium onWorkload Characterization (IISWC’10), Washington,DC, USA, 2010, IISWC ’10, pp. 1–11, IEEE ComputerSociety.[16] “The Rodinia benchmark suite Home Page,” 2011,http://lava.cs.virginia.edu/Rodinia/.<strong>JP2011</strong>-666


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Computación <strong>de</strong> altas prestaciones sobre arquitecturasparalelas heterogéneas<strong>JP2011</strong>-667


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-668


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Algoritmos eficientes para la transformadawavelet discreta en multicores y GPUsV. Galiano, O. López, M.P. Malumbres y H. Migallón 1Resumen— En este trabajo se analiza el comportamiento<strong>de</strong>l rendimiento para un conjunto <strong>de</strong> algoritmosutilizados en el cálculo <strong>de</strong> la transformada waveletdiscreta 2D (2D-DWT) utilizando tanto OpenMP sobreplataformas <strong>de</strong> memoria compartida o multinúcleo,como CUDA (Compute Unified Device Architecture)sobre GPUs (Graphics Processing Unit). Losalgoritmos propuestos se basan en el uso <strong>de</strong> filtros <strong>de</strong>convolución y en la transformada lifting. A<strong>de</strong>más, secompara el rendimiento obtenido por nuestros algoritmosfrente al reciente algoritmo SMDWT (SymmetricMask-based Wavelet Transform) en plataformas<strong>de</strong> memoria compartida; y frente a algoritmos basadosen las propuestas <strong>de</strong> la SDK <strong>de</strong> CUDA cuando seusa una GPU como plataforma <strong>de</strong> computación.Palabras clave— CUDA, OpenMP, transformadawavelet, codificación <strong>de</strong> imagen, algoritmos paralelosIntroducciónDurante la última década, se ha profundizadoen diferentes algoritmos <strong>de</strong> compresión <strong>de</strong> imágenespara evitar las conocidas limitaciones <strong>de</strong> los algoritmosbasados en bloques tales como la DCT [1](transformada discreta <strong>de</strong>l coseno), siendo ésta latécnica <strong>de</strong> compresión más utilizada hasta el momento.Algunas <strong>de</strong> las alternativas propuestas estánbasadas en técnicas más complejas como la codificaciónfractal o la cuantización vectorial, mientrasotras simplemente proponen el uso <strong>de</strong> una transformadamatemática diferente y más flexible. <strong>La</strong> transformadaDWT (transformada discreta wavelet) se haconsolidado como una herramienta muy potente parala compresión <strong>de</strong> imágenes y un gran número <strong>de</strong> codificadores<strong>de</strong> imágenes actuales, incluyendo el estándarJPEG2000, utilizan esta transformada en susalgoritmos (ver por ejemplo [2], [3]).Sin embargo, a pesar <strong>de</strong> los beneficios implícitos<strong>de</strong>l uso <strong>de</strong> la transformada wavelet, se presentannuevos problemas relacionados tanto con el incremento<strong>de</strong> la complejidad, como con el acceso intensivoa memoria, lo que conlleva un incremento enlos tiempos <strong>de</strong> ejecución. De hecho, en la implementaciónclásica <strong>de</strong> la transformada DWT [4], la<strong>de</strong>scomposición <strong>de</strong> la imagen se realiza mediante unfiltrado convolucional, cuya complejidad aumenta enfunción <strong>de</strong> la longitud <strong>de</strong>l filtro utilizado. A<strong>de</strong>más,en el cálculo <strong>de</strong> la transformada DWT, para cadanivel <strong>de</strong> <strong>de</strong>scomposición se realizan dos pasadas a laimagen, una por filas y otra por columnas, por lo quees necesario almacenar toda la imagen en memoria.Por otra parte, en la transformada DCT, al realizarsepor bloques, el requisito <strong>de</strong> memoria no es unproblema incluso para imágenes <strong>de</strong> gran tamaño.1 Dpto. Física y Arquitectura <strong>de</strong> Computadores,Univ. Miguel Hernán<strong>de</strong>z, e-mail:{vgaliano,otoniel,mels,hmigallon}@umh.esEl esquema lifting [5], [6] es, probablemente, elalgoritmo más estudiado para realizar un cálculo eficiente<strong>de</strong> la transformada wavelet. Dicho algoritmoutiliza menos coeficientes en los filtros, proporcionandouna implementación más rápida <strong>de</strong> la transformada.A<strong>de</strong>más, este esquema reduce la memorianecesaria, ya que los coeficientes wavelet calculadosson almacenados en la matriz <strong>de</strong> datos original, evitando<strong>de</strong> esta manera la necesidad <strong>de</strong> otra matrizpara almacenar dichos coeficientes wavelet. Hay quetener en cuenta que los coeficientes wavelet calculados<strong>de</strong>ben almacenarse en posiciones separadas <strong>de</strong>ntro<strong>de</strong> la matriz <strong>de</strong> datos, las bajas frecuencias por unlado y las altas por otro, este reor<strong>de</strong>namiento <strong>de</strong> coeficientesproduce conflictos en el uso <strong>de</strong> la memoriacaché. Por otra parte, se han propuesto otros algoritmospara el cálculo <strong>de</strong> la transformada waveletcon el fin <strong>de</strong> reducir los requisitos <strong>de</strong> memoria, comopor ejemplo los algoritmos basados en bloques [7] olos basados en línea [8]. Estas propuestas aumentanla flexibilidad <strong>de</strong>l algoritmo para imágenes <strong>de</strong> grantamaño y reducen los requisitos <strong>de</strong> memoria. Recientemente,en [9], los autores presentan un nuevométodo <strong>de</strong>nominado Symmetric Mask-based DiscreteWavelet Transform (SMDWT). Este algoritmo realizael cálculo <strong>de</strong> la transformada como si se tratase<strong>de</strong> una convolución matricial, <strong>de</strong> manera que utilizacuatro matrices, una para cada subbanda (LL, HL,LH y HH), con la intención <strong>de</strong> reducir los cálculosrepetitivos necesarios en el algoritmo tradicional. Eneste esquema, la transformada 2D-DWT se realiza enuna sola pasada. A<strong>de</strong>más, este algoritmo permite elcálculo in<strong>de</strong>pendiente <strong>de</strong> una única subbanda.En el diseño <strong>de</strong> codificadores <strong>de</strong> imagen y ví<strong>de</strong>obasados en la transformada wavelet, una <strong>de</strong> las tareascomputacionalmente más costosa es la transformadawavelet puesto que suele emplear entre el 30%y el 50% <strong>de</strong>l tiempo total <strong>de</strong> codificación (<strong>de</strong>pendiendo<strong>de</strong>l tamaño <strong>de</strong> la imagen y <strong>de</strong>l número <strong>de</strong>niveles <strong>de</strong> <strong>de</strong>composición wavelet). Por lo tanto, esvital reducir el tiempo <strong>de</strong> cálculo <strong>de</strong> la transformada2D-DWT <strong>de</strong>sarrollando codificadores eficientes queaprovechen recursos computacionales disponibles encada computador. En este sentido, la mayor parte <strong>de</strong>computadores actuales incluyen procesadores multinúcleo<strong>de</strong> manera que un algoritmo eficiente <strong>de</strong>bepo<strong>de</strong>r aprovechar la capacidad <strong>de</strong> cálculo en paraleloutilizando simultáneamente varios o todos los núcleos<strong>de</strong> dichos procesadores. Por otro lado, las GPUs seencuentran cada vez más presentes en los equipos<strong>de</strong> consumo, por lo que también <strong>de</strong>ben consi<strong>de</strong>rarsepara aprovecharlas como plataformas <strong>de</strong> cómputo.En este artículo, realizaremos unas optimizaciones<strong>JP2011</strong>-669


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011para el cálculo en paralelo sobre los métodos <strong>de</strong>scritosen [4] y [5]. Nuestro principal objetivo esla optimización <strong>de</strong>l uso <strong>de</strong> la memoria y la mejora<strong>de</strong>l rendimiento mediante la utilización <strong>de</strong> arquitecturasmultinúcleo, es <strong>de</strong>cir utilizando plataformas <strong>de</strong>memoria compartida. A<strong>de</strong>más, se diseñarán para suejecución en GPUs mediante CUDA, los mismos algoritmos<strong>de</strong>sarrollados para arquitecturas multinúcleo.Hay que remarcar que los algoritmos <strong>de</strong>sarrolladospara GPUs requieren <strong>de</strong> un uso eficiente <strong>de</strong>la memoria, en particular los algoritmos diseñadosse basan en el uso <strong>de</strong> la memoria compartida <strong>de</strong> laGPU. A<strong>de</strong>más, se presentarán nuevos métodos basadosen las propuestas incluidas en [10], comparándolostanto a nivel <strong>de</strong> rendimiento como a nivel <strong>de</strong>requisitos <strong>de</strong> memoria.I. Transformada Discreta Wavelet (DWT)<strong>La</strong> transformada DWT obtiene un esquema <strong>de</strong><strong>de</strong>scomposición multirresolución para señales <strong>de</strong> entrada.<strong>La</strong> señal original se transforma inicialmenteen dos subbandas <strong>de</strong> frecuencia (bajas y altas frecuencias).En la transformada clásica, la <strong>de</strong>scomposiciónse realiza mediante un filtro digital pasobajo H y un filtro digital paso alto G. Ambos filtrosse diseñan utilizando la función <strong>de</strong> escalado Φ(t) ylos correspondientes coeficientes wavelet Ψ(t). El algoritmoreduce el nivel <strong>de</strong> muestras <strong>de</strong> la señal a lamitad. En filtros FIR no recursivos y con longitudL, la función <strong>de</strong> transferencia <strong>de</strong> H y G se pue<strong>de</strong>representar <strong>de</strong>l siguiente modo:H(z) = h 0 + h 1 z −1 + h 2 z −2 + h 3 z −3 (1)G(z) = g 0 + g 1 z −1 + g 2 z −2 + g 3 z −3 (2)A. Transformada Wavelet Lifting (LDWT)Uno <strong>de</strong> los inconvenientes <strong>de</strong> la DWT es el incremento<strong>de</strong> los requisitos <strong>de</strong> memoria <strong>de</strong>bido a su algoritmobasado en la convolución <strong>de</strong> filtros. Una propuestaque reduce el tamaño <strong>de</strong> memoria necesariaen el cálculo <strong>de</strong> la transformada es el esquema lifting[5]. El principal beneficio en este esquema es lareducción <strong>de</strong>l número <strong>de</strong> operaciones necesarias pararealizar la transformada wavelet, comparándolo conel algoritmo convolucional clásico. El or<strong>de</strong>n <strong>de</strong> reducciónen el esquema lifting <strong>de</strong>pen<strong>de</strong> <strong>de</strong>l tipo <strong>de</strong>transformada wavelet a realizar, tal y como se indicaen [11].En el esquema clásico, el procesado in-situ <strong>de</strong> losdatos no es posible ya que cada muestra original senecesita para el cálculo <strong>de</strong> los coeficientes en sus vecinos.Por lo tanto, se necesita una nueva matriz paraalmacenar los coeficientes resultantes, duplicando, <strong>de</strong>esta manera, los requisitos <strong>de</strong> memoria. No obstante,en el esquema lifting se implementa una computaciónin-situ sin necesidad <strong>de</strong> memoria adicional alguna.A<strong>de</strong>más, el esquema lifting se pue<strong>de</strong> ejecutar sobreun número impar <strong>de</strong> muestras mientras que en elalgoritmo clásico se necesita <strong>de</strong> un número par <strong>de</strong>muestras.Usaremos el algoritmo euclí<strong>de</strong>o para factorizar lamatriz en varias fases mediante una secuencia alternativa<strong>de</strong> matrices triangulares superiores e inferiores.En (3), las variables h(z) y g(z) representan lainversa <strong>de</strong> los filtros paso bajo y paso alto respectivamente.Dichos filtros se divi<strong>de</strong>n en una parte impary otra par para generar una matriz P (z), como semuestra en (4).g (z) = g e(z2 ) + z −1 g o(z2 )h (z) = h e(z2 ) + z −1 g o(z2 ) (3)( )he (z) gP (z) =e (z)h o (z) g o (z)(4)Mediante el algoritmo euclí<strong>de</strong>o, <strong>de</strong> manera recursiva,encontraremos los máximos comunes divisores<strong>de</strong> la parte par e impar <strong>de</strong> los filtros originales. Deeste modo, h(z) y g(z) forman un filtro complementarioque se pue<strong>de</strong> factorizar en tres pasos tal y comose muestra a continuación,P (z) =m∏i=1(1 si (z)0 1) (1 0t i (z) 1) ( )k 0(5)0 1/kdon<strong>de</strong> s i (z) y t i (z) representan los polinomios <strong>de</strong><strong>La</strong>urent correspondientes a los pasos <strong>de</strong> predicción yactualización respectivamente, y k es una constantedistinta <strong>de</strong> cero.El proceso completo consiste en una primera transformaciónaproximada, uno o más pasos <strong>de</strong> prediccióny una posterior actualización y normalización<strong>de</strong> los coeficientes. En la primera transformación,las muestras <strong>de</strong> entrada se divi<strong>de</strong>n en dos conjuntos<strong>de</strong> datos, las muestras pares y las impares. Deeste modo, si consi<strong>de</strong>ramos {X i } = {Φ n,p } como lasmuestras <strong>de</strong> entrada en el nivel <strong>de</strong> <strong>de</strong>scomposición n,<strong>de</strong>finimos:{s0i}= {X2i }{d0i}= {X2i+1 }(6)Por tanto, en un paso <strong>de</strong> predicción, cada muestraen { }d 0 i se reemplaza por el error cometido en lapredicción { } <strong>de</strong> esa muestra con respecto a las muestrass0i :d 1 i = d 0 i − P ({ s 0 })i(7)mientras que en el paso <strong>de</strong> actualización, cada muestraen { s 0 i}se actualiza por{d1i}:s 1 i = s 0 i + U ({ d 1 })i(8)Después <strong>de</strong> m sucesivos pasos <strong>de</strong> actualización ypredicción, se obtienen los coeficientes <strong>de</strong> escaladoy wavelet <strong>de</strong>l siguiente modo:{Φ n+1,p } = K 0 × {s m i }{Ψ n+1,p } = K 1 × {d m i }(9)Un caso especial <strong>de</strong> filtro wavelet es el filtroDaubechies 9/7. Este filtro se utiliza frecuentemente<strong>JP2011</strong>-670


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011en compresión <strong>de</strong> imagen (ver por ejemplo [3], [12]),y se ha incluido en el estándar JPEG2000 [2]. Eneste trabajo, todos los algoritmos <strong>de</strong>sarrollados paracálculo <strong>de</strong> la transformada DWT utilizan este filtro.Los coeficientes <strong>de</strong> los filtros <strong>de</strong> <strong>de</strong>scomposiciónDaubechies 9/7 h[n] y g[n] son:h [n] = 0.026749, −0.016864, −0.078223, 0.266864, 0.602949,0.266864, −0.078223, −0.016864, 0.026749g [n] = 0.091272, −0.057544, −0.591272, 1.115087,− 0.591272, −0.057544, 0.091272,mientras que la <strong>de</strong>scomposición basada en lifting resulta:( ( ) ) ()1 α 1 + z−11 0P (z) =0 1 β (1 + z) 1( ( ) ) () ( )1 γ 1 + z−11 0 ζ 00 1 δ (1 + z) 1 0 1/ζ(10)don<strong>de</strong> α = −1.586134342, β = −0.052980118, γ =0.882911075, δ = 0.443506852 y ζ = 1.230174105.B. Symmetric Mask-based Wavelet Transform(SMDWT)En [9], los autores presentan una novedosa forma<strong>de</strong> calcular la transformada wavelet tratando <strong>de</strong> reducirla complejidad computacional. <strong>La</strong> transformadaSMDWT se realiza mediante una convoluciónmatricial utilizando cuatro matrices <strong>de</strong>rivadas <strong>de</strong>l filtroDaubechies 9/7 con coeficientes en coma flotante.En el esquema lifting 2D LDWT se requiere <strong>de</strong> uncálculo en sentido vertical y otro en sentido horizontal,y para cada uno <strong>de</strong> estos cálculos se <strong>de</strong>benrealizar cuatro pasos: división, predicción, actualizacióny escalado. Por el contrario, las cuatro bandasen la transformada 2D SMDWT se pue<strong>de</strong>n obtener<strong>de</strong> forma in<strong>de</strong>pendiente mediante cuatro matrices <strong>de</strong>tamaños 7 × 7, 7 × 9, 9 × 7 y 9 × 9 en el caso <strong>de</strong>l filtroDaubechies 9/7.II. Transformada Wavelet multinúcleoHemos utilizado la convolución basada en el filtroDaubechies 9/7 con el objetivo <strong>de</strong> <strong>de</strong>sarrollar unacomputación <strong>de</strong> la transformada 2D-DWT propuestaen [4] <strong>de</strong> forma paralela y optimizada. Por otrolado, hemos utilizado el algoritmo lifting propuestopor Swel<strong>de</strong>ns en [5], para optimizar la transformadalifting (2D-LWT).En los filtros basados en la convolución,necesitaremos un espacio <strong>de</strong> memoria adicionalpara almacenar la fila o columna <strong>de</strong> la actualconvolución, mientras que en la transformada liftingnecesitaremos un espacio <strong>de</strong> memoria adicionalpara almacenar una fila y una columna. Debemos<strong>de</strong>stacar que el algoritmo SMDWT requiere el doble<strong>de</strong>l tamaño <strong>de</strong> la imagen.Hemos utilizado OpenMP [13] como herramienta<strong>de</strong> <strong>de</strong>sarrollo <strong>de</strong> algoritmos paralelos en arquitecturasmultinúcleo. <strong>La</strong> plataforma multinúcleo utilizada esun Intel Core 2 Quad Q6600 2.4 GHz, con 4 núcleos,Tamaño Número Tamaño extra <strong>de</strong> memoria<strong>de</strong> imagen <strong>de</strong> núcleos Conv. Lifting1 520 1024512×512 2 1040 20484 2080 40961 2056 40962048×2048 2 4112 81924 8224 163841 4104 81924096×4096 2 8208 163844 16416 32768TABLA INúmero <strong>de</strong> píxeles en memoria necesarios utilizandofiltros <strong>de</strong> cuatro “taps”.<strong>de</strong>nominado SULLI. Cada proceso calcula la transformadawavelet <strong>de</strong> un bloque <strong>de</strong> filas y <strong>de</strong> un bloque<strong>de</strong> columnas, hay que tener en cuenta que se creantantos procesos como núcleos hay disponibles. Portanto, cada proceso (o núcleo) requiere un extra <strong>de</strong>memoria para realizar la transformada, lógicamenteel tamaño total <strong>de</strong> memoria adicional necesaria aumentaal aumentar el número <strong>de</strong> núcleos utilizados.Debemos <strong>de</strong>stacar que el resultado <strong>de</strong> los coeficienteswavelet se pue<strong>de</strong> almacenar en el espacio <strong>de</strong> memoriaocupada por la imagen original, evitando, <strong>de</strong> estemodo, duplicar los requisitos <strong>de</strong> memoria. <strong>La</strong> Tabla Imuestra la memoria adicional en píxeles utilizada porcada uno <strong>de</strong> los algoritmos <strong>de</strong>pendiendo <strong>de</strong>l número<strong>de</strong> núcleos utilizados. El peor caso se da para imágenespequeñas que, no obstante, requieren menos<strong>de</strong>l 2% <strong>de</strong> memoria adicional, siendo para el resto <strong>de</strong>casos inferior al 1%. Hay que remarcar que la memoriaadicional necesaria en el algoritmo SMDWT esel tamaño <strong>de</strong> la imagen. Los datos mostrados enla Tabla I ilustran una imagen con niveles <strong>de</strong> grisesrepresentados mediante coma flotante.El sistema operativo <strong>de</strong> SULLI es Ubuntu 9.04(Jaunty Jackalope) para sistemas <strong>de</strong> 64 bits. Hemosutilizado el compilador GNU gcc incluido en gcc4.3.3, las opciones <strong>de</strong> compilación utilizadas paraarquitecturas multinúcleo han sido “-O3 -m64 -fopenmp”. Para CUDA el compilador utilizado esnvcc incluido en el CUDA Toolkit 3.2 RC, siendo lasopciones <strong>de</strong> compilación utilizadas “-O3 -m64”.Hemos adaptado los algoritmos para obtener elmejor rendimiento en arquitecturas multinúcleo, teniendoen cuenta que estos algoritmos realizan unuso intensivo <strong>de</strong> memoria. En la figura 1 se muestranlos tiempos <strong>de</strong> cálculo necesarios para obtenerla transformada wavelet mediante convolución y liftingpara imágenes <strong>de</strong> diferentes tamaños: 512 × 512,2048 × 2048, y 4096 × 4096. No obstante, el cuello<strong>de</strong> botella en el acceso a memoria provoca pérdidas<strong>de</strong> eficiencia en el cálculo, ya que para imágenes pequeñasel cómputo asociado a cada fila y a cadacolumna es muy pequeño. Sin embargo, con imágenesgran<strong>de</strong>s se obtienen eficiencias casi i<strong>de</strong>ales parael caso <strong>de</strong> 2 núcleos y muy buenas en el caso <strong>de</strong> 4 núcleos.A<strong>de</strong>más, hemos comparado nuestros algoritmoscon la reciente propuesta para el cálculo <strong>de</strong> la<strong>JP2011</strong>-671


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011(a) Convolución(a) 2 Núcleos(b) LiftingFig. 1. Tiempo <strong>de</strong> computación <strong>de</strong> los algoritmos convolucióny lifting para arquitecturas multinúcleo.(b) 4 NúcleosFig. 2. Comparación entre los algoritmos basados en laconvolución y en la transformada lifting y el algoritmoSMDWT.DWT, <strong>de</strong>nominada “Symmetric Mask-based DWT”(SMDWT), introducida en [9] y que propone un enfoquenovedoso. Hemos <strong>de</strong>sarrollado el método <strong>de</strong>scritoen [9] y a<strong>de</strong>más, hemos paralelizado dicho algoritmo.En la figura 2 mostramos una comparación<strong>de</strong> los tiempos <strong>de</strong> cálculo para los algoritmos <strong>de</strong>convolución, lifting y SMDWT utilizando 2 y 4 núcleos.Como se pue<strong>de</strong> observar, nuestros algoritmos,tanto el basado en la convolución como el basado enla transformada lifting, presentan mejor rendimientoque el algoritmo SMDWT, obteniendo un factor <strong>de</strong>mejora <strong>de</strong> hasta 2, 5. Hay que remarcar, que los autoresen [9] proponen el algoritmo SMDWT tantopara reducir la complejidad computacional como porla capacidad <strong>de</strong> dicho algoritmo para obtener <strong>de</strong>forma in<strong>de</strong>pendiente cualquiera <strong>de</strong> las cuatro subbandas(LL, LH, HL o HH).Algunas aplicaciones requieren únicamente <strong>de</strong>l cálculo<strong>de</strong> la subbanda LL. En la figura 3 presentamosla misma comparación que en la figura 2 pero calculandoúnicamente la subbanda LL cuando se utilizael algoritmo SMDWT. Hay que remarcar que el comportamiento<strong>de</strong> nuestros algoritmos computando lascuatro subbandas es similar al comportamiento <strong>de</strong>lalgoritmo SMDWT computando únicamente la subbandaLL.III. Transformada Wavelet basada en GPUsEn las secciones anteriores hemos comprobadoque los algoritmos <strong>de</strong>sarrollados para plataformas <strong>de</strong>memoria compartida que calculan la transformada2D DWT obtienen buenos rendimientos. A continuación,nos preguntamos en esta sección si se pue<strong>de</strong>mejorar ese rendimiento con otro tipo <strong>de</strong> arquitectura,en particular con el uso <strong>de</strong> GPUs. Los procesadoresgráficos (GPU) están basados en un con-junto <strong>de</strong> unida<strong>de</strong>s multinúcleo llamadas multiprocesadores<strong>de</strong> streaming (SM) que contienen cada una<strong>de</strong> ellas un conjunto <strong>de</strong> procesadores <strong>de</strong> streaming(SP). CUDA es un mo<strong>de</strong>lo <strong>de</strong> computación heterogéneoque involucra tanto a la CPU como a la GPU.En la programación paralela con CUDA [14], [15],una aplicación consiste en un programa secuencial,ejecutado en el procesador host, que pue<strong>de</strong> ejecutarprogramas, conocidos como kernels, en el dispositivoparalelo, es <strong>de</strong>cir en la GPU. A<strong>de</strong>más, el procesadorhost pue<strong>de</strong> ser un sistema multinúcleo ejecutandocódigos paralelos, aunque en este caso únicamenteuno <strong>de</strong> los núcleos podrá realizar llamadas a los kernel<strong>de</strong> la GPU, o más específicamente las llamadas alos kernels <strong>de</strong>ben serializarse. Un kernel es un programaSPMD (Single Program Multiple Data) quese ejecuta con un número elevado <strong>de</strong> hilos o threads.Cada hilo ejecuta el mismo programa secuencial. Elprogramador organiza los hilos en una malla <strong>de</strong> bloques<strong>de</strong> hilos. Los hilos <strong>de</strong> un bloque <strong>de</strong>terminadopue<strong>de</strong>n colaborar entre ellos mediante mecanismos<strong>de</strong> sincronización y mediante los diferentes niveles<strong>de</strong> memoria <strong>de</strong> los que dispone una GPU: la memoriaglobal, que es la <strong>de</strong> mayor latencia; la memoriaconstante <strong>de</strong> sólo lectura; la memoria <strong>de</strong> texturas;la memoria compartida; y los registros. <strong>La</strong> memoriacompartida es visible por todos los hilos <strong>de</strong> unbloque, mientras que los registros son propios <strong>de</strong> cadahilo. Hay que tener en cuenta que CUDA no proporcionamecanismos globales <strong>de</strong> sincronización.Con el objetivo <strong>de</strong> implementar el algoritmobasado en la convolución presentado en la sección IIsobre una GPU, <strong>de</strong>bemos tener en cuenta que el elementoclave es la memoria compartida. Usaremosesta memoria compartida para almacenar la copia<strong>de</strong> datos <strong>de</strong> la fila o la columna con la que estén<strong>JP2011</strong>-672


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Ancho / (M+1) BloquesApronApronA Ap pr ro on nA Ap pr ro on nA Ap pr ro on nA Ap pr ro on nApronApronA Ap pr ro on nA Ap pr ro on nA Ap pr ro on nA Ap pr ro on nAlto Bloques(a) 2 NúcleosM cols44(a) Convolución por filasAncho BloquesApronApron(b) 4 NúcleosFig. 3. Comparación entre los algoritmos basados en la convolucióny en la transformada lifting y el cálculo <strong>de</strong> lasubbanda LL con el algoritmo SMDWTApronApronApronApronApronApronApronApronApronApronAlto/ (N+1) Bloques3trabajando los hilos <strong>de</strong> un bloque. Por otra parte,almacenaremos en la memoria constante los coeficientesh[n] y g[n] <strong>de</strong>scritos anteriormente. En estealgoritmo cada kernel <strong>de</strong> CUDA es llamado con unnúmero <strong>de</strong> bloques, y con un número <strong>de</strong> hilos porbloque. El número <strong>de</strong> bloques <strong>de</strong>be ser igual o superiora la dimensión mayor <strong>de</strong> la imagen, que será obien el número <strong>de</strong> filas o bien el número <strong>de</strong> columnas.Cada bloque calcula una sola fila o columna,copiando dicha fila o columna en la memoria compartida<strong>de</strong> la GPU. El tamaño <strong>de</strong> la memoria compartidaen la NVIDIA GTX 280 es únicamente <strong>de</strong>16KB.Uno <strong>de</strong> los principales objetivos conseguidos medianteeste algoritmo propuesto ha sido minimizarlos requisitos <strong>de</strong> memoria, <strong>de</strong> este modo almacenaremoslos coeficientes wavelet resultantes en el espacio<strong>de</strong> memoria <strong>de</strong> la imagen. Por otro lado, losmétodos incluidos en la SDK <strong>de</strong> CUDA [10] utilizantres veces el tamaño <strong>de</strong> la imagen. Estos métodosrealizan la convolución en dos pasos: en el primerpaso calculan la convolución por filas y almacenanlos coeficientes obtenidos en la memoria global <strong>de</strong>la GPU; y en el segundo paso calculan y almacenanla convolución por columnas en otro espacio <strong>de</strong>la memoria global <strong>de</strong> la GPU. Se pue<strong>de</strong> reducir losrequisitos <strong>de</strong> memoria en un tercio si los coeficienteswavelet obtenidos en el segundo paso son almacenadosen el espacio ocupado por la imagen original. Porotra parte, basándonos en la SDK <strong>de</strong> CUDA hemos<strong>de</strong>sarrollado dos métodos <strong>de</strong> la implementación <strong>de</strong>scritacomo convolución clásica (véase [10], [16]), elprimero <strong>de</strong> ellos, utilizando la memoria global <strong>de</strong> laGPU (CUDA-Mem 9/7 ), y el segundo, utilizando lamemoria <strong>de</strong> tipo textura (CUDA-Text 9/7 ).Tal y como se propone en [10], el comportamientoN rows(b) Convolución por columnasFig. 4. Distribución por bloques en la memoria compartida<strong>de</strong> la GPUen estos métodos se pue<strong>de</strong> mejorar consi<strong>de</strong>rablementeoptimizando el acceso a memoria para evitarlos conflictos (memory coalescence). Para po<strong>de</strong>roptimizar el acceso a memoria, los filtros <strong>de</strong> la convolución<strong>de</strong>ben ser separables en dos pasos, es <strong>de</strong>cir,una convolución por filas y otra por columnas,por tanto la convolución SMDWT <strong>de</strong>scrita en la secciónI-B no podría optimizarse con este sistema. Elfiltro Daubechies 9/7 se divi<strong>de</strong> en una convoluciónpor filas y una posterior convolución por columnas,por tanto es un filtro separable. Hemos implementadouna convolución (CUDA-Sep 9/7 ) que mejora elrendimiento mediante a) la reducción <strong>de</strong> las lecturas<strong>de</strong> un mismo píxel, b) acceso coalescente a memoria,c) alto rendimiento <strong>de</strong> la memoria compartida, y d)la reducción <strong>de</strong>l número <strong>de</strong> hilos en espera.Esta convolución separable se realiza en dos pasos,uno por filas y otro por columnas. Cada pasose compone <strong>de</strong> dos etapas, una carga inicial <strong>de</strong> losdatos <strong>de</strong>s<strong>de</strong> la memoria global <strong>de</strong> la GPU a la memoriacompartida <strong>de</strong>l bloque, y una etapa posterior enla cual cada hilo calcula y almacena los resultadosobtenidos en la memoria global. En la etapa inicial<strong>de</strong> carga <strong>de</strong> datos se almacenan en la memoria compartidalos píxeles asignados a cada bloque, M enconvolución por filas y N en columnas, a<strong>de</strong>más sonnecesarios un <strong>de</strong>terminado número <strong>de</strong> píxeles contiguosal bloque consi<strong>de</strong>rado, el número <strong>de</strong> píxelescontiguos necesarios viene dado por (filtersize −3<strong>JP2011</strong>-673


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Tiempo (s.)Fig. 5.0,0300,0250,0200,0150,0100,0050,000512 x 512 2048 x 2048 4096 x 4096CUDA-Conv 9/7 0,0008 0,0068CUDA-Mem 9/7 0,0011 0,0063 0,0240CUDA-Text 9/7 0,0016 0,0077 0,0269CUDA-Sep 9/7 0,0005 0,0026 0,0088Tiempos <strong>de</strong> ejecución sobre GPUs con CUDA1)/2, en particular para el filtro Daubechies 9/7 sonnecesarios 4 píxeles contiguos en cada extremo paralas filas y 3 píxeles para las columnas. En la figura 4,estos bloques contiguos y pertenecientes a otros bloquesse han representado en gris y señalizados como“Apron”.En la etapa <strong>de</strong> cálculo, tal y como se pue<strong>de</strong>ver en la figura 4, cada hilo lee los datos <strong>de</strong>s<strong>de</strong> lamemoria compartida y los almacena en su correspondienteposición <strong>de</strong> la imagen final. De este modo,hilos consecutivos acce<strong>de</strong>n a posiciones <strong>de</strong> memoriaconsecutivas por lo que no existen conflictos en el accesoa la memoria compartida (una <strong>de</strong>scripción más<strong>de</strong>tallada pue<strong>de</strong> verse en [10]).En la figura 5, comparamos los tiempos <strong>de</strong> ejecuciónobtenidos para la transformada 2D-DWTutilizando las cuatro implementaciones propuestasen CUDA: la implementación en CUDA <strong>de</strong>l algoritmobasado en la convolución <strong>de</strong>scrito en la secciónI (nombrado como CUDA-Conv 9/7 ); la implementación<strong>de</strong>l algoritmo básico <strong>de</strong>scrito en la SDK<strong>de</strong> CUDA utilizando tanto la memoria global (nombradocomo CUDA-Mem 9/7 ) como utilizando texturas(nombrado como CUDA-Text 9/7 ); y el algoritmo,<strong>de</strong>scrito en esta sección, que optimiza el accesoa memoria basado en filtros separables (nombradocomo CUDA-Sep 9/7 ). En la figura 5 po<strong>de</strong>mosobservar que los tiempos obtenidos con el algoritmopropuesto CUDA-Conv 9/7 son similares a losobtenidos con las implementaciones CUDA-Mem 9/7y CUDA-Text 9/7. Sin embargo, sí obtenemos unamejora consi<strong>de</strong>rable al optimizar el acceso a la memoriacompartida usando filtros separables. Por ejemplo,el factor <strong>de</strong> mejora obtenido por el algoritmoCUDA-Sep 9/7 es 2, 7 para un tamaño <strong>de</strong> imagen <strong>de</strong>4096 × 4096, .IV. ConclusionesHemos presentado varios algoritmos para el cálculo<strong>de</strong> la transformada discreta wavelet, basadostanto en la convolución como en la transformadalifting, en sistemas multinúcleo y en arquitecturasGPU. A<strong>de</strong>más, hemos comparado nuestras propuestascon otras propuestas recientes como la citadaSMDWT. El speed-up obtenido en sistemas multinúcleoes <strong>de</strong> 1, 9 utilizando dos procesadores y entre2, 4 y 3, 4 usando cuatro procesadores. Hemosquerido trasladar estos resultados obtenidos en sistemasmultinúcleo a arquitecturas con procesadoresgráficos, trasladando la memoria temporal <strong>de</strong> almacenamiento<strong>de</strong> la fila o columna a la memoria compartida<strong>de</strong> la GPU. El speed-up en la GPU respectoa un sistema multinúcleo ha sido superior a 20. Porotro lado, hemos comparado el rendimiento obtenidoen la GPU con otras propuestas <strong>de</strong> implementacionessimilares en CUDA.Como conclusión, nos gustaría <strong>de</strong>stacar que a)el uso <strong>de</strong> una arquitectura multinúcleo mejora elrendimiento consi<strong>de</strong>rablemente en el cálculo <strong>de</strong> laDWT, y b) obtenemos una ganancia muy consi<strong>de</strong>rableen GPUs que pue<strong>de</strong> ser incluso mejorada conun acceso optimizado a la memoria compartida.AcknowledgementsEl presente trabajo ha sido financiado por el Ministerio<strong>de</strong> Educación y Ciencia mediante el proyectoDPI2007-66796-C03-03 y por el Ministerio <strong>de</strong> Educacióny Ciencia mediante el proyecto TIN2008-06570-C04-04.Referencias[1] K. Rao and P. Yip. Discrete cosine transform: Algorithms,advantages, applications. In Aca<strong>de</strong>mic Press,USA, 1990.[2] ISO/IEC 15444-1. JPEG2000 image coding system, 2000.[3] A. Said and A. Pearlman. A new, fast and efficientimage co<strong>de</strong>c based on set partitioning in hierarchicaltrees. IEEE Transactions on Circuits, Systems andVi<strong>de</strong>o Technology, 6(3):243–250, 1996.[4] S. G. Mallat. A theory for multi-resolution signal <strong>de</strong>composition:The wavelet representation. IEEE Transactionson Pattern Analysis and Machine Intelligence,11(7):674–693, July 1989.[5] W. Swel<strong>de</strong>ns. The lifting scheme: a custom-<strong>de</strong>sign constructionof biorthogonal wavelets. Applied and ComputationalHarmonic Analysis, 3(2):186–200, April 1996.[6] W. Swel<strong>de</strong>ns. The lifting scheme: a construction of secondgeneration wavelets. SIAM Journal on MathematicalAnalysis, 29(2):511–546, March 1998.[7] Y. Bao and C.C. Jay Kuo. Design of wavelet-basedimage co<strong>de</strong>c in memory-constrined environment. IEEETrans. on Circuits and Systems for Vi<strong>de</strong>o Technology,11(5):642–650, May 2001.[8] C. Chrysafis and A. Ortega. Line-based, reduced memory,wavelet image compression. IEEE Transactions onImage Processing, 9(3):378–389, March 2000.[9] Chih-Hsien Hsia, Jing-Ming Guo, Jen-Shiun Chiang, andChia-Hui Lin. A novel fast algorithm based on smdwt forvisual processing applications. In Circuits and Systems,2009. ISCAS 2009. IEEE International Symposium on,pages 762 –765, May 2009.[10] V. Podlozhnyuk. Image convolution with cuda, June2007.[11] I. Daubechies and W. Swel<strong>de</strong>ns. Factoring wavelet transformsinto lifting steps. Fourier Analysis and Applications,4(3):247–269, 1998.[12] J.M. Shapiro. Embed<strong>de</strong>d image coding using zerotrees ofwavelet coefficients. IEEE Transactions on Signal Processing,41(12), December 1993.[13] OpenMP Architecture Review Board. Openmp c andc++ application program interface, version 2.0. March2002.[14] J. Nickolls, I. Buck, M. Garland, and K. Skadron. Scalableparallel programming with cuda. In Queue, volume6, pages 40–53, 2008.[15] NVIDIA Corporation. Nvidia cuda c programming gui<strong>de</strong>.version 3.2.[16] Ian Buck. Gpu computing with nvidia cuda. In ACMSIGGRAPH 2007 courses, SIGGRAPH ’07, New York,NY, USA, 2007. ACM.<strong>JP2011</strong>-674


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Tableless Distributed Routing inHeterogeneous MPSoC SystemsJosé Cano 1 , José Flich 1 , José Duato 1 , Marcello Coppola 2 , Riccardo Locatelli 2Abstract—In application-specific SoCs, the irregularity of thetopology ends up in a complex implementation of therouting algorithm, usually relying on routing tablesimplemented with memory structures. As system sizeincreases, the routing table increases in size with nonnegligibleimpact on power, area and latency overheads.In this paper we propose a routing mechanismfor application-specific SoCs able to implement in anefficient manner (without requiring routing tables andusing a small logic block in every switch) a routing algorithmin those irregular networks. The mechanismrelies on a tool that maps the initial irregular topologyof the SoC system into a logical regular structurewhere the mechanism itself can be applied. We provi<strong>de</strong><strong>de</strong>tails of both the mapping tool and the routingmechanism. Evaluation results show the effectivenessof the mapping tool as well as the low area and timingrequirements of the mechanism.Keywords—Systems-on-Chip, Networks-on-Chip, Routing.I. IntroductionAs technology advances, systems-on-chip (SoC)<strong>de</strong>signs become more complex with the inclusion ofmany IP components. Tens (and in the near futureseveral hundreds) of elements need to be connectedwithin the same chip, thus requiring an efficient onchipinterconnect. Usually, the system <strong>de</strong>sign is customizedtaking into account the future applicationthat will be running on top of it. Traffic patternsare known in advance, and the interconnect is customizedtoo. The net result of such <strong>de</strong>sign approachis a network within the chip [1] [2] with no regularshape and with varying switch complexities and linkbandwidths. Figure 1 shows an example where IPblocks are connected by using an on-chip networkwith 28 switches. As can be observed, the networktopology is totally irregular and heterogeneous.Two key pillars of an interconnect are the topologyand the routing algorithm. The topology sets thephysical connection pattern between end no<strong>de</strong>s and,as indicated previously, in application-specific SoCsystems is usually irregular. The routing algorithm,on the other hand, sets the paths that messages needto take within the network. Once the topology is set,then, the routing algorithm needs to be applied andmessages need to be instructed about the paths tofollow. In or<strong>de</strong>r to implement the routing algorithmtwo trends can be followed: source routing and distributedrouting [3].1 Grupo <strong>de</strong> Arquitecturas Paralelas , Universitat Politècnica<strong>de</strong> València. E-mail: jocare@gap.upv.es, {jflich,jduato}@disca.upv.esSTMicroelectronics , Grenoble, France. E-mail:{marcello.coppola, riccardo.locatelli}@st.comFig. 1. Example of a complex irregular topology for anapplication-specific SoC system. P means producers andC means consumers.Today, the majority of application-specific SoCsystems in current products are using irregulartopologies based on well-known on-chip technologies(examples are Spi<strong>de</strong>rgon STNoC [4], Arteris NoC [5],Sonics MicroNetwork [6] and AMBA [7]). Those irregularsolutions are mainly based on source routingand address <strong>de</strong>coding, and normally need a compleximplementation of the routing algorithm (with routingtables using memory structures). In<strong>de</strong>ed, thelack of regularity in the topology prevents simplificationsin the routing algorithm <strong>de</strong>sign. As systemsize increases, the routing table increases in sizewith non-negligible impact on power, area and latencyoverheads (for a comparison between logicbasedrouting and tables, refer to [8]).In this paper we address the implementation ofthe routing algorithm in application-specific SoC systemswhere the topology is set by the application,thus being totally irregular. The aim is to <strong>de</strong>sign amechanism (LBDRx) that enables the use of tablelessdistributed routing on every switch with a constantand reduced logic cost, regardless of systemsize. We also provi<strong>de</strong> a tool able to map the initialirregular topology into a logical regular structurewhere the LBDRx approach can be used. By doingthis, the routing algorithm can be efficiently implementedin the SoC <strong>de</strong>sign with no need of routingtables and with no topology change.There has been consi<strong>de</strong>rable work on routing algorithmsfor irregular NoCs [9] [10] [11]. However,none of the solutions allow the implementation of distributedrouting algorithms in irregular NoCs topologieswith no routing tables and minimum logic.The rest of the paper is organized as follows. SectionII <strong>de</strong>scribes the concrete contribution of the paperin a preliminary subsection, in or<strong>de</strong>r to clarify<strong>JP2011</strong>-675


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011and focus the <strong>de</strong>scription of the mechanism and themapping tool. Then, we <strong>de</strong>scribe the LBDRx mechanismto cover practical topologies from SoC <strong>de</strong>signs.In Section III we <strong>de</strong>scribe the mapping tool. Finally,in Section IV we provi<strong>de</strong> evaluation results and conclu<strong>de</strong>the paper in Section V.II. LBDRx <strong>de</strong>scriptionThe <strong>de</strong>scription of the proposed LBDRx mechanismwill be presented as an evolution from the basicLBDR mechanism [8] previously proposed (withlow coverage for complex irregular topologies) to themost enhanced version (with full coverage to all thecomplex topologies analyzed).A. Preliminary: Basic I<strong>de</strong>aIn regular networks, e.g. a 2D-mesh network, theregular connectivity pattern is useful when <strong>de</strong>signingthe routing algorithm. In<strong>de</strong>ed, with the Dimension-Or<strong>de</strong>r routing (DOR), the implementation is quitestraightforward as messages are forwar<strong>de</strong>d with minimalpaths first in the X direction and then in theY direction. Thus, there is no need for a routing table,only a set of gates is enough. This ren<strong>de</strong>rs to anefficient implementation of the routing algorithm interms of area, power, and <strong>de</strong>lay.If we consi<strong>de</strong>r small irregularities on 2D-mesh networks,for instance due to manufacturing <strong>de</strong>fects,then the inherent irregularity complicates the routingimplementation. For instance, DOR is no longervalid as some paths are not possible now. However,other routing algorithms are still suitable for suchtopologies, for instance, topology-agnostic routingalgorithms like up*/down* [12]. Their implementationis usually performed with routing tables. Effortsto provi<strong>de</strong> efficient implementations of such algorithmsin those irregular topologies have been performedin the recent years.One important method is LBDR, which collapsesall the routing information required on every switchon a small set of bits, thus reducing significantly implementationcosts. LBDR still relies on the factthat the topology is a 2D-mesh network but withsome missing links. Adding some bits enables LBDRto successfully <strong>de</strong>al with the irregularity induced bymissing links. However, LBDR still relies on the factthat every switch has at most four links connectingneighboring switches (at North, East, West, or Southdirections). LBDR uses, as DOR does, the coordinatesof the <strong>de</strong>stination switch in the message andthe coordinates of the current switch, to computethe appropriate set of output ports. Thus, LBDRstill benefits from the original 2D-mesh layout.In this paper, what we propose is the extensionand applicability of the LBDR concept to trulyapplication-specific and irregular networks (as an examplesee Figure 1). The approach we follow is tomap the topology into a 2D grid (notice, however, wedo not change the initial topology). Once the topologyis mapped, we need to provi<strong>de</strong> coordinates to everyswitch in the network. Based on the coordinatesof the <strong>de</strong>stination switch and the current switch, the<strong>de</strong>rived LBDR logic will <strong>de</strong>ci<strong>de</strong> the output port thatneeds to be used to forward the packet towards its<strong>de</strong>stination. In or<strong>de</strong>r to correctly map the topologyinto a 2D grid, we have <strong>de</strong>veloped a mapping algorithmthat will search the space of combinations andwill <strong>de</strong>liver the most suitable ones, always guaranteeing<strong>de</strong>adlock freedom and connectivity.Due to the mapping performed, and because of thehigh irregularity we will find, some switches will requirea varying number of ports to connect to otherswitches, and in that situation some links will connectswitches not placed closely in the 2D grid. Thiskind of connectivity has not been provi<strong>de</strong>d by theoriginal LBDR mechanism, and thus, requires modifications.In this paper, we further extend LBDR forits support in this kind of mappings.B. LBDR Extension: LBDRxWe start the <strong>de</strong>scription with the mechanism requiredat every switch to <strong>de</strong>al with the irregulartopologies. In or<strong>de</strong>r to be concise, we take as a referencethe mapping of the initial topology (Figure 1)that appears in Figure 2. This mapping is obtainedwith the mapping tool that will be <strong>de</strong>scribed in thenext section. The mapping is representative of allthe connectivity patterns between switches that weneed to address in this section.Fig. 2.Mapping example for the initial topology.As we can see in the figure, there are switches withvarying connectivity patterns with other switches.For instance, switch 1, mapped at row 2 and column2, is connected to switches 4, 2, and 21 with differentlink mapped lengths. In particular, mapped length oflinks are 2 hops for links connecting to switches 2 and4, and 3 hops for the link connecting to switch 21.In addition, links with the same number of mappedhops have different orientations/directions, thus, beingdifferent. This is the case for link connecting toswitch 4 which is located one hop north and one hopwest from switch 1, and link connecting to switch 2that is two hops north.As previously <strong>de</strong>scribed, LBDR relies on switcheswith up to four ports, and each one connectingswitches in one direction in the 2D mesh plane (N,<strong>JP2011</strong>-676


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011E, W and S). Also, the maximum distance coveredwith a link is 1 hop in the 2D grid. Thus, links withhigher mapping lengths are not supported. In or<strong>de</strong>rto overcome this limitation, LBDRx allows forswitches with up to 20 ports for connecting to otherswitches (ports used to connect end no<strong>de</strong>s are exclu<strong>de</strong>d).Also, any of these ports can be configuredas a 1-hop port, a 2-hop port, or a 3-hop port. AX-hop port connects two switches that are at mappingdistance X. In or<strong>de</strong>r to uniformly refer to X-hopports, we <strong>de</strong>fine additional directions. In particular,20 different directions are supported, and each of the20 possible ports of the switch can be configured toany of the 20 directions. Figure 3 shows all the possibleport directions supported by LBDRx.Fig. 4.Logic of LBDRx.Fig. 3.Possible directions in LBDRx.Simplified versions of the mechanism can be conceivedby restricting the type of ports that can besupported. For instance, the LDBR mechanism isembed<strong>de</strong>d in the proposed mechanism when only 1-hop ports are allowed. Another implementation isallowing 1-hop and 2-hop ports only, thus obtaininga LBDR2 mechanism. Therefore, the LBDRx proposalcan be seen as a method to further extend theconnectivity of switches when mapped on a 2D grid.As we will see in the evaluation section, LBDR3 isenough to map all the tested topologies, thus notrequiring a more complex implementation.It is worth mentioning that, although 20 ports areallowed on every switch, not all of them need to beimplemented. In<strong>de</strong>ed, only a subset of ports will beimplemented, e.g. switch 1 at Figure 2 will be implementedwith only 3 output ports.The logic required for LBDRx is shown in Figure4. The mechanism relies on some configuration bits(will be hardwired) grouped in two sets: routing bitsand connectivity bits. Routing bits indicate whichrouting options can be taken (set the routing algorithm),whereas connectivity bits indicate whethera switch is connected with its neighbors (set themapped topology). As we support 20-port switches,at maximum we will have 20 connectivity bits perswitch. We represent the connectivity bit for a portX as C x , where X can be a possible direction of anymapped port (N, E, W, S, NN, NE, ..., NNE, ...).The routing bits R xy (where x and y can be n, e,w, and s) indicate whether messages routed throughthe x output port may take at the next switch they port. In other words, these bits indicate whethermessages are allowed to change direction at the nextswitch. The value of these bits is computed in accordanceto the applied routing algorithm and to prevent<strong>de</strong>adlock while still guaranteeing connectivity.In or<strong>de</strong>r to simplify the routing logic, no new routingbits are used except those already <strong>de</strong>fined in LBDR:R ne , R nw , R en , R es , R wn , R ws , R se , R sw . Noticethat routing bits are used only between 1-hop links.By <strong>de</strong>fault, the LBDRx mechanism will assume messagescan take 2-hop and 3-hop links without restrictionalong their path without risk of inducing <strong>de</strong>adlock.The mapping strategy <strong>de</strong>scribed in section IIIwill guarantee in those cases the absence of <strong>de</strong>adlocks.Although allowing more routing bits wouldlead to greater flexibility, we noticed that they arenot nee<strong>de</strong>d in or<strong>de</strong>r to reach our objective (shown inthe evaluation section). This will also help to keep alow implementation cost of the mechanism.Routing logic of LBDRx is divi<strong>de</strong>d into two parts(see Figure 4). The first part of the logic computesthe relative position of the message’s <strong>de</strong>stination.For this, two comparators are used and coordinatesof the current switch (X curr and Y curr ) are comparedwith the coordinates of the message’s <strong>de</strong>stination(X dst and Y dst ) located in the message hea<strong>de</strong>r.At the output of this logic one or two signals may beactive (e.g. if the packet’s <strong>de</strong>stination is in the NWquadrant then N’ and W’ signals are active at thesame time). Note also that packets forwar<strong>de</strong>d to thelocal port are exclu<strong>de</strong>d from the routing logic.Additionally, four extra signals (NN’, EE’, WW’and SS’) are computed. These signals are set to oneif the message’s <strong>de</strong>stination is at least two hops awayin the corresponding direction (if NN’ is active, thenat least two hops must be performed in the N directionto get closer to its <strong>de</strong>stination). These signalscan be easily computed with additional comparatorsbetween the current and the <strong>de</strong>stination coordinates.Notice that in some situations different signals willbe active at the same time, for instance signals NN’and N’. These cases are filtered in the second partof the logic. Higher priority will be given to larger<strong>JP2011</strong>-677


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011hop ports. We refer to the signals produced by thecomparators as inten<strong>de</strong>d direction signals.The second part of the logic consists of a logic unitat each output port in the switch. Figure 4 shows the<strong>de</strong>tails. The logic is divi<strong>de</strong>d in three parts in or<strong>de</strong>rto address the logic for the different type of outputports (1-hop, 2-hop, and 3-hop ports). Notice that3-hop ports have the highest priority followed by 2-hop ports. This means that if a 3-hop output port iseligible for routing a message then, ports with lowermapping length will not be consi<strong>de</strong>red. To implementthis priority scheme, two control signals (2hopand 3hop signals) are used. Besi<strong>de</strong>s this, the logic tocompute 2-hop and 3-hop ports is quite straightforward.In<strong>de</strong>ed, a port X is eligible if the port existsin the switch (C x bit is set), and the message’s <strong>de</strong>stinationis in the same direction of the output port(direction signals). As an example, output port NNEis eligible for routing if the message’s <strong>de</strong>stination isin the NNE direction (signals NN’ and E’ are set).The logic for 1-hop ports is, however, slightly morecomplex. It <strong>de</strong>als also with the routing bits. Thelogic, in this case (excluding the priority signals) isimplemented with two inverters, four AND gates andone OR gate. The logic filters out the routing optionsthat could lead to <strong>de</strong>adlock situations (by using therouting bits). Obviously, connectivity bits and prioritysignals are used in combination with the previouslogic. The logic for the 1-hop output ports is thesame used in LBDR.As a final remark for the LBDRx routing mechanism,its success <strong>de</strong>pends strongly on the mappingperformed for the topology. Therefore, the mappingtool <strong>de</strong>scribed in the next section, is a key element toguarantee applicability of the LBDRx mechanism.III. Mapping ToolIn this section we <strong>de</strong>scribe the mapping tool requiredby the LBDRx mechanism. The mapping toolis adapted to different versions of LBDRx routing,e.g. with 3-hop links, 2-hop links, and with/withoutnon-minimal path support. The mapping tool takesas an input the topology and the type of LBDRx supportand outputs several possible solutions, each ofthem able to be used with the target LBDRx version.In<strong>de</strong>ed, the mapping tool (see Figure 5) provi<strong>de</strong>s forany possible solution the set of configuration bits togetherwith the mapping coordinates of every switchinto a 2D grid. It is worth highlighting that themapping tool does not physically change the topology,in<strong>de</strong>ed it only logically maps the topology ontoa 2D grid. In the next subsections we <strong>de</strong>scribe the<strong>de</strong>tails of each stage along with an example.C. Support for Non-minimal Mapped PathsThe previous logic guarantees minimal path routingin the mapped topology. As each output port isused when the <strong>de</strong>stination is located in the same directionof the output port, then every hop performedguarantees the message will get closer to its <strong>de</strong>stination.However, there are mapping cases that can notbe solved with only minimal path support. As anexample, in the mapped topology shown in Figure2, a message going from switch 1 (mapped in row 2and column 2) requires a mapped non-minimal pathto reach switch 23, as it needs to be forwar<strong>de</strong>d SSWand then NNW. This fact simply ren<strong>de</strong>rs the mappedtopology as unsupported by LBDRx (Figure 4).One possible solution is to discard the mappedtopology and obtain one that guarantees all thepaths will follow minimal paths. However, in somecomplex topologies, this kind of mappings will simplynot exist. To solve this problem in a smooth way,and allowing much more flexibility to the mechanism,we introduce a small additional logic on every switchto allow such non-minimal path support. The logicforces messages to take a non-minimal port (<strong>de</strong>route)whenever the LBDRx logic fails in routing the message(in our example, port SSW). The logic requiresa configuration register of size 5 bits (to select an outputport out of maximum 20 ports) per switch. It isworth mentioning that <strong>de</strong>routes need to be computedin accordance to the routing algorithm, as they mustnot introduce cycles that could lead to <strong>de</strong>adlocks.Fig. 5.Mapping tool.A. Compute Mapping of SwitchesThe first stage provi<strong>de</strong>s an initial mapping of theswitches into a 2D grid. Some basic assumptions areconsi<strong>de</strong>red:1. Only switches are consi<strong>de</strong>red for the mapping,thus not consi<strong>de</strong>ring end no<strong>de</strong>s.2. The 2D-mesh diameter will be minimized andma<strong>de</strong> as square as possible.3. Every possible mapping of switches onto the 2Dmesh is explored and further analyzed in the followingstages (most of them will result in mappingsnot supported by LBDRx).Fig. 6.Example of two initial mappings.As an example, Figure 6 shows two possible mappingscorresponding to the example topology provi<strong>de</strong>din Figure 5. At first sight we cannot <strong>de</strong>ducewhich one can be supported. For this, we need tocompute the connection pattern.<strong>JP2011</strong>-678


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011B. Compute the Connection PatternThe connection pattern consi<strong>de</strong>rs only links connectingswitches (switch-to-switch links) and the directionof each link (unidirectional links are consi<strong>de</strong>red).Several restrictions are enforced in this step(consi<strong>de</strong>ring LBDR2):1. Any switch has at maximum 12 outgoing portsand 12 incoming ports, possibly having lessnumber of ports, and not necessarily the samenumber of input and output ports.2. In every switch one possible direction out of 12can be taken through a single output port. Thedirections are the ones supported by LBDR2 (2-hop and 1-hop links <strong>de</strong>picted in Figure 3).Taking into account the previous restrictions,mappings with link lengths longer than the targetedLBDRx version will become not valid. Figure 7(a)shows the connectivity pattern for the previous twomapping cases. As can be seen, the second mappingcase is not compatible with LBDR2 since it containsa 3-hop link. Notice however, that if we use LBDR3both mappings are, then, supported.Fig. 7. Example of (a) connectivity pattern applied to twodifferent mappings, and (b) mapped topology with therouting algorithm applied.C. Compute a Proper Routing AlgorithmOnce we have obtained a correct mapping we needto check whether the mapped topology contains cyclesor not. In or<strong>de</strong>r to avoid them, it will be necessaryto apply a routing algorithm. In our case, therouting algorithm used is the Segment-Based Routing(SR) [13], a technique that divi<strong>de</strong>s the networkinto segments and puts a routing restriction in eachsegment. A routing restriction is placed between twoconsecutive links and prevents any message from usingboth links sequentially. Drawing routing restrictionsis a way of representing a routing algorithmsince restrictions establish the allowed paths. In or<strong>de</strong>rto compute the routing restrictions, only 1-hoplinks in the mapped topology are assumed. As commentedabove, this assumption simplifies the LBDRxlogic and still allows to reach our objective of avoidingcycles.In the first mapping in Figure 7(a), a cycle can beformed between switches 0, 3, and 2 in the counterclockwise direction. Figure 7(b) shows the validmapped topology with the unidirectional routing restrictionapplied at switch 2. Notice that LBDRxcomputes the routing bits from the routing restrictions<strong>de</strong>fined by the routing algorithm.D. Check Deadlock-Freedom and ConnectivityThe last step of the mapping tool is to verify themapping is <strong>de</strong>adlock-free and guarantees the connectivityof the initial topology. The routing algorithmapplied in the previous step ensured <strong>de</strong>adlockfreedombetween 1-hop links, thus, now it must bechecked along 2-hop and 3-hop links. On the otherhand, when applying the routing algorithm and whennot using <strong>de</strong>routes, some pair of end no<strong>de</strong>s may beunconnected. The reason is because LBDRx without<strong>de</strong>routes relies exclusively on minimal paths. Therefore,a routing restriction may lead to a path beingrouted non-minimally. At this stage, the tool iterateson all the communicating flows of the application(a flow is <strong>de</strong>fined as the path from a producer toa consumer). For each flow, the tool searches a validLBDRx path using the connectivity and routing bitsset by the mapped topology. If for a flow there isno connectivity, then, the mapping is not valid andwe will need either to search a new mapping or use<strong>de</strong>routes.On success of a mapping topology, the final outputis the mapping of each switch into the 2D gridand the configuration (connectivity, routing and <strong>de</strong>route)bits. Notice that the mapping tool succeeds ifat least one mapping solution is obtained. Also, if nomapping solution exists for a grid size, the mappingtool extends the grid by one row and/or column thushaving much larger flexibility. Figure 2 shows a successful<strong>de</strong>adlock-free mapping for the initial topology<strong>de</strong>picted in Figure 1 where connectivity betweenswitches is assured (LBDR3 with <strong>de</strong>routes was used).IV. EvaluationIn this section, we provi<strong>de</strong> a comprehensive evaluationof LBDRx. First, we show the results (TableI) of applying the mapping tool to different sets oftopologies with increasing complexity. The mappingtool was run in AMD Opteron (2,8 Ghz dual core,8Gb RAM) computers.Grid size Correct Deroutes TimeType 1 4x4 >10.000 not nee<strong>de</strong>d 3-5 mType 2 5X5 >100.000 not nee<strong>de</strong>d 10-15 mType 3 5X6 >100.000 not nee<strong>de</strong>d 30-45 mType 4 5X7 >100.000 10-15 1-2 hFig. 1 5X7 578.952 13-15 2 hTABLE ITopology mappingsThe main purpose was to compute the number ofcorrect mappings generated for every analyzed topologyand the time required to complete the procedure.In each case, the table shows the minimum grid sizenee<strong>de</strong>d to map the topology (4x4, 5x5, ..., 5x7), thenumber of correct mappings obtained, and the averagenumber of <strong>de</strong>routes used (per mapping), if necessary.Note that correct mappings will be those whichmet the restrictions imposed by the LBDRx versionapplied in each case. In the last column the compu-<strong>JP2011</strong>-679


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011tation time to complete the entire process is shown.This time <strong>de</strong>pends mainly on the complexity of eachtopology, and for these examples ranges from someminutes to several hours.In second place, all the LBDRx versions are comparedbetween them and with an example using routingtables from an implementation cost and efficiencyviewpoint, with a glance at scalability properties.LBDRx versions were <strong>de</strong>signed and synthesized withthe 45nm Nangate opensource library, and routingtables by using Memaker. In Figure 8, we observehow differences between all the LBDRx versions areslight in terms of area. When compared with a RAMmemory of 256 entries, the LBDRx versions are muchcompact (notice the logarithmic scale). For <strong>de</strong>lay(Figure 9), although similar, the LBDRx versionshave lower access latency.Fig. 8.Fig. 9.Routing Module Area.Routing Module Delay.V. ConclusionsIn this paper we have presented LBDRx, a seriesof routing mechanisms (with support to non-minimalpaths) for application-specific SoC systems where thetopology is totally irregular. The main goal of LB-DRx is to enable the use of table-less distributedrouting on every switch with a constant and reducedlogic cost, regardless of system size. Moreover, wepresented a mapping tool able to obtain differentmappings of the same irregular topology onto a 2Dgrid. The tool is key for the application of the LB-DRx mechanism.The provi<strong>de</strong>d results <strong>de</strong>monstrate the applicabilityof the mapping tool onto a wi<strong>de</strong> set of topologies. Inall cases, a valid mapping was achieved, thus routingtables were replaced by the LBDRx mechanism. Implementationcosts also showed the benefits of suchreplacement.As future work we plan to further explore the LB-DRx mechanism and the mapping tool, focusing onperformance issues. Different mappings could endup in different performance numbers. Thus, we planto optimize the tool to provi<strong>de</strong> the best mapping forthe target application.AcknowledgmentsThis work was supported by the Spanish MECand MICINN, as well as European ComissionFEDER funds, un<strong>de</strong>r Grant CSD2006-00046. Itwas also partly supported by the COMCAS project(CA501), a project labelled within the frameworkof CATRENE, the EUREKA cluster for Applicationand Technology Research in Europe on NanoElectronics.Finally, the authors would like to thank AntoniRoca for his assistance in the Area-Delay comparisontests.References[1] Luca Benini and Giovanni De Micheli, Networks onChips: Technology and Tools, Morgan Kaufmann PublishersInc., San Francisco, CA, USA, 2006.[2] Jose Flich and Davi<strong>de</strong> Bertozzi, Designing Network On-Chip Architectures in the Nanoscale Era, CRC Press,Inc., Boca Raton, FL, USA, 2010.[3] Jose Duato, Sudhakar Yalamanchili, and Ni Lionel,Interconnection Networks: An Engineering Approach,Morgan Kaufmann Publishers Inc., San Francisco, CA,USA, 2002.[4] Marcello Coppola, Miltos D. Grammatikakis, RiccardoLocatelli, Giuseppe Maruccia, and Lorenzo Pieralisi,Design of Cost-Efficient Interconnect Processing Units:Spi<strong>de</strong>rgon STNoC, CRC Press, Inc., Boca Raton, FL,USA, 2008.[5] Inc. Arteris, “Arteris noc,” http://www.arteris.com/,2010, [Online; accessed 31-August-2010].[6] Drew Wingard, “Micronetwork-based integration forsocs,” in In Proceedings of the 38th Design AutomationConference, 2001, pp. 673–677.[7] ARM Ltd., “The advanced microcontroller bus architecture(amba),” http://www.arm.com/products/systemip/amba/,2010, [Online; accessed 01-September-2010].[8] José Flich, Samuel Rodrigo, José Duato, Simone Medardoni,and Davi<strong>de</strong> Bertozzi, “Efficient implementation ofdistributed routing algorithms for nocs,” in IET Computersand Digital Techniques. 2009, pp. 460–475, IET.[9] M. K. F. Schafer, T. Hollstein, H. Zimmer, andM. Glesner, “Deadlock-free routing and componentplacement for irregular mesh-based networks-on-chip,” inProceedings of the 2005 IEEE/ACM International conferenceon Computer-ai<strong>de</strong>d <strong>de</strong>sign (ICCAD ’05). 2005,pp. 238–245, IEEE Computer Society.[10] Bolotin, E., Cidon, I., Ginosar, R., and Kolodny, A., “Efficientrouting in irregular topology nocs,” Tech. Rep.CCIT 554, Israel Institute of Technology, Technion Departmentof Electrical Engineering, 2005.[11] Igor Loi, Fe<strong>de</strong>rico Angiolini, and Luca Benini, “Synthesisof low-overhead configurable source routing tables fornetwork interfaces.,” in DATE. 2009, pp. 262–267, IEEE.[12] D. Gelernter, “A dag-based algorithm for prevention ofstore-and-forward <strong>de</strong>adlock in packet networks,” IEEETrans. Comput., vol. 30, pp. 709–715, October 1981.[13] Flich, J., Mejia, A., López, P., and Duato, J., “Regionbasedrouting: an efficient routing mechanism to tackleunreliable hardware in networks on chip,” in 1stACM/IEEE Int. Symp. Networks on Chip (ISNOC),2007.<strong>JP2011</strong>-680


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Uso <strong>de</strong>l conocimiento <strong>de</strong> la arquitectura Fermipara mejorar el rendimiento en aplicacionesCUDAYuri Torres, Arturo González-Escribano y Diego R. Llanos 1Resumen— <strong>La</strong>s unida<strong>de</strong>s <strong>de</strong> procesamiento gráfico(GPUs) actualmente están jugando un papel muy importantecomo aceleradores para cómputo <strong>de</strong> propósitogeneral. <strong>La</strong> implementación <strong>de</strong> códigos paralelos <strong>de</strong>alto rendimiento en GPUs es una tarea recomendadapara programadores experimentados, <strong>de</strong>bido al altogrado <strong>de</strong> dificultad <strong>de</strong> explotar eficientemente el uso<strong>de</strong> los sus recursos. <strong>La</strong> elección <strong>de</strong>l tamaño y la forma<strong>de</strong> los bloques <strong>de</strong> hilos son <strong>de</strong>cisiones importantes yaque tienen un impacto muy significativo sobre el rendimiento<strong>de</strong> las aplicaciones. <strong>La</strong> arquitectura Fermi <strong>de</strong>NVIDIA introduce nuevos criterios a la hora <strong>de</strong> seleccionarlos tamaños y la geometría <strong>de</strong> los bloques <strong>de</strong>hilos. En este artículo mostramos un estudio <strong>de</strong> dichoscriterios, así como una guía general para seleccionarun bloque <strong>de</strong> hilos apropiado para diferentes tipos <strong>de</strong>aplicaciones.Palabras clave— CUDA, Fermi, auto-tuning, GP-GPU.I. IntroducciónLAS unida<strong>de</strong>s <strong>de</strong> procesamiento gráfico (GPUs)han conseguido ser una importante plataformacomputacional en muchos campos científicos talescomo computación masiva <strong>de</strong> datos o computaciónbiomédica. Entre las principales ventajas <strong>de</strong> estosdispositivos <strong>de</strong>staca el bajo coste operacional, la facilidady sencillez ofrecida por los entornos <strong>de</strong> programacióny el alto potencial <strong>de</strong> rendimiento.<strong>La</strong> programación basada en el mo<strong>de</strong>lo GPGPU(computación GPU <strong>de</strong> propósito general) ha sidosimplificada al introducir mo<strong>de</strong>los <strong>de</strong> programacióncomo CUDA [1]. Sin embargo, explotar eficientementeestos dispositivos implica utilizar un elevado conocimiento<strong>de</strong> la arquitectura para aplicar a<strong>de</strong>cuadamentetécnicas <strong>de</strong> optimización <strong>de</strong> código.Fermi [2] [3] [4] es la última arquitectura <strong>de</strong>sarrolladapor la compañía NVIDIA para dispositivosGPUs. Comparada con versiones anteriores, Fermiintroduce varias mejoras que influyen significativamenteen las estrategias básicas <strong>de</strong> optimización existentesen las optimizaciones <strong>de</strong> códigos para GPU.Por ejemplo, explotar la coalescencia, maximizar laocupación <strong>de</strong> los multiprocesadores (SMs), la precarga<strong>de</strong> datos y el unrolling. También introduce laposibilidad <strong>de</strong> configurar su nueva memoria caché L1.<strong>La</strong> elección <strong>de</strong>l tamaño y la geometría <strong>de</strong>l bloque<strong>de</strong> hilos es una <strong>de</strong> las <strong>de</strong>cisiones más importantes a lahora <strong>de</strong> implementar cualquier código <strong>de</strong> alto rendimientoen dispositivos GPU. Actualmente, el tamañoy la geometría <strong>de</strong> los bloques son típicamente seleccionadosmediante prueba y error sin conocimiento1 Dpto. <strong>de</strong> Informática, Univ. <strong>de</strong> Valladolid, e-mail:{yuri.torres|arturo|diego}@infor.uva.esprevio <strong>de</strong> los posibles efectos que puedan causar sobrela arquitectura.En este artículo se presenta un estudio práctico<strong>de</strong> la arquitectura Fermi orientado a la elección <strong>de</strong>ltamaño y la geometría <strong>de</strong> los bloques <strong>de</strong> hilos. Se<strong>de</strong>scribe un nuevo enfoque para <strong>de</strong>terminar el mejorbloque <strong>de</strong> hilos y la mejor configuración <strong>de</strong> la memoriacaché L1 para diferentes tipos <strong>de</strong> aplicaciones.Los resultados <strong>de</strong> estudio experimental muestranla utilidad <strong>de</strong>l enfoque y como el conocimiento <strong>de</strong> laarquitectura hardware <strong>de</strong> estos dispositivos se pue<strong>de</strong>explotar para utilizar más eficiente sus recursos.El resto <strong>de</strong>l artículo está organizado <strong>de</strong> la siguienteforma: en la sección 2 se comentan los <strong>de</strong>talles introducidospor la arquitectura Fermi comparándoloscon las versiones anteriores. En la sección 3 se discutecómo la arquitectura afecta significativamente ala hora <strong>de</strong> seleccionar el tamaño y la geometría <strong>de</strong>lbloque <strong>de</strong> hilos. En la sección 4 se <strong>de</strong>scribe el diseño<strong>de</strong> experimentos con el objetivo <strong>de</strong> verificar nuestrashipótesis. En la sección 5 se <strong>de</strong>talla el banco <strong>de</strong>pruebas utilizado. En la sección 6 se muestran losresultados obtenidos mientras que en la sección 7 serefleja el trabajo relacionado. Finalmente, la sección8 contiene las conclusiones <strong>de</strong> este artículo.II. Arquitectura NVIDIA FermiFermi es la última generación <strong>de</strong> arquitecturas CU-DA [2] [3]. Esta nueva arquitectura incluye operaciones<strong>de</strong> doble precisión, soporte para la corrección <strong>de</strong>errores, un incremento en la rapi<strong>de</strong>z <strong>de</strong> los cambios<strong>de</strong> contexto y <strong>de</strong> las operaciones atómicas, y una jerarquíatransparente <strong>de</strong> memorias caché L1/L2 con laposibilidad <strong>de</strong> <strong>de</strong>sactivar la L1 o ampliar su tamañoa costa <strong>de</strong> reducir la memoria compartida explícitamentemanejable por el usuario. Esta sección discutelos <strong>de</strong>talles <strong>de</strong> la arquitectura Fermi más significativospara nuestro estudio.A. Memorias caché L1/L2En arquitecturas pre-Fermi cada SM tenía 16 KB<strong>de</strong> memoria compartida manejable explícitamentepor el usuario, sin presencia <strong>de</strong> memorias caché. Fermiintroduce dos memorias caché transparentes (L1y L2). <strong>La</strong> memoria L1 es configurable por el usuario.Por <strong>de</strong>fecto tiene 16 KB <strong>de</strong> caché L1 y 48 KB <strong>de</strong> memoriacompartida, pero se pue<strong>de</strong> configurar antes <strong>de</strong>lanzar cada kernel para tener 48 KB <strong>de</strong> caché L1 y 16KB <strong>de</strong> memoria compartida. <strong>La</strong> memoria caché L2es <strong>de</strong> tamaño fijo con 768 KB <strong>de</strong> capacidad. Hastala llegada <strong>de</strong> Fermi el tamaño <strong>de</strong> los segmentos<strong>JP2011</strong>-681


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Shared MemoryL2 CacheDRAML1 Cache48 or 16 Kb 16 or 48 KbP0 P1 P2 P3 P4 P5256 bytesThread384 bits768 Kb1.5 GbFig. 1. Jerarquía <strong>de</strong> memoria Fermi (NVidia GTX-480).<strong>de</strong> transacción <strong>de</strong> memoria eran <strong>de</strong> 32, 64 y 128 Bytes.Sin embargo, en Fermi son <strong>de</strong> 128 ó 32 Bytes,<strong>de</strong>pendiendo <strong>de</strong> si la caché L1 está activa.B. Bloque <strong>de</strong> hilos, Warps y SMsFermi dobla el número <strong>de</strong> registros por SM (32KB). El número <strong>de</strong> procesadores (SPs) por SM hasido multiplicado por cuatro (32 SPs). En Fermi elnúmero máximo <strong>de</strong> hilos por bloque es 1024, mientrasque el máximo número <strong>de</strong> hilos concurrentes enun SM es 1536.C. Conflictos en memoria globalActualmente en Fermi la memoria global <strong>de</strong> estosdispositivos está distribuida en 5 ó 6 bancos con suscorrespondientes controladores in<strong>de</strong>pendientes. Unproblema frecuente a la hora <strong>de</strong> implementar códigosparalelos sobre arquitecturas pre-Fermi era el partitioncamping [5]. Este problema surge cuando hilosconcurrentes activos en cualquier SM solicitan segmentos<strong>de</strong> memoria diferentes pertenecientes al mismobanco <strong>de</strong> memoria global. Ello implica una serialización<strong>de</strong> dichas transacciones. Con la introducción<strong>de</strong> las cachés L1 y L2 en Fermi, este problema se aliviócuando los mismos segmentos <strong>de</strong> transacción sesolicitan una y otra vez.III. selección <strong>de</strong>l tamaño y la geometría<strong>de</strong>l bloque <strong>de</strong> hilosEn esta sección discutimos cómo los <strong>de</strong>talles <strong>de</strong>la arquitectura Fermi afectan a las <strong>de</strong>cisiones <strong>de</strong> losprogramadores respecto al tamaño y geometría <strong>de</strong>los bloques <strong>de</strong> hilos, así como a la configuración <strong>de</strong>la memoria caché L1.A. Tamaño <strong>de</strong> bloque <strong>de</strong> hilosA.1 Maximizar ocupaciónEn CUDA el factor ocupación <strong>de</strong> un SM es el ratioentre el número <strong>de</strong> warps presentes en el mismo yel número máximo <strong>de</strong> warps soportados por un SM(48 warps en Fermi). Maximizar la ocupación es importantepara ocultar las latencias en los accesos amemoria global.Para obtener máxima ocupación es necesario seleccionarun tamaño <strong>de</strong> bloque <strong>de</strong> hilos apropiado.<strong>La</strong> arquitectura Fermi soporta 1024 hilos por bloque,1536 hilos por SM y un máximo <strong>de</strong> 8 bloquesresidiendo simultáneamente en un SM. Por lo tanto,el tamaño <strong>de</strong> bloques <strong>de</strong> hilos <strong>de</strong>be ser inferior o iguala 1024, a la vez divisor entero <strong>de</strong> 1536 y el máximonúmero <strong>de</strong> hilos <strong>de</strong>l SM dividido entre el tamaño <strong>de</strong>lbloque no pue<strong>de</strong> exce<strong>de</strong>r <strong>de</strong> 8. Por ello concluimosque los únicos tamaños <strong>de</strong> bloques <strong>de</strong> hilos que maximizanla ocupación son 192, 256, 384, 512 y 768.Finalmente, cuando se va a lanzar un kernel quenecesita menos <strong>de</strong> 192 hilos por el número <strong>de</strong> SMsen el dispositivo, pue<strong>de</strong> ser recomendable escoger tamaños<strong>de</strong> bloques más pequeños, que no consiganmaximizar la ocupación. De esta forma, se aumentael número <strong>de</strong> bloques y se distribuyen mejor el conjunto<strong>de</strong> hilos entre los SMs, aumentando el grado <strong>de</strong>paralelismo global.A.2 <strong>La</strong> coalescencia y la carga <strong>de</strong> accesos a memoria<strong>La</strong> coalescencia es una técnica <strong>de</strong> implementaciónpara conseguir que hilos consecutivos <strong>de</strong> un warp,cuando solicitan memoria global, pidan direccioneslógicas contiguas. Esta técnica permite minimizar elnúmero <strong>de</strong> segmentos <strong>de</strong> transacción solicitados a lamemoria global. <strong>La</strong> coalescencia es especialmente importanteen aquellos códigos don<strong>de</strong> existe un alto ratio<strong>de</strong> accesos a memoria.Una técnica común para facilitar la programación<strong>de</strong> la coalescencia es utilizar estructuras <strong>de</strong> datosalineadas con el número <strong>de</strong> hilos por warp y el tamaño<strong>de</strong> los segmentos <strong>de</strong> transacción. Para reducirlas probabilida<strong>de</strong>s <strong>de</strong> la aparición <strong>de</strong> partition camping,es también aconsejable usar estructuras <strong>de</strong> datosque estén perfectamente alineadas con el número<strong>de</strong> controladores <strong>de</strong> memoria global <strong>de</strong>l dispositivoGPU. Por ejemplo, facilita la programación el escogerarrays <strong>de</strong> enteros o floats cuya última dimensiónes múltiplo <strong>de</strong> 32 y a la vez <strong>de</strong>l número <strong>de</strong> bancos.Para kernels <strong>de</strong> CUDA don<strong>de</strong> prevalezca el patrón<strong>de</strong> acceso coalescente y un alto ratio <strong>de</strong> accesos a memoria(uno o más accesos a memoria por operaciónaritmética), consi<strong>de</strong>ramos que utilizando bloques <strong>de</strong>192 hilos se obtendrán los mejores resultados por dosmotivos: (1) se maximiza la ocupación, (2) se consigueel mayor número <strong>de</strong> bloques concurrentes porSM (8). De esta forma, cuando los warps <strong>de</strong> un bloquevan terminando este se <strong>de</strong>saloja lo antes posiblepor tener un menor número <strong>de</strong> warps. Por tanto, lacantidad <strong>de</strong> warps que están activos en el SM se mantieneen el máximo (48) la mayor cantidad <strong>de</strong> tiempoposible dando más oportunida<strong>de</strong>s a la ocultación <strong>de</strong>las latencias.Kernels <strong>de</strong> programas como la multiplicación <strong>de</strong>matrices, a pesar <strong>de</strong> su coalescencia, presentan característicasdiferentes. Tienen mucha carga computacionalpor hilo y reutilizan datos en segmentos <strong>de</strong>memoria requeridos previamente. En este caso se esperaque aumentar el tamaño <strong>de</strong> bloque hasta 768 hilos(mayor tamaño <strong>de</strong> bloque que maximiza la ocupa-<strong>JP2011</strong>-682


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011ción) mejore el rendimiento ya que se explota mejorla reutilización reduciendo el número <strong>de</strong> segmentos<strong>de</strong> transacción solicitados.A.3 Accesos no coalescentesEn códigos cuyo patrón <strong>de</strong> acceso a memoria globalno es coalescente el número <strong>de</strong> segmentos <strong>de</strong> transacciónque solicita un warp se ve incrementado significativamente,incrementando a su vez la probabilidad<strong>de</strong> conflictos en los bancos <strong>de</strong> memoria global (partitioncamping).Para reducir el cuello <strong>de</strong> botella provocado por lacantidad <strong>de</strong> segmentos <strong>de</strong> transacción solicitados amemoria global, proponemos dos estrategias básicas:(1) <strong>de</strong>sconectar el uso <strong>de</strong> la memoria caché L1, ya que<strong>de</strong> esta forma, el tamaño <strong>de</strong> los segmentos se reducea una cuarta parte y (2) disminuir el tamaño <strong>de</strong> bloquereduciendo la ocupación para reducir el número<strong>de</strong> segmentos solicitados por SM en un periodo <strong>de</strong>tiempo dado.B. <strong>La</strong> forma <strong>de</strong> los bloquesPara un tamaño <strong>de</strong> bloque <strong>de</strong> hilos dado existendiferentes posibles geometrías, con el mismo ratio <strong>de</strong>ocupación. Para la misma ocupación cada posiblegeometría tiene un impacto diferente sobre la coalescencia,los conflictos en los bancos <strong>de</strong> memoria y loscuellos <strong>de</strong> botella en los accesos a la memoria global.En programas cuya codificación explota eficientementela coalescencia, los mejores resultados se obtendráncon bloques <strong>de</strong> hilos cuyo número <strong>de</strong> columnassea múltiplo <strong>de</strong> 32 (tamaño <strong>de</strong>l warp). <strong>La</strong>s peticiones<strong>de</strong> memoria global <strong>de</strong> cada warp coinci<strong>de</strong>ncon segmentos <strong>de</strong> memoria completos, minimizandola cantidad <strong>de</strong> segmentos a transferir.IV. Diseño <strong>de</strong> experimentosEn esta sección introducimos el diseño <strong>de</strong> los experimentosrealizados para verificar las hipótesis previamentepresentadas. Para ello, programamos unaserie <strong>de</strong> benchmarks en CUDA y los ejecutamos condiferentes tamos <strong>de</strong> bloque.Los benchmarks discutidos en esta sección incluyen:una reducción <strong>de</strong> vectores, suma <strong>de</strong> matrices,una modificación <strong>de</strong> suma <strong>de</strong> matrices para simularun aumento <strong>de</strong> carga, multiplicación <strong>de</strong> matrices ycopias <strong>de</strong> datos con accesos dispersos y aleatorios sobrearrays bidimensionales.Para todos nuestros benchmarks consi<strong>de</strong>ramosbloques <strong>de</strong> diferentes tamaños, hasta 1024 hilos(el máximo en permitido en Fermi). Escogemos unnúmero <strong>de</strong> elementos por dimensión para la geometría<strong>de</strong>l bloque que es potencia <strong>de</strong> dos, o potencia<strong>de</strong> 2 multiplicada por 3. Así conseguimos todas lascombinaciones <strong>de</strong> geometrías que maximizan la ocupacióny otros tamaños <strong>de</strong> bloque más pequeños.Para el problema unidimensional <strong>de</strong> reducción <strong>de</strong>vectores se utiliza 4096 × 1023 elementos. Consi<strong>de</strong>randoque cada hilo trabaja sobre dos elementos, estopermite bloques <strong>de</strong> 32 hilos o más sin superar elnúmero máximo <strong>de</strong> bloques por dimensión soportadospor Fermi (65535).Para el resto <strong>de</strong> benchmarks usamos matrices cuadradas<strong>de</strong> 6144 elementos por dimensión. Este tamañoes suficientemente pequeño como para alojar3 matrices en la memoria global <strong>de</strong>l dispositivo.A<strong>de</strong>más, las cardinalida<strong>de</strong>s <strong>de</strong> cada dimensión sonmúltiplo <strong>de</strong>l número <strong>de</strong> bancos <strong>de</strong> memoria global<strong>de</strong> nuestro dispositivo, así como <strong>de</strong> las dimensiones<strong>de</strong> las geometrías probadas.Los experimentos han sido ejecutados sobre la tarjetaNvidia GeForce GTX 480. El sistema es un Intel(R)Core(TM) i7 CPU 960 3.20GHz <strong>de</strong> 64 bitscon 6 GB <strong>de</strong> memoria principal. El sistema operativousado es UBUNTU <strong>de</strong>sktop 10.10 (64 bits). Eldriver <strong>de</strong> CUDA utilizado es el correspondiente a laversión 3.0 <strong>de</strong>l toolkit.V. BenchmarksEn esta sección <strong>de</strong>scribimos los benchmarks clasificadospor tipo <strong>de</strong> aplicación.A. Accesos coalescentesEl primer benchmark es una reducción <strong>de</strong> vectorbasado en uno <strong>de</strong> los ejemplos <strong>de</strong>l SDK <strong>de</strong> CUDA.Ha sido necesario modificarlo para po<strong>de</strong>r variar el tamaño<strong>de</strong>l bloque. El kernel <strong>de</strong> este código aplica unareducción <strong>de</strong> dos elementos por cada hilo, escogidos<strong>de</strong> forma coalescente en cada warp. El kernel se lanzavarias veces con la mitad <strong>de</strong> bloques cada vez hastaterminar la reducción.El segundo es un código trivial <strong>de</strong> suma <strong>de</strong> matricesdon<strong>de</strong> cada hilo está asociado al cálculo <strong>de</strong>una posición <strong>de</strong> la matriz resultado. Esto implica 3accesos a memoria por cada hilo (dos <strong>de</strong> lectura yuno <strong>de</strong> escritura). Implica un patrón <strong>de</strong> acceso a memoriacompletamente coalescente sin reutilización <strong>de</strong>ningún elemento. En este caso, cada warp necesitaúnicamente un segmento <strong>de</strong> transacción <strong>de</strong> 128 bytespara las 32 peticiones realizadas por los hilos <strong>de</strong>un warp en cada acceso.Se ha escogido también un código trivial <strong>de</strong> multiplicación<strong>de</strong> matrices [1] don<strong>de</strong> cada hilo calcula elproducto escalar <strong>de</strong> una fila <strong>de</strong> la primera matriz yuna columna <strong>de</strong> la segunda. A pesar <strong>de</strong> ser un algoritmosencillo presenta un patrón <strong>de</strong> acceso diferenteen cada una <strong>de</strong> las tres matrices utilizadas. <strong>La</strong> combinación<strong>de</strong> los diferentes patrones produce un efectocomplejo <strong>de</strong> analizar.B. Accesos no coalescentesSe ha construido un benchmark sintético, <strong>de</strong>nominadoaccesos dispersos regulares diseñado con elobjetivo <strong>de</strong> crear un patrón <strong>de</strong> acceso disperso sobrela memoria global <strong>de</strong>l dispositivo, <strong>de</strong> tal forma quecada hilo pida un segmento <strong>de</strong> transacción diferente.Cada hilo pi<strong>de</strong> un elemento entero que se encuentraa 32 posiciones <strong>de</strong> memoria global <strong>de</strong> distancia<strong>de</strong>l anterior. Una vez accedido al elemento <strong>de</strong>seadose incrementa su valor y se almacena en la posición<strong>JP2011</strong>-683


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011siguiente, que está en el mismo segmento <strong>de</strong> transacción.También se utiliza una variante <strong>de</strong>l benchmark anterior<strong>de</strong>nominado accesos aleatorios. Cada hilo calculaun par <strong>de</strong> valores aleatorios, los cuales sirvenpara <strong>de</strong>terminar la posición a la que se acce<strong>de</strong> enuna matriz. Al igual que el benchmark anterior elespacio <strong>de</strong> hilos tiene tantos elementos como la matriz.Cada hilo realiza alre<strong>de</strong>dor <strong>de</strong> 20 operacionesaritméticas para el cálculo <strong>de</strong> los índices aleatorios.VI. Resultados experimentalesEn esta sección presentamos los resultados obtenidospor nuestros benchmarks, estudiando su relacióncon los <strong>de</strong>talles <strong>de</strong> la arquitectura Fermi comentadosen secciones previas.A. Acceso coalescenteA.1 Kernels pequeños sin reutilización <strong>de</strong> datosEn la tabla I se muestran los tiempos <strong>de</strong> ejecución<strong>de</strong> la reducción <strong>de</strong> vectores. Por el tamaño <strong>de</strong> datos<strong>de</strong> entrada escogido, el número <strong>de</strong> hilos por bloquetiene que ser como mínimo <strong>de</strong> 32. <strong>La</strong> implementación<strong>de</strong> la reducción presenta un patrón coalescente, don<strong>de</strong>no existe reutilización <strong>de</strong> datos entre hilos y cadahilo apenas tiene carga computacional, únicamentepara calcular las posiciones <strong>de</strong> trabajo en el vector.<strong>La</strong> tabla I confirma el resultado general predicho enla sección III: el mejor tamaño <strong>de</strong> bloque es el menorque maximiza la ocupación, es <strong>de</strong>cir 192.<strong>La</strong> tabla II muestra los tiempos <strong>de</strong> ejecución parala suma <strong>de</strong> matrices con las diferentes geometríasconsi<strong>de</strong>radas. Los resultados correspondientes a bloques<strong>de</strong> hilos que maximizan la ocupación <strong>de</strong> los SMsestán resaltados en negrita. Los resultados son similaresal caso anterior, obteniendo el mejor tamaño<strong>de</strong> bloque en 192 hilos. El tiempo <strong>de</strong> ejecución crecerápidamente al reducir el número <strong>de</strong> columnas por<strong>de</strong>bajo <strong>de</strong> 32 y no aprovecharse el efecto <strong>de</strong> coalescencia.No se reflejan en la tabla bloques con menos<strong>de</strong> 8 columnas por problemas <strong>de</strong> espacio. Siguen laten<strong>de</strong>ncia esperada.Los experimentos realizados <strong>de</strong>sactivando lacaché L1 no muestran un impacto significativo sobrelos resultados. Se reduce la cantidad <strong>de</strong> datos porsegmento a cambio <strong>de</strong> aumentar proporcionalmenteel número <strong>de</strong> éstos.A.2 Reutilización intensiva <strong>de</strong> datosEn la tabla III se muestran los resultados para lamultiplicación <strong>de</strong> matrices. Con menos <strong>de</strong> 32 columnas<strong>de</strong> hilos, el tiempo <strong>de</strong> ejecución aumenta rápidamenteya que el patrón <strong>de</strong> acceso ya no es coalescenteen la primera matriz (se omiten dichos resultados enla tabla). Debido a la reutilización <strong>de</strong> los datos <strong>de</strong> lasdos matrices <strong>de</strong> entrada, bloques más gran<strong>de</strong>s tienenmás posibilida<strong>de</strong>s <strong>de</strong> reutilizar las mismas líneas <strong>de</strong>caché. Los mejores resultados se obtienen con 768 hilos,los bloques más gran<strong>de</strong>s que maximizan la ocupación.Respecto a la geometría, para bloques <strong>de</strong> hilos conel mismo tamaño los mejores resultados se obtienenreduciendo el número <strong>de</strong> filas aumentando correspondientementeel número <strong>de</strong> columnas. Esta ten<strong>de</strong>nciase mantiene hasta geometrías <strong>de</strong> una fila don<strong>de</strong> lostiempos vuelven a incrementarse <strong>de</strong>bido a que en estealgoritmo domina la pérdida completa la reutilización<strong>de</strong> los datos <strong>de</strong> la segunda matriz <strong>de</strong> entrada.B. Accesos no coalescentes<strong>La</strong> tabla IV muestra los tiempos <strong>de</strong> ejecución paraeste benchmark. Es un kernel sin un patrón <strong>de</strong> memoriacoalescente y con muy poca carga <strong>de</strong> computacionalpor hilo. Como se discutió en la sección III-A.3 este tipo <strong>de</strong> códigos funcionan mejor por <strong>de</strong>bajo<strong>de</strong> máxima ocupación. Esto es <strong>de</strong>bido a que: (1) laslatencias producidas por la gran cantidad <strong>de</strong> segmentossolicitados no se pue<strong>de</strong>n ocultar con el máximonúmero <strong>de</strong> warps por SM, es <strong>de</strong>cir, 48 y (2) reduciendoel número <strong>de</strong> warps por SM se <strong>de</strong>crementael número total <strong>de</strong> segmentos solicitados simultáneamente,aliviando el cuello <strong>de</strong> botella que serializa losaccesos a memoria global.Por último en la tabla V se observan los resultadosobtenidos para el código con accesos aleatorios.Este algoritmo utiliza <strong>de</strong>masiados recursos por SM,por lo que bloques <strong>de</strong> 1024 hilos llevan a una ocupaciónnula, marcados con asteriscos en la tabla. Esteprograma tiene una carga media en cuanto a operacionesaritméticas por acceso a memoria se refiere.<strong>La</strong>s latencias <strong>de</strong> los accesos se balancean con el tiempo<strong>de</strong> cómputo en otros warps. Por tanto, los mejoresresultados vuelven a obtenerse con los bloques máspequeños <strong>de</strong> máxima ocupación (192 hilos). Al nohaber coalescencia, los resultados <strong>de</strong>pen<strong>de</strong>n exclusivamente<strong>de</strong>l tamaño <strong>de</strong> bloque, no <strong>de</strong> su geometría.<strong>La</strong> <strong>de</strong>sactivación <strong>de</strong> la caché L1 reduce el tamaño<strong>de</strong> los segmentos <strong>de</strong> transacción a una cuarta parte.Por tanto, en patrones dispersos o aleatorios don<strong>de</strong>apenas exista reutilización <strong>de</strong> segmentos, un menortamaño <strong>de</strong> estos disminuye el tráfico <strong>de</strong> datos entrelas distintas memorias y alivia los cuellos <strong>de</strong> botella.En el caso <strong>de</strong> accesos dispersos regulares se consigueuna mejora <strong>de</strong> rendimiento <strong>de</strong> entre 20-40 % para diferentestamaños <strong>de</strong> bloques. Para los accesos aleatorios,la mejora no es significativa ya que la alta cargacomputacional en los warps se solapa con los tiempos<strong>de</strong> trasferencia.VII. Trabajo relacionado<strong>La</strong> estrategia más común a la hora <strong>de</strong> implementarun código CUDA es seleccionar bloques <strong>de</strong> hiloscuyos tamaños consigan maximizar la ocupación <strong>de</strong>los SMs. El objetivo <strong>de</strong> maximizar la ocupación esreducir las latencias en los accesos a memoria global[1]. Este trabajo sigue la ten<strong>de</strong>ncia habitual <strong>de</strong>seleccionar bloques cuadrados cuyas cardinalida<strong>de</strong>sson potencias <strong>de</strong> dos con el objetivo <strong>de</strong> facilitar laimplementación <strong>de</strong> los códigos. El impacto <strong>de</strong> geometríasno cuadradas, así como las cardinalida<strong>de</strong>s <strong>de</strong>las dimensiones correspondientes a potencias <strong>de</strong> tres,<strong>JP2011</strong>-684


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011ColumnsRows 32 48 64 96 128 192 256 384 512 768 1 0241 1,1087 0,9048 0,7893 0,6852 0,6582 0,6268 0,6358 0,6312 0,6330 0,6635 0,7885TABLA IReducción <strong>de</strong> vector. Execution times (ms.)ColumnsRows 8 12 16 24 32 48 64 96 128 192 256 384 512 768 1 024128 9.0196 6.3564 5.49 5.48 5.7848 5.24 5.60 4.0032 4.86 4.80 3.36 3.88 4.2324 4.70 4.68 3.28 4.17 3.0716 5.05 4.43 3.23 3.45 3.04 3.38 4.1412 5.42 4.58 3.28 3.55 3.02 3.43 3.058 6.05 4.97 3.42 3.41 2.96 3.05 2.95 3.17 4.456 7.18 5.52 3.87 3.53 2.95 3.06 2.94 3.46 3.194 9.70 6.73 5.06 3.92 3.11 3.10 2.90 3.00 3.05 3.19 4.443 11.94 8.48 6.16 4.64 3.53 3.12 2.89 2.96 2.95 3.35 3.182 16.43 11.43 8.55 6.12 4.54 3.68 3.08 2.93 2.93 2.95 2.96 2.99 3.951 29.97 20.24 15.16 10.51 7.74 5.73 4.40 3.49 3.08 2.89 2.89 2.91 2.94 3.01 3.94TABLA IISuma <strong>de</strong> matrices. Execution times (ms.)ColumnsRows 32 48 64 96 128 192 256 384 512 768 1 02432 644124 584216 5218 6094 657912 5121 6478 59798 4982 5862 5265 5479 64706 4860 5775 5293 5940 54574 6177 4746 4855 4898 4915 4743 60663 7960 5918 4653 4928 4649 5421 45202 11890 8121 6103 4415 4339 4325 4450 4288 61721 23730 16086 12073 8399 6967 5855 5866 5909 6120 5951 7223TABLA IIImultiplicación <strong>de</strong> matrices. Execution times (ms.)ColumnsRows 8 12 16 24 32 48 64 96 128 192 256 384 512 768 1 024128 12.896 12.664 12.5 12.6 12.648 12.4 12.4 12.532 12.2 12.3 12.3 12.3 12.324 12.1 12.1 12.1 12.1 12.116 11.8 11.9 11.9 12.0 12.0 12.0 11.912 11.6 11.7 11.8 11.8 11.8 11.8 11.88 11.2 11.4 11.5 11.7 11.7 11.7 11.7 11.7 11.66 10.8 11.1 11.2 11.5 11.6 11.6 11.6 11.5 11.64 11.5 11.5 11.5 11.1 11.3 11.5 11.5 11.5 11.5 11.5 11.23 10.2 10.4 10.5 10.9 11.0 11.3 11.4 11.4 11.4 11.3 11.42 10.2 9.9 10.0 10.5 10.6 11.0 11.1 11.3 11.4 11.3 11.3 11.3 10.91 12.8 11.4 10.0 9.7 9.9 10.4 10.5 10.8 11.0 11.3 11.3 11.3 11.2 11.2 11.1TABLA IVAccesos regularmente dispersos. Execution times (ms.)<strong>JP2011</strong>-685


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011ColumnsRows 32 48 64 96 128 192 256 384 512 768 1 02432 *24 347.2716 388.41 345.63 *12 334.81 367.85 347.798 330.47 332.90 388.28 347.56 *6 324.86 325.46 334.77 369.78 347.234 325.50 347.18 330.47 334.99 388.41 347.18 *3 328.07 357.41 324.82 327.35 334.75 369.59 347.302 370.40 326.11 325.48 324.88 330.43 334.72 388.42 347.17 *1 634.43 490.32 370.41 328.04 325.47 324.82 330.43 334.80 388.49 347.45 *TABLA VAccesos aleatorios. Execution times (ms.)no están suficientemente estudiadas.Wynters, en [6], muestra una implementación trivial<strong>de</strong> la multiplicación <strong>de</strong> matrices don<strong>de</strong> se pruebanvarios tamaños <strong>de</strong> bloques. Este es otro ejemplodon<strong>de</strong> no se consi<strong>de</strong>ran las geometrías rectangulares.A<strong>de</strong>más, este trabajo está basado en arquitecturaspre-Fermi.En [7] y [8] se muestran implementaciones <strong>de</strong> variosproblemas variando una serie <strong>de</strong> parámetros significativostales como el tamaño <strong>de</strong> bloque, el tamaño<strong>de</strong> los datos <strong>de</strong> entrada, la precarga <strong>de</strong> datos y lacarga <strong>de</strong> trabajo por hilo entre otros. <strong>La</strong> información<strong>de</strong>l rendimiento obtenido en estas pruebas se analizapara reducir el espacio <strong>de</strong> búsqueda y ayudar alprogramador a seleccionar la configuración óptima.De nuevo, este trabajo sólo consi<strong>de</strong>ra arquitecturaspre-Fermi.Sobre Fermi, en [9], muestra cómo la jerarquía<strong>de</strong> memoria caché introducida por esta arquitecturamejora significativamente la localidad <strong>de</strong> los datosaumentando el rendimiento global <strong>de</strong> las aplicaciones.Sin embargo, este trabajo no estudia como serelacionan los efectos producidos por las memoriascaché con los diferentes tamaños y geometrías <strong>de</strong> losbloques <strong>de</strong> hilos.VIII. ConclusionesHoy en día <strong>de</strong>sarrollar códigos que consigan explotareficientemente las capacida<strong>de</strong>s <strong>de</strong> los dispositivosGPU sigue siendo un trabajo muy complicado ya quees necesario conocer estrechamente la arquitectura <strong>de</strong>cada dispositivo.Una <strong>de</strong> las <strong>de</strong>cisiones más importantes a la hora<strong>de</strong> <strong>de</strong>sarrollar códigos para estos dispositivos esla elección apropiada <strong>de</strong> los parámetros globales <strong>de</strong>configuración. Dichos parámetros incluyen el tamañoy la geometría <strong>de</strong>l bloque, así como configuración lamemoria caché L1. Estas elecciones presenta un impactosignificativo sobre el rendimiento global <strong>de</strong> lasaplicaciones, explicables a partir <strong>de</strong> las características<strong>de</strong> la arquitecta <strong>de</strong>l dispositivo GPU.<strong>La</strong> arquitectura Fermi introduce nuevas característicashardware que impi<strong>de</strong>n reutilizar el conocimientoadquirido con las versiones anteriores. Estetrabajo presenta un estudio y evaluación inicial <strong>de</strong>la arquitectura Fermi para ayudar a <strong>de</strong>terminar laconfiguración óptima.<strong>La</strong> elección <strong>de</strong> los parámetros globales están estrechamenterelacionados con la implementación <strong>de</strong>cada problema. En este artículo mostramos que unestudio combinado <strong>de</strong>l conocimiento <strong>de</strong> la arquitecturaGPU y las características propias <strong>de</strong> la implementación<strong>de</strong>l código pue<strong>de</strong> significativamente ayudar enla elección <strong>de</strong>l tamaño y la geometría <strong>de</strong>l bloque <strong>de</strong>hilos, así como en la configuración <strong>de</strong> la memoriacaché L1.Agra<strong>de</strong>cimientosEsta investigación está parcialmente financiadapor el Ministerio <strong>de</strong> Industria (CENIT MARTA,CENIT OASIS, CENIT OCEANLIDER), Ministerio<strong>de</strong> Ciencia y Tecnología (CAPAP-H3 network,TIN2010-12011-E) y el proyecto HPC-EUROPA2(N o :228398).Referencias[1] David B. Kirk and Wen-mei W. Hwu, Programming MassivelyParallel Processors: A Hands-on Approach, MorganKaufmann, Feb. 2010.[2] NVIDIA, “Whitepaper: NVIDIA’s next generationCUDA compute architecture: Fermi,” 2010,http://www.nvidia.com/object/fermi architecture.html,<strong>La</strong>st visit: Nov, 2010.[3] NVIDIA, “Fermi Architecture HomePage,” <strong>La</strong>st visit: August 2, 2010,http://www.nvidia.com/object/fermi architecture.html.[4] NVIDIA, “Nvidia cuda programming gui<strong>de</strong> 3.0 fermi,”2010.[5] Paulius Micikevicius Greg Ruetsch, “Nvidiaoptimizing matrix transpose in cuda,”http://<strong>de</strong>veloper.download.nvidia.com/compute/cuda/3 0/sdk/website/CUDA/website/C/src/transposeNew/doc/MatrixTranspose.pdf, June 2010, <strong>La</strong>st visit: Dec 2,2010.[6] Erik Wynters, “Parallel processing on nvidia graphics processingunits using cuda,” J. Comput. Small Coll., vol. 26,pp. 58–66, January 2011.[7] Shane Ryoo, Christopher I. Rodrigues, Sam S. Stone,John A. Stratton, Sain-Zee Ueng, Sara S. Baghsorkhi,and Wen-Mei W. Hwu, “Program optimization carvingfor GPU computing,” Journal of Parallel and DistributedComputing, vol. 68, no. 10, pp. 1389–1401, Oct. 2008.[8] Sara S. Baghsorkhi, Matthieu Delahaye, Sanjay J. Patel,William D. Gropp, and Wen-mei W. Hwu, “An adaptiveperformance mo<strong>de</strong>ling tool for gpu architectures,” SIG-PLAN Not., vol. 45, pp. 105–114, January 2010.[9] Changyou Zhang Xiang Cui, Yifeng Chen and Hong Mei,“Auto-tuning <strong>de</strong>nse matrix multiplication for GPGPUwith cache,” in Proc. ICPADS’2010, Shanghai, China,Dec. 2010, pp. 237–242.<strong>JP2011</strong>-686


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Estrategias <strong>de</strong> optimización en diferentesarquitecturas CUDA usando llCoMPRuymán Reyes, Juan José Fumero, Iván López, Francisco <strong>de</strong> San<strong>de</strong> 1Resumen— Debido al uso cada vez más extendido <strong>de</strong>aceleradores hardware en entornos <strong>de</strong> Computación<strong>de</strong> Altas Prestaciones, científicos e ingenieros inviertenmucho tiempo optimizando códigos para estetipo <strong>de</strong> plataformas. Los fabricantes por su parte,producen nuevas versiones <strong>de</strong> estos dispositivos cadapocos años. <strong>La</strong> cuestión que se <strong>de</strong>spren<strong>de</strong> <strong>de</strong> estoes: ¿merece la pena optimizar dichos códigos? ¿Oes preferible esperar a que la siguiente versión <strong>de</strong>lhardware incremente el rendimiento <strong>de</strong> nuestros programas?En este trabajo se muestran los efectos<strong>de</strong> aplicar diferentes técnicas <strong>de</strong> optimización ampliamenteconocidas en tecnología <strong>de</strong> compiladores, aun conjunto <strong>de</strong> códigos, mostrando cómo afectan alrendimiento en las nuevas arquitecturas. Realizar unaoptimización manual <strong>de</strong> los diferentes códigos seríauna labor inasumible si no contáramos con alguna herramienta<strong>de</strong> prototipado rápido, como llCoMP, que permiteque la generación <strong>de</strong> código se realice <strong>de</strong> formasemi-automática. Esperamos que tanto nuestro trabajoexperimental como las conclusiones obtenidasa raíz <strong>de</strong> él, sirvan <strong>de</strong> orientación a <strong>de</strong>sarrolladoresCUDA.Palabras clave— GPGPU, CUDA, llc, optimizaciónI. Introducción<strong>La</strong> Computación <strong>de</strong> Altas Prestaciones (CAP) estáevolucionando a pasos agigantados. El número <strong>de</strong>arquitecturas capaces <strong>de</strong> alcanzar altos rendimientosse ha incrementado notablemente [1] en los últimosaños.Simultáneamente el precio <strong>de</strong> estas arquitecturasse ha reducido, posibilitando construir sistemas conun coste muy razonable por GFLOP. Sistemas constituidospor varios nodos don<strong>de</strong> cada nodo está compuestoa su vez por varios procesadores multi-núcleoson comunes hoy en día. <strong>La</strong> llegada <strong>de</strong> aceleradoreshardware como las GPU incrementan el rendimientosin incrementar el coste por GFLOP.No obstante, el uso generalizado <strong>de</strong> máquinasheterogéneas multicore o manycore, con complejasjerarquías <strong>de</strong> memoria, requieren <strong>de</strong> <strong>de</strong>sarrolladores<strong>de</strong>dicados para extraer su máximo potencial.El pico <strong>de</strong> rendimiento teórico disponible en ellases difícilmente alcanzado con las herramientas y libreríasdisponibles en la actualidad. Si bien losusuarios con mayores necesida<strong>de</strong>s <strong>de</strong> cómputo soncientíficos e ingenieros <strong>de</strong>dicados a resolver problemascomputacionalmente costosos, ellos no cuentancon la experiencia requerida para manejar las herramientasdisponibles para programar estas arquitecturasemergentes. Es clave para el avance <strong>de</strong> la cienciauna mejora sustancial en la programabilidad <strong>de</strong>estas arquitecturas, y facilitar a usuarios no expertosun uso más eficiente <strong>de</strong> las mismas.1 Dept. <strong>de</strong> E. I. O. y Computación <strong>Universidad</strong> <strong>de</strong> <strong>La</strong> <strong>La</strong>guna,38271–<strong>La</strong> <strong>La</strong>guna, Spain e-mail: {rreyes}@ull.esNo hay que olvidar que incluso es posible quelos <strong>de</strong>sarrolladores expertos no estén a<strong>de</strong>cuadamentepreparados para explotar a<strong>de</strong>cuadamente estos sistemas.Por ejemplo, los aceleradores hardware comolas tarjetas gráficas, tienen una arquitectura variableentre diferentes versiones <strong>de</strong>l mismo dispositivo. Sibien es cierto que el esquema global es el mismo, yque el mo<strong>de</strong>lo <strong>de</strong> programación <strong>de</strong> alto nivel es relativamentepoco variable entre versiones, no hay queolvidar que para extraer el máximo rendimiento <strong>de</strong>cada nueva versión <strong>de</strong>l dispositivo, el <strong>de</strong>sarrollador<strong>de</strong>be conocer todas sus peculiarida<strong>de</strong>s.Tanto OpenMP como MPI no fueron diseñadospara la actual heterogeneidad <strong>de</strong> los sistemasdisponibles, y, aunque existen esfuerzos para mejoraresta situación ([2]), estos aún están lejos <strong>de</strong> convertirseen una solución estandarizada.<strong>La</strong> situación particular en el campo <strong>de</strong> los aceleradoresgráficos es más diversa. Aunque el estandar <strong>de</strong>facto para la programación <strong>de</strong> estos dispositivos hasido CUDA [3], a través <strong>de</strong> una interfaz C con extensionespropietarias, este está únicamente disponiblepara tarjetas <strong>de</strong>l fabricante NVIDIA. Intel ha <strong>de</strong>sarrolladosu propio lenguaje para aceleradores gráficos:ArBB [4]. Este nuevo lenguaje permite <strong>de</strong>sarrollosSIMD más veloces y una fácil transformación <strong>de</strong> loscódigos existentes. OpenCL [5] preten<strong>de</strong> ser un estandarin<strong>de</strong>pendiente <strong>de</strong>l fabricante, que intenta proporcionaruna interfaz común para la programación<strong>de</strong> distintos dispositivos heterogéneos. A pesar <strong>de</strong> suinmadurez, parece un firme candidato a convertirseen uno <strong>de</strong> los lenguajes estrella para programar unnúmero cada vez mayor <strong>de</strong> dispostivos hardware.El objetivo <strong>de</strong> este trabajo es usar nuestrolenguaje, llc, y su compilador, llCoMP, como herramientas<strong>de</strong> prototipado rápido para estudiar diferentescasos <strong>de</strong> optimización <strong>de</strong> bucles. El impacto<strong>de</strong> estas optimizaciones en el rendimiento son usadaspara realizar una comparativa utilizando tres arquitecturasCUDA diferentes. Los resultados pue<strong>de</strong>nservir como guía para los <strong>de</strong>sarrolladores que buscanmejorar el rendimiento <strong>de</strong> sus programas usandoarquitecturas CUDA, elevando su productividad através <strong>de</strong> la reducción <strong>de</strong>l tiempo <strong>de</strong>dicado al <strong>de</strong>sarrollo<strong>de</strong>l código fuente.<strong>La</strong>s dos contribuciones más importantes <strong>de</strong> estetrabajo son las siguientes:(1) Se revela como una <strong>de</strong> las primeras comparativasentre las nuevas FERMI y sus arquitecturaspre<strong>de</strong>cesoras.(2) Se presenta llCoMP, una herramienta <strong>de</strong>prototipado rápido capaz <strong>de</strong> generar semiautomáticamentecódigo y optimizaciones para<strong>JP2011</strong>-687


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011CUDA.El resto <strong>de</strong> este trabajo se organiza como sigue:En la sección II se hace un resumen <strong>de</strong> las principalescaracterísticas <strong>de</strong> llc. A continuación <strong>de</strong>scriben lasprincipales técnicas <strong>de</strong> optimización disponibles en ellenguaje en la sección III. En la sección IV se estudiala aplicación <strong>de</strong> algunas <strong>de</strong> estas optimizaciones acasos prácticos. Se muestran allí códigos <strong>de</strong> ejemploimplementados en llc así como algunos resultadoscomputacionales para que el lector se haga una i<strong>de</strong>a<strong>de</strong> las características y posibilida<strong>de</strong>s <strong>de</strong>l lenguaje ysu compilador. Por último, se ofrecen algunas conclusionesy líneas <strong>de</strong> trabajo abiertas en la secciónV.II. El lenguage llc y su compiladorllc es un lenguage paralelo <strong>de</strong> alto nivel en el queel paralelismo se expresa mediante directivas <strong>de</strong> compilaciónal estilo <strong>de</strong> OpenMP. <strong>La</strong> mayor parte <strong>de</strong> lasdirectivas <strong>de</strong> éste son aceptadas, aunque se han hechoalgunos añadidos para aumentar la expresividadsemántica <strong>de</strong>l lenguaje y permitir al <strong>de</strong>sarrollador <strong>de</strong>llc expresar con mayor legibilidad las particularida<strong>de</strong><strong>de</strong> su código.Nuestro propósito con llc y su compilador llCoMPno es incrementar la diversidad <strong>de</strong> lenguajes y entornos<strong>de</strong> programación disponibles para CAP. Alcontrario, presentamos una forma simple <strong>de</strong> <strong>de</strong>sarrolloenfocado a diferentes arquitecturas para disminuirla brecha entre ingenieros <strong>de</strong> sistemas y <strong>de</strong>sarrolladores<strong>de</strong> aplicaciones CAP. <strong>La</strong>s extensiones <strong>de</strong>llc o las técnicas implementadas en llCoMP pue<strong>de</strong>nservir <strong>de</strong> guía a <strong>de</strong>sarrolladores mainstream <strong>de</strong> caraa la resolución <strong>de</strong> los problemas <strong>de</strong> programabilidad<strong>de</strong> los sistemas actuales.llCoMP es un compilador source-to-source que traducecódigo C anotado con directivas llc en códigoparalelo <strong>de</strong> alto nivel. Aunque llc soporta losconstructos paralelos más comunes - forall, sections,pipelines y task queues -, la nueva versión <strong>de</strong>l backend<strong>de</strong> CUDA llCoMP solo soporta bucles forall,aunque otros constructos están bajo estudio paraser incluídas en futuras versiones. Puesto que todaslas directivas y cláusulas <strong>de</strong> OpenMP son reconocidaspor llCoMP, a partir <strong>de</strong> un mismo códigofuente pue<strong>de</strong>n generarse diferentes binarios (secuencialo paralelos) <strong>de</strong>pendiendo <strong>de</strong>l compilador seleccionadopara traducir el código generado por nuestrocompilador.<strong>La</strong> nueva versión <strong>de</strong>l compilador llc pue<strong>de</strong> serconsi<strong>de</strong>rada como un extractor <strong>de</strong> kernels <strong>de</strong> CUDAa partir <strong>de</strong> constructos OpenMP, aunque preferimosconsi<strong>de</strong>rarla como una herramienta <strong>de</strong> prototipado.llCoMP representa una capa software intermediaentre llc y diferentes backends para este lenguaje.El compilador ha sido diseñado con el propósito <strong>de</strong>que abordar implementaciones para diferentes arquitecturas<strong>de</strong>stino no requiera <strong>de</strong>masiado esfuerzo.llCoMP se ha implementado usando Python con unenfoque orientado a objetos. Para el frontend, hemosusado el módulo pycparser [6] para construir una representaciónintermedia <strong>de</strong>l código C. <strong>La</strong> arquitecturasofware <strong>de</strong>sarrollada nos permite escribir un conjunto<strong>de</strong> transformaciones source-to-source que posibilitanla escritura <strong>de</strong> kernels CUDA a partir <strong>de</strong> la informaciónextraída <strong>de</strong>l código llc original.A<strong>de</strong>más <strong>de</strong>l enfoque clásico <strong>de</strong>l <strong>de</strong>sarrollo <strong>de</strong> entornos<strong>de</strong> programación para CAP, don<strong>de</strong> la facilidad<strong>de</strong> uso está <strong>de</strong>stinada al usuario, nuestra propuestatambién está dirigida a arquitectos <strong>de</strong> hardware.Creemos que un rápido <strong>de</strong>sarrollo <strong>de</strong>l backen<strong>de</strong>s la clave para la adopción <strong>de</strong> una nueva arquitectura,y la implementación <strong>de</strong> una gran variedad<strong>de</strong> arquitecturas es esencial para la adaptación <strong>de</strong>un compilador. Si un nuevo backend para un compiladorse pue<strong>de</strong> implementar en pocas semanas, elhardware se pue<strong>de</strong> evaluar en menos tiempo por ungran número <strong>de</strong> usuarios, facilitando por tanto laadopción <strong>de</strong> un nuevo hardware.Para posibilitar un proceso rápido <strong>de</strong> construcción<strong>de</strong> backends introducimos el concepto <strong>de</strong> plantillas.<strong>La</strong>s plantillas capturan los patrones paralelos máshabituales. El compilador se ayuda <strong>de</strong> un conjunto<strong>de</strong> herramientas que, partiendo <strong>de</strong> la representaciónintermedia y <strong>de</strong> un análisis <strong>de</strong>l código fuente, permitengenerar códigos eficientes para la plataforma<strong>de</strong>stino.llCoMP traduce el código <strong>de</strong> entrada a su árbolsintáctico (AST) correspondiente. Este AST setransforma posteriormente para convertirlo en unarepresentación intermedia. Sobre esta representaciónintermedia se trabajará para aplicar cualquier transformacióny así po<strong>de</strong>r generar código CUDA, MPI,etc. Para po<strong>de</strong>r hacer transformaciones, se usan algunospatrones <strong>de</strong> software. Por ejemplo, para buscarun nodo en el AST, se usa el patrón Filter. Unavez que se se ha encontrado un <strong>de</strong>terminado nodo, sele pue<strong>de</strong> aplicar un mutador que es la sustitución <strong>de</strong>ese nodo por otro (patrón Mutator). Tras aplicar lastransformaciones necesarias mediante filtros y mutadores,el AST resultante se procesa mediante la claseWriter para producir el código correspondiente.<strong>La</strong>s transformaciones implementadas a través <strong>de</strong>lpatrón Mutator pue<strong>de</strong>n realizarse utilizando plantillasen lugar <strong>de</strong> implementarlas en código python.Una plantilla es un fragmento <strong>de</strong> código escrito enel lenguaje <strong>de</strong>stino, que se modifica en función <strong>de</strong>ciertos parámetros <strong>de</strong> entrada. Este código es interpretadoy traducido a la representación intermedia,y a continuación se inserta en el punto a<strong>de</strong>cuado <strong>de</strong>lAST. El diseño <strong>de</strong>l backend utilizando plantillas <strong>de</strong>código facilitará la implementación futura <strong>de</strong> nuevosbackends.<strong>La</strong> inicialización y la reserva <strong>de</strong> memoria son operacionescomunes para todos los tipos <strong>de</strong> dispositivoshardware. Cada una <strong>de</strong> estas operaciones i<strong>de</strong>ntificaun patrón y éste se implementa a través <strong>de</strong> una plantilla<strong>de</strong> código. Para manipular estas plantillas e insertarnuevo código en el AST llCoMP agrupa esteconjunto <strong>de</strong> operaciones en una interfaz común. Actualmente,los patrones implementados son:• Inicialización <strong>de</strong>l dispositivo:contiene tareas<strong>JP2011</strong>-688


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011como i<strong>de</strong>ntificación <strong>de</strong>l disposivo o la asignación<strong>de</strong> recursos.• Invocación <strong>de</strong>l kernel: el código que se ha <strong>de</strong>paralelizar es extraído <strong>de</strong>l código fuente llc yel compilador lo inserta en el punto especificadopor el arquitecto hardware.• Liberación <strong>de</strong> recursos.Aunque una implementación directa en CUDAsiempre obtendrá mejor rendimiento, hay ocasionesen las que pue<strong>de</strong> resultar más productivo <strong>de</strong>sarrollaren llc y obtener el código CUDA usando nuestrocompilador. Es más, si se necesita obtener unmayor rendimiento, se pue<strong>de</strong> modificar manualmenteel código generado por nuestro compilador y así producircódigo más eficiente.III. Optimizaciones en el backend <strong>de</strong> CUDAllCoMP permite seleccionar la plataforma parala cual se generará código a través <strong>de</strong> la directivapragma omp target [7], cuyo parámetro es el i<strong>de</strong>ntificador<strong>de</strong> la plataforma: CUDA, MPI o SMP seleccionadapor el programador para el código <strong>de</strong>stino<strong>de</strong> la región anotada. En caso <strong>de</strong> que el <strong>de</strong>sarrolladorelija CUDA como plataforma <strong>de</strong>stino podráhacer uso <strong>de</strong> diferentes optimizaciones disponibles enllCoMP.Para mantener la consistencia <strong>de</strong> memoria tras laejecución <strong>de</strong> una región paralela, llCoMP copia todaslas variables asociadas al ámbito <strong>de</strong> la región paralelahacia y <strong>de</strong>s<strong>de</strong> la tarjeta gráfica. Este comportamientose pue<strong>de</strong> modificar a través <strong>de</strong> las cláusulascopy in y copy out que permiten al programadorindicar explícitamente las variables que han <strong>de</strong> sercomunicadas, reduciendo <strong>de</strong> este modo las transferencias<strong>de</strong> memoria.Revisamos a continuación las optimizaciones implementadasen la actualidad.A. Optimización <strong>de</strong> bucles<strong>La</strong> optimización <strong>de</strong> bucles es un aspecto crucial ala hora <strong>de</strong> mejorar el rendimiento <strong>de</strong> cualquier aplicaciónparalela. llCoMP pone a disposición <strong>de</strong>l programadortres tipos <strong>de</strong> optimizaciones sobre bucles:• Desenrollado. Mediante la directiva pragmaunroll el programador anota los bucles que han<strong>de</strong> ser <strong>de</strong>senrollados. <strong>La</strong> cláusula factor <strong>de</strong> estadirectiva indica el factor <strong>de</strong> <strong>de</strong>senrollado.• Intercambio. Supuesto que no hay <strong>de</strong>pen<strong>de</strong>nciasen el cuerpo <strong>de</strong> dos bucles anidados, el intercambio<strong>de</strong> bucles pue<strong>de</strong> en ciertos casos mejorarel rendimiento. <strong>La</strong> directiva pragma llcinterchange permite en llc indicar al compiladorque intercambie entre sí dos bucles anidados.• Fusión. <strong>La</strong> cláusula COLLAPSE recibe comoparámetro un número positivo que indica alcompilador cuántos bucles <strong>de</strong>be fusionar antes<strong>de</strong> paralelizar el bucle resultante. El backend <strong>de</strong>CUDA genera kernels 2D para todos aquellosbucles anotados con esta cláusula.TABLA I: Plataformas utilizadas en los casos <strong>de</strong> estudioNombre Ilion Peco ZapeManuf. Intel Intel AMDMo<strong>de</strong>lo Q9500 E5520 Phenom 9550Núcleos 4 4 4Hilos 4 8 4L2 (Mb) 6 1 2L3 (Mb) - 8 2Reloj (GHz) 2.83 2.26 2.20Placa 9800GT C1060 GTX 480Memoria (Gb) 3 4 4B. Reducciones en paralelo<strong>La</strong> cláusula <strong>de</strong> reducción que se pue<strong>de</strong> añadir a ladirectiva pragma omp for señala al compilador que<strong>de</strong>be inyectar código específico para llevar a cabo unareducción. llCoMP aña<strong>de</strong> una plantilla genérica yoptimizada tomada <strong>de</strong> [8].C. Ajuste <strong>de</strong> los parámetros <strong>de</strong> ejecución <strong>de</strong>l kernelEl número <strong>de</strong> hilos por bloque a la hora <strong>de</strong> ejecutarun kernel <strong>de</strong> CUDA <strong>de</strong>be ser escogido cuidadosamentepues pue<strong>de</strong> influir <strong>de</strong> manera notable enel rendimiento.Los usuarios <strong>de</strong> llCoMP han <strong>de</strong> especificar elnúmero <strong>de</strong> hilos que ejecutarán un bloque <strong>de</strong> códigoparalelo. Usando esta información y, tras un análisis<strong>de</strong> los bucles, el compilador calcula el número <strong>de</strong> bloquesa<strong>de</strong>cuado para ejecutar el kernel. El número <strong>de</strong>hilos se especifica mediante la variable <strong>de</strong> entornoLLC GPU NUM THREADS.IV. Casos <strong>de</strong> estudioCon el fin <strong>de</strong> estudiar diferentes técnicas <strong>de</strong> optimización<strong>de</strong> bucles en arquitecturas CUDA, presentamosla implementación en llc <strong>de</strong> tres aplicaciones:Man<strong>de</strong>lbrot, Jacobi y una simulación <strong>de</strong> dinámicamolecular. El código fuente <strong>de</strong> estos ejemplos estádisponible en la web <strong>de</strong>l proyecto [9]. Todos loscódigos operan con números flotan<strong>de</strong>s <strong>de</strong> doble precisión.<strong>La</strong>s ejecuciones se han realizado en tres plataformasdiferentes <strong>de</strong>talladas en la tabla I. Nótese quecada sistema es completamente diferente. En lasgráficos se ha medido el tiempo <strong>de</strong> ejecución <strong>de</strong>los kernels <strong>de</strong> CUDA sin contabilizar las transferencias<strong>de</strong> memoria (excepto cuando el problema lo requiere).En algunos resultados se compara tambiénla diferencia <strong>de</strong> rendimiento entre ejecutar un códigoOpenMP en la CPU y el código CUDA correspondienteejecutado en la GPU. Nuestro propósito esmostrar la importante mejora obtenida añadiendouna tarjeta gráfica a un pequeño multiprocesador.A<strong>de</strong>más, el consumo <strong>de</strong> esta combinación <strong>de</strong> multiprocesador+aceleradortiene potencialmente un consumomenor que un sistema multinodo <strong>de</strong> equivalentepotencia.<strong>JP2011</strong>-689


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011A. Cálculo <strong>de</strong>l área <strong>de</strong>l conjunto <strong>de</strong> Man<strong>de</strong>lbrotEl conjunto <strong>de</strong> Man<strong>de</strong>lbrot es el dominio <strong>de</strong> convergencia<strong>de</strong> la serie compleja Z n = Z n−1 2 + C.Usando el método Monte-Carlo, el algoritmo <strong>de</strong>l Listado1 calcula una estimación <strong>de</strong> dicha área.Cando llCoMP genera el código CUDA, localizaregiones paralelas precedidas por la directiva omptarget seguida <strong>de</strong> la indicación CUDA (línea 1).Una vez <strong>de</strong>tecteda esta situación, el compiladoraña<strong>de</strong> los patrones <strong>de</strong> transferencia <strong>de</strong> datos en elcódigo generado y encapsula el cuerpo <strong>de</strong>l bucle enun kernel <strong>de</strong> CUDA. Finalmente, se insertan los patrones<strong>de</strong> lectura <strong>de</strong> datos y liberación <strong>de</strong> recursos.En el código se pue<strong>de</strong> ver, por ejemplo, como seutiliza la cláusula reduction <strong>de</strong> OpenMP, que activarála generación <strong>de</strong> un kernel especializado parareducción en el momento <strong>de</strong> la traducción, tal ycomose comentó en la sección III.El kernel implementado en llCoMP [8] usa direccionamientosentrelazados y realiza la primera sumamientras se cargan los datos <strong>de</strong>s<strong>de</strong> la memoria global.Estas mejoras aprovechan el dispositivo para realizarla reducción y minimizan la cantidad <strong>de</strong> informaciónque requiere ser transferida entre host y dispositivo.lanzamiento <strong>de</strong>l kernel (hilos, número <strong>de</strong> bloque ycantidad <strong>de</strong> memoria compartida por bloque). <strong>La</strong>única herramienta proporcionada por NVIDIA paraeste propósito es la calculadora <strong>de</strong> ocupación <strong>de</strong>CUDA [10]. <strong>La</strong> Figura 1 muestra cómo difieren estosparámetros <strong>de</strong> una tarjeta a otra. Nuestra experienciasugiere que encontrar la combinación óptima noes trivial.B. Método <strong>de</strong> JacobiUna cuestión clave en CUDA para mejorar elrendimiento es reducir las transferencias <strong>de</strong> datos entreel host y el dispositivo.Listado 2: Bucle <strong>de</strong> Jacobi realizado en llc/OpenMP1 while ((k < maxit ) && ( error > tol )) {2 error = 0.0;3 # pragma omp target <strong>de</strong>vice ( cuda )copy_in (uold , f, u) copy_out (u)4 # pragma omp parallel shared (uold , u,...) private (i, j, resid )5 {6 # pragma omp for7 for (i = 0; i < m; i ++)8 for (j = 0; j < n; j ++)9 uold [i][j] = u[i][j];10 # pragma omp for reduction (+: error )11 for (i = 0; i < (m - 2); i ++) {12 for (j = 0; j < (n - 2); j ++) {13 resid = ...14 ...15 error += resid * resid ;16 }17 }18 }19 k ++;20 error = sqrt ( error ) / ( double ) (n * m);21 }Fig. 1: Comparativa, en tres arquitecturas distintas,<strong>de</strong>l tiempo <strong>de</strong> cómputo <strong>de</strong>l área <strong>de</strong>l conjunto <strong>de</strong>Man<strong>de</strong>lbrot usando distinto número <strong>de</strong> hilos para untamaño <strong>de</strong> problema <strong>de</strong> 16384 puntos.<strong>La</strong> Figura 1 muestra, para las tres plataformasCUDA examinadas, el tiempo <strong>de</strong> ejecución necesariopara calcular el área <strong>de</strong>l conjunto <strong>de</strong> Man<strong>de</strong>lbrot variandoel número <strong>de</strong> hilos por bloque.Es importante resaltar que, para un dispositivodado, incrementar la ocupación <strong>de</strong> los multiprocesadorespue<strong>de</strong> resultar una mejor manera <strong>de</strong> optimizarel rendimiento que usar un elevado número<strong>de</strong> hilos. Aunque pueda resultar contrario a la intuición,en algunas situaciones, se ha obtenido unmejor rendimiento con un pequeño número <strong>de</strong> hilosen relación con el tamaño <strong>de</strong>l bloque. Con unmenor número <strong>de</strong> hilos, un mayor número <strong>de</strong> bloquespue<strong>de</strong>n ser asignados al mismo multiprocesadory, por consiguiente, más bloques pue<strong>de</strong>n ser ejecutadosconcurrentemente.Esta es una <strong>de</strong> las razones por las que es tan importanteelegir cuidadosamente los parámetros <strong>de</strong>El código <strong>de</strong>l Listado 2 es el bucle <strong>de</strong>l método <strong>de</strong>Jacobi en llc y OpenMP. En la línea 3 se especificael dispositivo sobre el que se ejecutará el bucle paralelo<strong>de</strong> las líneas 7 a la 11. <strong>La</strong>s cláusulas copy iny copy out <strong>de</strong> la directiva <strong>de</strong> la línea 3 indican lasregiones <strong>de</strong> memoria que serán transferidas a y <strong>de</strong>s<strong>de</strong>el dispositivo.Fig. 2: Aceleración <strong>de</strong>l código Jacobi para distintostamaños <strong>de</strong> entrada (<strong>La</strong>s dimensiones <strong>de</strong> las matricesson N × N), usando la Tesla C1060<strong>La</strong> figura 2 mi<strong>de</strong> el impacto en el rendimiento <strong>de</strong>esta característica <strong>de</strong> llc comparando una imple-<strong>JP2011</strong>-690


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Listado 1: Cálculo <strong>de</strong>l áera <strong>de</strong>l conjunto <strong>de</strong> Man<strong>de</strong>lbrot llc1 # pragma omp target <strong>de</strong>vice ( cuda ) copy_in (c)2 # pragma omp parallel for reduction (+: numoutsi<strong>de</strong> ) private (i,j,ztemp ,z) shared (nt ,c)3 {4 numoutsi<strong>de</strong> = 0;5 for (i = 0; i < npoints ; i ++) {6 z. creal = c[i]. creal ;7 z. cimag = c[i]. cimag ;8 for (j = 0; j < MAXITER ; j ++) {9 ztemp = (z. creal * z. creal ) - (z. cimag * z. cimag ) + c[i]. creal ;10 z. cimag = z. creal * z. cimag * 2 + c[i]. cimag ;11 z. creal = ztemp ;12 if (z. creal * z. creal + z. cimag * z. cimag > THRESOLD ) {13 numoutsi<strong>de</strong> ++;14 break ;15 }16 } /* for j */17 } /* for i */18 }mentación pura en OpenMP (8 hilos, uno por core)con el código CUDA generado por llCoMP especificando(etiqueta CUDA v2) las transferencias <strong>de</strong>memoria con dichas cláusulas y sin hacerlo (etiquetaCUDA v1).En nuestra estrategia <strong>de</strong> traducción sincronizamoslas memorias <strong>de</strong> host y dispositivo al final <strong>de</strong> cadaregión paralela. Dentro <strong>de</strong> una región paralela asumimosque las posiciones <strong>de</strong> memoria ubicadas en elhost no cambian.El bucle anidado <strong>de</strong>l método <strong>de</strong> Jacobi es un buencandidato a optimizarse utilizando fusión <strong>de</strong> bucles.Cuando el backend CUDA <strong>de</strong> llCoMP encuentradicha cláusula genera un kernel 2D. <strong>La</strong> coor<strong>de</strong>nada xrepresenta el primer bucle y la coor<strong>de</strong>nada y representalas iteraciones <strong>de</strong>l segundo bucle. Esta implementaciónproduce hilos CUDA más ligeros, reducelos conflictos en el acceso a memoria e incrementala granularidad. Sin embargo, <strong>de</strong>be ser escogida concuidado la configuración para lanzar el kernel paramejorar el rendimiento, como se pue<strong>de</strong> observar enla Figura 3. Los resultados computacionales que utilizanintercambio <strong>de</strong> bucles no producen mejoras significativas<strong>de</strong>l rendimiento.C. Dinámica molecular (MD)El código MD calcula la energía y fuerzas <strong>de</strong> unsistema formado por N partículas. El problema requierenumerosas iteraciones para obtener una aproximacióna la solución, cuya exactitud está <strong>de</strong>terminadapor el incremento temporal escogido para lasimulación.En cada paso <strong>de</strong> la simulación el algoritmo realizados operaciones básicas: calcular y actualizar. <strong>La</strong>actualización se realiza mediante un bucle for queactualiza las posiciones, velocida<strong>de</strong>s y aceleraciones<strong>de</strong> las partículas.Des<strong>de</strong> el punto <strong>de</strong> vista computacional, la rutina<strong>de</strong> cálculo es más costosa que la <strong>de</strong> <strong>de</strong> actualización.Con este problema preten<strong>de</strong>mos estudiar la mejorcombinación GPU/CPU para el código paralelo. Denotandoa la CPU con C y a la GPU con una G.Hemos medido el rendimiento <strong>de</strong> cuatro versiones diferentes<strong>de</strong>l código:CC: las dos rutinas en la CPU (código puroOpenMP)GG: las dos rutinas en la GPU (código puroCUDA)GC: cálculo en la GPU y actualización en la CPUCG: cálculo en la CPU y actualización en la GPUFig. 3: Aceleración en el código Jacobi usando lacláusula COLLAPSE(2). Los parámetros óptimos paraejecutar el kernel <strong>de</strong>pen<strong>de</strong>n <strong>de</strong> la arquitectura.Fig. 4: Aceleración <strong>de</strong>l código MD para diferentesestrategias <strong>de</strong> paralelización usando Tesla C1060 yocho hilos OpenMP<strong>JP2011</strong>-691


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>La</strong> figura 4 muestra la aceleración obtenida paratres tamaños diferentes <strong>de</strong>l problema (número <strong>de</strong>partículas, np). El mejor rendimiento se da cuandolas dos rutinas se ejecutan en la GPU. Para loscódigos híbridos OpenMP/CUDA, la mejor elecciónes alojar la parte más costosa en la GPU.A este código se le pue<strong>de</strong>n aplicar una gran variedad<strong>de</strong> optimizaciones. Una <strong>de</strong> las más obvias es<strong>de</strong>senrrollar los bucles en la rutina <strong>de</strong> cálculo. Otraposibilidad es fusionar los bucles <strong>de</strong> la función <strong>de</strong> actualizacióndado que hace un uso intensivo <strong>de</strong> memoriay se reduciría el número <strong>de</strong> accesos a ésta por hilo,disminuyendo así las posibilida<strong>de</strong>s <strong>de</strong> conflicto. Enla gráfica 5 se observan, para cada arquitectura, losefectos <strong>de</strong> las diferentes optimizaciones. Para cadaarquitectura se buscó la mejor configuración posiblepara ejecutar el kernel <strong>de</strong>l algoritmo.Fig. 5: Mejoras en el rendimiento usando <strong>de</strong>senrolladoy fusión <strong>de</strong> bucles en las arquitecturas evaluadasV. Conclusiones y líneas <strong>de</strong> trabajoabiertasDurante los últimos años, las arquitecturas compatiblescon CUDA han sufrido una gran evolución,siendo constante la mejora en el rendimiento. Sinembargo, parte <strong>de</strong> los trabajos <strong>de</strong> optimización realizadospara las primeras arquitecturas compatiblesse revelan ahora como ineficaces, ya que en versionesmás recientes no son necesarias, ya sea por la incorporación<strong>de</strong> memorias adicionales, o por la posibilidad<strong>de</strong> ejecutar con un mayor número <strong>de</strong> threads.Los <strong>de</strong>sarrolladores interesados en los aceleradoreshardware <strong>de</strong>berían centrar sus esfuerzos en técnicasavanzadas <strong>de</strong> optimización que pudieran ser útiles enversiones futuras <strong>de</strong> la arquitectura. En particular,utilizar kernels 2D para operar con matrices pareceuna buena forma <strong>de</strong> mejorar el rendimiento <strong>de</strong> loscódigos en nuevas arquitecturas.Nuestro estudio se ha visto enormemente facilitadogracias al uso <strong>de</strong> llCoMP. Sin esta herramienta, elesfuerzo requerido para implementar los códigos presentadosen la sección anterior y sus optimizacionesen las diferentes arquitecturas nos hubiese impedidopresentar los resultados a tiempo para ser útiles.<strong>La</strong>s distintas técnicas <strong>de</strong> optimización implementadas(o pendientes <strong>de</strong> finalizarse en el momento<strong>de</strong> la escritura <strong>de</strong> este trabajo) en el nuevo backend<strong>de</strong>l compilador <strong>de</strong> llc permiten testear fácil yrápidamente diferentes técnicas <strong>de</strong> optimización paracualquier código. <strong>La</strong> pérdida <strong>de</strong> rendimiento con respectoa una implementación directa en CUDA estáclaramente justificada por la significativa reducción<strong>de</strong>l esfuerzo <strong>de</strong> <strong>de</strong>sarrollo.A<strong>de</strong>más, el uso <strong>de</strong> llCoMP permite <strong>de</strong>scubrirfácilmente la técnica <strong>de</strong> optimización más a<strong>de</strong>cuada,lo que redunda en un aumento <strong>de</strong> la productividad<strong>de</strong>l <strong>de</strong>sarrollador. Nuestro compilador está diseñadopara ser flexible y portable. Esperamos a<strong>de</strong>más quecon la experiencia adquirida durante el <strong>de</strong>sarrollo <strong>de</strong>lbackend <strong>de</strong> CUDA la incorporación <strong>de</strong> nuevos backend(como OpenCL, por ejemplo) no requiera <strong>de</strong>masiadosesfuerzos.Actualmente trabajamos en los siquientes aspectos:• Incrementar el número <strong>de</strong> algoritmos paralelizadosusando llCoMP, prestando especial atencióna aquellos que tengan una aplicación prácticareal.• Estudiar e implementar nuevas optimizacionesque permitan mejorar el rendimiento <strong>de</strong>l códigogenerado.Agra<strong>de</strong>cimientosEste trabajo ha sido parcialmente financiado porla UE (FEDER), MEC (proyecto TIN2008-06570-C04-03) y el Gobierno <strong>de</strong> Canarias (ACIISI, proyectoSolSubC200801000285). Los resultados computacionaleshan sido obtenidos usando los sistemas <strong>de</strong>lgrupo HPCA <strong>de</strong> la UJI.Referencias[1] André Rigland Brodtkorb, Christopher Dyken, Trond R.Hagen, Jon M. Hjelmervik, and Olaf O. Storaasli, “Stateof-the-artin heterogeneous computing,” Scientific Programming,vol. 18, pp. 1–33, 2010.[2] Ayguadé, E. et. al., “Extending OpenMP to survivethe heterogeneous multi-core era,” International Journalof Parallel Programming, vol. 38, no. 5-6, pp. 440–459,2010, cited By (since 1996) 0.[3] John Nickolls, Ian Buck, Michael Garland, and KevinSkadron, “Scalable parallel programming with CUDA,”Queue, vol. 6, no. 2, pp. 40–53, 2008.[4] Intel, “Sophisticated library for vector parallelism: Intelarray building blocks,” 2010.[5] Khronos Group, “OpenCL the open standard for parallelprogramming of heterogeneous systems,” 2008.[6] Eli Ben<strong>de</strong>rsky, “Pycparse,” 2009.[7] Ayguadé, E. et. al., “A proposal to extend the OpenMPtasking mo<strong>de</strong>l for heterogeneous architectures,” inIWOMP’09, Dres<strong>de</strong>n, Germany, 06/2009 2009, Springer,vol. 5568, pp. 154–167, Springer.[8] M. Harris, “Optimizing parallel reduction in CUDA,”2007.[9] “llc Home Page,” 2011, http://llc.pcg.ull.es.[10] NVIDIA Corp., “Cuda occupancy calculator, 2007.,”2007.<strong>JP2011</strong>-692


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Sistema modular <strong>de</strong>sarrollado en FPGA, para elcálculo <strong>de</strong> mapas <strong>de</strong> disparidad <strong>de</strong> imágenesestereoscópicas.Salvador Ibarra 1 , J. Ignacio Benavi<strong>de</strong>s 2 y M. Hernán<strong>de</strong>z Calviño 3Resumen— <strong>La</strong> solución <strong>de</strong>l problema <strong>de</strong>correspon<strong>de</strong>ncia, para encontrar la profundidad <strong>de</strong> loscomponentes <strong>de</strong> una escena a partir <strong>de</strong> dos imágenes, esfundamental en los sistemas <strong>de</strong> visión estereoscópica.Este problema ha sido extensamente estudiado dandocomo resultado le creación <strong>de</strong> una gran cantidad <strong>de</strong>algoritmos <strong>de</strong> correspon<strong>de</strong>ncia estereoscópica. Decidirque algoritmo <strong>de</strong>be ser utilizado <strong>de</strong>pen<strong>de</strong> <strong>de</strong> laaplicación particular, <strong>de</strong>biendo hacer una evaluaciónobjetiva en cuanto a la precisión, tiempo <strong>de</strong> cómputo yrecursos utilizados que <strong>de</strong>manda la aplicación. Con el<strong>de</strong>sarrollo <strong>de</strong> nuevas tecnologías <strong>de</strong> hardware como es elcaso <strong>de</strong> los FPGAs, se ha creado un enorme interés enimplementar, sobre ellas, aplicaciones <strong>de</strong> visiónestereoscópica para sistemas <strong>de</strong> tiempo real. En el marco<strong>de</strong>l diseño e implementación <strong>de</strong> un sistema <strong>de</strong> visiónestereoscópica que pueda ser integrado en un dispositivoautónomo móvil, resulta necesario <strong>de</strong>sarrollaraplicaciones que permitan evaluar que tipo <strong>de</strong>algoritmos presentan mejores características cuando sonimplementados en hardware. Aquí presentamos unsistema que permite evaluar, <strong>de</strong> manera sencilla yeficiente, diferentes algoritmos <strong>de</strong> correspon<strong>de</strong>nciaestereoscópica. Los resultados obtenidos indican que laherramienta diseñada proporciona informaciónsuficiente para evaluarlos en dos aspectos básicos, suoperación y los recursos utilizados. <strong>La</strong> herramienta <strong>de</strong>be<strong>de</strong> ser todavía mejor optimizada para obtener resultadosprecisos <strong>de</strong>l tiempo <strong>de</strong> cómputo, sobre todo parasistemas <strong>de</strong> tiempo real.Palabras clave— Correspon<strong>de</strong>ncia estereoscópica,FPGA, Controlador <strong>de</strong> Memoria.EI. INTRODUCCIÓNl uso <strong>de</strong> la visión estereoscópica para recuperarinformación tridimensional <strong>de</strong> una escena y calcularla profundidad <strong>de</strong> la misma, se ha convertido en un tema<strong>de</strong> interés en los últimos años en el campo <strong>de</strong> la visiónartificial. Sus características en términos <strong>de</strong> fiabilidad,exactitud, costo, rangos <strong>de</strong> operación, la han convertidoen un método ampliamente usado en áreas como larobótica, vehículos autónomos no tripulados,aplicaciones <strong>de</strong> seguridad, interface hombre máquina,entre otros.1 Unidad Académica <strong>de</strong> Ingeniería Eléctrica, <strong>Universidad</strong> Autónoma <strong>de</strong>Zacatecas, Zacatecas,México, e-mail:sibarra@intranet.uaz.edu.mx.2 Depto. De Arquitectura <strong>de</strong> Computadores, Electrónica y TecnologíaElectrónica, Escuela Técnica Superior, <strong>Universidad</strong> <strong>de</strong> Córdoba,Córdoba, España, e-mail: el1bebej@uco.es.3 Facultad <strong>de</strong> Física, <strong>Universidad</strong> <strong>de</strong> la Habana, <strong>La</strong> Habana, Cuba,email: mhernan@fisica.uh.cu.Existen una gran cantidad <strong>de</strong> sistemas que <strong>de</strong>bido a suscaracterísticas, <strong>de</strong>ben <strong>de</strong> realizar el cálculo <strong>de</strong> laprofundidad <strong>de</strong> la escena en tiempo real. Por ejemplo unsistema <strong>de</strong> navegación implantado sobre un dispositivoautónomo móvil <strong>de</strong>be <strong>de</strong> ser capaz <strong>de</strong> analizar el estado<strong>de</strong> una escena en el or<strong>de</strong>n <strong>de</strong> milisegundos, con elpropósito <strong>de</strong> que su módulo <strong>de</strong> navegación pueda tomar<strong>de</strong>cisiones y evadir los obstáculos que se interponenentre él y la meta a alcanzar.El presente proyecto tiene como objetivo, <strong>de</strong>sarrollaruna plataforma modular que permita evaluar diferentesalgoritmos, implementados en hardware <strong>de</strong>correspon<strong>de</strong>ncia estereoscópica, <strong>de</strong> tal forma que searelativamente sencillo el cambio <strong>de</strong> métrica <strong>de</strong>evaluación <strong>de</strong> la correspon<strong>de</strong>ncia estéreo. El resto <strong>de</strong>ldocumento está dividido <strong>de</strong> la siguiente manera: En lasección 2, se muestran y discuten los resultados <strong>de</strong>implementaciones previas. <strong>La</strong> sección 3, <strong>de</strong>scribe lascaracterísticas <strong>de</strong> la visión estereoscópica y dada lanecesidad <strong>de</strong>l uso <strong>de</strong> los bancos <strong>de</strong> memoria externa a laFPGA, la utilización <strong>de</strong> los controladores <strong>de</strong> memoria,que tienen los FPGAs <strong>de</strong> la presente generación, dadaslas características <strong>de</strong> las placas <strong>de</strong> <strong>de</strong>sarrollo actuales. <strong>La</strong>sección 4, muestra cómo fue diseñado el sistema y lainteracción <strong>de</strong> sus partes. <strong>La</strong> sección 5, muestra yexplica los resultados <strong>de</strong>l <strong>de</strong>sarrollo e implementación<strong>de</strong> los elementos <strong>de</strong>l proyecto, así como <strong>de</strong> suintegración final. <strong>La</strong> sección 6, discute los resultadosobtenidos. <strong>La</strong> sección 7, <strong>de</strong>ntro <strong>de</strong>l marco <strong>de</strong> un trabajoincremental, se propone diferentes alternativas quepermitan el <strong>de</strong>sarrollo <strong>de</strong> un sistema que evalúeeficientemente la aplicación <strong>de</strong> los algoritmos <strong>de</strong>correspon<strong>de</strong>ncia estereoscópica en sistemas <strong>de</strong> tiemporeal.II.MARCO CONCEPTUALA. Geometría <strong>de</strong>l Sistema EstereoscópicoEl uso <strong>de</strong> la visión estereoscópica es una alternativapara encontrar la profundidad <strong>de</strong> una escena basada enun par <strong>de</strong> imágenes cuyos centros ópticos se encuentranseparados ligeramente entre sí. <strong>La</strong> separación que existeentre dos puntos correspondientes en el par <strong>de</strong> imágenesestereoscópicas, permite conocer la distancia a la que seencuentran los objetos <strong>de</strong>l centro óptico <strong>de</strong> los sensores<strong>de</strong> visión. En la medida que los objetos estén más cerca<strong>de</strong>l centro óptico <strong>de</strong> los sensores, se encontraran másseparados en las respectivas imágenes estereoscópicas.Conociendo los parámetros <strong>de</strong> las cámaras y habiendoencontrado la distancia que separa un punto en un par <strong>de</strong>imágenes estereoscópicas, la profundidad <strong>de</strong>l mismo<strong>JP2011</strong>-693


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011pue<strong>de</strong> ser calculada obteniendo el inverso <strong>de</strong> ladisparidad calculada para ese punto. En la figura 1 setiene que C L y C R representan los centro ópticos <strong>de</strong> lascámaras <strong>de</strong>recha e izquierda respectivamente, X L y X Rrepresentan la distancia <strong>de</strong>l centro óptico reflejado en laimagen al lugar don<strong>de</strong> el punto es reflejado en la imagenrespectiva, T es la distancia entre las dos cámaras y f esla longitud focal <strong>de</strong> la cámara. Entonces la disparidad<strong>de</strong>l punto P está dada pord = X L - X R (1)Para <strong>de</strong>terminar la profundidad <strong>de</strong> la escenatridimensional usando los puntos <strong>de</strong> disparidad quecorrespon<strong>de</strong>n a ambas imágenes, basados en lageometría <strong>de</strong> la cámara, se pue<strong>de</strong> usar la siguienteexpresión.Z = f ∙ (T/d) (2)Entonces dado lo anterior, el problema fundamentalconsiste en encontrar la correspon<strong>de</strong>ncia exacta entredos puntos. <strong>La</strong> correspon<strong>de</strong>ncia estereoscópica es elproceso por el cual dado un punto en la escena 3-D sellega a <strong>de</strong>terminar cuál es su proyección en sendasimágenes <strong>de</strong>l par estereoscópico. Existen diferentestécnicas para encontrar la correspon<strong>de</strong>nciaestereoscópica, las cuales se divi<strong>de</strong>n principalmente entécnicas basadas en el área <strong>de</strong> las imágenes y técnicasbasadas en las características <strong>de</strong> las imágenes. Delmismo modo existen diferentes métricas para el cálculo<strong>de</strong> dicha disparidad. Algunas <strong>de</strong> estas pue<strong>de</strong>n serfácilmente paralelizadas e implementadas en hardware<strong>de</strong> tal modo que permiten al análisis <strong>de</strong> sistemas entiempo real, tal es el caso <strong>de</strong> la métrica <strong>de</strong> Suma <strong>de</strong> losvalores absolutos <strong>de</strong> las diferencias.Fig. 1 Geometría <strong>de</strong> un sistema estereoscópicoFuente (V. Simhadri, 2009)B. Controladores <strong>de</strong> Memoria ExternaCada día es más común encontrar <strong>de</strong>sarrollos<strong>de</strong> sistemas <strong>de</strong> visión estereoscópica basados en FPGA,lo que no es <strong>de</strong> extrañar dadas las excelentescaracterísticas que éstas proveen para el <strong>de</strong>sarrollo <strong>de</strong>este tipo <strong>de</strong> sistemas. Por otro lado, existen aplicacionesque requieren <strong>de</strong>l uso <strong>de</strong> gran<strong>de</strong>s cantida<strong>de</strong>s <strong>de</strong>memoria, siendo insuficiente la memoria que proveenlos FPGAs, por lo que resulta común hoy en día,encontrar tarjetas <strong>de</strong> <strong>de</strong>sarrollo que adicionan memorias<strong>de</strong> última generación. Así mismo los FPGAs, proveencores controladores <strong>de</strong> memoria para su uso.En los sistemas actuales los circuitos lógicosprogramables, tienen la capacidad <strong>de</strong> conectarse con unagran variedad <strong>de</strong> tipos <strong>de</strong> memoria como pue<strong>de</strong>n ser,SDRAM, DDR, DDR2, DDR3, entre otras. Dado queresulta complicado el <strong>de</strong>sarrollo <strong>de</strong> controladoresespecíficos para cada tipo <strong>de</strong> memoria, las compañías<strong>de</strong>sarrolladoras <strong>de</strong> dispositivos lógicos programables,han optado por <strong>de</strong>sarrollar controladores <strong>de</strong> memoriaque le permitan al usuario un acceso sencillo y eficientea memoria. Tal es el caso <strong>de</strong> Xilinx que ha <strong>de</strong>sarrolladoel Multi-Port Memory Controller (MPMC) que permiteel acceso a memoria por parte diferentes procesadores operiféricos implementados al interior <strong>de</strong>l FPGA [9].El MPMC es un controlador <strong>de</strong> memoria multipuerto,que <strong>de</strong>pendiendo <strong>de</strong>l tipo <strong>de</strong> FPGA en que seimplemente pue<strong>de</strong> controlar hasta 8 puertos. Cada uno<strong>de</strong> estos puertos pue<strong>de</strong> ser parametrizable y se pue<strong>de</strong>seleccionar por cada puerto hasta siete interfacesdiferentes <strong>de</strong> comunicación. El MPMC actúa como elcontrolador y el árbitro que permite en un momentoespecífico la interacción <strong>de</strong> uno <strong>de</strong> los ocho puertos conla memoria, por medio <strong>de</strong> elementos FIFO <strong>de</strong> cadapuerto. Cada una <strong>de</strong> las interfaces <strong>de</strong> comunicaciónpermite diferentes modos <strong>de</strong> acce<strong>de</strong>r a la memoria, perouna vez que el MPMC por medio <strong>de</strong> sus líneas <strong>de</strong>control, indica que tiene atrapados la dirección y el dato,el dispositivo asociado a éste pue<strong>de</strong> enviar o solicitar elsiguiente dato.Una <strong>de</strong> las interfaces provistas por el MPMC, es laNative Port Interface (NPI), que es la interface nativa<strong>de</strong>l controlador, permite transferencia <strong>de</strong> datos en 32 o64 bits, y diferentes modos <strong>de</strong> transferencia como son elmodo sencillo, modo burst y el modo <strong>de</strong> cacheline,permitiendo <strong>de</strong> forma simultánea la lectura y escritura<strong>de</strong> datos <strong>de</strong> los FIFOs <strong>de</strong>l controlador. Por lo sencillo <strong>de</strong>esta interface pue<strong>de</strong> ser prácticamente adaptada a casicualquier protocolo <strong>de</strong> comunicación.III.TRABAJOS PREVIOS RELACIONADOSSi bien en los últimos años se han <strong>de</strong>sarrollado unconjunto <strong>de</strong> propuestas Software, para la solución <strong>de</strong>lproblema <strong>de</strong> correspon<strong>de</strong>ncia estereoscópica, el avanceen las tecnologías <strong>de</strong> los dispositivos lógicosprogramable, especialmente las FPGAs, ha permitidoque se <strong>de</strong>sarrollen una serie <strong>de</strong> propuestas hardware,basadas en ellas, <strong>de</strong>bido a las características que estospresentan tales como: su capacidad <strong>de</strong> cómputo enparalelo, su capacidad <strong>de</strong> reconfiguración y laposibilidad <strong>de</strong> utilizar bloques <strong>de</strong> memoria interna comoelementos <strong>de</strong> almacenamiento <strong>de</strong> imágenes. Estaspropuestas hacen énfasis en aspectos en los que el<strong>de</strong>sarrollo <strong>de</strong> sistemas <strong>de</strong> visión estereoscópica basadosen FPGA permite ayudar, especialmente si estos seránutilizados en aplicaciones <strong>de</strong> tiempo real. En [1] sepresenta un algoritmo <strong>de</strong> correspon<strong>de</strong>ncia estéreoimplementado en hardware. Utilizando como métrica <strong>de</strong>costo y agregación la suma <strong>de</strong> los valores absolutos <strong>de</strong>las diferencias. Posteriormente, el resultado es refinado<strong>JP2011</strong>-694


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011por medio <strong>de</strong> un proceso que utiliza un autómata celular.Los resultados muestran que el algoritmo pue<strong>de</strong> serimplementado eficientemente en hardware y que elcálculo <strong>de</strong> la profundidad <strong>de</strong> las escenas se ajusta a lostiempos <strong>de</strong>mandados por sistemas <strong>de</strong> tiempo real. En[2], se presenta un sistema <strong>de</strong> tiempo real <strong>de</strong>sarrolladoen hardware para la extracción <strong>de</strong>l mapa <strong>de</strong> profundidad,su propuesta utiliza el filtro <strong>de</strong> la mediana para elcálculo <strong>de</strong> predicciones y <strong>de</strong>cidir qué tan parecido es unframe con respecto al anterior, <strong>de</strong> tal modo que pue<strong>de</strong>nminimizar el tiempo <strong>de</strong> cómputo, los resultados indicanque el consumo <strong>de</strong> tiempo es 56 veces menor conrespecto a la misma implementación realizada ensoftware.<strong>La</strong> implementación <strong>de</strong>l algoritmo <strong>de</strong> suma <strong>de</strong> losvalores absolutos <strong>de</strong> las diferencias (SAD), en sistemas<strong>de</strong> tiempo real, para resolver el problema <strong>de</strong> encontrar lacorrespon<strong>de</strong>ncia estereoscópica, ha sido tratada pordiversos autores. En [3] se presenta el diseño <strong>de</strong> unaarquitectura basada en la FPGA <strong>de</strong> Altera Stratix IIusando ventanas <strong>de</strong> 4 x4 y profundidad <strong>de</strong> 90 pixeles. Sudiseño alcanza un procesamiento <strong>de</strong> 85 fps en imágenes<strong>de</strong> 1024 x 1024 pixeles. En [4], se presenta un sistemabasado en una FPGA <strong>de</strong> Xilinx Virtex II, que procesanimágenes provenientes <strong>de</strong> tres cámaras con tamaños <strong>de</strong>ventana <strong>de</strong> 15 x 15 y rango <strong>de</strong> disparidad <strong>de</strong> 32 pixeles,alcanzando un procesamiento <strong>de</strong> 100 fps., sobreimágenes <strong>de</strong> 320 x 240 pixeles. En [5] utilizando unsistema basado en FPGA procesa imágenes <strong>de</strong> 512 x 512pixeles con una disparidad <strong>de</strong> 255 pixeles, usandotamaño <strong>de</strong> ventanas <strong>de</strong> 5 x 5, alcanzando unprocesamiento <strong>de</strong> 25.6 fps. Por su parte en [6], sepresenta una implementación que a<strong>de</strong>más <strong>de</strong> cumplircon los parámetros <strong>de</strong> los sistemas <strong>de</strong> tiempo real,muestra tener una buena exactitud, alcanzando unprocesamiento <strong>de</strong> 60 fps. sobre imágenes <strong>de</strong> 750 x 400pixeles con un rango <strong>de</strong> disparidad <strong>de</strong> 60 pixeles ytamaño <strong>de</strong> ventana <strong>de</strong> 23 x 23.<strong>La</strong> implementación <strong>de</strong> medidas no-paramétricas ensistemas <strong>de</strong> tiempo real es evaluada en [7] queimplementa la transformada no paramétrica Censussobre imágenes <strong>de</strong> 512 x 480 pixeles usando un rango <strong>de</strong>disparidad <strong>de</strong> 52 pixeles y tamaño <strong>de</strong> ventana <strong>de</strong> 7 x 7,obteniendo un procesamiento <strong>de</strong> 200 fps. En [8] sepresenta una implementación basada en FPGA <strong>de</strong> latransformada no paramétrica Census con tamaño <strong>de</strong>ventana <strong>de</strong> 7 x 7, con una disparidad máxima <strong>de</strong> 64pixeles, sobre imágenes <strong>de</strong> 640 x 480 pixeles,alcanzando en procesamiento <strong>de</strong> 130 fps.IV.ESTRUCTURA DEL PERIFERICOEl <strong>de</strong>sarrollo <strong>de</strong> este trabajo, está fundamentado en lacreación <strong>de</strong> un conjunto <strong>de</strong> periféricos que son añadidosa un sistema controlado por el procesador embebidoMicroBlaze (MB) <strong>de</strong>ntro <strong>de</strong> un FPGA Spartan 6 LX45T<strong>de</strong> Xilinx. Aunque las funciones que realiza elprocesador sobre los dispositivos son mínimas, seprovee <strong>de</strong> una interface con la cual la interacción con losperiféricos es sencilla, aunado a esto se aprovechanrutinas <strong>de</strong> uso común <strong>de</strong>sarrolladas en trabajosanteriores [10], [11].<strong>La</strong> figura 2 muestra el diagrama general <strong>de</strong>l sistema,don<strong>de</strong> se pue<strong>de</strong> observar al MB conectado por medio <strong>de</strong>lProcessor Local Bus (PLB) al controlador serie RS232.Esta conexión tiene como principal objetivo, por unlado, tener un medio por el cual se puedan controlar losdiferentes dispositivos que se le conectan al sistema ypor otro, monitorear cuando así sea necesario, lasseñales provenientes <strong>de</strong> estos dispositivos.Fig. 2 Diagrama General <strong>de</strong>l sistema <strong>de</strong> correspon<strong>de</strong>nciaestereoscópicaSe ha <strong>de</strong>sarrollado una interface hacia el controladorPLB, por medio <strong>de</strong> la cual se pue<strong>de</strong> acce<strong>de</strong>r hasta a 8registros diferentes <strong>de</strong> escritura <strong>de</strong> 32 bits cada uno, <strong>de</strong>lmismo modo la interface provee la circuitería necesariapara po<strong>de</strong>r leer un dato proveniente <strong>de</strong> uno <strong>de</strong> ochoregistros <strong>de</strong> entrada <strong>de</strong> 32 bits. Esta interface permitein<strong>de</strong>pendizar los periféricos <strong>de</strong>sarrollados, <strong>de</strong>lcontrolador PLB. El acceso a los registros <strong>de</strong>entrada/salida <strong>de</strong> la interface se logra realizando unallamada a la dirección base más el <strong>de</strong>splazamiento <strong>de</strong>lregistro. <strong>La</strong> figura 3 muestra el diagrama esquemático <strong>de</strong>este módulo.Los trabajos anteriormente mencionados, logranalcanzar las frecuencias <strong>de</strong> procesamiento indicadas,<strong>de</strong>bido principalmente a dos situaciones, 1- tienen unflujo <strong>de</strong> datos <strong>de</strong> entrada que no proviene <strong>de</strong> memoriasino <strong>de</strong> sensores ópticos y 2-utilizan elementos internos<strong>de</strong> la FPGA para almacenar el flujo <strong>de</strong> datos en pipeline.Fig. 3 Interface con el bus PLB<strong>JP2011</strong>-695


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Como se mencionó anteriormente el MPMC cumplecon el objetivo <strong>de</strong> ser la interfaz entre la memoriaexterna <strong>de</strong>l sistema y los diferentes dispositivos querequieran <strong>de</strong> ella. En el sistema <strong>de</strong>sarrollado se pue<strong>de</strong>observar que se tiene acceso a la memoria externa pordos vías, una vía es por medio <strong>de</strong>l controlador ProcessorLocal Bus (PLB) utilizado principalmente por el MBpara acce<strong>de</strong>r a datos e instrucciones, la otra vía es por laNative Port Interface (NPI) que es utilizada por elperiférico encargado <strong>de</strong> generar las direcciones <strong>de</strong>memoria <strong>de</strong> don<strong>de</strong> se quieren tomar los datos <strong>de</strong> lasimágenes estéreo previamente almacenadas y don<strong>de</strong> sequiere guardar la información <strong>de</strong>l mapa <strong>de</strong> disparidad,información generada por el módulo <strong>de</strong> cálculo <strong>de</strong> lasuma <strong>de</strong> las diferencias absolutas.Del mismo modo que se <strong>de</strong>sarrolló la interface con elcontrolador PLB, se <strong>de</strong>sarrolló una interface <strong>de</strong>comunicación con el controlador <strong>de</strong> memoria MPMC enel modo NPI <strong>de</strong> 32 bits. Esta interface permite lalectura/escritura en memoria externa una vez quepreviamente han sido registrados tanto la dirección <strong>de</strong>lectura/escritura como el dato a ser enviado a memoria.En la figura 4, se observa esta interface. <strong>La</strong> máquina <strong>de</strong>estados genera las señales <strong>de</strong> control necesarias paraleer/escribir un dato <strong>de</strong> 32 bits en memoria por medio<strong>de</strong>l NPI, en el caso <strong>de</strong> la escritura toma 5 ciclos <strong>de</strong> relojen efectuarla, en el caso <strong>de</strong> la lectura el tiempo pue<strong>de</strong>variar siendo mínimo <strong>de</strong> 5 ciclos, esto se <strong>de</strong>be a que elcontrolador y por la política <strong>de</strong> arbitraje seleccionada(round robin), pue<strong>de</strong> estar atendiendo las solicitu<strong>de</strong>s <strong>de</strong>lMB por el puerto PLB.disparidad. El otro módulo es el encargado <strong>de</strong> hacer alcálculo <strong>de</strong> la disparidad basado en un algoritmo queutiliza como métrica <strong>de</strong> medida la Suma <strong>de</strong>l valorabsoluto <strong>de</strong> las diferencias (SAD).<strong>La</strong> generación <strong>de</strong> direcciones <strong>de</strong> memoria es realizadapor un módulo que consta <strong>de</strong> dos elementos como semuestra en la figura 5. El primer modulo genera lalógica necesaria para el cálculo <strong>de</strong> la coor<strong>de</strong>nadas (x,y)<strong>de</strong>l elemento que se <strong>de</strong>sea almacenar o recuperar <strong>de</strong> lamemoria. El cálculo <strong>de</strong> estas coor<strong>de</strong>nadas se efectúabasado en las necesida<strong>de</strong>s <strong>de</strong> datos requeridos por losalgoritmos <strong>de</strong> cálculo <strong>de</strong> disparidad que obtienen mapas<strong>de</strong>nsos. El segundo módulo genera la dirección efectiva<strong>de</strong> memoria <strong>de</strong> don<strong>de</strong> el dato será recuperado oalmacenado, basado simplemente en una dirección basey las coor<strong>de</strong>nadas <strong>de</strong>l (x,y) <strong>de</strong>l sistema. Por ejemplo, sise tiene una imagen sintética <strong>de</strong> 388 x 288 pixeles[tomada <strong>de</strong>, 13] y se <strong>de</strong>sea recuperar el dato <strong>de</strong> lacoor<strong>de</strong>nada (x=10, y=20) a partir <strong>de</strong> la memoria base88000000hex, el módulo realiza el cálculo mostrado enla figura 6, dando como resultado la dirección real <strong>de</strong>memoria 88019850hex que es <strong>de</strong> don<strong>de</strong> se tomará eldato.Fig. 5 Generador <strong>de</strong> dirección efectiva <strong>de</strong> memoriaFig. 4 Interface con el MPMC en el modo NPIUna vez que se han registrado la dirección y el datoque se <strong>de</strong>sean leer/escribir en memoria, se manda unaseñal <strong>de</strong> inicio a la máquina <strong>de</strong> estados que controla elproceso, adicionalmente se le indica si el proceso que sequiere efectuar es <strong>de</strong> lectura o <strong>de</strong> escritura (LNE=1Lectura, LNE=0 Escritura). <strong>La</strong> máquina <strong>de</strong> estadosrespon<strong>de</strong> que el proceso terminó satisfactoriamente conuna señal <strong>de</strong> LF=1 en caso <strong>de</strong> que el proceso sea <strong>de</strong>lectura, o con una señal <strong>de</strong> EF=1 en caso <strong>de</strong>l queproceso sea <strong>de</strong> escritura.El elemento principal <strong>de</strong>l sistema, es un periférico quepermite calcular al mapa <strong>de</strong> disparidad <strong>de</strong> dos imágenesestéreo almacenadas en memoria. Este periférico estádividido en dos módulos, uno encargado <strong>de</strong> controlar ygenerar las direcciones <strong>de</strong> memoria para tomar los datoscon los que se calculará la disparidad, así como paragenerar las direcciones don<strong>de</strong> se almacenara el mapa <strong>de</strong>El cálculo <strong>de</strong> la disparidad es realizado por el móduloque se muestra en la figura 7, este módulo cargainicialmente la ventana izquierda <strong>de</strong> 3x3 <strong>de</strong> acuerdo alos datos que le provee el puerto NPI a su vezalimentado por el generador <strong>de</strong> direcciones,posteriormente <strong>de</strong> la misma forma es cargada la ventana<strong>de</strong>recha y se calcula la suma <strong>de</strong> diferencias absolutas,teniendo como resultado el primer mínimo,posteriormente se cargan tres elementos nuevos para lanueva ventana <strong>de</strong>recha y se calcula la segunda diferenciaabsoluta, este valor se compara con el anterior y si esmenor que el mínimo anterior, se ha encontrado unnuevo mínimo, el valor <strong>de</strong>l mínimo y su posición sonalmacenados en registros para su posterior utilización,el proceso se repite para una disparidad máxima <strong>de</strong> 32posiciones. Una vez terminado el proceso, el resultadoes la posición don<strong>de</strong> se encontró la mínima diferenciaabsoluta. Este valor es almacenado en el mapa <strong>de</strong>disparidad..Fig. 6 Cálculo <strong>de</strong> la dirección efectiva<strong>JP2011</strong>-696


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011V. RESULTADOS DE LA IMPLEMENTACIÓNLos periféricos <strong>de</strong>sarrollados que integran el sistemafueron probados inicialmente <strong>de</strong> forma in<strong>de</strong>pendiente yfinalmente fueron integrados en un sistema embebidocontrolado por el MB. El controlador <strong>de</strong> la interfacePLB fue probado exhaustivamente y se logro unacomunicación total con sus registros.Fig. 7 Cálculo <strong>de</strong> la Suma <strong>de</strong>l valor absoluto <strong>de</strong> las diferencias y <strong>de</strong> lamínima diferencia<strong>La</strong> interface con el puerto nativo, permite queregistrados la dirección y el dato que se quiere escribir,se genere una señal <strong>de</strong> control que permita acce<strong>de</strong>r amemoria externa y almacenar el dato, lo mismo se logrópara el proceso <strong>de</strong> lectura <strong>de</strong> datos. El hecho <strong>de</strong> registrarpreviamente la dirección y el dato, hace necesarioagregar un estado adicional a la máquina <strong>de</strong> estados quecontrola la interface, lo cual aña<strong>de</strong> un ciclo <strong>de</strong> reloj alproceso <strong>de</strong> lectura/escritura <strong>de</strong> los datos.El periférico que calcula el mapa <strong>de</strong> disparidad, fuecomparado con una implementación <strong>de</strong>sarrollada porsoftware con la misma plataforma, los resultadosmuestran que se logra obtener un mapa <strong>de</strong> disparidadsemejante, tal como se muestra en la figura 9. Se pue<strong>de</strong>observar que existe un pequeño incremento <strong>de</strong> falsospositivos en la implementación por hardware <strong>de</strong>bidoprincipalmente a la precisión <strong>de</strong> datos utilizados en estaimplementación. El <strong>de</strong>sarrollo <strong>de</strong>l periférico se realizósiguiendo el algoritmo SAD <strong>de</strong> forma estrictamenteprocedimental, sin ningún tipo <strong>de</strong> optimización. En unaprimera aproximación, tomando cada uno <strong>de</strong> los pixelesconforme estos se van necesitando y sin almacenar datosque puedan se reutilizados, los resultados obtenidosmuestran que la implementación hardware, si bien esmás rápida que la implementación <strong>de</strong> software, no logralos requerimientos mínimos necesarios para un sistemaque trabaje en tiempo real, ya que solo pue<strong>de</strong> procesar1.17 fps teniendo imágenes <strong>de</strong> 384 x 288 pixeles, conuna disparidad máxima <strong>de</strong> 32 pixeles y un tamaño <strong>de</strong>ventana <strong>de</strong> 3 x 3. Una segunda implementación,utilizando el modo <strong>de</strong> lectura <strong>de</strong> burst <strong>de</strong>l NPI leyendo32 palabras, permite un acceso más eficiente a memoria.Los datos son almacenados en BRAM para tres líneas <strong>de</strong>la imagen, y los datos <strong>de</strong> las líneas inferiores sonreutilizados <strong>de</strong> tal forma que se realizan menos accesos amemoria <strong>de</strong> forma que reducen el cuello <strong>de</strong> botella, <strong>de</strong>forma que se pue<strong>de</strong>n procesar 16.57 fps, tiemposuficiente para algunas aplicaciones <strong>de</strong> tiempo real. Esposible <strong>de</strong> forma sencilla duplicar o cuadruplicar elnúmero <strong>de</strong> frames por segundo, añadiendo estructuras enparalelo que permitan realizar el cálculo <strong>de</strong>l SADmínimo en varias regiones <strong>de</strong> la imagen <strong>de</strong> formasimultanea.VI.CONCLUCIONES<strong>La</strong>s interfaces que se <strong>de</strong>sarrollaron, tanto para elacceso al bus PLB, como para el acceso al puerto nativo<strong>de</strong>l MPMC en su modalidad <strong>de</strong> 32 bits, <strong>de</strong>jan por unlado, interactuar <strong>de</strong> forma sencilla con estoscontroladores y por otro lado, en el momento <strong>de</strong> diseño,la manipulación <strong>de</strong> los controladores es más or<strong>de</strong>nada,permitiendo aislar efectivamente los elementos <strong>de</strong>diseño, con lo cual el proceso <strong>de</strong> <strong>de</strong>tección y corrección<strong>de</strong> errores (<strong>de</strong>bugging) resulta menos complicado. Sibien el objetivo final <strong>de</strong>l proyecto es <strong>de</strong>sarrollar unsistema <strong>de</strong> visión que cumpla con los requisitos <strong>de</strong>tiempo real, la herramienta, en su estado actual, resultaefectiva porque permite probar diferentes algoritmos,con el mo<strong>de</strong>lo <strong>de</strong>sarrollado, aislando el acceso a losdatos <strong>de</strong>l propio algoritmo. A partir <strong>de</strong> ahí se pue<strong>de</strong>n sepue<strong>de</strong> comenzar a diseñar estrategias que permitanlograr el requisito <strong>de</strong> velocidad en los sistemas <strong>de</strong>tiempo real.Fig. 9 Mapas <strong>de</strong> disparidad resultantes <strong>de</strong> las implementaciones <strong>de</strong>software y hardwareSe ha logrado una in<strong>de</strong>pen<strong>de</strong>ncia entre lamétrica que se <strong>de</strong>sea utilizar para el cálculo <strong>de</strong> ladisparidad <strong>de</strong> un sistema estéreo, y el módulo quegenera las direcciones <strong>de</strong> memoria don<strong>de</strong> están lasimágenes estereoscópicas. De este modo es posibleprobar una amplia variedad <strong>de</strong> métricas que generanmapas <strong>de</strong> disparidad <strong>de</strong>nsos, utilizando el mismomódulo <strong>de</strong> direccionamiento. Por otro lado es posible <strong>de</strong>manera rápida y sencilla cambiar el tamaño <strong>de</strong> lasimágenes y la disparidad con la cual se <strong>de</strong>sea realizar elcálculo.En la primera implementación que se realizo enhardware, se pue<strong>de</strong> observar claramente que el cuello <strong>de</strong>botella se encuentra en el acceso a memoria, <strong>de</strong>bido alque el controlador consume por lo menos 5 ciclos <strong>de</strong>reloj en entregar un dato. Se puedo observar quecambiando <strong>de</strong> protocolo para el acceso a memoria yteniendo elementos <strong>de</strong> almacenamiento que permitan reusar datos que ya han sido previamente cargados, sepue<strong>de</strong> incrementar significativamente la cantidad <strong>de</strong>frames por segundo que se pue<strong>de</strong>n procesar. Si a loanterior se le agregan arquitecturas en paralelo paracalcular el SAD mínimo en diferentes regiones <strong>de</strong> lasimágenes, el incremento aún es mayor<strong>JP2011</strong>-697


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Puesto que el objetivo <strong>de</strong>l sistema que se presenta, esla evaluación <strong>de</strong> los algoritmos <strong>de</strong> correspon<strong>de</strong>nciaestereoscópica en sistemas <strong>de</strong> tiempo real, en estemomento el sistema diseñado resulta una herramientaa<strong>de</strong>cuada para probar diferentes métricas <strong>de</strong> visiónestereoscópica, así como también probar diferentesvalores <strong>de</strong> disparidad y tamaños <strong>de</strong> ventana, aunquecomo ya se explico no alcanza a procesar una imagencambiante en tiempo real por el cuello <strong>de</strong> botella queimpone la utilización <strong>de</strong>l MPMC. Una vez analizadoslos algoritmos tanto en precisión como en consumo <strong>de</strong>recursos, se pasará a la etapa <strong>de</strong> optimización <strong>de</strong>lsistemaVII.TRABAJO FUTUROPara el trabajo futuro se prevé expandir lasposibilida<strong>de</strong>s <strong>de</strong>l periférico, <strong>de</strong> forma tal que permitaconfigurar las características principales para el mapa <strong>de</strong>disparidad como son, el tamaño <strong>de</strong> las imágenes, el nivel<strong>de</strong> disparidad, el tamaño <strong>de</strong> las ventanas entre otros.En el marco <strong>de</strong> referencia <strong>de</strong> <strong>de</strong>sarrollar un sistema entiempo real que permita a un dispositivo autónomomóvil, navegar en un entorno <strong>de</strong>sconocido, resultanecesario optimizar el periférico que calcula el mapa <strong>de</strong>disparidad. Una <strong>de</strong> las posibles vías, es implementar unaarquitectura <strong>de</strong> memoria interna al FPGA, <strong>de</strong> tal modoque permita un acceso más eficiente a memoria y que reuseparte <strong>de</strong> los datos que ya han sido previamentecargados en el periférico.Conference on Computer Vision and PatternRecognitionWorkshps, 2006.[8] A. Naoulou, J. Boizard, J. Yves, M. Devy, “Analternative to sequential architectures to improve theprocessing time of the stereovision algorithms”,Proceedings of the International Conference on FieldProgrammable Logic and Applications”, 2006.[9] Xilinx, “Multi-Port Memory Controller (MPMC)(v6.02.a)”,http://www.xilinx.com/support/documentation/ip_documentation/mpmc.pdf, Xilinx, 2011.[10] M. Calviño, “Ambiente para la <strong>de</strong>puracion y prueba<strong>de</strong> aceleradores <strong>de</strong> hardware”, Jornadas <strong>de</strong> Paralelismo,Castellon, España, 2008[11] S. Ibarra, M. Calviño, J. Benavi<strong>de</strong>s, “Diseño yevaluación <strong>de</strong> un acelerador hardware configurable pararealizar la convolución, acoplado como periférico alMicroblaze”, XXI Jornadas <strong>de</strong> Paralelismo, Valencia,España, 2010[12] V. Simhadri, Y. Osturk, “RASCor: An associativehardware algorithm for real time stereo”, Computers andElectrical Engineering, Vol. 35, pp. 459-477, Elsevier,2009.[13] D. Scharstein, R. Szeliski, Middlebury StereoDatasets, http://vision.middlebury.edu/stereo/data/REFERENCIAS[1] L. Nalpantidis, G. Ch. Sirakoulis, and A. Gasteratos,“A Dense Stereo Correspon<strong>de</strong>nce Algorithm forHardware Implementation with Enhanced DisparitySelection”, SETN '08 Proceedings of the 5th Hellenicconference on Artificial Intelligence: Theories, Mo<strong>de</strong>lsand Applications, pp. 365-370, Springer-Verlag Berlin,Hei<strong>de</strong>lberg, 2008.[2] Dong-Sun Kim, Sang-Seol Lee and Byeong-HoChoi, “A Real-Time Stereo Depth Extraction Hardwarefor Intelligent Home Assistant Robot”, IEEETransactions on Consumer Electronics, Vol. 56, Issue 3,pp. 1782-1788, Octubre 2010.[3] C. Cuadrado, A. Zuolaga, J. Martin, J. <strong>La</strong>izaro, J.Jimenez, “Real time stereo visión processing system in aFPGA”, Proceedings of the IEEE 32 nd AnnualConference on Industrial Electronics, 2006[4] L. Mingxiang , J. Youn<strong>de</strong>, “Stereo system onprogrammable chip (SVSoC) for small robotnavigation”, Proceedings of the IEEE /RSJ InternationalConference on Intelligent Robots and Systems, 2006 .[5] S. Perri, D. Colonna, P. Zicari, P. Corsonello, “SADbasedstereo matching circuit for FPGAs”, Proceedingsof the 13 th IEEE international Conference onElectronics, Circuits and Systems, 2006[6] K. Ambrosch, W. Kubinger, “Accurate hardwarebasedstereo vison”, Computer Vision and ImageUn<strong>de</strong>rstanding, pp. 1303-1316, Elsevier, 2010.[7] J. Woodfill, G. Gordon, R. Buck, “The TyzxDeepSea high speed stereo vision system, a taskable,embed<strong>de</strong>d stereo camara”, Proceedings of the 2006<strong>JP2011</strong>-698


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Estrategias <strong>de</strong> optimización en GPU y CPUmulti-core <strong>de</strong> mo<strong>de</strong>los SPHJ.M. Domínguez, A.J.C. Crespo, A. Barreiro y M. Gómez-Gesteira 1Resumen—En este trabajo se presenta unaimplementación <strong>de</strong>l mo<strong>de</strong>lo <strong>de</strong> dinámica <strong>de</strong> fluidos SPHpara CPU y GPU. Se explica cuáles son los problemas quepresentan cada implementación y las estrategias <strong>de</strong>optimización aplicadas para mejorar el rendimiento en estemétodo concreto, aunque aplicables a muchos otrosproblemas. Los resultados muestran importantes mejorasconseguidas en cada arquitectura y una comparativaobjetiva entre las implementaciones más eficientes <strong>de</strong> CPUy GPU.Palabras clave—High Performance Computing, GPU,OpenMP, SPH, Smoothed Particle Hydrodynamics,Dinámica <strong>de</strong> fluidos.EI. INTRODUCCIÓNL método Smoothed Particle Hydrodynamics (SPH)es un método sin malla lagrangiano <strong>de</strong>sarrollado enlos años 70 en astrofísica [1]. Des<strong>de</strong> entonces se haaplicado a varias ramas <strong>de</strong> la ingeniería, pero su uso<strong>de</strong>staca particularmente en el estudio <strong>de</strong> 1 lahidrodinámica <strong>de</strong> problemas <strong>de</strong> superficie libre, comoflujos violentos e interacción entre olas y estructuras.Permite simular escenarios sin necesidad <strong>de</strong> construircostosos mo<strong>de</strong>los a escala, a<strong>de</strong>más <strong>de</strong> proporcionardatos difíciles <strong>de</strong> medir en un mo<strong>de</strong>lo real.SPHysics es una implementación <strong>de</strong>l mo<strong>de</strong>lo SPH paraestudiar los flujos <strong>de</strong> superficie libre. Es producto <strong>de</strong>lesfuerzo <strong>de</strong> investigadores <strong>de</strong> Johns Hopkins University(U.S.A.), <strong>Universidad</strong> <strong>de</strong> Vigo (España) y TheUniversity of Manchester (Reino Unido). Consiste en uncódigo open-source escrito en Fortran que se pue<strong>de</strong><strong>de</strong>scargar en www.sphysics.org. Sin embargo, estemo<strong>de</strong>lo posee un coste computacional muy elevado porlo que pequeñas simulaciones <strong>de</strong> unos segundos pue<strong>de</strong>nrequerir varios días <strong>de</strong> cálculo. Por esta razón y pararealizar simulaciones con el tamaño necesario pararepresentar casos reales en un tiempo asequible, esimprescindible <strong>de</strong>sarrollar implementaciones quepuedan explotar el paralelismo <strong>de</strong> los sistemas hardwaredisponibles en el mercado.<strong>La</strong>s CPUs (Central Processing Units) actuales secaracterizan por poseer múltiples cores (núcleos <strong>de</strong>procesamiento) por lo que es posible repartir la carga <strong>de</strong>computo <strong>de</strong> un programa entre los distintos cores,dividiendo también así el tiempo <strong>de</strong> ejecución. Por otrolado, las GPUs (Graphics Processing Units) son una1 EPHYSLAB Environmental Physics <strong>La</strong>borarory, <strong>Universidad</strong> <strong>de</strong>Vigo, Campus As <strong>La</strong>goas s/n 32004 Ourense, e-mail:jmdominguez@uvigo.esnueva tecnología importada <strong>de</strong> la industria <strong>de</strong> losvi<strong>de</strong>ojuegos que se pue<strong>de</strong> utilizar para la computacióncientífica gracias a su arquitectura paralela. Haciendouso <strong>de</strong> estas tecnologías se ha <strong>de</strong>sarrollado un nuevocódigo llamado DualSPHysics, implementado en C++con OpenMP (Open Multi-Processing) y CUDA(Compute Unified Device Architecture), capaz <strong>de</strong>ejecutarse en CPU y GPU. <strong>La</strong> validación <strong>de</strong> este códigocon un experimento real pue<strong>de</strong> encontrarse en [2]. Másinformación sobre el proyecto DualSPHysics pue<strong>de</strong>encontrarse en la web www.dual.sphysics.org, mientrasque diferentes aplicaciones y animaciones pue<strong>de</strong>n verseen www.vimeo.com/dualsphysics.Obtener el máximo rendimiento <strong>de</strong> estas arquitecturasparalelas no es trivial, en especial cuando se trata <strong>de</strong>GPUs. En este trabajo se presenta una serie <strong>de</strong>estrategias <strong>de</strong> optimización para CPU y GPU aplicadasal método SPH, pero que pue<strong>de</strong>n ser adoptadas pormuchos otros métodos. También se muestra unacomparativa <strong>de</strong> rendimiento entre CPU multi-core yGPU lo más objetiva posible.II.IMPLEMENTACIÓN DEL MODELO SPHSPH es un método sin malla don<strong>de</strong> el fluido se<strong>de</strong>scribe mediante un conjunto <strong>de</strong> nodos distribuidos enel espacio (a los que llamaremos partículas) en don<strong>de</strong> seregistran diferentes propieda<strong>de</strong>s físicas (masa, <strong>de</strong>nsidad,velocidad, posición, presión). <strong>La</strong>s ecuacioneshidrodinámicas <strong>de</strong> movimiento <strong>de</strong> cada partícula fluidase integran en el tiempo y las magnitu<strong>de</strong>s físicasrelevantes se calculan para cada partícula como unainterpolación <strong>de</strong> los valores <strong>de</strong> las partículas máscercanas. <strong>La</strong>s leyes <strong>de</strong> conservación <strong>de</strong> la dinámica <strong>de</strong>fluidos se expresan <strong>de</strong> forma discreta usando ecuacionesintegrales en lugar <strong>de</strong> la forma <strong>de</strong> ecuacionesdiferenciales. En el caso <strong>de</strong> los contornos, sólo seresuelven las ecuaciones <strong>de</strong> conservación <strong>de</strong> la masa yse calcula cómo evoluciona su presión, pero no seintegran las ecuaciones <strong>de</strong> movimiento. De este modoexisten dos tipos <strong>de</strong> partículas, fluidas y contorno, y lainteracción entre ellas también requiere diferentesoperaciones.<strong>La</strong>s principales características <strong>de</strong>l método SPH se<strong>de</strong>scriben <strong>de</strong> forma <strong>de</strong>tallada en [3] y [4]. Aquí se<strong>de</strong>scribirán sólo las cuestiones principales relacionadascon la implementación. Conceptualmente, un códigoSPH se trata <strong>de</strong> un proceso iterativo que consta <strong>de</strong> trespasos principales:<strong>JP2011</strong>-699


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20111. Lista <strong>de</strong> vecinos (LV): <strong>La</strong>s partículas sólointeractúan con las partículas <strong>de</strong> alre<strong>de</strong>dorsituadas a una <strong>de</strong>terminada distancia, por lo que eldominio se divi<strong>de</strong> en celdas <strong>de</strong> ese tamaño parareducir la búsqueda <strong>de</strong> vecinos a las celdasadyacentes. Para ello se ha implementado la listaCell-linked <strong>de</strong>scrita en [5]. Como existen dos tipos<strong>de</strong> partículas (contorno y fluido), que convienemantener agrupadas, en realidad se crean doslistas in<strong>de</strong>pendientes, una para cada tipo.2. Computo <strong>de</strong> fuerzas (CF): Cada partícula sólobusca a sus partículas vecinas <strong>de</strong>ntro <strong>de</strong> su propiacelda y <strong>de</strong>ntro <strong>de</strong> las celdas contiguas, y trasverificar que están <strong>de</strong>ntro <strong>de</strong>l radio <strong>de</strong> acción secalculan las fuerzas <strong>de</strong> interacción entre ellas.Como la interacción contorno-contorno no esnecesaria sólo se realizan interacciones fluidofluido(F-F), fluido-contorno (F-C) y contornofluido(C-F).3. Computo <strong>de</strong> paso (CP): Una vez que las fuerzasentre partículas han sido calculadas, todas lasmagnitu<strong>de</strong>s físicas <strong>de</strong> las partículas se actualizanen función <strong>de</strong> estas fuerzas, para el siguiente paso<strong>de</strong> tiempo.El caso <strong>de</strong> estudio empleado en este trabajo consiste enel colapso <strong>de</strong> un volumen <strong>de</strong> agua <strong>de</strong>bido a la gravedady su interacción con una estructura rectangular (verfigura 1). Un caso <strong>de</strong> estudio similar se ha empleadopara mostrar la precisión <strong>de</strong>l mo<strong>de</strong>lo SPHysics en [6].Fig. 1. Distintos instantes en la evolución <strong>de</strong>l fluido en el caso <strong>de</strong>estudio.Como ya se comentó el método SPH es muy costosoen tiempo <strong>de</strong> cálculo. Esto es <strong>de</strong>bido a que en laaproximación <strong>de</strong> fluido débilmente compresible <strong>de</strong> SPH,el tiempo <strong>de</strong> cada paso es muy reducido (<strong>de</strong> 10 -5 a 10 -4segundos) lo cual obliga a tener que realizar muchospasos para obtener un segundo <strong>de</strong> simulación. Por otrolado, el número <strong>de</strong> pares <strong>de</strong> partículas que interactúanentre sí es muy elevado. Así para el caso <strong>de</strong> estudio, con1 millón <strong>de</strong> partículas se necesitan más <strong>de</strong> 26,000 pasos<strong>de</strong> tiempo para completar 1.5 segundos <strong>de</strong> simulaciónfísica, y cada partícula tiene una media <strong>de</strong> 300 partículasvecinas con las que interactúa. Esto hace que el paso CFse lleve más <strong>de</strong>l 99% <strong>de</strong>l tiempo en una ejecución enCPU single-core y un 96% en GPU. Por ello todos losesfuerzos para reducir el tiempo <strong>de</strong> ejecución <strong>de</strong>ben serenfocados en reducir el coste <strong>de</strong> esta parte <strong>de</strong>l código.III.ESTRATEGIAS DE OPTIMIZACIÓN EN CPUCada partícula posee una conjunto <strong>de</strong> magnitu<strong>de</strong>s(posición, velocidad, <strong>de</strong>nsidad,...) almacenadas cada unaen un array. En cada paso <strong>de</strong> tiempo en LV se <strong>de</strong>terminala celda en la que está cada partícula, para <strong>de</strong>spuésor<strong>de</strong>nar las partículas en función <strong>de</strong> dicha celda. Estoproporciona dos ventajas importantes: Al reor<strong>de</strong>nar losdatos <strong>de</strong> las partículas según su celda se aumenta laproximidad en memoria entre las partículas que van ainteraccionar, y por otro lado permite i<strong>de</strong>ntificar laspartículas <strong>de</strong> una celda simplemente como un rango. Deesta forma en CF la interacción se realiza entre celdas,es <strong>de</strong>cir, todas las partículas <strong>de</strong> una celda con todas las<strong>de</strong> otra celda. Como el tamaño <strong>de</strong> celda coinci<strong>de</strong> con ladistancia máxima <strong>de</strong> interacción (a la que llamaremos2h) sólo es necesario que una celda interactué consigomisma y con las <strong>de</strong> alre<strong>de</strong>dor, comprobando para cadapar <strong>de</strong> partículas si están <strong>de</strong>ntro <strong>de</strong> la distancia <strong>de</strong>interacción o no.Algunas <strong>de</strong> las optimizaciones que se pue<strong>de</strong>n realizarsobre la implementación en CPU son las siguientes:A. Uso <strong>de</strong> la simetría en el cálculo <strong>de</strong> fuerzasAl computar la fuerza que ejerce una partícula i sobreotra partícula j, se pue<strong>de</strong> obtener la fuerza <strong>de</strong> j sobre isimplemente cambiando el signo. Esto permite reducir ala mitad el número <strong>de</strong> interacciones que es necesarioevaluar. Para ello, en 3D cada celda sólo interactuarácon 13 celdas y parte <strong>de</strong> sí misma, en lugar <strong>de</strong> 27.B. División en celdas más pequeñasUsar celdas <strong>de</strong> un tamaño 2h provoca que gran parte<strong>de</strong> los pares <strong>de</strong> partículas que se evalúan no requierancomputar la interacción por estar a mayor distancia <strong>de</strong> larequerida, siendo así vecinos potenciales pero no reales.En la figura 2 pue<strong>de</strong> verse como reduciendo el tamaño<strong>de</strong> las celdas es posible aumentar el porcentaje <strong>de</strong>vecinos reales. Sin embargo esto también conlleva unaumento <strong>de</strong>l número total <strong>de</strong> celdas, así como las celdascon las que <strong>de</strong>be interactuar cada una. Debido a estosólo es rentable usar celdas <strong>de</strong> tamaño h, con lo que seconsigue aumentar la proporción <strong>de</strong> vecinos reales <strong>de</strong>l19% al 31%.60%50%40%30%20%10%0%0 250,000 500,000 750,000 1,000,000NCells 2hCells 2h/2Cells 2h/3Cells 2h/4Fig. 2. Porcentaje <strong>de</strong> vecinos reales frente a potenciales según eltamaño <strong>de</strong> celda y el número <strong>de</strong> partículas (N).C. Uso <strong>de</strong> instrucciones SSE<strong>La</strong>s CPUs actuales disponen <strong>de</strong> unos conjuntos <strong>de</strong>instrucciones especiales (SSE, SSE2, SSE3,...) <strong>de</strong> tipoSIMD (Single Instruction, Multiple Data) con las que sepue<strong>de</strong>n hacer operaciones sobre conjuntos <strong>de</strong> datos.Utilizando estas instrucciones es posible realizar unaoperación básica (suma, resta, multiplicación, división,comparación,...) sobre 4 números reales (<strong>de</strong> precisiónsimple) <strong>de</strong> forma simultánea. Otra ventaja es que su<strong>JP2011</strong>-700


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011traducción a código máquina es directa por lo queproporciona un mayor rendimiento. Sin embargopresenta algunas <strong>de</strong>sventajas importantes; sólo esaplicable en casos concretos, cuando los cálculos sepue<strong>de</strong>n realizar en packs <strong>de</strong> 4 valores, es bastantecomplicado usarlas <strong>de</strong> forma eficiente y su codificaciónes muy engorrosa. Estas instrucciones se aplicaronfundamentalmente al cálculo <strong>de</strong> fuerzas entre partículas,agrupando previamente los pares <strong>de</strong> interacción en packs<strong>de</strong> 4.D. Programación multi-core con OpenMPHoy en día las CPUs disponen <strong>de</strong> varios cores ounida<strong>de</strong>s <strong>de</strong> procesamiento, por lo que es fundamentaldistribuir la carga <strong>de</strong> cálculo <strong>de</strong> una aplicación entretodos ellos para maximizar el rendimiento <strong>de</strong> la CPU. <strong>La</strong>opción elegida fue el interfaz <strong>de</strong> programación paralelaOpenMP, ya que se trata <strong>de</strong> un mo<strong>de</strong>lo <strong>de</strong> programaciónportable y flexible, cuya implementación no suponegran<strong>de</strong>s cambios en el código.Se aplicó paralelismo a diversas partes <strong>de</strong>l código peroen el cálculo <strong>de</strong> fuerzas es don<strong>de</strong> su uso tiene mayorimportancia. En el paso CF se probaron distintasaproximaciones pero la que mejor resultados aportaconsiste en repartir las celdas entre todos los hilos <strong>de</strong>procesamiento disponibles. Cada hilo se encarga <strong>de</strong>realizar la interacción <strong>de</strong> cada una <strong>de</strong> sus celdas con susvecinas guardando las fuerzas resultantes en un arraypropio, y posteriormente se acumulan las fuerzascalculadas por cada hilo en un único array. Paraconseguir que el reparto <strong>de</strong> carga entre los hilos seaequilibrado se utiliza una planificación dinámica enbloques <strong>de</strong> 10 celdas que son asignados a los hilos amedida que estos quedan libres <strong>de</strong> carga.IV.ESTRATEGIAS DE OPTIMIZACIÓN EN GPUSe parte <strong>de</strong> una implementación híbrida don<strong>de</strong> sólo CFes implementada en GPU, ya que esta parte <strong>de</strong>l códigoconsume más <strong>de</strong>l 99% <strong>de</strong>l tiempo <strong>de</strong> ejecución en CPU(single-core). Debido a que la memoria <strong>de</strong> la GPU esin<strong>de</strong>pendiente <strong>de</strong> la memoria <strong>de</strong> la CPU, siempre que se<strong>de</strong>see procesar datos en la GPU es necesariotransferirlos previamente, y una vez completado elproceso realizar otra transferencia para recuperar losresultados obtenidos <strong>de</strong> la GPU. Esto supone que pararealizar un paso <strong>de</strong> tiempo es necesario realizar lassiguientes fases: (i) generar la lista <strong>de</strong> vecinos en CPU,(ii) transferir datos <strong>de</strong> las partículas y su división enceldas a la GPU, (iii) calcular las fuerzas en GPU, (iv)recuperar la fuerzas calculadas en GPU y (v) actualizarmagnitu<strong>de</strong>s <strong>de</strong> las partículas para el siguiente paso <strong>de</strong>tiempo.En GPU la forma <strong>de</strong> calcular las fuerzas difiere <strong>de</strong> laimplementación en CPU, ya que en lugar <strong>de</strong> hacer lainteracción <strong>de</strong> una celda completa <strong>de</strong> partículas con susceldas vecinas, en GPU cada partícula busca todos susvecinos recorriendo todas las celdas contiguas a<strong>de</strong>más<strong>de</strong> la propia. De esta forma a cada hilo <strong>de</strong> ejecución enGPU (thread) se le asigna una partícula y sólo se encarga<strong>de</strong> calcular las fuerzas para esta partícula. Con estaaproximación no es posible aplicar la simetría en elcálculo <strong>de</strong> fuerzas ya que varios hilos podrían intentarmodificar la misma posición <strong>de</strong> memoriasimultáneamente originando un error. Este problemapodría evitarse mediante el uso <strong>de</strong> barreras <strong>de</strong>sincronización, pero entonces, <strong>de</strong>jaría <strong>de</strong> ser rentable<strong>de</strong>bido a su elevado coste.Los problemas principales que presenta estaimplementación son:1. Transferencias CPU-GPU: Como ya se explicó, alser una implementación parcial en GPU, esnecesario realizar varias transferencias <strong>de</strong> datosentre CPU y GPU por cada paso <strong>de</strong> tiempo que secalcula, lo cual limita significativamente elrendimiento <strong>de</strong> la GPU.2. Divergencia: En CUDA los hilos se agrupan enconjuntos <strong>de</strong> 32 threads llamados warp. Cuando seejecuta una operación sobre un warp, los 32threads realizan dicha operación <strong>de</strong> formasimultánea. Pero <strong>de</strong>bido a bifurcacionescondicionales en el código, no todos los hilospue<strong>de</strong>n realizar la misma operación. Entonces lasdistintas operaciones se realizan secuencialmenteocasionando una pérdida importante <strong>de</strong>rendimiento. Este problema se da en CF porquecada thread tiene que evaluar para su partícula quévecinos potenciales son reales, antes <strong>de</strong> proce<strong>de</strong>r acalcular la fuerza, y <strong>de</strong>scartar al resto.3. Acceso irregular a memoria: De formasimplificada, el acceso a la memoria global <strong>de</strong> laGPU se realiza en bloques <strong>de</strong> 32, 64 o 128 bytes,por tanto el número <strong>de</strong> accesos para satisfacer unwarp <strong>de</strong>pen<strong>de</strong> fundamentalmente <strong>de</strong> si los datossolicitados están agrupados o no. Para más <strong>de</strong>tallesobre el acceso a la memoria global se pue<strong>de</strong>consultar [7]. En CF, pese a que los datos estánor<strong>de</strong>nados según la celda <strong>de</strong> las partículas, no esposible acce<strong>de</strong>r a memoria <strong>de</strong> forma regular yaque cada partícula tiene distintos vecinos y portanto cada thread tendrá que acce<strong>de</strong>r a distintasposiciones <strong>de</strong> memoria que no siempre estaránpróximas a las <strong>de</strong>l resto <strong>de</strong>l warp.4. Desbalanceo <strong>de</strong> carga: En CUDA los warps seejecutan en grupos llamados bloques. Cuando unbloque entra en ejecución se le asignan unosrecursos que no estarán disponibles para otrosbloques hasta que su ejecución se complete.Debido a que cada partícula pue<strong>de</strong> tener distintonúmero <strong>de</strong> vecinos, es posible que un thread tengaque realizar muchas más interacciones que elresto, y así mantener un warp en ejecuciónmientras que el resto <strong>de</strong> threads <strong>de</strong>l mismo warp eincluso <strong>de</strong>l bloque pue<strong>de</strong>n haber terminado. Estoreduce el rendimiento ya que provoca un usoineficiente <strong>de</strong> los recursos <strong>de</strong> la GPU.Con el fin <strong>de</strong> evitar o al menos minimizar losproblemas <strong>de</strong>scritos anteriormente se realizaron lassiguientes optimizaciones:A. Implementación completa en GPUPara minimizar las transferencias entre CPU y GPU sepue<strong>de</strong> implementar todo el proceso en GPUmanteniendo todos los datos en la memoria <strong>de</strong> la GPU.Esto permite reducir drásticamente el número <strong>de</strong>transferencias, ya que sólo sería necesario recuperar losresultados concretos que se <strong>de</strong>seen y cada muchos pasos<strong>JP2011</strong>-701


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>de</strong> tiempo. Por otro lado, al implementar LV y SU en laGPU también se consigue reducir su tiempo <strong>de</strong>ejecución.Como en el caso <strong>de</strong> la implementación en CPU losdatos <strong>de</strong> las partículas (posición, velocidad,...) sonalmacenados en arrays, pero <strong>de</strong>ntro <strong>de</strong> la memoria <strong>de</strong> laGPU. En el paso LV en GPU primero se calcula la celdaque le correspon<strong>de</strong> a cada partícula. Después se usa laimplementación <strong>de</strong> RadixSort <strong>de</strong> NVIDIA [8] paraobtener cuál <strong>de</strong>be ser su posición al or<strong>de</strong>nar laspartículas según su celda, y a partir <strong>de</strong> estas nuevasposiciones se obtienen todos los vectores <strong>de</strong> datosor<strong>de</strong>nados. Por último se crea un vector <strong>de</strong> índicesdon<strong>de</strong> se almacena, para cada celda, la posición queocupa (en los arrays <strong>de</strong> datos) la primera y últimapartícula <strong>de</strong> dicha celda. <strong>La</strong> implementación <strong>de</strong> SU enGPU es sencilla ya que sólo hay que actualizar lasmagnitu<strong>de</strong>s <strong>de</strong> las partículas según las fuerzas aplicandouna fórmula.B. Maximizar la ocupación <strong>de</strong> la GPU<strong>La</strong> ocupación es la relación entre el número <strong>de</strong> warpsactivos y el máximo posible por SM (StreamingMultiprocessor). Debido a que el acceso a la memoriaglobal <strong>de</strong> la GPU en CF es muy irregular, esfundamental tener la mayor cantidad <strong>de</strong> warps activos,ya que esta es la forma <strong>de</strong> ocultar las latencias <strong>de</strong>lacceso a la memoria y mantener el hardware lo másocupado posible. El número <strong>de</strong> warps activos <strong>de</strong>pen<strong>de</strong><strong>de</strong>: los registros que necesita un kernel (procedimientoque se ejecuta en la GPU), características <strong>de</strong> la GPU(consultar tabla I) y <strong>de</strong>l número <strong>de</strong> hilos por bloquecuando se ejecuta un kernel.Con esta optimización el tamaño <strong>de</strong> bloque es ajustadosegún los registros <strong>de</strong>l kernel y las características <strong>de</strong>lhardware, para lograr la mayor ocupación posible. En lafigura 3 pue<strong>de</strong> verse como en una GPU sm13 para 35registros usando 256 threads se consigue 25% <strong>de</strong>ocupación, frente al 44% conseguido con 448 threads.TABLA ICARACTERÍSTICAS DE LAS GPUS SEGÚN COMPUTE CAPABILITY.Especificaciones técnicas 1.0 1.1 1.2 1.3 2.xMáx. <strong>de</strong> threads por bloque 512 1024Máx. <strong>de</strong> bloques activos por SM 8Máx. <strong>de</strong> warps activos por SM 24 32 48Máx. <strong>de</strong> threads activos por SM 768 1024 1536Máx. <strong>de</strong> registros 32-bit por SM 8 K 16 K 32 K100%80%60%40%20%0%20 25 30 35 40 45 50 55Registerssm12-13 (256 threads)sm20-21 (256 threads)sm12-13 (varying threads) sm20-21 (varying threads)Fig. 3. Ocupación <strong>de</strong> la GPU según el número <strong>de</strong> registros necesarios,para un tamaño <strong>de</strong> bloque variable o fijo <strong>de</strong> 256 threads.C. Reducir los accesos a memoria globalUna forma <strong>de</strong> reducir el número <strong>de</strong> accesos a lamemoria en el kernel <strong>de</strong> CF consiste en agrupar algunosdatos y evitar leer valores que se puedan calcular a partir<strong>de</strong> otros. De esta forma se pasa <strong>de</strong> usar 6 arrays (pos yvel <strong>de</strong> 12 bytes y rhop, csound, tensil y prrhop <strong>de</strong> 4bytes), a usar 2 únicos arrays (pos+prrhop y vel+rhop<strong>de</strong> 16 bytes cada uno).D. Simplificar la búsqueda <strong>de</strong> vecinosEn el kernel <strong>de</strong> interacción cada thread tiene quebuscar los vecinos <strong>de</strong> su partícula, para ello <strong>de</strong>berecorrer todas las partículas <strong>de</strong> su propia celda y todaslas <strong>de</strong> alre<strong>de</strong>dor (en total 27 celdas). Este proceso sepue<strong>de</strong> extraer <strong>de</strong>l kernel <strong>de</strong> interacción si previamente secalcula cuales son los rangos <strong>de</strong> partículas con las queva a interaccionar cada celda. Como las partículas estánor<strong>de</strong>nadas según su celda y las celdas en los ejes X, Y yZ, se pue<strong>de</strong>n utilizar 9 rangos <strong>de</strong> partículas para las 27celdas. Al disponer <strong>de</strong> estos rangos, el kernel <strong>de</strong>interacción se simplifica bastante, reduciéndose losaccesos a memoria y la divergencia en los warps,a<strong>de</strong>más también se reduce el uso <strong>de</strong> registros <strong>de</strong>l kernello que permite aumentar la ocupación <strong>de</strong> la GPU. Sinembargo esto provoca un mayor consumo <strong>de</strong> la memoriaya que se necesitan 144 bytes por cada celda.E. Fusionar interacciones F-F con F-CEl acceso a la memoria global <strong>de</strong> la GPU es dosór<strong>de</strong>nes <strong>de</strong> magnitud más lento que el acceso a losregistros. Por esta razón, para minimizar estos accesos,cada thread empieza guardando en registros todos losdatos necesarios <strong>de</strong> su partícula, así sólo necesita leer <strong>de</strong>la memoria los datos <strong>de</strong> las partículas con las queinteractúa. Lo mismo se hace para acumular las fuerzas,éstas se acumulan en registros y sólo al final se escribenen memoria global.Sin embargo y tal como se explicó en el apartado II,las partículas están divididas en 2 grupos (contorno yfluido) y para calcular todas las fuerzas es necesariorealizar tres interacciones (F-F, F-C y C-F). Esto suponeque los datos <strong>de</strong> las partículas asociadas a los threads seleen 2 veces (cuando interaccionan con otras partículasfluido y cuando lo hacen con las contorno), y lo mismoocurre con la escritura <strong>de</strong> los resultados en memoriaglobal. Para evitar esto, en el mismo kernel se hace lainteracción <strong>de</strong>l fluido con el fluido y <strong>de</strong>spués con elcontorno, leyendo los datos al principio y escribiendolos resultados al final.F. Simplificar el kernel <strong>de</strong> interacción C-FAl no po<strong>de</strong>r aplicar la simetría en el cálculo <strong>de</strong> fuerzasse pue<strong>de</strong> implementar un kernel específico para lainteracción C-F, ya que para las partículas contorno sólose necesita calcular una pequeña parte <strong>de</strong> los datos quese necesitan para las <strong>de</strong> fluido. Sin embargo esto nosupone una gran mejora <strong>de</strong>bido a que el número <strong>de</strong>partículas contorno es muy inferior al <strong>de</strong> fluido y portanto su impacto en el rendimiento no es <strong>de</strong>stacable. Enla figura 4 se muestra la proporción <strong>de</strong> partículas <strong>de</strong>contorno frente al total <strong>de</strong>l caso empleado en estetrabajo.<strong>JP2011</strong>-702


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011100%80%60%40%20%0%0 500,000 1,000,000 1,500,000 2,000,000Fig. 4. Proporción <strong>de</strong> partículas contorno en el caso <strong>de</strong> estudio.G. Dividir en celdas más pequeñasNComo ya se explicó en la implementación en CPU,consiste en dividir el dominio en celdas <strong>de</strong> tamaño h enlugar <strong>de</strong> 2h con el fin <strong>de</strong> aumentar la proporción <strong>de</strong>vecinos reales <strong>de</strong>l 19% al 31%. Esto a<strong>de</strong>más <strong>de</strong> reducirla cantidad <strong>de</strong> pares <strong>de</strong> partículas que se evalúan,también reduce el problema <strong>de</strong> la divergencia. Elinconveniente es que aumenta el consumo <strong>de</strong> memoriaya que el número <strong>de</strong> celdas se multiplica por 4 y elnúmero <strong>de</strong> rangos <strong>de</strong> partículas que se compruebandurante la búsqueda <strong>de</strong> vecinos <strong>de</strong> cada partícula pasa <strong>de</strong>9 a 25 (consumiendo 400 bytes por celda).V. RESULTADOSA continuación se presentan los resultados obtenidosen CPU y en GPU al ir aplicando todas lasoptimizaciones comentadas en los apartados anteriores.<strong>La</strong>s simulaciones se han ejecutado bajo un sistemaoperativo Ubuntu 10.10 <strong>de</strong> 64 bits. <strong>La</strong>s características<strong>de</strong>l hardware empleado para la obtención <strong>de</strong> tiempos enCPU son: INTEL Core i7 940 a 2.93 GHz, 6 GB <strong>de</strong>RAM DDR3 a 1333 Mhz, Placa base GA-EX58-UD3RGIGABYTE. Para los tiempos en GPU se utilizó unatarjeta NVIDIA GTX 480 (<strong>de</strong>dicada sólo a cálculo),cuyas características son: 15 Multiprocesadores, 480cores, 1536 MB <strong>de</strong> memoria GDDR5 y Computecapability 2.0.Tanto para CPU como para GPU, los resultadosmuestran el speedup (rendimiento versión mejorada /rendimiento versión básica) conseguido al comparar elrendimiento <strong>de</strong> la versión básica (sin ningunaoptimización) con otras don<strong>de</strong> se incluyen lasoptimizaciones explicadas. El rendimiento se mi<strong>de</strong> enpasos <strong>de</strong> tiempo computados por segundo.En la figura 5 se muestra la mejora <strong>de</strong> rendimientoconseguida en CPU, según el número <strong>de</strong> partículas <strong>de</strong> lasimulación (N), tras aplicar las tres primeras mejorasexplicadas en el apartado III. Para 300,000 partículas seconsigue un speedup <strong>de</strong> 2.26 con respecto a la versión<strong>de</strong>l código sin optimizaciones.2.52.01.51.00 100,000 200,000 300,000NSSE(h)SSE(2h)Simetria(h)Simetria(2h)Fig. 5. Speedup conseguido en CPU single-core aplicando lasoptimizaciones <strong>de</strong>scritas en el apartado III. El speedup <strong>de</strong> SSEincluye el uso <strong>de</strong> la simetría y el valor entre paréntesis es eltamaño <strong>de</strong> celda.<strong>La</strong> figura 6 muestra los resultados con OpenMP. Enesta figura se observa como el uso <strong>de</strong> 8 hilos hace subirel speedup <strong>de</strong> 2.26 a 9.56 (hay que tener en cuenta quela CPU cuenta con 4 cores reales, 8 al tenerhyperthreading activado). Otro <strong>de</strong>talle significativo esque los speedups aumentan con el número <strong>de</strong> partículas.9.07.05.03.01.00 100,000 200,000 300,000N8 Threads4 ThreadsSingle-coreFig. 6. Speedup conseguido en CPU multi-core con respecto a laimplementación sin optimizaciones. En todos los resultados seaplico la simetría, instrucciones SSE y h como tamaño <strong>de</strong> celda.En la figura 7 se muestra el speedup logrado en GPUal implementar las mejoras explicadas en el apartado IV.Cada línea <strong>de</strong> la grafica correspon<strong>de</strong> al resultado <strong>de</strong>aplicar una nueva optimización a<strong>de</strong>más <strong>de</strong> las anteriores.Pue<strong>de</strong> verse cómo para 2 millones <strong>de</strong> partículas seconsigue duplicar el rendimiento aplicando todas lasoptimizaciones hasta la F. Con la optimización G (usoceldas <strong>de</strong> tamaño h) sólo hay resultados hasta 1.8millones <strong>de</strong> partículas ya que las necesida<strong>de</strong>s <strong>de</strong>memoria son mayores que la capacidad <strong>de</strong> la GPUempleada.2.52.01.51.00 500,000 1,000,000 1,500,000 2,000,000NG-Cells(h)F-SimpleCBE-FusionD-NeighSearchC-GlobalMemB-OccupancyA-FullGPUFig. 7. Speedup conseguido en GPU al ir aplicando todas las mejoras<strong>de</strong>scritas en el apartado IV. El speedup <strong>de</strong> cada optimizaciónincluye a todas las anteriores.Una comparativa entre CPU y GPU pue<strong>de</strong> verse en lafigura 8. Se muestra el speedup conseguido con laimplementación más eficiente en GPU frente a la másrápida <strong>de</strong> CPU Single-core y Multi-core <strong>de</strong> 8 threads. Eltiempo <strong>de</strong> ejecución y los pasos <strong>de</strong> cálculo realizadospue<strong>de</strong>n verse en la tabla II.60504030201000 500,000 1,000,000NGPU vs Single-coreGPU vs 8 ThreadsFig. 8. Speedup <strong>de</strong> la versión GPU más optimizada frente a la másrápida <strong>de</strong> CPU.<strong>JP2011</strong>-703


Runtime (h)Memory (Gb)<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011VersiónCPUSingle-coreCPU8 ThreadsTABLA IIRESULTADOS DE SIMULACIONES EN CPU Y GPU.Partículas Tiempo Pasos/seg. Pasos503,492 14.6 h 0.38 19,8551,011,354 40.7 h 0.18 26,493503,492 3.4 h 1.64 19,8221,011,354 9.5 h 0.78 26,492GPU 503,492 0.3 h 21.18 19,8301,011,354 0.7 h 10.12 26,480Como ya se explicó anteriormente la implementaciónmás eficiente en GPU tiene un consumo muy elevado <strong>de</strong>memoria, por lo que el máximo <strong>de</strong> partículas que sepue<strong>de</strong> alcanzar es <strong>de</strong> 1.8 millones en una GTX 480. Paraevitar esta limitación en el código DualSPHysics seimplementaron tres versiones; una con todas las mejoras(FastCells(h)), sin la optimización D (SlowCells(h)) ysin las optimizaciones D y G (SlowCells(h)). Estopermite simular hasta 9 millones <strong>de</strong> partículas comopue<strong>de</strong> verse en la figura 9.1.51.00.50.00 2,500,000 5,000,000 7,500,000 10,000,000NSlowCells(2h)SlowCells(h)FastCells(h)Fig. 9. Consumo <strong>de</strong> memoria (en GBytes) para distintas versiones <strong>de</strong>GPU.En la figura 10 se muestran los tiempos <strong>de</strong> ejecución<strong>de</strong> las tres versiones GPU y <strong>de</strong> las versiones Single-corey Multi-core <strong>de</strong> CPU. Pue<strong>de</strong> verse como las versionesGPU con menor consumo <strong>de</strong> memoria presentan unmenor rendimiento, aunque siguen siendo mucho máseficientes que las CPU.10864200 2,500,000 5,000,000NCPU Single-coreCPU 8 threadsSlowCells(2h)SlowCells(h)FastCells(h)Fig. 10. Tiempos <strong>de</strong> ejecución (en horas) para distintas versiones enCPU y GPU.GPU. Cabe <strong>de</strong>stacar que estas optimizaciones sellevaron a cabo para la aplicación <strong>de</strong> un mo<strong>de</strong>lo SPH,pero la mayoría pue<strong>de</strong>n ser aplicadas a muchos otrosproblemas.Finalmente se presentó una comparativa <strong>de</strong>rendimiento real entre GPU y CPU, don<strong>de</strong> se utilizó elcódigo más optimizado para cada arquitectura sobre unhardware actual (CPU i7 940 a 2.93 GHz y GPU GTX-480). Se obtuvo un speedup cercano al 60 comparandoGPU con CPU Single-core, y <strong>de</strong> 13.3 con CPU Multicore<strong>de</strong> 8 threads.Es necesario seguir investigando cómo mejorar elrendimiento, fundamentalmente en GPU don<strong>de</strong> todavíahay varios inconvenientes que se pue<strong>de</strong>n intentarmejorar. De todas formas, para reducir tiempos <strong>de</strong>ejecución y aumentar el tamaño <strong>de</strong> las simulaciones esimprescindible implementar una versión con MPI que sepueda ejecutar en clústeres <strong>de</strong> CPUs y GPUs.AGRADECIMIENTOSEl presente trabajo ha sido financiado por la Xunta <strong>de</strong>Galicia, Programa <strong>de</strong> Consolidación e Estructuración <strong>de</strong>Unida<strong>de</strong>s <strong>de</strong> Investigación (Grupos <strong>de</strong> ReferenciaCompetitiva) cofinanciado por European RegionalDevelopment Fund (FEDER).REFERENCIAS[1] R. A. Gingold y J. J. Monagham, “Smoothed particlehydrodynamics: theory and application to non- spherical stars”,Mon Not R Astr Soc 181: 375-389, 1977.[2] A. J. C. Crespo, J. M. Dominguez, A. Barreiro, M. Gómez-Gesteira y B. D. Rogers, “GPUs, a new tool of acceleration inCFD: Efficiency and reliability on Smoothed ParticleHydrodynamics methods”, PLoS ONE, doi:10.1371/journal.pone.0020685, 2011.[3] M. Gómez-Gesteira, B. D. Rogers, R. A. Dalrymple y A. J. C.Crespo, “State-of-the-art of classical SPH for free-surfaceflows”, Journal of Hydraulic Research, 48 Extra Issue, 6–27,2010.[4] M. B. Liu y G. R. Liu, “Smoothed Particle Hydrodynamics(SPH): an Overview and Recent Developments”, Arch ComputMethods Eng 17: 25-76, 2010.[5] J. M. Dominguez, A. J. C. Crespo, M. Gómez-Gesteira and J. C.Marongiu, “Neighbour lists in Smoothed ParticleHydrodynamics”, International Journal for Numerical Methodsin Fluids, doi: 10.1002/fld.2481, 2010.[6] M. Gómez-Gesteira y R. Dalrymple, “Using a 3D SPH methodfor wave impact on a tall structure”, Journal of Waterway, Port,Coastal, and Ocean Engineering, 130(2), 63-69, 2004.[7] NVIDIA Corporation, NVIDIA CUDA Programming Gui<strong>de</strong> Ver.3.2, 2010.[8] N. Satish, M. Harris, y M. Garland, “Designing Efficient SortingAlgorithms for Manycore GPUs”, In Proceedings of IEEEInternational Parallel & Distributed Processing Symposium2009, 2009.VI.CONCLUSIONES Y TRABAJO FUTUROSe presentó un código basado en el método SPH parala simulación dinámica <strong>de</strong> fluidos con unaimplementación CPU y otra GPU. Sobre cadaimplementación se mostró que el cómputo <strong>de</strong> fuerzas erala parte más costosa en tiempo. Una vez analizadoscuales eran los problemas que presentaba cadaimplementación, se aplicaron una serie <strong>de</strong>optimizaciones para minimizarlos y mejorar elrendimiento. Con estas optimizaciones se logrómultiplicar la velocidad por 10 en CPU y por 2.6 en<strong>JP2011</strong>-704


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Implementación <strong>de</strong>l algoritmo <strong>de</strong> registro nolineal DARTEL sobre una plataformaheterogéneaPedro Valero 1 , José L. Sánchez 2 , Enrique Arias 2 y Diego Cazorla 2Resumen— Actualmente, en el campo <strong>de</strong> la imagenmédica, los métodos <strong>de</strong> registro <strong>de</strong>formable estánadquiriendo cada vez más importancia, <strong>de</strong>bido a lavaliosa información que aportan. Estos métodos sonutilizados en un gran número <strong>de</strong> tareas críticas comoen diagnósticos, planificación <strong>de</strong> cirugía o radioterapia,etc. Sin embargo, estos métodos consumen untiempo <strong>de</strong> ejecución consi<strong>de</strong>rable, por lo que es importanteobtener nuevas implementaciones que reduzcandicho tiempo. <strong>La</strong>s actuales GPUs disponen<strong>de</strong> un elevado número <strong>de</strong> núcleos y ancho <strong>de</strong> banda,convirtiéndose en un excelente dispositivo para conseguirel propósito <strong>de</strong> acelerar aplicaciones. En estetrabajo se presenta una nueva implementación <strong>de</strong> uno<strong>de</strong> los algoritmos <strong>de</strong> registro <strong>de</strong>formable más utilizados,DARTEL. Los resultados experimentales muestranuna redución <strong>de</strong>l tiempo <strong>de</strong> ejecución, siendo laimplementación en GPU hasta 4 veces más rápida quela implementación secuencial. Una directa consecuencia<strong>de</strong> estos resultados es, en última instancia, proveeruna mejor atención médica.Palabras clave—Imagen médica, registro <strong>de</strong>formable,DARTEL, GPU.I. IntroducciónEL registro <strong>de</strong> imagen es el proceso <strong>de</strong> alinear geométricamentedos o más imágenes <strong>de</strong> la mismaescena, tomadas en diferentes instantes, <strong>de</strong>s<strong>de</strong> diferentespuntos <strong>de</strong> vista, o por diferentes sensores. Hoyen día, el registro <strong>de</strong> imágenes es utilizado en clasificaciónmultiespectral, monitorización <strong>de</strong>l medio ambiente,pronóstico <strong>de</strong>l tiempo, integración <strong>de</strong> información<strong>de</strong>ntro <strong>de</strong> sistemas <strong>de</strong> información geográfica,localización <strong>de</strong> objetivos, calidad <strong>de</strong> control automática,etc. Se han publicado diversos resúmenessobre métodos <strong>de</strong> registro <strong>de</strong> imagen [1], [2].En el campo <strong>de</strong> imagen médica, el registro <strong>de</strong> imagenes el proceso <strong>de</strong> alinear imágenes cuyas característicaspuedan ser relacionadas [3]. Este procesopue<strong>de</strong> ser intra-operativo, aplicado a diferentesimágenes <strong>de</strong>l mismo paciente, o inter-operativo,aplicado a diferentes imágenes <strong>de</strong> diferentes pacientes.El especialista médico utiliza el registro <strong>de</strong>imágenes para diferentes tareas críticas tales como,diagnósticos, planificación <strong>de</strong> cirugía o radioterapia,verificación <strong>de</strong> dosis, cirugía guiada por imagen,seguimiento <strong>de</strong>l progreso <strong>de</strong> la enfermedad o respuestaal tratamiento, registro basado en atlas, etc.El registro alinea imágenes aplicando transformacionesgeométricas a una <strong>de</strong> ellas para igualarla a1 Inst. <strong>de</strong> Investigación en Informática, Univ. <strong>de</strong> Castilla-<strong>La</strong>Mancha, e-mail: Pedro.Valero<strong>La</strong>ra@uclm.es2 Dpto. <strong>de</strong> Sistemas Informáticos, Univ. <strong>de</strong> Castilla-<strong>La</strong> Mancha, e-mail: jose.sgarcia, enrique.arias,diego.cazorla@uclm.esotra. Estas técnicas pue<strong>de</strong>n agruparse en técnicas <strong>de</strong>registro rígido o técnicas <strong>de</strong> registro <strong>de</strong>formable. Elregistro rígido solo permite transformaciones rígidas,como rotaciones y traslaciones. En el otro caso, elregistro <strong>de</strong>formable utiliza técnicas como transformacioneselásticas para corregir <strong>de</strong>formaciones quelos métodos rígidos no pue<strong>de</strong>n corregir.El algoritmo “Diffeomorphic Anatomical RegistrationThrough Exponentiated Lie algebra”, DARTEL[4], [5], es uno <strong>de</strong> los más sofisticados y comunmenteutilizados en este campo. DARTEL forma parte <strong>de</strong>la herramienta software “Statistical Parametric Mapping”(SPM) [6], la cual fue originalmente <strong>de</strong>sarrolladapara el mapeo paramétrico estadístico <strong>de</strong> datosPET (Positron Emission Tomography) y fMRI (functionalMagnetic Resonance Imaging). Uno <strong>de</strong> los usosmás habituales <strong>de</strong> DARTEL consiste en realizar elregistro basado en atlas para imágenes cerebralesen tres dimensiones. Este proceso es computacionalmentemuy costoso, y se requieren nuevas implementacionesmás eficientes y rápidas.Estas circunstancias, es <strong>de</strong>cir, el importante esfuerzocomputacional requerido y la necesidad <strong>de</strong> tiemposrápidos <strong>de</strong> respuesta, unido a la organización inherentementeparalela <strong>de</strong> los datos <strong>de</strong> las imágenesnos conducen al uso <strong>de</strong> la computación paralela comoalternativa más a<strong>de</strong>cuada para mejorar este tipo<strong>de</strong> aplicaciones.Hoy en día la computación heterogénea es una alternativaque se a<strong>de</strong>cúa bastante bien a las altasnecesida<strong>de</strong>s computacionales que tienen algunas aplicaciones.En particular, las plataformas basadas enGPUs tienen un excelente ratio rendimiento/coste,y por ello están siendo ampliamente utilizadas paraacelerar aplicaciones <strong>de</strong> propósito general (GPGPU)[7], [8].Se han llevado a cabo varios estudios en el campo<strong>de</strong>l registro <strong>de</strong> imagen con el uso <strong>de</strong> GPUs. Sin embargo,sólo un número limitado <strong>de</strong> ellos se centran enregistro <strong>de</strong>formable [9], [10]. <strong>La</strong> GPUs han sido utilizadasprincipalmente en registro rígido como en lageneración <strong>de</strong> “Digital Reconstructed Radiograph”(DDR) [11], [12], [13], [14], [15].En este trabajo, se presenta una implementación<strong>de</strong>l algoritmo <strong>de</strong> registro <strong>de</strong>formable DARTEL parauna plataforma heterogénea basada en GPU. A día<strong>de</strong> hoy, y según conocen los autores, no existe ningunaimplementación <strong>de</strong> DARTEL basada en GPU.El trabajo sigue la siguiente estructura: <strong>La</strong> sección2 presenta el algoritmo DARTEL. En la sección 3<strong>JP2011</strong>-705


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011se <strong>de</strong>scribe la implementación <strong>de</strong> DARTEL basadaen GPU. En la sección 4 se muestra el análisis <strong>de</strong>rendimiento llevado a cabo. Finalmente, en la sección5 se resumen las conclusiones.II. DARTELComo se ha mencionado en la sección anterior,DARTEL es un algoritmo <strong>de</strong> registro <strong>de</strong>formablepara imagen médica. DARTEL se divi<strong>de</strong> en dospartes (Figura 1). <strong>La</strong> primera consiste en obteneruna plantilla a partir <strong>de</strong>l atlas. <strong>La</strong> plantilla muestralas características en común <strong>de</strong> los pacientes queforman el atlas. Normalmente, estos pacientes compartenla misma patología. <strong>La</strong> segunda parte consisteen obtener una imagen <strong>de</strong>formada a partir <strong>de</strong>la plantilla proce<strong>de</strong>nte <strong>de</strong> la primera parte, y nuevasimágenes pertenecientes a otros pacientes (una porpaciente). De esta manera, es posible <strong>de</strong>tectar si unpaciente sufre la misma patología compartida por todoslos pacientes que forman el atlas.DARTEL utiliza imágenes segmentadas en materiablanca y gris, por lo cual, en primer lugar, esnecesario segmentar las imágenes <strong>de</strong> cada paciente<strong>de</strong>l atlas. Este proceso no forma parte <strong>de</strong> DARTEL,y <strong>de</strong>be ser llevado a cabo antes <strong>de</strong> aplicar dicho algoritmo.<strong>La</strong> primera parte (Create Template) es un procesoiterativo en don<strong>de</strong> a partir <strong>de</strong> una plantilla inicial yun conjunto <strong>de</strong> imágenes (Atlas) se crea la plantillafinal. Para cada imagen <strong>de</strong>l altas se crea un “campo<strong>de</strong> flujo” el cual codifica cómo cada imagen <strong>de</strong>beser <strong>de</strong>formada para ajustarse mejor a la forma <strong>de</strong> laplantilla. Cuando se obtiene la plantilla, se realiza unproceso <strong>de</strong> suavizado (Smooth). Este proceso se llevaa cabo para obtener una plantilla más precisa.<strong>La</strong> segunda parte se divi<strong>de</strong> en dos etapas. <strong>La</strong>primera consiste en generar los campos <strong>de</strong> flujo (ExistingTemplate). <strong>La</strong> siguiente se realiza para obtenerlas imágenes <strong>de</strong>formadas (Create Warped). Paracada imagen <strong>de</strong> entrada se genera una imagen <strong>de</strong>formada.III. Implementación paralela <strong>de</strong> DARTELpara GPUComo se menciona en la sección I, las actualesGPUs están siendo ampliamente utilizadas para aceleraraplicaciones <strong>de</strong> propósito general. Uno <strong>de</strong> losmotivos <strong>de</strong> utilizar estos dispositivos para este fin, esla aparición <strong>de</strong> nuevas herramientas software que permitental uso. Una <strong>de</strong> las más utilizadas hoy en día esCUDA [16]. En CUDA, los cálculos son distribuidosen una malla o grid <strong>de</strong> bloques <strong>de</strong> hilos. Todos losbloques <strong>de</strong> hilos tienen el mismo tamaño (número <strong>de</strong>hilos). Estos hilos ejecutan el código <strong>de</strong>stinado a laGPU, <strong>de</strong>nominado kernel. <strong>La</strong> dimensiones <strong>de</strong> la mallay <strong>de</strong> los bloques <strong>de</strong> hilos <strong>de</strong>ben ser cuidadosamenteelegidos para maximizar el rendimiento <strong>de</strong> la GPU.CUDA incluye herramientas <strong>de</strong> <strong>de</strong>sarrollo softwareC/C++, librerías <strong>de</strong> funciones, mecanismos <strong>de</strong> monitorizacióno perfilado, . . . , todo ello formando unaApplication Programming Interface (API) propia.Se han paralelizado las partes computacionalmentemás costosas <strong>de</strong> DARTEL las cuales consumenalre<strong>de</strong>dor <strong>de</strong>l 73 % <strong>de</strong>l tiempo total <strong>de</strong> ejecución. Acontinuación, se <strong>de</strong>tallan cada una <strong>de</strong> estas partes:DARTEL utiliza la estrategia <strong>de</strong>l algoritmo llamado“<strong>La</strong>rge Deformation Diffeomorphic MetricMapping” (LDDMM) [17], el cual trata unagran <strong>de</strong>formación como una composición <strong>de</strong> secuencias<strong>de</strong> <strong>de</strong>formaciones más pequeñas. Cadapequeña <strong>de</strong>formación es indicada por una matriz<strong>de</strong> <strong>de</strong>formación. Una <strong>de</strong> las partes más costosasconsiste en inicializar este conjunto <strong>de</strong> matrices.<strong>La</strong>s matrices Jacobianas codifican el estiramiento,corte y rotación que forma la <strong>de</strong>formación.Una fase importante consiste en calcular las <strong>de</strong>formaciones,las cuales se obtienen a partir <strong>de</strong> lacomposición <strong>de</strong> las <strong>de</strong>formaciones o composiciónJacobiana.No es posible utilizar métodos tradicionales paraalmacenar todo el conjunto formado por las matrices<strong>de</strong> <strong>de</strong>formación <strong>de</strong>bido a las limitaciones<strong>de</strong> memoria. Por esa razón, DARTEL utiliza laaproximación llamada “full multigrid” (FMG)[18] para almacenar estas matrices. Este métodoconsiste en comprimir la información almacenadapor las matrices <strong>de</strong> <strong>de</strong>formación, aplicandociertas operaciones matemáticas.Algorithm 1 Pseudocódigo <strong>de</strong> DARTELTemplate, FlowField[n] :DARTEL Template Creation (Atlas[n], Flow-Field[n], Template)FlowFields[n] : DARTEL Warped Creation (Images[n],Template)1: while ( doi < n)2: Small Deformations()3: Jacobian Composition()4: FMG() ⊲ Full Multigrid Method5: i++6: end whileComo se pue<strong>de</strong> ver en el código <strong>de</strong>l Algoritmo 1,DARTEL es un proceso iterativo. Hay tantas iteraciones(n) como imágenes en el atlas en el caso <strong>de</strong> laprimera etapa, y tantas como imágenes <strong>de</strong> entradaen la segunda etapa. El pseudocódigo sólo muestralas funciones paralelizadas y su or<strong>de</strong>n.Cada punto <strong>de</strong> la imagen tiene asociado un conjunto<strong>de</strong> matrices, según el algoritmo LDDMM utilizadopor DARTEL. Cada función consiste en aplicar elmismo conjunto <strong>de</strong> operaciones matemáticas sobrelas matrices asociadas a cada punto <strong>de</strong> la imagen.Así pues, estas funciones consisten en un proceso iterativocon tantas iteraciones como puntos <strong>de</strong> la imagen(m).Cada iteración es in<strong>de</strong>pendiente ya que el procesamiento<strong>de</strong> cada punto no <strong>de</strong>pen<strong>de</strong> <strong>de</strong>l procesamiento<strong>de</strong> los <strong>de</strong>más. Por esa razón, es posible explotarel nivel <strong>de</strong> paralelismo <strong>de</strong> datos <strong>de</strong>l algoritmo, ejecutandotodas las iteraciones <strong>de</strong> forma simultánea.<strong>JP2011</strong>-706


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Create TemplateExisting TemplateCreate WarpedInput Images (Atlas)Input ImagesWhite and grey mattersegmentationWhite and grey mattersegmentationDARTELWarpedSegmented Images (Atlas)Segmented ImagesCreate Initial TemplateDARTELDARTELFlow FieldsFlow FieldsTemplateSmoothTemplateFig. 1. Etapas para generar una plantilla y una imagen <strong>de</strong>formada utilizando el algoritmo DARTEL.Debido a los requisitos <strong>de</strong> DARTEL y al tamaño <strong>de</strong>los datos utilizados (imágenes médicas cerebrales entres dimensiones), no es posible computar todas lasimágenes o un conjunto <strong>de</strong> ellas al mismo tiempo.Por lo tanto, sólo se explota el paralelismo a nivel<strong>de</strong> datos <strong>de</strong> los puntos <strong>de</strong> cada imagen. A<strong>de</strong>más, esnecesario un alto número <strong>de</strong> transferencias entre lasmemorias <strong>de</strong> CPU y GPU.<strong>La</strong>s llamadas a las funciones paralelas son similaresa la implementación secuencial pero es necesario indicarel número <strong>de</strong> hilos que ejecutan el código <strong>de</strong> lafunción. El número <strong>de</strong> hilos está dado por el número<strong>de</strong> puntos <strong>de</strong> la imagen (Algoritmo 2).Se han llevado a cabo ciertas optimizaciones centradasen maximizar la utilización <strong>de</strong> los núcleos,minimizar la sobrecarga <strong>de</strong> las trasferencias entre lasmemorias <strong>de</strong> la GPU y CPU, y utilizar los registrosen la mayor medida posible.IV. Evaluación <strong>de</strong> RendimientoEn esta sección se presenta la evaluación <strong>de</strong>rendimiento <strong>de</strong> la implementación <strong>de</strong> DARTE parala plataforma basada en GPU.Se han utilizado imágenes en tres dimensiones, cadauna consistente en un conjunto <strong>de</strong> imágenes endos dimensiones (capas), correspondientes a las vistasaxial, sagital y coronal. Para los casos <strong>de</strong> prueba,DARTEL ha generado imágenes en tres dimensiones(plantilla e imagen <strong>de</strong>formada) con los sigu-Algorithm 2 Pseudocódigo <strong>de</strong> la versión basada enGPU <strong>de</strong> DARTELTemplate, FlowField[n] :DARTEL Template Creation (Atlas[n], Flow-Field[n], Template)FlowFields[n] : DARTEL Warped Creation (Images[n],Template )1: while do (i < n)2: CPU-GPU Data transferences ⊲ Input data3: Small Deformations kernel< m >()4: GPU-CPU Data transferences ⊲ Outputdata5: CPU-GPU Data transferences6: Jacobian Composition kernel< m >()7: GPU-CPU Data transferences8: CPU-GPU Data transferences9: FMG kernel< m >() ⊲ Full MultigridMethod10: GPU-CPU Data transferences11: i++12: end whileientes tamaños, 60 imágenes en la vista axial, 60imágenes en la vista sagital, y 72 imágenes en la vistacoronal. Por tanto, las imágenes <strong>de</strong> la vista axial son<strong>de</strong> 60×72 píxeles, las imágenes <strong>de</strong> la vista sagital son<strong>de</strong> 60 × 72 píxeles, y las imágenes <strong>de</strong> la vista coronalson <strong>de</strong> 60×60 píxeles. Finalmente, cada imagen tiene(60 × 72) 2 × 60 × 60 = 67, 184, 640, 000 píxeles<strong>JP2011</strong>-707


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>La</strong> plataforma utilizada está formada por unaCPU CPU Intel Core 2 Quad (Q9400)-2.66 GHz y4GB <strong>de</strong> memoria principal, y una GPU GForce GTX285 GPU con 240 núcleos y 1GB <strong>de</strong> memoria <strong>de</strong>ví<strong>de</strong>o.Los resultados experimentales se muestran entérminos <strong>de</strong> tiempo <strong>de</strong> ejecución en segundos yspeedup para ambas implementaciones, secuencial yparalela. Otra métrica que hemos utilizado es el consumoeléctrico. <strong>La</strong>s medidas <strong>de</strong>l consumo se han realizadoutilizando el sistema <strong>de</strong>scrito en [19].Para la primera parte, se ha utilizado un atlas con30 imágenes diferentes en tres dimensiones. <strong>La</strong>s pruebashan consistido en 11 ejecuciones con diferentesnúmero <strong>de</strong> imágenes <strong>de</strong> entrada, <strong>de</strong>s<strong>de</strong> 20 a 30. Parala segunda parte, las pruebas han consistido en 4ejecuciones diferentes, <strong>de</strong>s<strong>de</strong> 1 a 4 imágenes <strong>de</strong> entrada.<strong>La</strong> Tabla 1 muestra el número <strong>de</strong> imágenes(N.I.),tiempo <strong>de</strong> ejecución para la implementaciónsecuencial (T.S.), tiempo <strong>de</strong> ejecución para la implementaciónparalela (T.P.), y speedup (S.). <strong>La</strong> Figura2 muestra la ten<strong>de</strong>ncia <strong>de</strong>l speedup para ambaspartes <strong>de</strong> DARTEL (primera - arriba y segunda -abajo).Primera Parte DARTELN.I. T.S.(s) T.P.(s) S.20 7,723.83 1,964.89 3.9421 8,125.09 2,063.98 3.9422 8,515.01 2,163.36 3.9423 8,909.4 2,258.36 3.9524 9,306.92 2,346.53 3.9725 9,678.8 2,448.9 3.9526 10,042.6 2,533.49 3.9627 10,436 2,641.68 3.9528 10,810.5 2,730.54 3.9629 11,253.7 2,839.41 3.9630 11,589.1 2,938.78 3.95Segunda Parte DARTEL1 374.39 88.92 4.212 751.47 177.42 4.233 1,128.48 256.54 4.244 1,496.84 355.25 4.21TABLA ITiempo <strong>de</strong> ejecución para ambas implementaciones yspeedup obtenido.Realmente, no toda la implementación <strong>de</strong> DAR-TEL ha sido paralelizada, De hecho, <strong>de</strong>spués <strong>de</strong> realizarun estudio <strong>de</strong> perfilado las tres partes con mayorcoste computacional son las mostradas en el Algoritmo1. Según este estudio, las operaciones correspondientesal Small Deformations representan,aproximadamente, el 3.75 % <strong>de</strong>l tiempo total <strong>de</strong> ejecución;la Jacobian Composition representa cerca <strong>de</strong>l40 % <strong>de</strong>l tiempo total <strong>de</strong> ejecución; y el FMG representael 28.7 % <strong>de</strong>l tiempo total <strong>de</strong> ejecución. Estasfases son similares en ambas partes, representando almenos el 73 % <strong>de</strong>l tiempo total <strong>de</strong> ejecución.Tratando cada una <strong>de</strong> estas operaciones <strong>de</strong> formain<strong>de</strong>pendiente, el speedup para Small Deformationses <strong>de</strong> hasta 24×; el speedup para JacobianComposition es <strong>de</strong> hasta 13, 5×; y el speedupSpeedupSpeedup54.543.5320 3054.543.5Número <strong>de</strong> imágenes31 2 3 4Número <strong>de</strong> imágenesFig. 2. Speedup total alcanzado.para FMG es <strong>de</strong> hasta 2, 6×.Sin embargo, la parte secuencial <strong>de</strong>l algoritmo evitaobtener un mejor rendimiento. De hecho, hemosobtenido una implementación con un speedup medio<strong>de</strong> 3.95 para la primera parte, y <strong>de</strong> 4.22 para la segunda.Por otro lado, la Figura 3 muestra el consumoeléctrico para ambas partes (primera - arriba y segunda- abajo) <strong>de</strong> DARTEL. Los resultados correspon<strong>de</strong>nal primer caso <strong>de</strong> la Tabla 1 para cada parte.En los <strong>de</strong>más casos el resultado sigue la misma ten<strong>de</strong>ncia.Como se pue<strong>de</strong> observar en la Figura 3, lospicos <strong>de</strong> consumo <strong>de</strong> la implementación basada enGPU son mayores que en la implementación secuencial.Estos picos correspon<strong>de</strong>n a las transferencias entrela memoria <strong>de</strong> la CPU y la memoria <strong>de</strong> la GPU.Sin embargo, el valor medio <strong>de</strong> la implementaciónbasada en GPU es ligeramente superior al <strong>de</strong> laimplementación secuencial. Por lo tanto, la implementaciónparalela consume menos energía que laimplementación secuencial <strong>de</strong>bido a la significativareducción en tiempo <strong>de</strong> ejecución.Para la primera parte, el consumo <strong>de</strong> energíamedio para la implementación secuencial ha sido <strong>de</strong>134.47 w durante 7723.8 s con un gasto total <strong>de</strong>1,038,619.39 J; para la implementación paralela hasido <strong>de</strong> 170.78 w durante 1964.8 s con un gasto total<strong>de</strong> 335,548.54 J. De otra manera, en la segunda parteel consumo medio para la implementación secuencialha sido <strong>de</strong> 134.66 w durante 374.3 s con un consumo<strong>JP2011</strong>-708


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011VatiosVatios300250200150100SecuencialParalelaMedia SecuencialMedia Paralela500 1964.8 7723.8300250200150100Tiempo(s)SecuencialParalelaMedia SecuencialMedia Paralela500 88.9 374.3Tiempo(s)Fig. 3. Consumo <strong>de</strong> energía <strong>de</strong> DARTEL.total <strong>de</strong> 50,403.24 J y para la implementación paralelaha sido <strong>de</strong> 173.75 w durante 88.9s con lo quese obtiene 15,446.38 J. Por lo tanto, se han conseguidounos beneficios <strong>de</strong>l 67.69 % y <strong>de</strong>l 69.35 % para laprimera y segunda parte respectivamente.V. ConclusionesEl análisis <strong>de</strong> imagen en el ámbito <strong>de</strong> la medicinaes una disciplina cada vez más imprescindible,siendo los algoritmos <strong>de</strong> registro <strong>de</strong>formable unos <strong>de</strong>los más importantes por la valiosa información queofrecen. En este trabajo se ha presentado un nuevaimplementación <strong>de</strong>l algoritmo <strong>de</strong> registro <strong>de</strong>formableDARTEL que acelera el tiempo <strong>de</strong> ejecución con respectoa la versión secuencial disponible. Dicha implentaciónha sido obtenida para una plataformaheterogénea basada en GPU, haciendo uso <strong>de</strong> CU-DA. DARTEL realiza un registro basado en atlas <strong>de</strong>imágenes cerebrales en tres dimensiones. <strong>La</strong>s principalesfunciones <strong>de</strong> DARTEL consisten en procesarun gran conjunto <strong>de</strong> matrices asociadas a los puntos<strong>de</strong> las imágenes. Se ha explotado el paralelismoa nivel <strong>de</strong> punto ya que el procesamiento asociadoa cada uno <strong>de</strong> ellos es in<strong>de</strong>pendiente <strong>de</strong>l aplicado alresto. Los resultados obtenidos muestran una significanteredución en tiempo <strong>de</strong> ejecución y en consumoeléctrico, que en media suponen factores <strong>de</strong> 4 y 3,2respectivamente.Agra<strong>de</strong>cimientosEste trabajo ha sido parcialmente financiado por elproyecto AlzTools (Ref: TSI-020110-2009-362) concedidopor el Ministerio <strong>de</strong> Industria, Turismo yComercio.Referencias[1] L.G. Brown, A survey of image registration techniques,ACM Computing Surveys 24, 326-376 (1992).[2] B. Zitová, J. Flusser, Image registration methods: a survey,Image and Vision Computing 21, 977-1000 (2003).[3] J. V. Hajnal, D. L. Hill, D. J. Hawkes, Medical ImageRegistration, CRC Press (2001).[4] J. Ashburner, A fast diffeomorphic image registration algorithm,NeuroImage 38, 95-113 (2007).[5] J. Ashburner, Computational anatomy with the SPM software,Magnetic Resonance Imaging 27, 1163-1174 (2009).[6] SPM, Statistical Parametric Mapping Framework, http://www.fil.ion.ucl.ac.uk/spm/.[7] GPGPU, General-purpose computation using graphicshardware, http://www.gpgpu.org.[8] J. D. Owens, D. Luebke, N. Govindaraju, M. harris, J.krüger, A. E. Lefohn, T. Purcell, A survey of generalpurposecomputation on graphics hardware, ComputerGraphics Forum 26, 80-113, (2007).[9] C. Vetter, C. Guetter, C. Xu, R. Westermann, Non-rigidmulti-modal registration on the GPU, Medical Imaging2007: Image Processing vol. 6515, pp. 651228 (2007).[10] G. C. Sharp, N. Kandasamy, H. Singh, M. Folkert, GPUbasedstreaming architectures for fast cone-beam CT imagereconstruction and Deamons <strong>de</strong>formable registration,Physics in Medicine and Biology 52(19), 5771-5783, 2007.[11] A. Khamene, R. Chisu, W. Wein, N. Navab, F. Sauer, Anovel projection based approach for medical image registration,WBIR, vol. 4057, pp. 247-256 (2006).[12] F. Ino, J. Gomita, Y. Kawasaki, K. Hagihara, A GPG-PU approach for accelerating 2-D/3-D rigid registrationof medical images, Parallel and Distributed Processingand Applications (ISPA), vol. 4330, pp. 939-950 (2006).[13] A. Khamene, P. Bloch, W. Wein, M. Svatos, F. Sauer,Automatic registration of portal images and volumetricCT for patient positioning in radiation therapy, MedicalImage Analysis, pp. 96-112 (2006).[14] K. Kim, S. park, H. Hong, Y. G. Shin, Fast 2D-3D registrationusing GPU-based preprocessing, 7th InternationalWorkshop on Enterprise Networking and Computing intHealthcare Industry, pp. 139-143 (2005).[15] O. Sadowsky, J. D. Cohen, R. H. Taylor, Ren<strong>de</strong>ring tetrahedralmeshes with higher-or<strong>de</strong>r attenuation functions fordigital rediograph reconstruction, IEEE Visualization, pp.303-310 (2005).[16] NVIDIA, NVIDIA CUDA Compute Unified DeviceArchitecture-Programming Gui<strong>de</strong>, Version 3.1 2009,http://www.nvidia.com/object/cuda_home.html.[17] M. F. Beg, M. I. Miller, A. Trouvé, L. Younes, Computinglarge <strong>de</strong>formation metric mapping via geo<strong>de</strong>sic flows ofdiffeomorphisms, Computer Vision 61, 139-157 (2005).[18] H. W. Press, S. A. Teukolsky, W. T. Vetterling, B. P.Flannery, Numerical recipes in C, 2nd ed. CambridgeUniv. Press, 1992.[19] Roberto Uribe Pare<strong>de</strong>s, Pedro Valero <strong>La</strong>ra, EnriqueArias Antúnez, José Luis Sánchez García, Diego CazorlaLópez, GPU-based implementation for Range Queries onSpaghettis Data Structures, Technical Report DIAB-10-12-1, Computing Systems Dept., University of Castilla-<strong>La</strong>Mancha (2010).<strong>JP2011</strong>-709


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-710


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Compilación para sistemas <strong>de</strong> altas prestaciones<strong>JP2011</strong>-711


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011<strong>JP2011</strong>-712


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Checkpoint Size Reduction in Application-levelFault Tolerant SolutionsIván Cores, Gabriel Rodríguez, María Martín and Patricia González 1Abstract— Systems inten<strong>de</strong>d for the execution oflong-running parallel applications should provi<strong>de</strong>fault tolerant capabilities, since the probability of failureincreases with the execution time and the numberof no<strong>de</strong>s. Checkpointing and rollback recovery isone of the most popular techniques to provi<strong>de</strong> faulttolerancesupport. However, in or<strong>de</strong>r to be useful forlarge scale systems, current checkpoint-recovery techniquesshould tackle the problem of reducing checkpointingcost. This paper addresses this issue throughthe reduction of the checkpoint file sizes. Different solutionsto reduce the size of the checkpoints generatedat application level are proposed and implemented ina checkpointing tool. Detailed experimental resultson a multicore cluster show the effectiveness of theproposed methods.Keywords—Fault Tolerance; Checkpointing; ParallelProgrammingI. IntroductionCurrent trends in high-performance computing(HPC) systems show that future improvements inperformance will be achieved through increases insystem scale. Todays large computational problemscan be solved in clustered multi-core systems withcore numbers in the range of one-hundred thousandto one million and more. However, as parallel platformsincrease their number of resources, so does thefailure rate of the global system [1]. Thus, programmerswill need a way to ensure that not all computationdone is lost on machine failures.Many fault tolerance methods for parallel applicationsexist in the literature, checkpoint-recovery [2]being one of the most popular. It periodically savesthe computation state to stable storage, so that theapplication execution can be resumed by restoringsuch state. The overhead of saving checkpoints todisk is the main performance cost in checkpointrecoverymethods.Most existing checkpoint systems are implementedat the operating system level. In system-level checkpointing(SLC) the whole state of the processes (programcounter, registers and memory) are saved tostable storage. The most important advantage ofthis approach is its transparency. However, checkpointingto a parallel file system is expensive at largescale [1], [3]. Moreover, I/O bandwidths of largescalefacilities do not increase as quickly as their computationalcapability [4]. Therefore, complete SLCof large parallel machines could become impracticable.A more attractive alternative for current andfuture HPC systems is application-level checkpointing(ALC), where the application program saves and1 Computer Architecture Group, Universityof A Coruña, Spain. E-mail:{ivan.coresg,grodriguez,mariam,pglez}@udc.esrestores its own state, which allows to store onlyuserspace data.The aim of this paper is to evaluate different techniquesto reduce the checkpoint sizes and, thus, thecomputational and/or I/O cost of checkpointing inALC approaches. The rest of the paper is organizedas follows. Section II proposes different techniques tooptimize the checkpoint sizes in ALC solutions. SectionIII explains the implementation <strong>de</strong>tails of thosetechniques on an ALC tool. Section IV evaluates theperformance of the proposed methods. Section V <strong>de</strong>scribesrelated work. Finally, Section VI conclu<strong>de</strong>sthe paper.II. Checkpoint Size Optimization onApplication-Level CheckpointingThe majority of the checkpointing tools proposedin the literature work at the system level. The basicdifference between SLC and ALC, in terms of statefile size optimizations, surges from the fact that SLCsees the application memory as a single continuum,while ALC distinguishes a disperse set of contiguousmemory blocks, each containing memory allocated toone or more variables. The exact number <strong>de</strong>pends onthe aliasing relationships of the application data.The following sections <strong>de</strong>al with the utilization ofdifferent checkpoint size optimization solutions intoan application-level approach focusing on its applicationto array variables. In the context of ALC, morenoticeable gains can be achieved by applying optimizationtechniques only to array variables. Applyingthem also to scalar variables results in minimaldifferences in state file sizes and adds performanceoverhead <strong>de</strong>rived from the analyses required to instrumentthe target optimizations.A. Live variable analysisThe knowledge of application memory in ALC canbe used to select those variables that are live duringthe creation of state files, avoiding storage of<strong>de</strong>ad variables. Depending on the consi<strong>de</strong>red application,applying this technique can significantlyreduce checkpoint file sizes.The i<strong>de</strong>ntification of these variables can be performedat compile-time through a standard live variableanalysis. A variable x is said to be live at agiven statement s in a program if there is a controlflow path from s to a use of x that contains no <strong>de</strong>finitionof x prior to its use. The set LV in of livevariables at a statement s can be calculated usingthe following expression:LV in (s) = (LV out (s) − DEF (s)) ∪ USE(s)<strong>JP2011</strong>-713


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011where LV out (s) is the set of live variables after executingstatement s, and USE(s) and DEF (s) arethe sets of variables used and <strong>de</strong>fined by s, respectively.The live variable analysis should take intoaccount interprocedural data flow.Checkpoints in application-level approaches areusually triggered by an explicit call to a checkpointfunction in the application co<strong>de</strong>. This guaranteesthat checkpoints are not performed during a systemcall, which may have internal state unknown to thecheckpointer, but rather insi<strong>de</strong> user-level co<strong>de</strong>. Inthis way, checkpoint callsites are limited and knownat compile time, which allows for the live variableanalysis to be boun<strong>de</strong>d and not span the whole applicationco<strong>de</strong>. For each checkpoint callsite c i , it is onlynecessary to store the set of variables which are livewhen the control flow enters the callsite, LV in (c i ).Live variables should be marked for inclusion in futurecheckpoints right before the checkpoint callsite.Variables that become <strong>de</strong>ad following the control flowmay be unmarked, further reducing the sizes of futurecheckpoint files.B. Incremental checkpointing and zero-blocks exclusionThe most popular technique for checkpoint file sizereduction in SLC approaches is incremental checkpointing[5], [6], [7]. This technique involves creatingtwo different types of checkpoints: full and incremental.Full checkpoints contain all the application data.Incremental checkpoints only contain data that haschanged since the last checkpoint. Usually, a fixednumber of incremental checkpoints is created in betweentwo full ones. During a restart, the state isrestored by using the most recent full checkpoint file,and applying in an or<strong>de</strong>red manner all the differencesbefore resuming the execution.There exist in the literature different solutionsto implement incremental checkpointing in SLC approaches.One of them is to use the virtual memorypage protection mechanisms [5]: upon startinga checkpoint, pages to be saved are marked as readonly.When the page is effectively saved into thecheckpoint its original status is recovered. When theapplication tries to write to a read-only page, therace condition is resolved by the fault handler. Anotheroption is to use a kernel-level memory managementmodule that employs a page table dirty bitscheme [7]. The third classical choice is the hashbasedcheckpoint [6], which uses a secure hash functionto obtain a unique i<strong>de</strong>ntifier for each block ofapplication memory to be written into state files.This value is stored and compared against the valuecalculated for the same block upon creating a newcheckpoint. If the two hash values differ, the blockcontents have changed and it is stored again in thenew checkpoint file.In ALC it is unadvisable to track changes to memoryblocks using the virtual memory page protectionmechanism or dirty bits as array variables donot necessarily start at page boundaries. Evaluating0 1 2 3 4 5 6 7 8 9 ...H-0 H-1 H-2 H-3 H-4 H-5 H-6 H-7 H-8 H-9...0 1 2 6 7 9 ...0 1 2 3 4 5 6 7 8 9 ...H-0 H-1 H-2*H-3*H-4*H-5*H-6* H-7 H-8 H-92 3 4 5 6Data blockFig. 1.HDDEmpty blockHDDCheckpoint 2(Incremental)Block modifiedsince last ckpt.Checkpoint 1(Full)0H-0Block idHash valueMemory of array AContinueexecutionMemory of array AConstruction of an incremental checkpointMark ofempty blockmemory changes for each array as a whole is also unadvisable,following the locality principle. The bestcompromise is to divi<strong>de</strong> array variables into chunksof memory of a previously specified size, assumed tobe constant, and control changes into these chunksusing a secure hash function. The calculated hashvalue for each chunk of memory is stored in memoryand used for comparison when creating incrementalcheckpoints.When working with real scientific applications itis well known that quite often many elements of thearrays are null, resulting in memory blocks that containonly zeros. Therefore, a possible optimizationto further reduce the checkpoint file size is to avoidstorage of those zero-blocks. In addition to controlthe changes into memory blocks, the hash functionmay be used to <strong>de</strong>tect zero-blocks. Once a zero-blockis <strong>de</strong>tected, instead of dumping it into the checkpointfile, a small marker is saved indicating that this blockis zero. During restart this marker is i<strong>de</strong>ntified andthe target memory is filled with zeros, which recoversthe original state at a negligible cost in terms ofboth performance and disk usage. The constructionof an incremental checkpoint is <strong>de</strong>picted in Figure 1.The process of restarting from incremental checkpointsis shown in Figure 2. The last available fullcheckpoint is restored first, and the updates containedin each incremental checkpoint are then appliedin an or<strong>de</strong>red manner.III. ImplementationThe techniques <strong>de</strong>scribed in Section IIhave been implemented on CPPC [8], anopen-source checkpointing tool available fromhttp://cppc.<strong>de</strong>s.udc.es un<strong>de</strong>r GPL license.A. CPPC overviewCPPC is an application-level checkpointing toolfocused on the insertion of fault tolerance into longrunningmessage-passing applications. It is <strong>de</strong>signedwith special focus on portability: it uses portableco<strong>de</strong> and protocols, and generates portable checkpointfiles, allowing for execution restart on different<strong>JP2011</strong>-714


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 20110 1 2 6 7 9 ...0 1 2 3 4 5 6 7 8 9 ...Data blockFig. 2....Empty blockHDDCheckpoint 1(Full)Checkpoint 2 (Incremental)HDD2 3 4 5 6Overwritten blockStep 1Step 2Memory of array AMark ofempty blockRestart from an incremental checkpointRestartFig. 3. Integration of a parallel application with the CPPCframeworkarchitectures and/or operating systems.CPPC appears to the user as a compiler tool anda runtime library. The integration between the applicationand the CPPC framework is automaticallyperformed by the CPPC compiler, a source-to-sourcetool that converts an application co<strong>de</strong> into an equivalentversion with ad<strong>de</strong>d checkpointing capabilities.The global process is <strong>de</strong>picted in Figure 3. At compiletime, the CPPC compiler instruments the co<strong>de</strong>by inserting calls to the CPPC library. At runtime,the application will send petitions to the CPPC controller.From the structural point of view, the controllerconsists of three basic layers: a faca<strong>de</strong>, thatkeeps track of the state to be stored when the nextcheckpoint is reached; the checkpointing layer, whichgathers, manages and puts together all data to bestored into the state files; and a writing layer which<strong>de</strong>couples the other two layers from the specific fileformat used for state storage. Currently CPPC provi<strong>de</strong>sa writing plugin based on the Hierachical DataFormat 5 (HDF5) [9], a hierarchical data format andassociated library for the portable transfer of graphicaland numerical data between computers.B. Live variable analysisThe live variable analysis explained in Section II-Aconstitutes one of the passes of the CPPC compiler.It does not currently perform optimal bounds checksfor pointers and arrays variables. This means thatsome arrays and pointers are registered in a conservativeway: they are entirely stored if they are usedat any point in the re-executed co<strong>de</strong>.When <strong>de</strong>aling with calls to precompiled procedureslocated in external libraries, the <strong>de</strong>fault behavior isto assume all parameters to be of input type. Therefore,all not previously inclu<strong>de</strong>d variables containedin the set LV in (s p ), being s p the analyzed procedurecall, will be marked for inclusion.C. Incremental checkpointing and zero-blocks exclusionFor the implementation of incremental checkpointing,the HDF-5 writer was modified to divi<strong>de</strong> arrayvariables into blocks of memory. The size ofthese memory blocks may have a great impact on theperformance of the incremental checkpointing technique.CPPC allows the user to choose the size tobe applied to each particular application.The new HDF-5 writer also calculates the hashvalues of the memory blocks. The choice of thehash function impacts the correctness, since manyhash functions present a significant probability ofcollisions, that is, situations where a memory blockchanges from one checkpoint to the next checkpointbut its hash value remains the same. Secure hashfunctions should be used to implement reliable incrementalcheckpointing techniques [10]. The implementationof incremental checkpointing in CPPC allowsthe user to choose between different secure hashfunctions, such as MD5 or SHA.The calculated hash functions are used to <strong>de</strong>tectboth zero-blocks that can be exclu<strong>de</strong>d in thenext checkpoint and changes in the memory blocksfrom previous checkpoints. In or<strong>de</strong>r to <strong>de</strong>tect zeroblocksthe calculated hash values are compared to theknown hash value of a zero-block. To <strong>de</strong>tect changesin the memory blocks, the hash values calculated inprevious checkpoints have to be stored to be comparedwith the new ones. In our implementation,the hash co<strong>de</strong>s are stored into main memory ratherthan in disk, to improve the performance of the technique.Only the modified blocks with non-zero elementswill be stored in the checkpoint file. In or<strong>de</strong>r to enablefull data recovery during restart, an i<strong>de</strong>ntifier isstored in the checkpoint file for each modified memoryblock, including zero-blocks (see Figure 1 andFigure 2). This i<strong>de</strong>ntifier indicates the original positionof the block in memory relative to the start ofthe array. CPPC uses the high-or<strong>de</strong>r bit of the i<strong>de</strong>ntifierto mark the zero-blocks that are not inclu<strong>de</strong>din the checkpoint file but should be restored in thisstep.In addition to the checkpointing mechanism, therestart mechanism has also been modified to complywith incremental checkpointing as <strong>de</strong>scribed inSection II-B. The last available full checkpoint is restoredfirst and the modifications contained in theassociated incremental checkpoints are or<strong>de</strong>rly updated.IV. Experimental ResultsThis section assesses the impact of the <strong>de</strong>scribedoptimization techniques in the size of the checkpoint<strong>JP2011</strong>-715


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLE ICheckpoint sizes per process (in MB)IncrementalNPB SLC ALC Base LiveVar Full Incr. 1 Incr. 2BT (B.4) 175.98 109.95 109.76 106.48 95.02 95.02CG (C.8) 219.85 151.65 66.33 58.74 2.48 2.48EP (C.8) 67.42 1.18 1.04 1.04 1.04 1.04FT (C.8) 962.93 768.14 640.10 640.18 512.15 512.15IS (C.8) 354.52 288.12 288.10 192.18 46.48 47.95LU (B.8) 93.51 27.16 26.69 26.62 20.03 20.03MG (C.8) 502.15 435.89 435.85 303.25 303.04 303.04SP (B.4) 168.55 102.35 102.25 96.36 77.33 77.33files and in the execution time overheads. A multicorecluster was used to evaluate our proposal. Itconsists of 16 no<strong>de</strong>s, each one of them powered bytwo Intel Xeon E5620 quad-core CPUs with 16 GBof RAM. The cluster no<strong>de</strong>s are connected throughan Infiniband network. The front-end is powered byone Intel Xeon E5502 quad-core CPU with 4 GB ofRAM. The connection between the front-end and theexecution no<strong>de</strong>s is an Infiniband network too. Finally,the working directory is mounted via NFS andis connected to the cluster by a Gigabit Ethernetnetwork.The application testbed was comprised of the eightapplications in the MPI version of the NAS ParallelBenchmarks v3.1 [11] (NPB from now on). These arewell-known and wi<strong>de</strong>spread applications that provi<strong>de</strong>a <strong>de</strong>-facto test suite. Out of the NPB suite, the BT,LU and SP benchmarks were run using class B, whilethe rest were run using class C due to memory constraints.The experiments can be divi<strong>de</strong>d into two blocks.The first block analyzes the checkpoint size optimizationobtained using the proposed techniques.The second block evaluates the execution overheadcaused by the computation of the hash functions, andthe restart overhead caused by the restart mechanismin the incremental technique. All the experimentswere run on a single no<strong>de</strong> using all the 8 cores, exceptfor BT and SP, that run over 4 cores, as they requirea square number of processes. All the checkpointfiles were stored into the working directory mountedvia NFS.A. Checkpoint file sizesThe reduction in checkpoint file size is the maingoal of the techniques <strong>de</strong>scribed in this work. TableI allows to compare the checkpoint file size reductionobtained by the different techniques. Thefirst column shows results for a SLC approach. Thesecond column shows results for an ALC approachwithout applying any optimization technique (basecase), that is, all the user variables are stored inthe checkpoint file. The remaining columns showresults for checkpoint file sizes when using the livevariable analysis and the incremental checkpointingtechnique proposed in this paper. Two incremen-TABLE IICheckpoint latency (in s)IncrementalNPB ALC Base LiveVar Full Incr. 1BT 5.65 5.42 5.55 5.26CG 14.24 6.52 5.42 0.39EP 0.05 0.07 0.05 0.03FT 89.56 62.25 65.40 50.29IS 26.48 26.81 17.10 4.95LU 2.68 2.78 2.50 1.87MG 39.36 37.89 28.24 27.33SP 5.05 5.37 5.21 4.30tal checkpoints were created after a full checkpoint.As can be seen, ALC obtains better results than theSLC approach and its checkpoint files can be furtherreduced using the optimization techniques proposedin this paper.Live variable analysis significantly reduces checkpointfile sizes for CG (56.26% of reduction) and obtainsa consi<strong>de</strong>rable gain in FT (16.7%). It can beconclu<strong>de</strong>d that this technique may have great influenceon reducing file sizes for certain applicationsand, as it introduces overhead only at compile time,no application can be adversely affected by its use.The incremental checkpointing proposed in thispaper achieves important file size reductions for almostall the applications. Note that reductionsachieved in the full checkpoint relative to the livevariable technique are due to the elimination of zeroblocks.These reductions may vary with the size ofthe memory block. Table I shows results for memoryblocks of 8K elements, where reductions respect tothe base case range from 3% (BT) to 60% (CG) forthe full checkpoint and from 12% (BT) to 98% (CG)for the incremental checkpoints.B. Checkpoint latencyTable II shows the checkpoint latency obtained forthe different NPB applications. The checkpoint latencyis <strong>de</strong>fined as the ellapsed time between the callto the checkpointing function and the return of controlto the application. The experiments were repeated10 times for each application and the mini-<strong>JP2011</strong>-716


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011TABLE IIIRestart times (in s)NPB ALC Base LiveVar Zero Incr.BT 4.44 5.22 4.55 11.15CG 11.71 6.02 4.56 4.54EP 0.10 0.09 0.09 0.24FT 58.36 48.80 49.92 156.46IS 22.03 22.05 15.01 20.83LU 2.08 2.04 2.08 4.90MG 33.12 33.12 23.81 66.14SP 4.31 4.32 4.08 9.42mum time obtained is reported.The main goal of the experiment is to measure theoverhead introduced by the computation of the hashfunctions and the inspections nee<strong>de</strong>d to create theincremental checkpoint. The hash function selectedin CPPC for these experiments was MD5. From theresults, it can be observed that the overhead introducedby the incremental checkpointing technique ishid<strong>de</strong>n by the gain obtained from the reduction incheckpoint size. Results for the creation of the fullcheckpoint in the incremental technique allow alsoto assess the gain obtained when solely applying thezero-blocks exclusion.In general, both the live variable analysis, whoseoverhead is moved to compile time, and the incrementalcheckpointing technique with zero-blocks exclusion,perform better than the base approach. Insome cases the reduction in checkpoint overhead canbe as high as 30 − 40% (CG or IS).CPPC can be configured so that the checkpoint isbuilt in parallel with the execution of the applicationby creating new threads. Thus, the application executiondoes not have to be stalled until the checkpointsare created and the above latencies may behid<strong>de</strong>n.C. Restart overheadRestart times are shown in Table III. The restarttime inclu<strong>de</strong>s the read of the checkpoint files and therestart of the application to the point where the thecheckpoint was dumped. Again, at least 10 executionswere performed for each application and theminimum time obtained is reported. The memorywas freed before each execution to avoid the effectof page cache and to guarantee that checkpoint filesare read from disk.Column labeled as “Zero” shows the restart overheadwhen there is no incremental checkpoint file butthe full one. These results allow to evaluate the overheadwhen applying only the zero-blocks exclusion,which is always less than the overhead of the baseapproach.The incremental checkpointing technique presentsa high overhead at restart compared to the others.This is due to a larger volume of data to be movedand read in the case of incremental checkpointing(that can be calculated as the sum of the last threecolumns of Table I). A possible approach to reducethis overhead would be to bring together thefull checkpoint file and the incremental ones into anunique file at the checkpoint server before a restartis required. The number of incremental checkpointswill have a great influence in the restart overhead.There exist studies [12] that provi<strong>de</strong> a mo<strong>de</strong>l to <strong>de</strong>terminethe optimal number of incremental checkpointsbetween two consecutive full checkpoints.V. Related WorkThe live variable analysis, presented in Section II-A, can be seen as a complementary approach tomemory exclusion techniques proposed by Plank etal. [13].As regards incremental checkpointing, as mentionedin Section II-B, there exist in the literaturea number of techniques to implement it in SLC [5],[6], [7], [14], [15], [16]. The implementation proposedin this paper is inspired by the hash-based approaches[6], [16] but it is inten<strong>de</strong>d for ALC. Usingan application-level approach reduces drastically thenumber of memory blocks to be checked in runtimeand, thus, the overhead of the approach. The reductionin the number of analyzed blocks implies also areduction in the size of the hash tables to be stored.This reduction allows to store these tables into mainmemory instead of disk, reducing even more the overheadof the technique. Additionally, the size of thegenerated checkpoint files is reduced through the <strong>de</strong>tectionand elimination of zero-blocks.The i<strong>de</strong>a of not storing zero-blocks has a certainsimilarity to the technique used in the SLCtool Berkeley <strong>La</strong>b’s Checkpoint/Restart (BLCR) Library[17] to exclu<strong>de</strong> zero pages, that is, those thathave never been touched and logically contain all zeros.Other alternative present in the literature to reducethe checkpoint size is data compression. Itwas implemented, for instance, in the CATCH compiler[18] and ickp checkpointer [19]. Experimentalresults show that compression significantly reducescheckpoint sizes. However, the potential benefits ofcompression for reducing the overhead of checkpointing<strong>de</strong>pend on the time required to compress data,the compression rate and the ratio of processor speedto disk speed.CATCH also implements adaptive checkpoint,that is, it uses a heuristic algorithm to <strong>de</strong>terminethe optimal places, in terms of checkpoint size, toinsert checkpoints. This technique could be usefulfor programs with large variations in memory usage.All the techniques mentioned so far focus on reductionof the checkpoint file sizes. Another wayto reduce the computational and I/O cost of checkpointingis to avoid the storage of checkpoint files onthe parallel file system. In [20] Plank et al. proposedto replace stable storage with memory and processorredundancy. Some recent works [21], [22], [23] haveadapted the technique, known as diskless checkpointing,to contemporary architectures. The main draw-<strong>JP2011</strong>-717


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011back of diskless checkpoiniting is its large memoryrequirements.VI. Concluding RemarksThis work has analyzed different alternatives toreduce the size of the checkpoint files generated inALC approaches: live variable analysis, zero-blockselimination and incremental checkpointing. Thetechniques have been implemented in an ALC tool,CPPC, obtaining important file size reductions.The reduction of the checkpoint sizes will be particularlyuseful for parallel applications with a largenumber of parallel processes, where the transferenceof a large amount of checkpoint data to stable storagecan saturate the network and cause a drop inapplication performance.The results have shown that incremental checkpointingis the most effective of the three exploredmethods in terms of checkpoint size reduction. However,global storage requirements increase for thistechnique as it is necessary to keep stored at leastone full checkpoint and all the incremental ones associated.Additionally, it complicates the restart,resulting in an overhead that may become important<strong>de</strong>pending on the number of incremental checkpointsand the characteristics of the network. The resultsindicate that merging the checkpoint files beforerestarting could significantly reduce restart times.As regards live variable analysis and zero-blockelimination techniques, the checkpoint size reductionsobtained are not as significant, however, they<strong>de</strong>crease globally the storage <strong>de</strong>mand and are ableto reduce the overhead of both the checkpoint filewriting and the restart phase. At present, our implementationof the live variable analysis does notperform optimal bounds checks for pointer and arrayvariables. This means that they are entirely storedif they are used at any point in the re-executed co<strong>de</strong>.Thus, there is still room for future optimizations inthis compilation analysis.AcknowledgmentThis research was supported by the Ministry ofScience and Innovation of Spain (Project TIN2010-16735) and by the Galician Goverment (Project10PXIB105180PR).References[1] Bianca Schroe<strong>de</strong>r and Garth A Gibson, “Un<strong>de</strong>rstandingfailures in petascale computers,” Journal of Physics:Conference Series, vol. 78, no. 1, pp. 012022, 2007.[2] E.N. Elnozahy, L. Alvisi, Y.-M. Wang, and D.B. Johnson,“A survey of rollback-recovery protocols in messagepassingsystems,” ACM Computing Surveys, vol. 34, no.3, pp. 375–408, 2002.[3] Franck Cappello, “Fault tolerance in petascale/ exascalesystems: Current knowledge, challenges and researchopportunities,” International Journal of High PerformanceComputing Applications, vol. 23, no. 3, pp. 212–226, 2009.[4] Kamil Iskra, John W. Romein, Kazutomo Yoshii, andPete Beckman, “Zoid: I/o-forwarding infrastructure forpetascale architectures,” in Proceedings of the 13th ACMSIGPLAN Symposium on Principles and practice of parallelprogramming. 2008, PPoPP ’08, pp. 153–162, ACM.[5] J. S. Plank, J. Xu, and R. H. B. Netzer, “Compresseddifferences: an algorithm for fast incremental checkpointing,”Tech. Rep. CS-95-302, University of Tennessee, Departmentof Computer Science, Aug. 1995.[6] S. Agarwal, R. Garg, and M. S. Gupta, “Adaptive incrementalcheckpointing for massively parallel systems,”in Proceedings of the 18th Annual International Conferenceon Supercomputing (ICS’04), Saint Malo, France,26 June–01 July 2004, pp. 277–286, ACM, New York.[7] R. Gioiosa, J. C. Sancho, S. Jiang, and F. Petrini, “Transparent,incremental checkpointing at kernel level: a foundationfor fault tolerance for parallel computers,” in Proceedingsof the ACM/IEEE SC2005 Conference on HighPerformance Networking and Computing (SC’05), Seattle,WA, USA, 12–18 November 2005, IEEE ComputerSociety Press, Los Alamitos.[8] G. Rodríguez, M.J. Martín, P. González, J. Touriño, andR. Doallo, “CPPC: A compiler-assisted tool for portablecheckpointing of message-passing applications,” Concurrencyand Computation: Practice and Experience, vol.22, no. 6, pp. 749–766, 2010.[9] The HDF5 Group, “HDF-5: Hierarchical Data Format,”http://www.hdfgroup.org/HDF5/. <strong>La</strong>st accessedJune 2010.[10] Hyo-Chang Nam, Jong Kim, SungJe Hong, and SungguLee, “Secure checkpointing,” Journal of Systems Architecture,vol. 48, pp. 237–254, 2003.[11] National Aeronautics and Space Administration, “TheNAS Parallel Benchmarks,” http://www.nas.nasa.gov/Software/NPB, <strong>La</strong>st accessed June 2010.[12] Nichamon Naksinehaboon, Yudan Liu, Chokchai (Box)Leangsuksun, Raja Nassar, Mihaela Paun, andStephen L. Scott, “Reliability-aware approach: An incrementalcheckpoint/restart mo<strong>de</strong>l in hpc environments,”in Proceedings of the 2008 Eighth IEEE InternationalSymposium on Cluster Computing and the Grid, 2008,pp. 783–788.[13] J.S. Plank, M. Beck, and G. Kingsley, “Compiler-assistedmemory exclusion for fast checkpointing,” IEEE TechnicalCommittee on Operating Systems and ApplicationEnvironments, vol. 7, no. 4, pp. 10–14, 1995.[14] E.N. Elnozahy, D.B. Johnson, and W. Zwaenepoel, “Theperformance of consistent checkpointing,” in ReliableDistributed Systems, 1992. Proceedings., 11th Symposiumon, Oct. 1992, pp. 39 –47.[15] J. S. Plank, M. Beck, G. Kingsley, and K. Li, “Libckpt:Transparent Checkpointing un<strong>de</strong>r Unix,” in Usenix WinterTechnical Conference, January 1995, pp. 213–223.[16] Hyo-Chang Nam, Jong Kim, SungJe Hong, and SungguLee, “Probabilistic checkpointing,” in Fault-TolerantComputing, 1997. FTCS-27. Digest of Papers., Twenty-Seventh Annual International Symposium on, June 1997,pp. 48 –57.[17] <strong>La</strong>urence Berkeley National <strong>La</strong>boratory, “Berkeley<strong>La</strong>b Checkpoint/Restart,” https://ftg.lbl.gov/CheckpointRestart/. <strong>La</strong>st accessed December 2010.[18] C.-C.J. Li and W.K. Fuchs, “Catch-compiler-assistedtechniques for checkpointing,” in Fault-Tolerant Computing,1990. FTCS-20. Digest of Papers., 20th InternationalSymposium, June 1990, pp. 74 –81.[19] James S. Plank and Kai Li, “ickp: A consistent checkpointerfor multicomputers,” IEEE Parallel Distrib.Technol., vol. 2, pp. 62–67, June 1994.[20] J. S. Plank, K. Li, and M. A. Puening, “Diskless checkpointing,”IEEE Transactions on Parallel and DistributedSystems, vol. 9, no. 10, pp. 972–986, October1998.[21] Zizhong Chen, Graham E. Fagg, Edgar Gabriel, Julien<strong>La</strong>ngou, Thara Angskun, George Bosilca, and Jack Dongarra,“Fault tolerant high performance computing bya coding approach,” in Proceedings of the tenth ACMSIGPLAN symposium on Principles and practice of parallelprogramming, New York, NY, USA, 2005, PPoPP’05, pp. 213–223, ACM.[22] Leonardo Arturo Bautista Gomez, Naoya Maruyama,Franck Cappello, and Satoshi Matsuoka, “Distributeddiskless checkpoint for large scale systems,” ClusterComputing and the Grid, IEEE International Symposiumon, vol. 0, pp. 63–72, 2010.[23] Ge-Ming Chiu and Jane-Ferng Chiu, “A new disklesscheckpointing approach for multiple processor failures,”IEEE Transactions on Dependable and Secure Computing,vol. 99, no. PrePrints, 2010.<strong>JP2011</strong>-718


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Source-to-Source Transformations for EfficientSIMD Co<strong>de</strong> GenerationAlejandro Berna 1 , Marta Jiménez 1 , Jose M. Llabería 1AbstractIn the last years, there has been much effort in commercial compilersto generate efficient SIMD instructions-based co<strong>de</strong> sequencesfrom conventional sequential programs. However, thesmall numbers of compilers that can automatically use theseinstructions achieve in most cases unsatisfactory results. Therefore,the co<strong>de</strong> often has to be written manually in assembly languageor using compiler built-in functions to achieve highperformance. In this work, we present source-to-source transformationsthat help commercial vectorizing compilers to generateefficient SIMD co<strong>de</strong>. Experimental results show that excellentperformance can be achieved. In particular, for the problem ofmatrix product (SGEMM) we almost achieve as high performanceas hand-optimized numerical libraries. Our source-tosourcetransformations are based on the scalar replacement andunroll and jam transformations presented by Callahan et all. Inparticular, we extend the use of scalar replacement to vectorialreplacement and combine this transformation with unroll and jamand outer loop vectorization to fully exploit the vector registerlevel and thus to help the compiler to generate efficient SIMDco<strong>de</strong>. We will show experimentally the effectiveness of our proposal.Categories and Subject DescriptorsD.3.4 [Processors]: compilers, optimization: C.1.2 [MultipleData Stream Architectures (Multiprocessors)]: Singleinstruction-stream,multiple-data-stream processors (SIMD)General TermsAlgorithms, Performance.KeywordsSIMD; vectorization; source-to-source transformations; registertiling;1. IntroductionThe ISA of all today´s microprocessors has been exten<strong>de</strong>d withmultimedia instructions [9]. Multimedia extensions follow theSIMD paradigm by exploiting wi<strong>de</strong> data paths and functionalunits that simultaneously operate on narrow data paths of packeddata elements (relatively short vectors that resi<strong>de</strong> in memory orregisters). The number of packed data elements (VL) supportedby the SIMD instructions has been increased with each microprocessorgeneration, going from 64 bits data registers in thePentium II with the MMX technology to the 256 bits data registersin Sandy Bridge with the AVX1 technology. Moreover,SIMD extensions have also evolved in number of instructions1 Departament d’Arquitectura <strong>de</strong> Computadors, Universitat Politècnica <strong>de</strong>Catalunya, Barcelona, Spain, e-mail:{aberna, marta, llaberia}@ac.upc.eduand data types. MMX technology has 57 SIMD instructions andhandles only integer data types while AVX1 technology has hundredsof instructions and handles both integer and floating-point(single and double) data types[12][20].SIMD instructions are useful in multimedia and signalprocessing applications [23][30], but also in scientific and numericalapplications [1][8][18]. They offer higher performance, agood performance/power ratio, and better resource utilization.However, compilers still do not have good support for SIMDinstructions due to the difficulty of automatically vectorizingconventional sequential programs. The few commercial compilersthat can automatically use these instructions achieve in mostcases unsatisfactory results.To overcome the lack of a<strong>de</strong>quate compiler support for SIMDextensions, often the co<strong>de</strong> has to be written manually in assemblylanguage or using compiler built-in functions [12]. However,these methods, although very effective, are tedious, error proneand result in highly machine-specific co<strong>de</strong>, so that porting anapplication to a new target processor requires significant programmingeffort.Manufacturers have tried to minimize the complexity of writingSIMD optimized co<strong>de</strong>s by providing numerical libraries (suchas MKL [11]) that attain high performance un<strong>de</strong>r their particularmicroprocessor. However, not all applications can take advantageof these libraries and there are many situations in which none ofthe routines provi<strong>de</strong>d can specifically solve the task at hand.We believe that restructuring a co<strong>de</strong> to better exploit SIMDcapabilities should be the job of a compiler. Compilers, not programmers,should handle the machine-specific <strong>de</strong>tails required toobtain high performance on each particular architecture. Algorithmshould be expressed in a natural machine-in<strong>de</strong>pen<strong>de</strong>ntform and the compiler should apply the appropriate transformationto optimize the resulting co<strong>de</strong>.In this paper, we present high level (source-to-source) transformationsthat help actual commercial vectorizing compilers togenerate efficient SIMD co<strong>de</strong> on scientific numerical applications.The proposed transformations are simple enough to besuitable for automatic implementation by compilers.Our proposal is based on an effective use of the vector registers.As already known, the existence of a gap between memoryand CPU performance ma<strong>de</strong> effective use of the register file imperativefor excellent performance. It is well-known that theallocation of array values that exhibit reuse to registers can significantlyimprove the memory performance of programs. However,in many production compilers array references are left asreferences to main memory rather than references to registersbecause the data flow analysis used by the compiler is not powerfulenough to recognize most opportunities for reuse in subscriptedvariables.Callahan et all in [5] presented a source-to-source transformation,called scalar replacement, that exposed the reuse availablein array references in an innermost loop. They also showed experimentallyhow another loop transformation called unroll and<strong>JP2011</strong>-719


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011jam, could expose more opportunities for scalar replacement bymoving reuse across an outer loop into the innermost loop.In this work, we will apply the i<strong>de</strong>a of scalar replacement andunroll and jam to vectorized loop nests and show experimentallytheir effectiveness. We refer as vectorial replacement to the scalarreplacement transformation applied to SIMD vectorized loopnests.Summarizing, the contribution of this paper are the following:An approach that combines 3 source-to-source transformations(outer-loop vectorization, unroll and jam ofvectorized loops and vectorial replacement) that helpcompilers to generate efficient SIMD co<strong>de</strong> in scientificnumerical applications.Experimental evaluation exhibiting the impact of thesetransformations using simple kernels of loop nests on aNehalem platform.The rest of this paper is organized as follows: Section 2 explainsprevious work related to source-to-source loop transformations.Section 3 <strong>de</strong>scribes our approach to help the compiler tovectorize outer loops and to apply unroll and jam and vectorialreplacement. Section 4 gives an exten<strong>de</strong>d example using matrixproduct kernel. In Section 5 we show performance results of ourapproach compared to scalar version, inner-loop vectorized versionsand vendor supplied numerical libraries. Finally, Section 6conclu<strong>de</strong>s.2. Related WorkLittle published work exists which directly <strong>de</strong>als with high levelco<strong>de</strong> transformation techniques for processors with SIMD capabilities.Several researchers [3][7][15][19][21][24] have workedon vectorizing compilers, but not on high level (source-to-source)co<strong>de</strong> transformations to help compilers to generate efficientSIMD co<strong>de</strong>s. These researchers focus on automatically i<strong>de</strong>ntifyvectorizable section of co<strong>de</strong> and generate appropriate SIMD instructions.Their proposals are low level optimizations to be implementedinsi<strong>de</strong> compilers. Our work instead proposes highlevel transformations for generating efficient SIMD co<strong>de</strong> whilewaiting for commercial compilers to implement novel approachesfrom previous researchers.Moreover, most of these auto-vectorization approaches focuson innermost loops [7][15][24] or block vectorization [4]. OnlyNuzman et all in [19] <strong>de</strong>als with outer loop vectorization andshow its effectiveness. Their proposal consists on implementingin-place outer loop vectorization insi<strong>de</strong> the GCC compiler. Incontrast, we perform outer loop vectorization as a high level(source-to-source) transformation.Aditionally, Callahan et all in [5] presented a source-to-sourcetransformation, called scalar replacement, that exposes the reuseavailable in array references in an innermost loop. They alsoshowed experimentally how another loop transformation, calledunroll and jam, could expose more opportunities for scalar replacementby moving reuse across an outer loop into the innermostloop. In our work, we extend the use of scalar replacementand unroll and jam to SIMD vectorized loop nests and show experimentallytheir effectiveness. We do not know any previouswork that extends these techniques for SIMD co<strong>de</strong>s.Finally, there exist several hand-co<strong>de</strong>d numerical libraries optimizedfor SIMD processors [11][25] that achieve very highperformance for some particular class of microporcessors and forsome particular functions. However, as already mentioned, notall applications can take advantage of these libraries and thereare many situations in which none of the routines provi<strong>de</strong>d canspecifically solve the task at hand. Our techniques, instead, canbe applied to more general co<strong>de</strong>s.3. Source-to-Source Co<strong>de</strong> TransformationsOur approach to combine source-to-source transformations proposedin this work are based on three observations. First, weobserve that commercial compilers only perform inner loop vectorization.However, in most co<strong>de</strong>s it is necessary to vectorizeouter loops to achieve high performance.Second, we observe that compilers are not able to unroll andjam loops with non unit stri<strong>de</strong>. As we will see later, optimizingtransformations like register tiling [6][13][14] requires innerloops to be fully unrolled. Therefore, when combining registertiling with vectorization it sometimes becomes necessary to fullyunroll strip-mined (non-unit stri<strong>de</strong>) loops and jam together theinner (vector) loops.Third, we observe that compilers are not able to allocate adjacentarray values to vector registers and exploit the reuse availablein array references in an innermost loop. However, it is wellknownthat the allocation of array values that exhibit reuse toregisters can significantly improve the memory performance ofprograms [6][13][14].In the next subsections we show how we solve these threecompilers limitations by applying source-to-source transformations.For the rest of this section and for simplicity, we assumethat loop nests are fully permutable and perfectly nested, andloop bounds are constants. For handle more general loop boundsthat are max or min functions of surrounding loop iteration variables,we would need to use the theory of unimodular transformationswhen performing loop permutation [16] and In<strong>de</strong>x SetSplitting [29] for making sure that a particular loop perform aconstant number of iterations.We also assume that previous analysis to <strong>de</strong>ci<strong>de</strong> which loopsshould and could be vectorized has already been performed. Thispaper only focuses on the co<strong>de</strong> generation phase of source-tosourcetransformations. Depen<strong>de</strong>nce and <strong>de</strong>cision analysis toknow if transformations are legal and to <strong>de</strong>ci<strong>de</strong> which loop is thebest candidate to vectorize are out of the scope of this paper[2][17][22][23][26][27].3.1 Outer Loop VectorizationLet consi<strong>de</strong>r the following loop nest:for ( i1=L1; i1


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011for ( i=L; i


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Source co<strong>de</strong>void cross_add(float *A, float *B,int dimi, int dimj){long int i, j, vi;for (i=0; i


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Source co<strong>de</strong>void multiply(float* A, float* B,float* C, int dimi,int dimk, int dimj){long int i, j, k;for (i = 0; i < dimi; i++)for (j = 0; j < dimj; j++)for (k = 0; k < dimk; k++)C[i*dimj+j]+=A[i*dimk+k]*B[k*dimj+j];}ASM..LOOP_I:.....LOOOP_K:movq %rbx, %rcxmovq %r14, %rcxmovss (%r12,%rbp,4), %xmm0shufps $0, %xmm0, %xmm0..LOOP_J:movups (%rdx,%rcx,4), %xmm1movups 16(%rdx,%rcx,4),%xmm2mulps %xmm0, %xmm1mulps %xmm0, %xmm2addps (%rsi,%rcx,4), %xmm1addps 16(%rsi,%rcx,4),%xmm2movaps %xmm1, (%rsi,%rcx,4)movaps %xmm2, 16(%rsi,%rcx,4)addq $8, %rcxcmpq %r10, %rcxjb ..LOOP_Jaddq %r9, %r15incq %rbpcmpq %r8, %rbpjb ..LOOP_K...jb ..LOOP_IFigure 6. Matrix product. The left column shows the sourceco<strong>de</strong> and the right the assembly co<strong>de</strong>.the loop nest (no matters which is the original loop or<strong>de</strong>r) makingloop j the innermost loop. Since icc only performs inner loopvectorization, this loop or<strong>de</strong>r allows icc to vectorize loop j.Moreover, loop j is unrolled by a factor of 8 (2 vectors). Finally,icc also exploits the reuse of the invariant reference of matrix Ain the inner loop j by loading it only once in a vector registerduring the execution of loop j.Our objective in this section is to generate an efficient co<strong>de</strong>that fully exploits the register level of the memory hierarchy andthe SIMD capabilities of the target machine. To this end, we firstapply register tiling [6][14][26] to the source co<strong>de</strong> as shown inFigure 7a. BI and BJ are the tile sizes in dimension i and j, respectively,and their values <strong>de</strong>pend on the available SIMD registersand their sizes on the target architecture. For simplicity andwithout loss of generalization, we assume dimi and dimj to bemultiple of BI and BJ, respectively.It is well-known that loop tiling [16] is loop transformationthat a compiler can use to automatically create block algorithms.The advantage of block algorithms is that, while computing withina block, there is a high <strong>de</strong>gree of data locality, allowing betterregister, cache or memory hierarchy performance. Loop tiling forany memory level can be implemented by combining two wellknowntransformations: strip-mining and loop interchange. However,the implementation of tiling for the register level requiresan extra phase not nee<strong>de</strong>d for other memory levels. Since registersare only addressable using the register number, it is necessaryto fully unroll the loops that traverse the iterations insi<strong>de</strong> theregister tiles. Therefore, in our example of Figure 7a, it is necessaryto fully unroll loops i and j to exploit the register level. Atlast, scalar replacement [5][6] can be used to eliminate redundantloads and stores in the new unrolled loop body.When combining register tiling with vectorization we needfirst vectorize the <strong>de</strong>sired loop (loop j, in our example) beforefully unroll the register tile. Thus, the outer loop j is vectorizedas explained in subsection 3.1. We apply strip-mining to loop jwith a step size of VL and then permute the resulting elementlong int ii, jj, i, j, k; a)for (ii = 0; ii < dimi; ii+=BI)for (jj = 0; jj < dimj; jj+=BJ)for (k = 0; k < dimk; k++)for(j = jj; j < jj+BJ; j++)for(i = ii; i < ii+BI; i++)C[i*dimj+j]+=A[i*dimk+k]*B[k*dimj+j];loop of VL iterations to become the innermost (the vector statement).The resulting co<strong>de</strong> is shown in Figure 7b assuming BJ ismultiple of VL for simplicity.As already mentioned, now it is necessary to fully unroll theloops that traverse the iterations insi<strong>de</strong> the register tile (loop iand j in Figure 7b). To fully unroll the strip-mined loop j weperform unroll and jam as explained in Section 3.2. The resultingco<strong>de</strong> is shown in Figure 8a, assuming BI = 2 and BJ=2*VL.At this point icc vectorizes dimension j keeping loop k as innermostloop. However, icc does not remove redundant vectorloads and stores from the new unrolled loop body. As we can seein Figure 8c, the elements of C are loa<strong>de</strong>d and stored in eachiteration of loop k unnecessarily. Therefore we need to applyvectorial replacement to reference C as explained in section 3.3.Figure 8b shows the resulting source co<strong>de</strong> using pointers as temporaryvariables to i<strong>de</strong>ntify the adjacent array references. We cansee in Figure 8d how icc is now able to remove redundant memoryinstructions.Summarizing, by combining register tiling with the source-tosourcetransformations proposed in Section 3, we help icc compilerto generate efficient co<strong>de</strong> that fully exploit the register leveland the SIMD capabilities of the target machine.5. Performance ResultsFirst <strong>de</strong>tails of our evaluation environment are presented includinga <strong>de</strong>scription of the architecture, compiler and kernels used.Then, kernel performance is <strong>de</strong>scribed and analyzed.5.1 Evaluation environmentAll kernels in this study have been executed in the same machineand compiled by the same version of the icc with the same flagsand options.Target architecturelong int ii, jj, i, j, k, vj; b)for (ii = 0; ii < dimi; ii+=BI)for (jj = 0; jj < dimj; jj+=BJ)for (k = 0; k < dimk; k++)for(j = jj; j < jj+BJ; j+=VL)for(i = ii; i < ii+BI; i++)for(vj=j; vj


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Source co<strong>de</strong>long int ii, jj, k, vj; a)for (ii = 0; ii < dimi; ii+=2)for (jj = 0; jj < dimj; jj+=2*VL)for (k = 0; k < dimk; k++)#pragma iv<strong>de</strong>pfor(vj=jj; vj


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011Device Size Associativity/#L1 I-Cache 32 KB 4-wayL1 D-Cache 32 KB 8-wayL2 Cache 256 KB 8-wayL3 shared Cache 8 MB 16-wayTLB1 32 entries 4-wayTLB2 512 entries 4-wayGeneral Purpose 64-bit-wi<strong>de</strong> 16 registersRegisters (GPRs)XMM registers 128-bit-wi<strong>de</strong> 16 registersTable 1. Memory hierarchy of the Intel Xeon E5520.Description Loop <strong>de</strong>pth ISCross addition of 2 vectors (Figure 1) 2 RectangularRectangular matrix product (Figure 6) 3 RectangularTriangular matrix product (Figure 9) 3 TriangularTable 2. Characteristics of the evaluated kernels.void multiply(const float *restrict A,const float *restrict B,float *restrict C,int dimi,int dimk,int dimj){long int i,j,k;for(k = 0; k < dimk; k++)for(i = k; i < dimi; i++)for(j = k; j < dimj; j++)C[i*dimj+j] += A[i*dimk+k] * B[k*dimj+j];}Figure 9. Triangular matrix product.We can observe that vector executions (ORI, SIMD andSIMD+VR) obtain always better performance than scalar executions(Scalar). On the other hand, SIMD version is still far awayto the ORI version because SIMD does not apply vectorial replacement,performing therefore excessive redundant memoryoperations insi<strong>de</strong> the innermost loop. Finally, it can be seen thatSIMD+VR outperforms ORI version because better register reuseis done.Figure 10b shows the performance obtained for the rectangularmatrix product. In the ORI version (co<strong>de</strong> of Figure 6) of thiskernel, icc was able to vectorize loop j (inner loop vectorization)and unroll it by a factor of 8 (2 vectors). Again, icc was also ableto perform scalar replacement to reference A of the loop body. Inthe other three versions (Scalar, SIMD and SIMD+VR) registertiling has been applied with tile sizes 6 and 8 for dimension i andj, respectively. Moreover, in the Scalar and SIMD+VR versionscalar and vectorial replacement has been respectively applied.In this case, ORI version again performs better than the Scalarversion since it is vectorized. However, the SIMD version performsslightly better than the ORI version because SIMD exploitsbetter the register level due to the register tiling transformation.Although SIMD version does not perform vectorial replacement,it exploits reuses of accesses to A and B insi<strong>de</strong> the register tile.Finally version SIMD+VR again obtains highest performancesince it highly reduces the memory operations (it avoids loadsand stores of C in the innermost loop). Moreover, we can alsosee in Figure 10b that the performance of SIMD+VR starts to<strong>de</strong>crease at problem size of 216. For medium problem sizes,tiling only at the register level can substantially increase TLBmisses and cache misses are not mo<strong>de</strong>rated. This problem canbe solved by performing tiling also for higher levels of the memoryhierarchy.Figure 10c shows the performance obtained for the triangularmatrix product. In the ORI version of this kernel, icc was notable to vectorize because it does not support non-rectangular loopstructure, but it applies scalar replacement to reference A in theinnermost loop j. In the other three versions (Scalar, SIMD andSIMD+VR) we apply tiling at the register level with tile sizes 6and 8 for dimensions i and j respectively and use In<strong>de</strong>x SetSplitting [29] to distinguish loop nests that traverse (nonrectangular)boundary tiles from loop nests that traverse (rectangular)non-boundary tiles. These later loop nests can be vectorizedand fully unrolled.In this kernel, both ORI and Scalar versions are executed inscalar. The slight difference in performance between them is dueto the loop or<strong>de</strong>r. The loop or<strong>de</strong>r in ORI version is ikj and thereforereference to A exhibit reuse between different iterations ofthe innermost loop. In the ORI version, the loop body containsthree memory operations (1 load from B and C and 1 store fromC). However, the loop or<strong>de</strong>r in Scalar version is ijk and thusreference to C exhibit reuse between different iterations of theinnermost loop. In this version, the loop body only contains twomemory operations (1 load from A and B).Again, we can also see in Figure 10c that SIMD version obtainbetter performance than ORI and Scalar versions thanks tothe vector execution, but SIMD+VR outperforms them. In allthree kernels, the SIMD version shows speedup of around 2xover the Scalar version and the SIMD+VR version obtains anadditional 2x speedup over the SIMD version.Finally, we want to point out the difference in performancefor small problem sizes between the triangular and the rectangularmatrix product kernels. We can observe that SIMD+VR obtainsvery high performance for small problem sizes (from 24 to196) in the rectangular matrix product while the same versionobtains very low performance in the triangular matrix product.The reason is that for very small problem sizes, the executiontime wasted on boundary tiles in the triangular matrix product issignificant and these tiles are not vectorized and unrolled.a) b) c) d)Figure 10. a) Performance of cross addition of 2 vectors. b) Performance of rectangular matrix product. c) Performance of triangular matrix product.d) Performance of SGEMM for the ATLAS and MKL hand-optimized libraries and our best co<strong>de</strong> (SIMD+VR + cache tiling).<strong>JP2011</strong>-725


<strong>Actas</strong> XXII Jornadas <strong>de</strong> Paralelismo (<strong>JP2011</strong>) , <strong>La</strong> <strong>La</strong>guna, Tenerife, 7-9 septiembre 2011At last, we compare our optimized co<strong>de</strong>s against handoptimizedassembly-written numerical libraries. Figure 10dshows the SGEMM performance obtained by ATLAS [25] andMKL [11] and the performance obtained by our optimized rectangularmatrix product. To do a fairly comparison, we add cachetiling to the SIMD+VR version of Figure 10d. Cache tiling iseffective for reducing the capacity cache miss rate and mo<strong>de</strong>ratingTLB misses. Thus, for medium matrix sizes that do not fit atthe cache level it achieves the same performance level as forsmaller sizes.We can see that MKL achieves the peak performance of acore (2.26GHz * 4 Single Precision Floating Point elements perinstruction * 2 instructions per cycle = 18,08 GFLOPS). On theother hand, ATLAS and SIMD+VR+Cache achieve a performanceof 14 GFLOPS approximately (77% of the peak performance).We can also observe in Figure 10d that for large matrix sizesATLAS achieves slightly better performance than our optimizedversion. The reason is that ATLAS copies the matrices into smallcontiguous blocks in memory in or<strong>de</strong>r to minimize TLB missesand cache conflicts. In our optimized version we do not use datacopying. However, for small problem sizes, our optimized co<strong>de</strong>outperforms ATLAS.Summarizing, results show that source-to-source optimizedco<strong>de</strong>s can almost achieve the same performance as handoptimizedassembly-written co<strong>de</strong>s.6. ConclusionsSIMD instructions are so far not really exploited by compilers formedia processors. Taking advantage of such instructions is onlypossible if processor-specific assembly routines or compiler intrinsicsare used, resulting in low portability of software.The optimizations proposed in this paper are high-level(source-to-source) transformations that help compilers to generateefficient SIMD co<strong>de</strong>. We have seen that the SIMD+VR versionobtains speedups of around 4x over the Scalar version.Working at the source level prevent us from controlling manyof the low level transformations typically performed by the compiler’sback-end (instruction scheduling, register allocation, etc.)making it difficult (if not impossible) to generate the optimalco<strong>de</strong>. By integrating these transformations insi<strong>de</strong> a productioncompiler, we could achieve even more better performance.AcknowledgmentsThis research has been supported by an Intel-UPC ResearchGrant, the Spanish Ministry of Education (contract no. TIN2007-60625), and the European Union (un<strong>de</strong>r the HiPEAC-2 Networkof Excelence, FP7/ICT 217068).References[1] D. Aber<strong>de</strong>en, and J. Baxter. EMMERALD: a fast matrix-matrix multiplyusing Intel’s SSE instructions, J. Concurrency Comput.: Pract.Exp., 13, 103-119, 2001.[2] U. Banerjee. Depen<strong>de</strong>nce analysis for supercomputing. Norwell, Mass.Kluwer Aca<strong>de</strong>mic Publishers, 1988.[3] A. Bik. The Software Vectorization Handbook. Applying MultimediaExtensions for Maximum Performance". Intel Press. 2004.[4] A. Bik, M. Girkar, P. M. Grey, and X. Tian. Automatic Intra-RegisterVectorization for the Intel Architecture. Int. J. Parallel Program. 30, 2,65-98. April 2002.[5] D. Callahan, S. Carr, and K. Kennedy. Improving register allocationfor subscripted variables. PLDI '90. pp. 53-65. June 1990.[6] S. Carr. Memory-hierarchy management. Ph.D. Thesis, Rice University,February 1993.[7] G. Cheong, M.S. <strong>La</strong>m, An optimizer for multimedia instruction sets, in:The Second SUIF Compiler Workshop, Stanford University, USA,1997.[8] Y.F. Fung, M.F. Ercan, T.K. Ho, and W.L. Cheung. A parallel solutionto linear systems. Microprocess. Microsyst., 26, 39-44, 2002.[9] M. Hassaballah, S. Omran, and Y. B. Mahdy. A Review of SIMDMultimedia Extensions and their Usage in Scientific and EngineeringApplications. The Computer Journal, Vol. 51 (6): 630-649. January2008.[10] Intel Corporation. Intel C/C++ Compiler User and Reference Gui<strong>de</strong>.Or<strong>de</strong>r Number 304968-023US.[11] Intel Corporation. Intel Math Kernel Library Reference Manual. Or<strong>de</strong>rNumber 630813-038US.[12] Intel Corporation (2010). Intel Advanced Vector Extensions ProgrammingReference. Or<strong>de</strong>r Number 319433-009, December 2010.[13] M. Jimenez, J. Llaberia, A. Fernan<strong>de</strong>z. On the Performance of Handsvs. Automatically Optimized Numerical Co<strong>de</strong>s. HPCA-6 IEEE ComputerSociety, January 2000, p. 183-194[14] M. Jimenez, J. Llaberia, A. Fernan<strong>de</strong>z. Register Tiling in NonrectangularIteration Spaces. "ACM transactions on programming languagesand systems", Juliol 2002, vol. 24, núm. 4, p. 409-453.[15] A. Krall and S. Lelait. Compilation Techniques for Multimedia Processors.Int. J. of Parallel Programming. 28, 4, 347-361. August 2000.[16] M. <strong>La</strong>m, E. Rothberg, and M. Wolf. The Cache Performance and Optimizationof Blocked Algorithms. ASPLOS'91, pp. 63-74, 1991.[17] D. Maydan, J. Hennessy and M. <strong>La</strong>m. Efficient and exact data <strong>de</strong>pen<strong>de</strong>nceanalysis. PLDI’91, pp. 1-14, June 1991.[18] A. Muezerie, R.J. Nakashima, G. Travieso, and J. Slaets. Matrix calculationswith SIMD floating point instructions on x86 processors.HPCA’01, pp. 50-55, September 2001.[19] D. Nuzman, A. Zaks. Outer-loop vectorization: revisited for shortSIMD architectures. PACT '08, pp.2-11, 2008.[20] A. Peleg, U. Weiser. MMX Technology Extension to the Intel Architecture,IEEE Micro, Vol. 16, No. 4, pp. 42-50, August 1996.[21] I. Pryanishnikov , A. Krall , N. Horspool. Compiler optimizations forprocessors with SIMD instructions. Software—Practice & Experience,v.37 n.1, p.93-113, January 2007[22] W. Pugh. "A practical algorithm for exact array <strong>de</strong>pen<strong>de</strong>nce analysis".Communications of the ACM, Vol. 35, No. 8, pp. 102-114, 1992.[23] P. Ranganathan, S. Adve, and N. P. Jouppi. Performance of image andvi<strong>de</strong>o processing with general-purpose processors and media ISA extensions.ISCA '99, 124-135, 1999.[24] N. Sreraman and R. Govindarajan. A vectorizing compiler for multimediaextensions. J. of Parallel Programming, 28, 363-400. 2000.[25] R. C. Whaley, A. Petitet, J. Dongarra. Automated Empirical Optimizationof Software and the ATLAS project, Parallel Computing, 27(1-2):3-35, 2001.[26] M. Wolf and M. <strong>La</strong>m. A data locality optimizing algorithm. PLDI’91,pp. 30-44, June 1991.[27] M. Wolf, D. Maydan and D.K. Chen. "Combining loop transformationsconsi<strong>de</strong>ring caches and scheduling". MICRO-29, pp. 274-286, December1996.[28] M. Wolf. Improving locality and parallelism in nested loops. Ph.D.Thesis, Stanford University, 1992.[29] M. Wolfe. High performance compilers for parallel computing. Addison-WesleyPublishing Company, 1996.[30] C.-L. Yang, B. Sano, and A. R. Lebeck. Exploiting Parallelism inGeometry Processing with General Purpose Processors and Floating-Point SIMD Instructions, IEEE Transactions on Computers, 49(9),934-946, September 2000.<strong>JP2011</strong>-726


Índice <strong>de</strong> AutoresAAbad, P. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267Ab<strong>de</strong>lli, Oussama. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .57Abellán, José L. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209Acacio, Manuel E.. . . . . . . . . . . . . . . . . . . . . . .203, 209, 227Acosta, Alejandro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87Acosta, Mario C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153Alfaro, Francisco J. . . . . . . . . . . . . . . . . . . . . . . 261, 297, 403Allan<strong>de</strong>, C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649Almeida, Francisco . . . . . . . . . . . . . . 87, 329, 507, 513, 589Alonso-Jordá, Pedro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81Alves, Rui . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57Amor, M. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619, 625Andrés, David <strong>de</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373Andujar, Francisco J. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297Andújar, Francisco J. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403Anguita, Mancia . . . . . . . . . . . . . . . . . . . . . . . . 153, 537, 599Aragón, Juan L.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .227, 233Arcas, Oriol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283Arenas, M.G. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595Arias, Enrique . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353, 705Armas, Sergio. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .329Arnal, T. Monreal . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291, 563Artigas, F. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113Avilés-Gonález, A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551Ayuso, F. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323BBarreiro, A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699Barrientos, R.J.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .359Bataller, Jordi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171Bauset, Víctor Fernán<strong>de</strong>z. . . . . . . . . . . . . . . . . . . . . . . . . .607Beivi<strong>de</strong>, Ramón . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421, 451Benavi<strong>de</strong>s, José Ignacio . . . . . . . . . . . . . . . . . . . . . . 305, 693Bermú<strong>de</strong>z, Aurelio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445Berna, Alejandro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 719Bernabé, S. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101Bertozzi, D. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215Bezerra, Aprigio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251, 501Blanco, H. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525Blanco, Vicente . . . . . . . . . . . . . . . . . . . . . . . . . 329, 513, 643Bohrloch, Tim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385Bosque, J.L. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451, 631Botella, G. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323Báguena, Miguel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379CCabaleiro, J.C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643Cabrera, Eduardo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165Cacheiro, Javier López . . . . . . . . . . . . . . . . . . .495, 519, 543Calafate, Carlos T. . . . . . . . . . . . . . . . . . . 367, 379, 385, 427Calviño, M.H.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .693Camacho, Hugo E. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537Camacho, J.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .277Camarero, C.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .451Caminero, B.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .483Cano, José . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 675Cano, Juan Carlos . . . . . . . . . . . . . . . . . . 367, 379, 385, 427Carrión, C.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .483Casado, L.G. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21Casado, Rafael . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445Castillo, C. Núñez . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397Castillo, J.C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513Castillo, P.A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595Cazorla, D. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 705Cazorla, Diego . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353Cecilia, José M.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .159, 177Cepas, Eduardo J. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177Cerrudo, L. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661Chaves-González, José M.. . . . . . . . . . . . . . . . . . . . . . . . .125Colaso, A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267Conejero, J. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483Coppola, Marcello . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 675Cores, I. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 713Crespo, A. J. C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699Cristal, Adrián . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283Cuesta, B. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197, 203César, E.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .649DDoallo, Ramón . . . . . . . . . . . . . . . . . . . . . . . . . . 433, 439, 625Domínguez, J. M. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699Dorta, A. J. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661Duato, J.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .221Duato, José . 185, 197, 203, 215, 277, 311, 341, 403, 409,415, 557, 675Díaz, Antonio F. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537, 637EEscu<strong>de</strong>ro-Sahuquillo, Jesús . . . . . . . . . . . . . . . . . . . 409, 415Espinosa, Antonio . . . . . . . . . . . . . . . . . . . . . . . . . . . 251, 501Expósito, Roberto R.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .433Ezzatti, Pablo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27FFalgueras, J. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531Favalli, M. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215Fedorova, A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245Fernán<strong>de</strong>z, J. C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341Fernán<strong>de</strong>z, Jesualdo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177Fernán<strong>de</strong>z, Juan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209Fernán<strong>de</strong>z-Albor, Víctor . . . . . . . . . . . . . . . . . . . . . . 495, 519Fernán<strong>de</strong>z-Baldomero, F. Javier . . . . . . . . . . . . . . . 153, 599Fernán<strong>de</strong>z-Bauset, Víctor . . . . . . . . . . . . . . . . . . . . . . . . . 335Fernán<strong>de</strong>z-Pascual, Ricardo . . . . . . . . . . . . . . . . . . . 203, 239Ferreira, Tharso. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .251, 501Flich, José . . . . . . . . . . . . 221, 261, 277, 409, 415, 575, 675Flores, A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227Fogue, Manuel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367Fraguela, B.B. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625Franco, D. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397Friginal, Jesús. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .373Fumero, J. J. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661, 687


GGaliano, V. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669García, C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323García, Carlos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51, 273García, I. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21, 135García, J. M. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203García, José M. . . . . . . . . . . . . . . . . 159, 177, 233, 239, 255García, Pedro Javier . . . . . . . . . . . . . . . . . . . . . . . . . . 409, 415García, Ricardo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33García-Guirado, Antonio . . . . . . . . . . . . . . . . . . . . . 239, 255García-Loureiro, Antonio . . . . . . . . . . . . . . . . 495, 519, 543García-Sánchez, P.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .595Garrido, Piedad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367Garzón, E. M. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135Gautier, Thierry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51Gil, José Antonio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459Gil, Pedro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373Giménez, Domingo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589Gomez-Folgar, Fernando . . . . . . . . . . . . . . . . . 495, 519, 543González, C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661González, E. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467González, P. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 713González, Raquel . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141, 147González, S. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261González, Santos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297González, Sonia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273González, Yanira . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45González-Escribano, Arturo . . . . . . . . . . . . . . . . . . . . . . . 681González-Férez, P.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .551González-Linares, José María . . . . . . . . . . . . . . . . . . . . . 305González-Álvarez, David L. . . . . . . . . . . . . . . . . . . . . . . . . . 3Gracia, D. Suárez . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291, 563Graciani, Ricardo. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .519Gramacho, Joao . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75Gran, E. G. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409Gregorio, J.A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267Grillo, L. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661Guerrero, Ginés D. . . . . . . . . . . . . . . . . . . . . . . . . . . . 159, 177Guil, Nicolás. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .305Guirado, F. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525Gutiérrez, E. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191Gutiérrez, Eladio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583Gómez, C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215Gómez, J.I. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359Gómez, M.E. . . . . . . . . . . . . . . . . . . . . . . . . . . . 197, 203, 215Gómez-García, Daniel . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415Gómez-Gesteira, M. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699Gómez-Luna, Juan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305Gómez-Pulido, Juan A.. . . . . . . . . . . . .3, 9, 15, 63, 95, 125HHaijema, Rene . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131Hassan, Houcine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185Hendrix, Eligius M.T. . . . . . . . . . . . . . . . . . . . . . . . . . 21, 131Heras, Dora B. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655Hernán<strong>de</strong>z, C.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .221Hernán<strong>de</strong>z, Moisés . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159Hernán<strong>de</strong>z, Porfídio . . . . . . . . . . . . . . . . . . . . . . . . . . 251, 501Herrera, J.F.R.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .21Heymann, Elisa . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475Huertas, Juan Manuel Orduña . . . . . . . . . . . . . . . . . . . . . 607IIbarra, S. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693Ibáñez, Miguel Lozano. . . . . . . . . . . . . . . . . . . . . . . . . . . .607Inuggi, Alberto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159JJiménez, Marta . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 719Jorba, J. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649KKarathia, Hiren . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57Kulakowski, Pawel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445L<strong>La</strong>go, J. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531<strong>La</strong>mas, Antonio Molinera . . . . . . . . . . . . . . . . . . . . . . . . . 489<strong>La</strong>nza-Gutiérrez, José M. . . . . . . . . . . . . . . . . . . . . . . . 63, 95León, Coromoto . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39, 45, 69Llabería., Jose M. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 719Llanos, Diego R. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 681Llor, J. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391Locatelli, Riccardo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 675Lod<strong>de</strong>, Mario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575Lorenzo, Juan A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655Lorenzo, Oscar G. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655Lozano, Miguel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335Ludovici, D. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215Lugones, D.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .397Luque, Emilio . . . . . . . . . . . . . . . . . . . . . . . 75, 165, 397, 569Lysne, O. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409Lérida, J. L. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525López, I. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467, 661, 687López, Maria <strong>de</strong>l Mar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475López, O. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119, 669López, Otoniel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33López, P. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215López, Pedro. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .557MMalumbres, Manuel P.. . . . . . . . . . . . . . . .33, 119, 391, 669Mantas, José Miguel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589Manzoni, Pietro . . . . . . . . . . . . . . . . . . . . 367, 379, 385, 427March, José Luis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185Martinez, C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451Martinez, Francisco J. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367Martí, Antonio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33Martín, M. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 713Martínez, A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 613Martínez, Carmen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421Martínez, D.R. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643Martínez, Miguel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33Martínez-Naredo, Pablo . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81Martínez-Rach, M. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119Martínez-Zaldívar, F.J. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81Mayo, R.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .311, 341Mena, Lionel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329Menezo, L.G. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267Merelo, J.J. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595Migallón, H. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347, 669


Migallón, V. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347Mora, A.M. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595Morajko, A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 613, 649Morales, A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329, 507Moreno, Francisco Grimaldo . . . . . . . . . . . . . . . . . . . . . . 607Moretó, Miquel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421Moure, Juan Carlos . . . . . . . . . . . . . . . . . . . . . . . . . . 251, 501Márquez-Barja, Johann . . . . . . . . . . . . . . . . . . . . . . . . . . . 427Mén<strong>de</strong>z, Sandra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569NNegrillo, Alberto Megía . . . . . . . . . . . . . . . . . . . . . . . . . . . 489Nielsen, E. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467Nieto, Erik. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .537OOliver, J. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119Orduña, Juan M. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335Ortega, G. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135Ortega, J. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595, 637Ortega, Julio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537Ortiz, A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 637PPadrón, E.J. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619Pastor, L. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631Pelayo, F. L. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317Peláez, Ignacio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87Pena, T.F. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643Penadés, J. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347Petit, Salvador . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185, 557Peña, A. J. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311, 341Peña-Ortiz, Raúl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459Pichel, Juan C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655Piernas, J. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551Piñol, Pablo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33, 119Plata, O. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191Plaza, A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101Pont, Ana. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .459Pousa, A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245Prieto, A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 637Prieto, Manuel . . . . . . . . . . . . . . . . . . . . . . . 51, 245, 323, 359Prieto, P.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .267Puente, V. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267QQuiles, F. J. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409Quiles, Francisco José . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415Quintana-Ortí, Enrique S. . . . . . . . . . . . . . . . . . 27, 311, 341Quislant, R. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191RRamet, D. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531Ramos, Alfonso . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255Ramos, Julián . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583Ramos, Sabela . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439Ranilla, José . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81Reaño, C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311Regueiro, C.V. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619Remón, Alfredo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27Rexachs, Dolores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75, 569Reyes, R. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687Rivera, Alejandro. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .171Rivera, Francisco F. . . . . . . . . . . . . . . . . . . . . . . . . . . 643, 655Robles, A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197, 203Robles, OD. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631Roca, A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221Rodríguez, G. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 713Romero, L.F.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .107Romero, Sergio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583Ros, A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197, 203Rubio-<strong>La</strong>rgo, Álvaro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Rueda, Francisco J. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153Ruiz, Juan-Carlos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373SSaborido, Juan José . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519Sahuquillo, Julio . . . . . . . . . . . . . . . . . . . . . . . . 185, 459, 557Samarín, Alejandro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329San<strong>de</strong>, F. <strong>de</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661, 687Santos, A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513Sarmiento, A.L. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619Sazei<strong>de</strong>s, Yiannakis. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .233Segredo, Eduardo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39, 69Segura, Carlos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39, 45, 69Senar, Miquel Àngel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475Serna, M. Ángeles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445Silla, F. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221, 311, 341Silva, Fernando José Mateus . . . . . . . . . . . . . . . . . . . . . . . . . 9Skeie, T. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409Solsona, Francesc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57Sonmez, Nehir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283Stafford, E. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451Strano, A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215Suárez, A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147Sáez, J.C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245Sánchez, C. Fernán<strong>de</strong>z . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495Sánchez, Daniel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233Sánchez, José Antonio Rueda . . . . . . . . . . . . . . . . . . . . . . 489Sánchez, José L. . . . . . . . . . . . . . . . . . . . . . . . . 261, 297, 403Sánchez, José Luis . . . . . . . . . . . . . . . . . . . . . . . . . . . 353, 705Sánchez, Lidia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141, 147Sánchez, M. Guadalupe . . . . . . . . . . . . . . . . . . . . . . . . . . . 171Sánchez-Pérez, Juan M. . . . . . . . . . . . . . . 3, 15, 63, 95, 125Sánchez-Pérez, Juan Manuel . . . . . . . . . . . . . . . . . . . . . . . . . 9TTabik, S.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .107Tabik, Siham. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .131Taboada, Guillermo L.. . . . . . . . . . . . . . . . . . . . . . . .433, 439Taboada, Manel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165Tenllado, C.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .359Tirado, F. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323Toharía, P. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631Tomás, L.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .483Torres, Alvaro. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .385Torres, Yuri . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 681Touriño, Juan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433, 439Trelles, O. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531Trenas, María A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583Triviño, F. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261


Triviño, Francisco . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297UUnsal, Osman S. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283Uribe-Pare<strong>de</strong>s, Roberto . . . . . . . . . . . . . . . . . . . . . . . . . . . 353Usié, Anabel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57VValero, Alejandro. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .557Valero, Mateo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283Valero, P.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .317, 705Valero-<strong>La</strong>ra, Pedro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353Valin, R. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495, 543Vallejo, Enrique . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421Vallejo, F. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451Vallepuga, José . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141, 147Vega-Rodríguez, Miguel A. . . . . . . . . . 3, 9, 15, 63, 95, 125Vegas, Hugo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51Vidal, Antonio M.. . . . . . . . . . . . . . . . . . . . . . . . . . . . .81, 589Vidal, Vicente . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171Vigueras, Guillermo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335Vilaplana, Jordi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57Villalba, Julio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273Villar, Juan Antonio . . . . . . . . . . . . . . . . . . . . . . . . . . 403, 415Viñas, M. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625Vázquez, F. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135Vázquez-Poletti, José Luis . . . . . . . . . . . . . . . . . . . . . . . . 489YYúfera, V. Viñals . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291, 563ZZablah, Isaac. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .543Zapata, E.L. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107, 191, 305

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!