Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

28
Computação Paralela: Benefícios e Desafios Luciano Palma Community Manager – Servers & HPC Intel Software do Brasil [email protected]

description

Palestra ministrada por Luciano Palma no Intel Software Conference 2013, nos dias 6 de Agosto (NCC/UNESP/SP) e 12 de Agosto (COPPE/UFRJ/RJ).

Transcript of Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Page 1: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Computação Paralela: Benefícios e Desafios

Luciano Palma

Community Manager – Servers & HPC

Intel Software do Brasil

[email protected]

Page 2: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

A Capacidade Computacional evoluiu. O Software não acompanhou.

A densidade de transistores continua aumentando, mas…

… o aumento da velocidade (clock) não

A grande maioria dos PCs vendidos são multi-core, mas…

… muitos programas / cargas ainda não tiram proveitodo paralelismo possível

O Processamento Paralelo é chave para obtero máximodesempenhopossível

Page 3: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Lei de Moore

Se transistores fossem pessoas

Agora imagine o que 1,3 bilhões de pessoas poderiam fazer num palco.

Essa é a escala da Lei de Moore

0.1

1

10

100

1000

1970

1975

1980

1985

1990

1995

2000

2005

2010

2015

2020

Watts

Per ProcessorPower

Wall

0.1

1

10

100

1000

0.1

1

10

100

1000

1970

1975

1980

1985

1990

1995

2000

2005

2010

2015

2020

1970

1975

1980

1985

1990

1995

2000

2005

2010

2015

2020

Watts

Per ProcessorPower

Wall

1

10

100

1000

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

TPCC 4 Processor

Published

Single Core

Dual

Core

Quad

Core

1

10

100

1000

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

TPCC 4 Processor

Published

1

10

100

1000

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

TPCC 4 Processor

Published

Single Core

Dual

Core

Quad

Core

Page 4: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Por que Programação Paralela é Importante?

Competitividadena Indústria

PesquisaCientífica

SegurançaNacional

Modelagem de

Clima/Tempo

Segurança Nacional

Pesquisa Farmacêutica

Maiores Desafios Maior Complexidade Computacional…

… mantendo um “orçamento energético” realista

Imagens Médicas

Exploração de Energia

Simulações

Desempenho Computacional

Total por país

Análises Financeiras

Projeto de novos Produtos

CAD/manufatura

Criação de Conteúdo Digital

Corrida Computacional

Page 5: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Em Computação de Alto Desempenho(HPC), a Simulação é crucial

• The Scientific Method is Dead-Long Live the (New) Scientific Method, June 2005

• Richard M. Satava, MD Journal of Surgical Innovation

A Nova Computação estimulou um Novo Método Científico*

Método Científico Clássico

Hipótese Análise

Conclusão

Refinamento

Experimentação

Modelagem e

Simulação/Refinamento do

Experimento

Previsão

Análise

Conclusão

Refinamento

Hipótese Experimentação

Para simular efetivamente… precisamos nos basear em computação paralela!

Page 6: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Exemplo de como a Computação Paralela tem ajudado...

Problema: Processamento de Imagens de RessonânciaMagnética Pediátrica é difícil. A reconstrução da imagem precisaser rápida• Crianças não ficam paradas

não seguram a respiração

• Baixa tolerância a exames demorados

• Custos e Riscos da Anestesia

Solução: MRI Avançada: Processamento Paralelo de Imagens e Compressed Sensingreduziram dramaticamente o tempo de aquisição da MRI• Reconsturção 100x mais rápida

• MRI de qualidade mais alta e mais rápida

• Esta imagem: paciente de 8 meses com massa cancerígena no fígado

– Reconstrução Serial: 1 hora

– Reconstrução Paralela: 1 minuto

Page 7: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Computação Serial vs. Paralela

Serialização

Faz Sentido!

Fácil para fazer “debug”

Determinístico

No entanto… … aplicações serializadas não maximizam o desempenho de saída(output) e não evoluirão no tempo com o avanço das tecnologias

Paralelização – dá para fazer?!

Depende da quantidade de trabalhoa realizar e da habilidadede dividir a tarefa

