42
Vetorização e Otimização de Código Luciano Palma Community Manager – Servers & HPC Intel Software do Brasil [email protected]

Vetorização e Otimização de Código - Intel Software Conference 2013

Embed Size (px)

Citation preview

Page 1: Vetorização e Otimização de Código - Intel Software Conference 2013

Vetorização e Otimização de Código

Luciano Palma

Community Manager – Servers & HPC

Intel Software do Brasil

[email protected]

Page 2: Vetorização e Otimização de Código - Intel Software Conference 2013

Inovação acelerada em processadores

Multi Core Many Core128 Bits

256 Bits

512 Bits

Page 3: Vetorização e Otimização de Código - Intel Software Conference 2013

Intel inside, inside Intel…

Page 4: Vetorização e Otimização de Código - Intel Software Conference 2013

Implementação Escalar

Modo EscalarUma instrução produz

um resultado

for (i=0;i<=MAX;i++)

c[i]=a[i]+b[i];

Page 5: Vetorização e Otimização de Código - Intel Software Conference 2013

Implementação Vetorizada

Processamento SIMD

(vetorizado)Instruções SSE, AVX, AVX2

Uma instrução pode produzir

múltiplos resultados

for (i=0;i<=MAX;i++)

c[i]=a[i]+b[i];

Page 6: Vetorização e Otimização de Código - Intel Software Conference 2013

Vetores SIMD (AVX)

Page 7: Vetorização e Otimização de Código - Intel Software Conference 2013

Como aproveitar isso tudo?

APIs nativas para multithreading demandamexperiência para escrever código correto e eficiente

– Mais complexo para expandir, especialmente para sistemasque usam outros processos multithreaded.

Instruções de vetorização também apresentam desafios

– Inline assembly e intrinsics requerem experiência de baixonível e não escalam facilmente

– A vetorização feita pelo compilador é bem-vinda, mas podenão funcionar sempre. Além disso, pode ser prejudicada pelasemântica da linguagem.

Page 8: Vetorização e Otimização de Código - Intel Software Conference 2013

Construções de vetores com

Intel® Cilk™ Plus

Page 9: Vetorização e Otimização de Código - Intel Software Conference 2013

Intel® Cilk™ Plus: solução simples e eficiente

Intel CilkPlus

Benefícios

Intel CilkPlus

O que é?

• Suportado pelo compilador:

3 simples palavras-chave

• Array notation

• Hyperobjects – evitam races de forma eficiente

• Pragmas e atributos para definir vetorização

• Suporta C and C++

• Sintaxe fácil de aprender e usar

• Código rápido e reutilizável (vetores maiores)

• Fork/join: simples de entender,

reproduz comportamento serial

• Baixo overhead: escalabilidade p/ muitos núcleos

• Reducers: + rápidos do que locks, semântica do código serial

Page 10: Vetorização e Otimização de Código - Intel Software Conference 2013

O que o Intel® Cilk™ Plus NÃO É

Não é uma solução completa para multithreading

Solução completa: Intel® Threading Building Blocks

Não é uma solução de paralelismo de cluster entre diversos nós

Solucão: Intel® Cluster Studio

Não é uma ferramenta para tornar o projeto de aplicaçõesparalelas mais simples

Solução: Intel® Parallel Advisor

Page 11: Vetorização e Otimização de Código - Intel Software Conference 2013

Técnicas de Vetorização

Page 12: Vetorização e Otimização de Código - Intel Software Conference 2013

Notação de Arrays - Intel® Cilk™ Plus

Sintaxe para especificar seções dos arrays nas quais executardeterminadas operações

Sintaxe: [<limite inferior> : <tamanho> : <passo>]

• Exemplos

a[0:N] = b[0:N] * c[0:N];

a[:] = b[:] * c[:] // se a, b, c são declarados

com tamanho N

A vetorização automática do compilador C++ Intel® pode usaressa informação para aplicar operações únicas para múltiploselementos do array usando Intel® Streaming SIMD Extensions (Intel® SSE) e Intel® Advanced Vector Extensions (Intel® AVX)

• Exemplo mais avançado:

x[0:10:10] = sin(y[20:10:2]);

Page 13: Vetorização e Otimização de Código - Intel Software Conference 2013

Exemplo de Notação de Arrays