É necessário entender a entrada (input), saída (output) e suas dependências

for (i=0; i< num_sites; ++i) {

search (searchphrase, website[i]);

}

parallel_for (i=0; i< num_sites; ++i) {

search (searchphrase, website[i]);

}

Page 8: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Dividindo o trabalho…

Decomposição de Tarefas: Executa diferentes funções do programa em paralelo. Limitada escalabilidade, portantoprecisamos de…

Decomposição de Dados:Dados são separados em blocos e cada bloco é processado em umatask diferente.

A divisão (splitting) pode sercontínua, recursiva.

Maiores conjuntos de dados mais tasks

O Paralelismo cresce à medida queo tamanho do problema cresce

#pragma omp parallel shared(data, ans1, ans2)

{

#pragma omp sections

{

#pragma omp section

ans1=do_this(data);

#pragma omp section

ans2=do_that(data);

}

}

#pragma omp parallel_for shared(data, ans1)

private(i)

for(i=0; i<N; i++) {

ans1(i) = do_this(data(i));

}

#pragma omp parallel_for shared(data, ans2)

private(i)

for(i=0; i<N; i++) {

ans2(i) = do_that(data(i));

}

Page 9: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Técnicas de Programação Paralela: Como dividir o trabalho entre sistemas?

É possível utilizar Threads (OpenMP, TBB, Cilk, pthreads…) ouProcessos (MPI, process fork..) para programar em paralelo

Modelo de Memória Compartilhada

Único espaço de memória utilizado por múltiplos processadores

Espaço de endereçamento unificado

Simples para trabalhar, mas requer cuidado para evitar condições de corrida(“race conditions”) quando existe dependência entre eventos

Passagem de Mensagens

Comunicação entre processos

Pode demandar mais trabalho para implementar

Menos “race conditions” porque as mensagens podem forçar o sincronismo

“Race conditions”

acontecem quando processos ou

threads separados modificam ou

dependem das mesmas coisas…

Isso é notavelmente difícil de

“debugar”!

Page 10: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Exemplo de uso

OpenMP – Cálculo de π

Page 11: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Cálculo de π – Teoriaπ pode ser calculado através da integral abaixo

π = ∫ f(x) * dx = 4 / (1 + x2) * dx = 3.141592654...0

1

Page 12: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

π = 4 / (1 + 0,52) * 1 = 4 / 1,25 π = 3,2

Cálculo de π – Primeira AproximaçãoValor grosseiramente aproximado de π

Page 13: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

f(0,25) = 3,735; f(0,75) = 2,572 π = 3,153

3,735 * 0,5

= 1,867

2,572 * 0,5

= 1,286

Cálculo de π – Segunda AproximaçãoCom mais aproximações, o valor de π tende ao valor teórico

Page 14: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Aproximação com 10 intervalos π = 3,14243

,99

0 *

0,1

= 0

,39

9

3,9

12

* 0

,1 =

0,3

91

3,7

65

* 0

,1 =

0,3

76

3,5

63

* 0

,1 =

0,3

56

3,3

26

* 0

,1 =

0,3

33

3,0

71

* 0

,1 =

0,3

97

2,8

12

* 0

,1 =

0,2

81

2,5

60

* 0

,1 =

0,2

56

2,3

22

* 0

,1 =

0,2

32

2,1

02

* 0

,1 =

0,2

10

Cálculo de π – Aumentando os intervalos…Quanto mais intervalos, maior a precisão do cálculo

Page 15: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Solução do Problema com ParalelismoCada thread realiza o cálculo de alguns intervalos

3,9

12

* 0

,1 =

0,3

91

3,7

65

* 0

,1 =

0,3

76

3,5

63

* 0

,1 =

0,3

56

3,3

26

* 0

,1 =

0,3

33

3,0

71

* 0

,1 =

0,3

97

2,8

12

* 0

,1 =

0,2

81

2,5

60

* 0

,1 =

0,2

56

2,3

22

* 0

,1 =

0,2

32

2,1

02

* 0

,1 =

0,2

10

3,9

90

* 0

,1 =

0,3

99

REDUÇÃO

PI = 3,1424

3,9