void foo(double * a, double * b, double * c, double * d,

double * e, int n) {

for(int i = 0; i < n; i++)

a[i] *= (b[i] - d[i]) * (c[i] + e[i]);

}

void goo(double * a, double * b, double * c, double * d,

double * e, int n) {

a[0:n] *= (b[0:n] - d[0:n]) * (c[0:n] + e[0:n]);

}

icl -Qvec-report3 -c test-array-notations.cppIntel(R) C++ Intel(R) 64 Compiler XE for applications running on Intel(R) 64, Version 12.1.4.325 Build 20120410Copyright (C) 1985-2012 Intel Corporation. All rights reserved.

test-array-notations.cpptest-array-notations.cpp(2): (col. 2) remark: loop was not vectorized: existence of vector dependence.test-array-notations.cpp(3): (col. 3) remark: vector dependence: assumed FLOW dependence between a line 3 and e line 3.<snip>test-array-notations.cpp(7): (col. 6) remark: LOOP WAS VECTORIZED.

Page 14: Vetorização e Otimização de Código - Intel Software Conference 2013

Vetorização + Threading

Page 15: Vetorização e Otimização de Código - Intel Software Conference 2013

Quais loops podem ser vetorizados?

ContávelContador constante durante o loop

Entradas e Saídas ÚnicasSaída do loop não pode ser dependente de dados

(deve ser baseada no contador)

Código “straight-line”Instruções SIMD são iguais para diversas iterações do

loop. Não pode haver “branching”

O mais interno de loops encadeados

Sem chamadas de funçõesSomente funções matemáticas intrínsecas ou inlines

http://d3f8ykwhia686p.cloudfront.net/1live/intel/CompilerAutovectorizationGuide.pdf

Page 16: Vetorização e Otimização de Código - Intel Software Conference 2013

Funções vetorizadas pelo compilador

Page 17: Vetorização e Otimização de Código - Intel Software Conference 2013

Funções Elementares no Intel® Cilk™ Plus

• O compilador não pode assumir que uma função definidapelo usuário é segura para vetorização

• É possível tornar uma função “elementar”: indicar aocompilador que a função pode ser aplicada a múltiploselementos de um array em paralelo de forma segura

• Utilize __declspec(vector) na declaração *E* na definiçãoda função, pois isso afetará o name-mangling

• Ao usar cláusulas disponíveis para ajudar diretamente o compilador na geração do código, consulte a documentação para detalhes

Page 18: Vetorização e Otimização de Código - Intel Software Conference 2013

Exemplo de Função Elementar

double user_function(double x);

__declspec(vector) double elemental_function(double x);

double a[100];

double b[100];

void foo() {

a[:] = user_function(b[:]);

a[:] = elemental_function(b[:]);

}

icl /Qvec-report3 /c test-elemental-functions.cppIntel(R) C++ Intel(R) 64 Compiler XE for applications running on Intel(R) 64, Version 12.1.4.325 Build 20120410Copyright (C) 1985-2012 Intel Corporation. All rights reserved.

test-elemental-functions.cpp

test-elemental-functions.cpp(9): (col. 4) remark: LOOP WAS VECTORIZED.test-elemental-functions.cpp(8): (col. 4) remark: loop was not vectorized: nonstandard loop is not a vectorization candidate.

Page 19: Vetorização e Otimização de Código - Intel Software Conference 2013

Obstáculos para Vetorização

Acesso não-contíguo à memória

"vectorization possible but seems inefficient“

Endereçamento indireto (3o exemplo): “Existence of vector dependence”

Page 20: Vetorização e Otimização de Código - Intel Software Conference 2013

Obstáculos para Vetorização

Dependência de Dados

No segundo caso, se não houver dependência(aliasing), o uso de #pragma ivdep permite

“forçar” a vetorização

Page 21: Vetorização e Otimização de Código - Intel Software Conference 2013

Intel® Cilk™ Plus - Tasking

Page 22: Vetorização e Otimização de Código - Intel Software Conference 2013

Palavras-chave do Intel® Cilk™ Plus

Cilk Plus adiciona 3 palavras-chave ao C/C++:

_cilk_spawn

_cilk_sync

_cilk_for

Usando #include <cilk/cilk.h>, você pode usar as palavras-chave: cilk_spawn, cilk_sync e cilk_for.

O runtime do CILK Plus controla a criação de threads e seuagendamento. O pool de threads é criado antes do uso das palavras-chave do CILK Plus.

Por default, o número de threads é igual ao número de núcleos (incluindo hyperthreads), mas pode ser controladopelo usuário

Page 23: Vetorização e Otimização de Código - Intel Software Conference 2013

cilk_spawn e cilk_sync

cilk_spawn dá ao runtime a

permissão para rodar uma função-filha de forma assíncrona.

– Não é criada (nem necessária) uma 2a thread!

– Se não houver workers disponíveis, a função-filha seráexecutada com uma chamada a uma função serial.

– O scheduler pode “roubar” a fila da função-pai e executá-la em paralelo com a função-filha.

– A função-pai não tem garantia de rodar em paralelo com a função-filha.

cilk_sync aguarda a conclusão de todas as funções-filhas

antes que a execução prossiga além daquele ponto.

– Existem pontos de sincronismo (cilk_sync) implícitos

Page 24: Vetorização e Otimização de Código - Intel Software Conference 2013

Um exemplo simples

Computação recursiva do número de Fibonacci:

int fib(int n)

{

int x, y;

if (n < 2) return n;

x = cilk_spawn fib(n-1);

y = fib(n-2);

cilk_sync;

return x+y;

}

Chamadas assíncronas devemcompletar antes de usar x.

Execução pode continuarenquanto fib(n-1) roda.

Page 25: Vetorização e Otimização de Código - Intel Software Conference 2013

cilk_for

Semelhante a um loop “for” regular.

cilk_for (int x = 0; x < 1000000; ++x) { … }

Qualquer iteração pode executar em paralelo com qualqueroutra.

Todas as interações completam antes do programa prosseguir.

Limitações:

– Limitado a uma única variável de controle.

– Deve ser capaz de voltar ao início de qualquer iteração, randomicamente.

– Iterações devem ser independentes umas das outras.

Page 26: Vetorização e Otimização de Código - Intel Software Conference 2013

Nos bastidores do cilk_for…

void run_loop(first, last) {

if ((last - first) < grainsize) {

for (int i=first; i<last ++i)

{LOOP_BODY;}

}

else {

int mid = (last-first)/2;

cilk_spawn run_loop(first, mid);

run_loop(mid, last);

}

}

Page 27: Vetorização e Otimização de Código - Intel Software Conference 2013

Exemplos de cilk_for

cilk_for (int x; x < 1000000; x += 2) { … }

cilk_for (vector<int>::iterator x =

y.begin();

x != y.end(); ++x) { … }

cilk_for (list<int>::iterator x = y.begin();

x != y.end(); ++x) { … }

O contador do loop não pode ser calculado em tempo de compilação usando uma lista. (y.end() – y.begin() não é definido)

Não há acesso randômico aos elementos de uma lista. (y.begin() + n não é definido.)

Page 28: Vetorização e Otimização de Código - Intel Software Conference 2013

Serialização

Todo programa Cilk Plus tem um equivalente serial, chamado de serialização

A serialização é obtida removendo as palavras-chavecilk_spawn e cilk_sync e substituindocilk_for por for

O compilador produzirá a serialização se vocêcompilar com /Qcilk-serialize (Windows*) ou–cilk-serialize (Linux*/OS X*)

Rodar um programa com somente um worker é equivalente a rodar a serialização.

Page 29: Vetorização e Otimização de Código - Intel Software Conference 2013

Semântica Serial

Um programa CILK Plus determinístico terá a mesmasemântica se sua serialização.

– Facilita a realização de testes de regressão;

– Facilita o debug:

– Roda com somente um núcleo

– Roda serializado

– Permite composição

– Vantagens dos hyperobjects

– Ferramentas de análise robustas (Cilk Plus SDK)

– cilkscreen race detector

– cilkview scalability analyzer

Page 30: Vetorização e Otimização de Código - Intel Software Conference 2013

Sincronismos implícitos

void f() {

cilk_spawn g();

cilk_for (int x = 0; x < lots; ++x) {

...

}

try {

cilk_spawn h();

}

catch (...) {

...

}

}Ao final de uma funcão utilizando spawn

Ao final do corpo de um cilk_for (não sincroniza g())

Ao final de um bloco try contendo um spawn

Antes de entrar num bloco try contendo um sync

Page 31: Vetorização e Otimização de Código - Intel Software Conference 2013

Composição

Sincronismos implícitos são importantes para tornarcada chamada de função uma “caixa preta”.