12 *

0,1

= 0

,391

3,9

12 *

0,1

= 0

,391

3,7

65 *

0,1

= 0

,376

3,7

65 *

0,1

= 0

,376

3,5

63 *

0,1

= 0

,356

3,5

63 *

0,1

= 0

,356

3,3

26 *

0,1

= 0

,333

3,3

26 *

0,1

= 0

,333

3,0

71 *

0,1

= 0

,397

3,0

71 *

0,1

= 0

,397

2,8

12 *

0,1

= 0

,281

2,8

12 *

0,1

= 0

,281

2,5

60 *

0,1

= 0

,256

2,5

60 *

0,1

= 0

,256

2,3

22 *

0,1

= 0

,232

2,3

22 *

0,1

= 0

,232

2,1

02 *

0,1

= 0

,210

2,1

02 *

0,1

= 0

,210

3,9

90 *

0,1

= 0

,399

3,9

90 *

0,1

= 0

,399

3,9

12 *

0,1

= 0

,391

3,9

12 *

0,1

= 0

,391

3,9

12 *

0,1

= 0

,391

3,9

12 *

0,1

= 0

,391

3,7

65 *

0,1

= 0

,376

3,7

65 *

0,1

= 0

,376

3,7

65 *

0,1

= 0

,376

3,7

65 *

0,1

= 0

,376

3,5

63 *

0,1

= 0

,356

3,5

63 *

0,1

= 0

,356

3,5

63 *

0,1

= 0

,356

3,5

63 *

0,1

= 0

,356

3,3

26 *

0,1

= 0

,333

3,3

26 *

0,1

= 0

,333

3,3

26 *

0,1

= 0

,333

3,3

26 *

0,1

= 0

,333

3,0

71 *

0,1

= 0

,397

3,0

71 *

0,1

= 0

,397

3,0

71 *

0,1

= 0

,397

3,0

71 *

0,1

= 0

,397

2,8

12 *

0,1

= 0

,281

2,8

12 *

0,1

= 0

,281

2,8

12 *

0,1

= 0

,281

2,8

12 *

0,1

= 0

,281

2,5

60 *

0,1

= 0

,256

2,5

60 *

0,1

= 0

,256

2,5

60 *

0,1

= 0

,256

2,5

60 *

0,1

= 0

,256

2,3

22 *

0,1

= 0

,232

2,3

22 *

0,1

= 0

,232

2,3

22 *

0,1

= 0

,232

2,3

22 *

0,1

= 0

,232

2,1

02 *

0,1

= 0

,210

2,1

02 *

0,1

= 0

,210

2,1

02 *

0,1

= 0

,210

2,1

02 *

0,1

= 0

,210

3,9

90 *

0,1

= 0

,399

3,9

90 *

0,1

= 0

,399

3,9

90 *

0,1

= 0

,399

3,9

90 *

0,1

= 0

,399

Thread Thread Thread Thread

Page 16: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Agora um pouco de hardware…

Page 17: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

17

Engenharia e Arquitetura…

Page 18: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Intel inside, inside Intel…

Um processador com múltiplos cores possui

componentes “comuns” aos cores.

Estes compontentes recebem o nome de Uncore.

Page 19: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Intel inside, inside Intel…

E agora, dentro do core…

Page 20: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Por que descer neste nível?

Utilizar todas as “threads de hardware” Não esquecer o HyperThread

Utilizar todas as unidades de execução

Retirar o máximo de instruções por ciclo de clock

Otimizar o uso dos unidades de vetores (AVX/AVX2)

Loops otimizados

Manter as caches com dados/instruções válidos

Evitar “cache misses”

Aproveitar o “branch prediction”

Evitar o “stall” da pipeline

Para tirar o máximo proveito dos recursos do hardware!

Page 21: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Por que descer neste nível?

Utilizar todas as “threads de hardware” Não esquecer o HyperThread

Utilizar todas as unidades de execução

Retirar o máximo de instruções por ciclo de clock

Otimizar o uso dos unidades de vetores (AVX/AVX2)

Loops otimizados

Manter as caches com dados/instruções válidos

Evitar “cache misses”

Aproveitar o “branch prediction”

Evitar o “stall” da pipeline

Para tirar o máximo proveito dos recursos do hardware!

Page 22: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Por que descer neste nível?

Utilizar todas as “threads de hardware” Não esquecer o HyperThread

Utilizar todas as unidades de execução

Retirar o máximo de instruções por ciclo de clock

Otimizar o uso dos unidades de vetores (AVX/AVX2)

Loops otimizados

Manter as caches com dados/instruções válidos

Evitar “cache misses”

Aproveitar o “branch prediction”

Evitar o “stall” da pipeline

Para tirar o máximo proveito dos recursos do hardware!

Page 23: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Existem recursos para lhe ajudar!

Ferramentas de Software da Intel

IDZ – Intel Developer Zone

http://software.intel.com

Page 24: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Intel® Cilk™ Plus

• Extensões para as linguagens C/C++ para simplificar o paralelismo

• Código abertoTambém um produto Intel

Intel® Threading Building Blocks

• Template libraries amplamente usadas em C++ para paralelismo

• Código abertoTambém um produto Intel

Domain Specific Libraries

• Intel® Integrated Performance Primitives

• Intel® Math Kernel Library

Padrões estabelecidos

• Message Passing Interface (MPI)

• OpenMP*

• Coarray Fortran

• OpenCL*

Modelos de Programação Paralela

Níveis de abstração conforme a necessidade

Mesmos modelos para multi-core (Xeon) e

many-core (Xeon Phi)

Page 25: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Nota sobre Otimização

Page 26: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

• INFORMATION IN THIS DOCUMENT IS PROVIDED IN CONNECTION WITH INTEL PRODUCTS. NO LICENSE, EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE, TO ANY INTELLECTUAL PROPERTY RIGHTS IS GRANTED BY THIS DOCUMENT. EXCEPT AS PROVIDED IN INTEL'S TERMS AND CONDITIONS OF SALE FOR SUCH PRODUCTS, INTEL ASSUMES NO LIABILITY WHATSOEVER AND INTEL DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY, RELATING TO SALE AND/OR USE OF INTEL PRODUCTS INCLUDING LIABILITY OR WARRANTIES RELATING TO FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR INFRINGEMENT OF ANY PATENT, COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT.

• A "Mission Critical Application" is any application in which failure of the Intel Product could result, directly or indirectly, in personal injury or death. SHOULD YOU PURCHASE OR USE INTEL'S PRODUCTS FOR ANY SUCH MISSION CRITICAL APPLICATION, YOU SHALL INDEMNIFY AND HOLD INTEL AND ITS SUBSIDIARIES, SUBCONTRACTORS AND AFFILIATES, AND THE DIRECTORS, OFFICERS, AND EMPLOYEES OF EACH, HARMLESS AGAINST ALLCLAIMS COSTS, DAMAGES, AND EXPENSES AND REASONABLE ATTORNEYS' FEES ARISING OUT OF, DIRECTLY OR INDIRECTLY, ANY CLAIM OF PRODUCT LIABILITY, PERSONAL INJURY, OR DEATH ARISING IN ANY WAY OUT OF SUCH MISSION CRITICAL APPLICATION, WHETHER OR NOT INTEL OR ITSSUBCONTRACTOR WAS NEGLIGENT IN THE DESIGN, MANUFACTURE, OR WARNING OF THE INTEL PRODUCT OR ANY OF ITS PARTS.

• Intel may make changes to specifications and product descriptions at any time, without notice. Designers must not rely on the absence or characteristics of any features or instructions marked "reserved" or "undefined". Intel reserves these for future definition and shall have no responsibility whatsoever for conflicts or incompatibilities arising from future changes to them. The information here is subject to change without notice. Do not finalize a design with this information.

• The products described in this document may contain design defects or errors known as errata which may cause the product to deviate from published specifications. Current characterized errata are available on request.

• Intel processor numbers are not a measure of performance. Processor numbers differentiate features within each processor family, not across different processor families. Go to: http://www.intel.com/products/processor_number.