Quem chama a função não sabe (nem se importa) se a função chamada implementa spawns.

A abstração serial é mantida.

Que chama a função não precisa se preocupar com data races na função chamada.

cilk_sync sincroniza somente funções-filhas que

foram “spawned” dentro da mesma função do sync: nenhuma ação ocorre “à distância”.

Page 32: Vetorização e Otimização de Código - Intel Software Conference 2013

Um exemplo de soma

int compute(const X& v);

int main()

{

const std::size_t n = 1000000;

extern X myArray[n];

// ...

int result = 0;

for (std::size_t i = 0; i < n; ++i)

{

result += compute(myArray[i]);

}

std::cout << "The result is: "

<< result

<< std::endl;

return 0;

}

Page 33: Vetorização e Otimização de Código - Intel Software Conference 2013

Somando com Intel® Cilk™ Plus

int compute(const X& v);

int main()

{

const std::size_t n = 1000000;

extern X myArray[n];

// ...

int result = 0;

cilk_for (std::size_t i = 0; i < n; ++i)

{

result += compute(myArray[i]);

}

std::cout << "The result is: "

<< result

<< std::endl;

return 0;

}

Race!

Page 34: Vetorização e Otimização de Código - Intel Software Conference 2013

Solução com Locks

int compute(const X& v);

int main()

{

const std::size_t n = 1000000;

extern X myArray[n];

// ...

mutex L;

int result = 0;

cilk_for (std::size_t i = 0; i < n; ++i)

{

int temp = compute(myArray[i]);

L.lock();

result += temp;

L.unlock();

}

std::cout << "The result is: "

<< result

<< std::endl;

return 0;

}

Problemas

Sobrecarga e

contenção dos Locks

Page 35: Vetorização e Otimização de Código - Intel Software Conference 2013

Solução com Reducer do CILK™ Plus

int compute(const X& v);

int main()

{

const std::size_t ARRAY_SIZE = 1000000;

extern X myArray[ARRAY_SIZE];

// ...

cilk::reducer_opadd<int> result;

cilk_for (std::size_t i = 0; i < ARRAY_SIZE; ++i)

{

result += compute(myArray[i]);

}

std::cout << "The result is: "

<< result.get_value()

<< std::endl;

return 0;

}

Declare result como

reducer de soma (int)

Atualizações são

resolvidas automatica/e, sem races nem contenção

Ao final, o valor (int) pode

ser recuperado (soma)

Page 36: Vetorização e Otimização de Código - Intel Software Conference 2013

Biblioteca de “HyperObjects”

A biblioteca de hyperobjects do Intel® Cilk™ Plus’s contém os“reducers” mais utilizados (e mais) :

– reducer_list_append

– reducer_list_prepend

– reducer_max

– reducer_max_index

– reducer_min

– reducer_min_index

– reducer_opadd

– reducer_ostream

– reducer_basic_string

– holder

– …

Você pode escrever seu próprio reducer usandocilk::monoid_base e cilk::reducer.

Page 37: Vetorização e Otimização de Código - Intel Software Conference 2013

Use o Intel® Cilk™ Plus

Disponível em:

Intel® C++ Composer XE 2011

– Incluído no Intel® Parallel Studio XE 2011 SP1

– Avaliação gratuita (30 dias) emhttp://software.intel.com/en-us/articles/intel-software-evaluation-center/

Patch do gcc* 4.7 (Open Source)

– Obtenha em: http://cilk.com

Page 38: Vetorização e Otimização de Código - Intel Software Conference 2013

Material complementar

Sobre Intel® Cilk™ Plushttp://cilk.com

Intel® Threading Building Blockshttp://threadingbuildingblocks.org

Suportehttp://premier.intel.com

Fóruns de usuárioshttp://software.intel.com/pt-br/forumshttp://software.intel.com/en-us/forums/intel-cilk-plus

Apresentações técnicashttp://software.intel.com/en-us/articles/intel-software-development-products-technical-presentations/(incluem mais detalhes do Cilk Plus, vetorização, Intel® Cluster Studio e muito mais!)

Page 39: Vetorização e Otimização de Código - Intel Software Conference 2013

Nota sobre Otimização

Page 40: Vetorização e Otimização de Código - 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 41: Vetorização e Otimização de Código - 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 42: Vetorização e Otimização de Código - Intel Software Conference 2013