• Contact your local Intel sales office or your distributor to obtain the latest specifications and before placing your product order.• Copies of documents which have an order number and are referenced in this document, or other Intel literature, may be obtained by calling 1-800-548-

4725, or go to: http://www.intel.com/design/literature.htm• Intel, Core, Atom, Pentium, Intel inside, Sponsors of Tomorrow, Pentium, 386, 486, DX2 and the Intel logo are trademarks of Intel Corporation in the

United States and other countries.

• *Other names and brands may be claimed as the property of others.• Copyright ©2012 Intel Corporation.

Legal Disclaimer

Page 27: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013

Risk Factors

The above statements and any others in this document that refer to plans and expectations for the second quarter, the year and the future are forward-looking statements that involve a number of risks and uncertainties. Words such as “anticipates,” “expects,” “intends,” “plans,” “believes,” “seeks,” “estimates,” “may,” “will,” “should” and their variations identify forward-looking statements. Statements that refer to or are based on projections, uncertain events or assumptions also identify forward-looking statements. Many factors could affect Intel’s actual results, and variances from Intel’s current expectations regarding such factors could cause actual results to differ materially from those expressed in these forward-looking statements. Intel presently considers the following to be the important factors that could cause actual results to differ materially from the company’s expectations. Demand could be different from Intel's expectations due to factors including changes in business and economic conditions, including supply constraints and other disruptions affecting customers; customer acceptance of Intel’s and competitors’ products; changes in customer order patterns including order cancellations; and changes in the level of inventory at customers. Uncertainty in global economic and financial conditions poses a risk that consumers and businesses may defer purchases in response to negative financial events, which could negatively affect product demand and other related matters. Intel operates in intensely competitive industries that are characterized by a high percentage of costs that are fixed or difficult to reduce in the short term and product demand that is highly variable and difficult to forecast. Revenue and the gross margin percentage are affected by the timing of Intel product introductions and the demand for and market acceptance of Intel's products; actions taken by Intel's competitors, including product offerings and introductions, marketing programs and pricing pressures and Intel’s response to such actions; and Intel’s ability to respond quickly to technological developments and to incorporate new features into its products. Intel is in the process of transitioning to its next generation of products on 22nm process technology, and there could be execution and timing issues associated with these changes, including products defects and errata and lower than anticipated manufacturing yields. The gross margin percentage could vary significantly from expectations based on capacity utilization; variations in inventory valuation, including variations related to the timing of qualifying products for sale; changes in revenue levels; segment product mix; the timing and execution of the manufacturing ramp and associated costs; start-up costs; excess or obsolete inventory; changes in unit costs; defects or disruptions in the supply of materials or resources; product manufacturing quality/yields; and impairments of long-lived assets, including manufacturing, assembly/test and intangible assets. The majority of Intel’s non-marketable equity investment portfolio balance is concentrated in companies in the flash memory market segment, and declines in this market segment or changes in management’s plans with respect to Intel’s investments in this market segment could result in significant impairment charges, impacting restructuring charges as well as gains/losses on equity investments and interest and other. Intel's results could be affected by adverse economic, social, political and physical/infrastructure conditions in countries where Intel, its customers or its suppliers operate, including military conflict and other security risks, natural disasters, infrastructure disruptions, health concerns and fluctuations in currency exchange rates. Expenses, particularly certain marketing and compensation expenses, as well as restructuring and asset impairment charges, vary depending on the level of demand for Intel's products and the level of revenue and profits. Intel’s results could be affected by the timing of closing of acquisitions and divestitures. Intel's results could be affected by adverse effects associated with product defects and errata (deviations from published specifications), and by litigation or regulatory matters involving intellectual property, stockholder, consumer, antitrust, disclosure and other issues, such as the litigation and regulatory matters described in Intel's SEC reports. An unfavorable ruling could include monetary damages or an injunction prohibiting Intel from manufacturing or selling one or more products, precluding particular business practices, impacting Intel’s ability to design its products, or requiring other remedies such as compulsory licensing of intellectual property. A detailed discussion of these and other factors that could affect Intel’s results is included in Intel’s SEC filings, including the report on Form 10-K for the year ended Dec. 31, 2011.

Rev. 4/17/12

Page 28: Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013