From Wikipedia, the free encyclopedia
Advanced Vector Extensions (AVX, also known as Gesher New Instructions and then Sandy Bridge New Instructions) are SIMD extensions to the x86 instruction set architecture for microprocessors from Intel and Advanced Micro Devices (AMD). They were proposed by Intel in March 2008 and first supported by Intel with the Sandy Bridge[1] microarchitecture shipping in Q1 2011 and later by AMD with the Bulldozer[2] microarchitecture shipping in Q4 2011. AVX provides new features, new instructions, and a new coding scheme.
AVX2 (also known as Haswell New Instructions) expands most integer commands to 256 bits and introduces new instructions. They were first supported by Intel with the Haswell microarchitecture, which shipped in 2013.
AVX-512 expands AVX to 512-bit support using a new EVEX prefix encoding proposed by Intel in July 2013 and first supported by Intel with the Knights Landing co-processor, which shipped in 2016.[3][4] In conventional processors, AVX-512 was introduced with Skylake server and HEDT processors in 2017.
Advanced Vector Extensions
[edit]
AVX uses sixteen YMM registers to perform a single instruction on multiple pieces of data (see SIMD). Each YMM register can hold and do simultaneous operations (math) on:
- eight 32-bit single-precision floating-point numbers or
- four 64-bit double-precision floating-point numbers.
The width of the SIMD registers is increased from 128 bits to 256 bits, and renamed from XMM0–XMM7 to YMM0–YMM7 (in x86-64 mode, from XMM0–XMM15 to YMM0–YMM15). The legacy SSE instructions can still be utilized via the VEX prefix to operate on the lower 128 bits of the YMM registers.
AVX-512 register scheme as extension from the AVX (YMM0-YMM15) and SSE (XMM0-XMM15) registers
| 511 256 | 255 128 | 127 0 |
| ZMM0 | YMM0 | XMM0 |
| ZMM1 | YMM1 | XMM1 |
| ZMM2 | YMM2 | XMM2 |
| ZMM3 | YMM3 | XMM3 |
| ZMM4 | YMM4 | XMM4 |
| ZMM5 | YMM5 | XMM5 |
| ZMM6 | YMM6 | XMM6 |
| ZMM7 | YMM7 | XMM7 |
| ZMM8 | YMM8 | XMM8 |
| ZMM9 | YMM9 | XMM9 |
| ZMM10 | YMM10 | XMM10 |
| ZMM11 | YMM11 | XMM11 |
| ZMM12 | YMM12 | XMM12 |
| ZMM13 | YMM13 | XMM13 |
| ZMM14 | YMM14 | XMM14 |
| ZMM15 | YMM15 | XMM15 |
| ZMM16 | YMM16 | XMM16 |
| ZMM17 | YMM17 | XMM17 |
| ZMM18 | YMM18 | XMM18 |
| ZMM19 | YMM19 | XMM19 |
| ZMM20 | YMM20 | XMM20 |
| ZMM21 | YMM21 | XMM21 |
| ZMM22 | YMM22 | XMM22 |
| ZMM23 | YMM23 | XMM23 |
| ZMM24 | YMM24 | XMM24 |
| ZMM25 | YMM25 | XMM25 |
| ZMM26 | YMM26 | XMM26 |
| ZMM27 | YMM27 | XMM27 |
| ZMM28 | YMM28 | XMM28 |
| ZMM29 | YMM29 | XMM29 |
| ZMM30 | YMM30 | XMM30 |
| ZMM31 | YMM31 | XMM31 |
AVX introduces a three-operand SIMD instruction format called VEX coding scheme, where the destination register is distinct from the two source operands. For example, an SSE instruction using the conventional two-operand form a ← a + b can now use a non-destructive three-operand form c ← a + b, preserving both source operands. Originally, AVX’s three-operand format was limited to the instructions with SIMD operands (YMM), and did not include instructions with general purpose registers (e.g. EAX). It was later used for coding new instructions on general purpose registers in later extensions, such as BMI. VEX coding is also used for instructions operating on the k0-k7 mask registers that were introduced with AVX-512.
The alignment requirement of SIMD memory operands is relaxed.[5] Unlike their non-VEX coded counterparts, most VEX coded vector instructions no longer require their memory operands to be aligned to the vector size. Notably, the VMOVDQA instruction still requires its memory operand to be aligned.
The new VEX coding scheme introduces a new set of code prefixes that extends the opcode space, allows instructions to have more than two operands, and allows SIMD vector registers to be longer than 128 bits. The VEX prefix can also be used on the legacy SSE instructions giving them a three-operand form, and making them interact more efficiently with AVX instructions without the need for VZEROUPPER and VZEROALL.
The AVX instructions support both 128-bit and 256-bit SIMD. The 128-bit versions can be useful to improve old code without needing to widen the vectorization, and avoid the penalty of going from SSE to AVX, they are also faster on some early AMD implementations of AVX. This mode is sometimes known as AVX-128.[6]
These AVX instructions are in addition to the ones that are 256-bit extensions of the legacy 128-bit SSE instructions; most are usable on both 128-bit and 256-bit operands.
| Instruction | Description |
|---|---|
VBROADCASTSS, VBROADCASTSD, VBROADCASTF128
|
Copy a 32-bit, 64-bit or 128-bit memory operand to all elements of a XMM or YMM vector register. |
VINSERTF128
|
Replaces either the lower half or the upper half of a 256-bit YMM register with the value of a 128-bit source operand. The other half of the destination is unchanged. |
VEXTRACTF128
|
Extracts either the lower half or the upper half of a 256-bit YMM register and copies the value to a 128-bit destination operand. |
VMASKMOVPS, VMASKMOVPD
|
Conditionally reads any number of elements from a SIMD vector memory operand into a destination register, leaving the remaining vector elements unread and setting the corresponding elements in the destination register to zero. Alternatively, conditionally writes any number of elements from a SIMD vector register operand to a vector memory operand, leaving the remaining elements of the memory operand unchanged. On the AMD Jaguar processor architecture, this instruction with a memory source operand takes more than 300 clock cycles when the mask is zero, in which case the instruction should do nothing. This appears to be a design flaw.[7] |
VPERMILPS, VPERMILPD
|
Permute In-Lane. Shuffle the 32-bit or 64-bit vector elements of one input operand. These are in-lane 256-bit instructions, meaning that they operate on all 256 bits with two separate 128-bit shuffles, so they can not shuffle across the 128-bit lanes.[8] |
VPERM2F128
|
Shuffle the four 128-bit vector elements of two 256-bit source operands into a 256-bit destination operand, with an immediate constant as selector. |
VTESTPS, VTESTPD
|
Packed bit test of the packed single-precision or double-precision floating-point sign bits, setting or clearing the ZF flag based on AND and CF flag based on ANDN. |
VZEROALL
|
Set all YMM registers to zero and tag them as unused. Used when switching between 128-bit use and 256-bit use. |
VZEROUPPER
|
Set the upper half of all YMM registers to zero. Used when switching between 128-bit use and 256-bit use. |
- Intel
- Sandy Bridge processors (Q1 2011) and newer, except models branded as Celeron and Pentium.[9]
- Pentium and Celeron branded processors starting with Tiger Lake (Q3 2020) and newer.[10]
- AMD:
- Bulldozer processors (Q4 2011) and newer.[11]
Issues regarding compatibility between future Intel and AMD processors are discussed under XOP instruction set.
- VIA:
- Nano QuadCore
- Eden X4
- Zhaoxin:
- WuDaoKou-based processors (KX-5000 and KH-20000)
Compiler and assembler support
[edit]
- Absoft supports with -mavx flag.
- The Free Pascal compiler supports AVX and AVX2 with the -CfAVX and -CfAVX2 switches from version 2.7.1.
- RAD studio (v11.0 Alexandria) supports AVX2 and AVX512.[12]
- The GNU Assembler (GAS) inline assembly functions support these instructions (accessible via GCC), as do Intel primitives and the Intel inline assembler (closely compatible to GAS, although more general in its handling of local references within inline code). GAS supports AVX starting with binutils version 2.19.[13]
- GCC starting with version 4.6 (although there was a 4.3 branch with certain support) and the Intel Compiler Suite starting with version 11.1 support AVX.
- The Open64 compiler version 4.5.1 supports AVX with -mavx flag.
- PathScale supports via the -mavx flag.
- The Vector Pascal compiler supports AVX via the -cpuAVX32 flag.
- The Visual Studio 2010/2012 compiler supports AVX via intrinsic and /arch:AVX switch.
- NASM starting with version 2.03 and newer. There were numerous bug fixes and updates related to AVX in version 2.04.[14]
- Other assemblers such as MASM VS2010 version, YASM,[15] FASM and JWASM.
Operating system support
[edit]
AVX adds new register-state through the 256-bit wide YMM register file, so explicit operating system support is required to properly save and restore AVX’s expanded registers between context switches. The following operating system versions support AVX:
- DragonFly BSD: support added in early 2013.
- FreeBSD: support added in a patch submitted on January 21, 2012,[16] which was included in the 9.1 stable release.[17]
- Linux: supported since kernel version 2.6.30,[18] released on June 9, 2009.[19]
- macOS: support added in 10.6.8 (Snow Leopard) update[20][unreliable source?] released on June 23, 2011. In fact, macOS Ventura does not support x86 processors without the AVX2 instruction set.[21]
- OpenBSD: support added on March 21, 2015.[22]
- Solaris: supported in Solaris 10 Update 10 and Solaris 11.
- Windows: supported in Windows 7 SP1, Windows Server 2008 R2 SP1,[23] Windows 8, Windows 10.
- Windows Server 2008 R2 SP1 with Hyper-V requires a hotfix to support AMD AVX (Opteron 6200 and 4200 series) processors, KB2568088
- Windows XP and Windows Server 2003 do not support AVX in both kernel drivers and user applications.
Advanced Vector Extensions 2
[edit]
Advanced Vector Extensions 2 (AVX2), also known as Haswell New Instructions,[24] is an expansion of the AVX instruction set introduced in Intel’s Haswell microarchitecture. AVX2 makes the following additions:
- expansion of most vector integer SSE and AVX instructions to 256 bits
- Gather support, enabling vector elements to be loaded from non-contiguous memory locations
- DWORD- and QWORD-granularity any-to-any permutes
- vector shifts.
Sometimes three-operand fused multiply-accumulate (FMA3) extension is considered part of AVX2, as it was introduced by Intel in the same processor microarchitecture. This is a separate extension using its own CPUID flag and is described on its own page and not below.
| Instruction | Description |
|---|---|
VBROADCASTSS, VBROADCASTSD
|
Copy a 32-bit or 64-bit register operand to all elements of a XMM or YMM vector register. These are register versions of the same instructions in AVX1. There is no 128-bit version, but the same effect can be simply achieved using VINSERTF128. |
VPBROADCASTB, VPBROADCASTW, VPBROADCASTD, VPBROADCASTQ
|
Copy an 8, 16, 32 or 64-bit integer register or memory operand to all elements of a XMM or YMM vector register. |
VBROADCASTI128
|
Copy a 128-bit memory operand to all elements of a YMM vector register. |
VINSERTI128
|
Replaces either the lower half or the upper half of a 256-bit YMM register with the value of a 128-bit source operand. The other half of the destination is unchanged. |
VEXTRACTI128
|
Extracts either the lower half or the upper half of a 256-bit YMM register and copies the value to a 128-bit destination operand. |
VGATHERDPD, VGATHERQPD, VGATHERDPS, VGATHERQPS
|
Gathers single- or double-precision floating-point values using either 32- or 64-bit indices and scale. |
VPGATHERDD, VPGATHERDQ, VPGATHERQD, VPGATHERQQ
|
Gathers 32 or 64-bit integer values using either 32- or 64-bit indices and scale. |
VPMASKMOVD, VPMASKMOVQ
|
Conditionally reads any number of elements from a SIMD vector memory operand into a destination register, leaving the remaining vector elements unread and setting the corresponding elements in the destination register to zero. Alternatively, conditionally writes any number of elements from a SIMD vector register operand to a vector memory operand, leaving the remaining elements of the memory operand unchanged. |
VPERMPS, VPERMD
|
Shuffle the eight 32-bit vector elements of one 256-bit source operand into a 256-bit destination operand, with a register or memory operand as selector. |
VPERMPD, VPERMQ
|
Shuffle the four 64-bit vector elements of one 256-bit source operand into a 256-bit destination operand, with a register or memory operand as selector. |
VPERM2I128
|
Shuffle (two of) the four 128-bit vector elements of two 256-bit source operands into a 256-bit destination operand, with an immediate constant as selector. |
VPBLENDD
|
Doubleword immediate version of the PBLEND instructions from SSE4. |
VPSLLVD, VPSLLVQ
|
Shift left logical. Allows variable shifts where each element is shifted according to the packed input. |
VPSRLVD, VPSRLVQ
|
Shift right logical. Allows variable shifts where each element is shifted according to the packed input. |
VPSRAVD
|
Shift right arithmetically. Allows variable shifts where each element is shifted according to the packed input. |
- Intel
- Haswell processors (Q2 2013) and newer, except models branded as Celeron and Pentium.
- Celeron and Pentium branded processors starting with Tiger Lake (Q3 2020) and newer.[10]
- AMD
- Excavator processors (Q2 2015) and newer.
- VIA:
- Nano QuadCore
- Eden X4
AVX-512 are 512-bit extensions to the 256-bit Advanced Vector Extensions SIMD instructions for x86 instruction set architecture proposed by Intel in July 2013.[3]
AVX-512 instructions are encoded with the new EVEX prefix. It allows 4 operands, 8 new 64-bit opmask registers, scalar memory mode with automatic broadcast, explicit rounding control, and compressed displacement memory addressing mode. The width of the register file is increased to 512 bits and total register count increased to 32 (registers ZMM0-ZMM31) in x86-64 mode.
AVX-512 consists of multiple instruction subsets, not all of which are meant to be supported by all processors implementing them. The instruction set consists of the following:
- AVX-512 Foundation (F) – adds several new instructions and expands most 32- and 64-bit floating-point SSE-SSE4.1 and AVX/AVX2 instructions with EVEX coding scheme to support the 512-bit registers, operation masks, parameter broadcasting, and embedded rounding and exception control
- AVX-512 Conflict Detection Instructions (CD) – efficient conflict detection to allow more loops to be vectorized, supported by Knights Landing[3]
- AVX-512 Exponential and Reciprocal Instructions (ER) – exponential and reciprocal operations designed to help implement transcendental operations, supported by Knights Landing[3]
- AVX-512 Prefetch Instructions (PF) – new prefetch capabilities, supported by Knights Landing[3]
- AVX-512 Vector Length Extensions (VL) – extends most AVX-512 operations to also operate on XMM (128-bit) and YMM (256-bit) registers (including XMM16-XMM31 and YMM16-YMM31 in x86-64 mode)[25]
- AVX-512 Byte and Word Instructions (BW) – extends AVX-512 to cover 8-bit and 16-bit integer operations[25]
- AVX-512 Doubleword and Quadword Instructions (DQ) – enhanced 32-bit and 64-bit integer operations[25]
- AVX-512 Integer Fused Multiply Add (IFMA) – fused multiply add for 512-bit integers.[26]: 746
- AVX-512 Vector Byte Manipulation Instructions (VBMI) adds vector byte permutation instructions which are not present in AVX-512BW.
- AVX-512 Vector Neural Network Instructions Word variable precision (4VNNIW) – vector instructions for deep learning.
- AVX-512 Fused Multiply Accumulation Packed Single precision (4FMAPS) – vector instructions for deep learning.
- VPOPCNTDQ – count of bits set to 1.[27]
- VPCLMULQDQ – carry-less multiplication of quadwords.[27]
- AVX-512 Vector Neural Network Instructions (VNNI) – vector instructions for deep learning.[27]
- AVX-512 Galois Field New Instructions (GFNI) – vector instructions for calculating Galois field.[27]
- AVX-512 Vector AES instructions (VAES) – vector instructions for AES coding.[27]
- AVX-512 Vector Byte Manipulation Instructions 2 (VBMI2) – byte/word load, store and concatenation with shift.[27]
- AVX-512 Bit Algorithms (BITALG) – byte/word bit manipulation instructions expanding VPOPCNTDQ.[27]
- AVX-512 Bfloat16 Floating-Point Instructions (BF16) – vector instructions for AI acceleration.
- AVX-512 Half-Precision Floating-Point Instructions (FP16) – vector instructions for operating on floating-point and complex numbers with reduced precision.
Only the core extension AVX-512F (AVX-512 Foundation) is required by all implementations, though all current implementations also support CD (conflict detection). All central processors with AVX-512 also support VL, DQ and BW. The ER, PF, 4VNNIW and 4FMAPS instruction set extensions are currently only implemented in Intel computing coprocessors.
The updated SSE/AVX instructions in AVX-512F use the same mnemonics as AVX versions; they can operate on 512-bit ZMM registers, and will also support 128/256 bit XMM/YMM registers (with AVX-512VL) and byte, word, doubleword and quadword integer operands (with AVX-512BW/DQ and VBMI).[26]: 23
AVX-512 CPU compatibility table
[edit]
|
Subset |
F |
CD |
ER |
PF |
4FMAPS |
4VNNIW |
VPOPCNTDQ |
VL |
DQ |
BW |
IFMA |
VBMI |
VBMI2 |
BITALG |
VNNI |
BF16 |
VPCLMULQDQ |
GFNI |
VAES |
VP2INTERSECT |
FP16 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Intel Knights Landing (2016) | Yes | Yes | No | ||||||||||||||||||
| Intel Knights Mill (2017) | Yes | No | |||||||||||||||||||
| Intel Skylake-SP, Skylake-X (2017) | No | No | Yes | No | |||||||||||||||||
| Intel Cannon Lake (2018) | Yes | No | |||||||||||||||||||
| Intel Cascade Lake-SP (2019) | No | Yes | No | ||||||||||||||||||
| Intel Cooper Lake (2020) | No | Yes | No | ||||||||||||||||||
| Intel Ice Lake (2019) | Yes | No | Yes | No | |||||||||||||||||
| Intel Tiger Lake (2020) | Yes | No | |||||||||||||||||||
| Intel Rocket Lake (2021) | No | ||||||||||||||||||||
| Intel Alder Lake (2021) | PartialNote 1 | PartialNote 1 | |||||||||||||||||||
| AMD Zen 4 (2022) | Yes | Yes | No | ||||||||||||||||||
| Intel Sapphire Rapids (2023) | No | Yes | |||||||||||||||||||
| AMD Zen 5 (2024) | Yes | No |
[28]
^Note 1 : Intel does not officially support AVX-512 family of instructions on the Alder Lake microprocessors. In early 2022, Intel began disabling in silicon (fusing off) AVX-512 in Alder Lake microprocessors to prevent customers from enabling AVX-512.[29]
In older Alder Lake family CPUs with some legacy combinations of BIOS and microcode revisions, it was possible to execute AVX-512 family instructions when disabling all the efficiency cores which do not contain the silicon for AVX-512.[30][31][32]
Compilers supporting AVX-512
[edit]
- Clang 3.9 and newer[33]
- GCC 4.9 and newer[34]
- ICC 15.0.1 and newer[35]
- Microsoft Visual Studio 2017 C++ Compiler[36]
Assemblers supporting AVX-512
[edit]
- FASM
- NASM 2.11 and newer[14]
AVX-VNNI is a VEX-coded variant of the AVX512-VNNI instruction set extension. Similarly, AVX-IFMA is a VEX-coded variant of AVX512-IFMA. These extensions provide the same sets of operations as their AVX-512 counterparts, but are limited to 256-bit vectors and do not support any additional features of EVEX encoding, such as broadcasting, opmask registers or accessing more than 16 vector registers. These extensions allow support of VNNI and IFMA operations even when full AVX-512 support is not implemented in the processor.
- Intel
- Alder Lake processors (Q4 2021) and newer.
- AMD
- Zen 5 processors (Q3 2024) and newer.[37]
- Intel
- Sierra Forest E-core-only Xeon processors (Q2 2024) and newer.
- Grand Ridge special-purpose processors and newer.
- Meteor Lake mobile processors (Q4 2023) and newer.
- Arrow Lake desktop processors (Q4 2024) and newer.
AVX10, announced in July 2023,[38] is a new, «converged» AVX instruction set. It addresses several issues of AVX-512, in particular that it is split into too many parts[39] (20 feature flags). The initial technical paper also made 512-bit vectors optional to support, but as of revision 3.0 vector length enumeration is removed and 512-bit vectors are mandatory.[40]
AVX10 presents a simplified CPUID interface to test for instruction support, consisting of the AVX10 version number (indicating the set of instructions supported, with later versions always being a superset of an earlier one).[41] For example, AVX10.2 indicates that a CPU is capable of the second version of AVX10.[42] Initial revisions of the AVX10 technical specifications also included maximum supported vector length as part of the ISA extension name, e.g. AVX10.2/256 would mean a second version of AVX10 with vector length up to 256 bits, but later revisions made that unnecessary.
The first version of AVX10, notated AVX10.1, does not introduce any instructions or encoding features beyond what is already in AVX-512 (specifically, in Intel Sapphire Rapids: AVX-512F, CD, VL, DQ, BW, IFMA, VBMI, VBMI2, BITALG, VNNI, GFNI, VPOPCNTDQ, VPCLMULQDQ, VAES, BF16, FP16). For CPUs supporting AVX10 and 512-bit vectors, all legacy AVX-512 feature flags will remain set to facilitate applications supporting AVX-512 to continue using AVX-512 instructions.[42]
AVX10.1 was first released in Intel Granite Rapids[42] (Q3 2024) and AVX10.2 will be available in Diamond Rapids.[43]
APX is a new extension. It is not focused on vector computation, but provides RISC-like extensions to the x86-64 architecture by doubling the number of general-purpose registers to 32 and introducing three-operand instruction formats. AVX is only tangentially affected as APX introduces extended operands.[44][45]
- Suitable for floating-point-intensive calculations in multimedia, scientific and financial applications (AVX2 adds support for integer operations).
- Increases parallelism and throughput in floating-point SIMD calculations.
- Reduces register load due to the non-destructive instructions.
- Improves Linux RAID software performance (requires AVX2, AVX is not sufficient)[46]
- Cryptography
- BSAFE C toolkits uses AVX and AVX2 where appropriate to accelerate various cryptographic algorithms.[47]
- OpenSSL uses AVX- and AVX2-optimized cryptographic functions since version 1.0.2.[48] Support for AVX-512 was added in version 3.0.0.[49] Some of these optimizations are also present in various clones and forks, like LibreSSL.
- Multimedia
- Blender uses AVX, AVX2 and AVX-512 in the Cycles render engine.[50]
- Native Instruments’ Massive X softsynth requires AVX.[51]
- dav1d AV1 decoder can use AVX2 and AVX-512 on supported CPUs.[52][53]
- SVT-AV1 AV1 encoder can use AVX2 and AVX-512 to accelerate video encoding.[54]
- Science, engineering an others
- Esri ArcGIS Data Store uses AVX2 for graph storage.[55]
- Prime95/MPrime, the software used for GIMPS, started using the AVX instructions since version 27.1, AVX2 since 28.6 and AVX-512 since 29.1.[56]
- Einstein@Home uses AVX in some of their distributed applications that search for gravitational waves.[57]
- TensorFlow since version 1.6 and tensorflow above versions requires CPU supporting at least AVX.[58]
- EmEditor 19.0 and above uses AVX2 to speed up processing.[59]
- Microsoft Teams uses AVX2 instructions to create a blurred or custom background behind video chat participants,[60] and for background noise suppression.[61]
- simdjson, a JSON parsing library, uses AVX2 and AVX-512 to achieve improved decoding speed.[62][63]
- x86-simd-sort, a library with sorting algorithms for 16, 32 and 64-bit numeric data types, uses AVX2 and AVX-512. The library is used in NumPy and OpenJDK to accelerate sorting algorithms.[64]
- Tesseract OCR engine uses AVX, AVX2 and AVX-512 to accelerate character recognition.[65]
Since AVX instructions are wider, they consume more power and generate more heat. Executing heavy AVX instructions at high CPU clock frequencies may affect CPU stability due to excessive voltage droop during load transients. Some Intel processors have provisions to reduce the Turbo Boost frequency limit when such instructions are being executed. This reduction happens even if the CPU hasn’t reached its thermal and power consumption limits.
On Skylake and its derivatives, the throttling is divided into three levels:[66][67]
- L0 (100%): The normal turbo boost limit.
- L1 (~85%): The «AVX boost» limit. Soft-triggered by 256-bit «heavy» (floating-point unit: FP math and integer multiplication) instructions. Hard-triggered by «light» (all other) 512-bit instructions.
- L2 (~60%):[dubious – discuss] The «AVX-512 boost» limit. Soft-triggered by 512-bit heavy instructions.
The frequency transition can be soft or hard. Hard transition means the frequency is reduced as soon as such an instruction is spotted; soft transition means that the frequency is reduced only after reaching a threshold number of matching instructions. The limit is per-thread.[66]
In Ice Lake, only two levels persist:[68]
- L0 (100%): The normal turbo boost limit.
- L1 (~97%): Triggered by any 512-bit instructions, but only when single-core boost is active; not triggered when multiple cores are loaded.
Rocket Lake processors do not trigger frequency reduction upon executing any kind of vector instructions regardless of the vector size.[68] However, downclocking can still happen due to other reasons, such as reaching thermal and power limits.
Downclocking means that using AVX in a mixed workload with an Intel processor can incur a frequency penalty. Avoiding the use of wide and heavy instructions help minimize the impact in these cases. AVX-512VL allows for using 256-bit or 128-bit operands in AVX-512 instructions, making it a sensible default for mixed loads.[69]
On supported and unlocked variants of processors that down-clock, the clock ratio reduction offsets (typically called AVX and AVX-512 offsets) are adjustable and may be turned off entirely (set to 0x) via Intel’s Overclocking / Tuning utility or in BIOS if supported there.[70]
- F16C instruction set extension
- Memory Protection Extensions
- Scalable Vector Extension for ARM — a new vector instruction set (supplementing VFP and NEON) similar to AVX-512, with some additional features.
- ^ Kanter, David (September 25, 2010). «Intel’s Sandy Bridge Microarchitecture». www.realworldtech.com. Retrieved February 17, 2018.
- ^ Hruska, Joel (October 24, 2011). «Analyzing Bulldozer: Why AMD’s chip is so disappointing — Page 4 of 5 — ExtremeTech». ExtremeTech. Retrieved February 17, 2018.
- ^ a b c d e James Reinders (July 23, 2013), AVX-512 Instructions, Intel, retrieved August 20, 2013
- ^ «Intel Xeon Phi Processor 7210 (16GB, 1.30 GHz, 64 core) Product Specifications». Intel ARK (Product Specs). Retrieved March 16, 2018.
- ^ «14.9». Intel 64 and IA-32 Architectures Software Developer’s Manual Volume 1: Basic Architecture (PDF) (-051US ed.). Intel Corporation. p. 349. Retrieved August 23, 2014.
Memory arguments for most instructions with VEX prefix operate normally without causing #GP(0) on any byte-granularity alignment (unlike Legacy SSE instructions).
- ^ «i386 and x86-64 Options — Using the GNU Compiler Collection (GCC)». Retrieved February 9, 2014.
- ^ «The microarchitecture of Intel, AMD and VIA CPUs: An optimization guide for assembly programmers and compiler makers» (PDF). Retrieved October 17, 2016.
- ^ «Chess programming AVX2». Archived from the original on July 10, 2017. Retrieved October 17, 2016.
- ^ «Intel Offers Peek at Nehalem and Larrabee». ExtremeTech. March 17, 2008.
- ^ a b «Intel® Celeron® 6305 Processor (4M Cache, 1.80 GHz, with IPU) Product Specifications». ark.intel.com. Retrieved November 10, 2020.
- ^ Butler, Michael; Barnes, Leslie; Das Sarma, Debjit; Gelinas, Bob (March–April 2011). «Bulldozer: An Approach to Multithreaded Compute Performance» (PDF). IEEE Micro. 31 (2): 6–15. doi:10.1109/MM.2011.23. S2CID 28236214. Archived from the original (PDF) on May 19, 2024.
- ^ «What’s New — RAD Studio». docwiki.embarcadero.com. Retrieved September 17, 2021.
- ^ «GAS Changes». sourceware.org. Retrieved May 3, 2024.
- ^ a b «NASM — The Netwide Assembler, Appendix C: NASM Version History». nasm.us. Retrieved May 3, 2024.
- ^ «YASM 0.7.0 Release Notes». yasm.tortall.net.
- ^ Add support for the extended FPU states on amd64, both for native 64bit and 32bit ABIs, svnweb.freebsd.org, January 21, 2012, retrieved January 22, 2012
- ^ «FreeBSD 9.1-RELEASE Announcement». Retrieved May 20, 2013.
- ^ x86: add linux kernel support for YMM state, retrieved July 13, 2009
- ^ Linux 2.6.30 — Linux Kernel Newbies, retrieved July 13, 2009
- ^ Twitter, retrieved June 23, 2010
- ^ «Devs are making progress getting macOS Ventura to run on unsupported, decade-old Macs». August 23, 2022.
- ^ Add support for saving/restoring FPU state using the XSAVE/XRSTOR., retrieved March 25, 2015
- ^ Floating-Point Support for 64-Bit Drivers, retrieved December 6, 2009
- ^ Haswell New Instruction Descriptions Now Available, Software.intel.com, retrieved January 17, 2012
- ^ a b c James Reinders (July 17, 2014). «Additional AVX-512 instructions». Intel. Retrieved August 3, 2014.
- ^ a b «Intel Architecture Instruction Set Extensions Programming Reference» (PDF). Intel. Retrieved January 29, 2014.
- ^ a b c d e f g «Intel® Architecture Instruction Set Extensions and Future Features Programming Reference». Intel. Retrieved October 16, 2017.
- ^ «Intel® Software Development Emulator | Intel® Software». software.intel.com. Retrieved June 11, 2016.
- ^ Alcorn, Paul (March 2, 2022). «Intel Nukes Alder Lake’s AVX-512 Support, Now Fuses It Off in Silicon». Tom’s Hardware. Retrieved March 7, 2022.
- ^ Cutress, Ian; Frumusanu, Andrei (August 19, 2021). «Intel Architecture Day 2021: Alder Lake, Golden Cove, and Gracemont Detailed». AnandTech. Retrieved August 25, 2021.
- ^ Alcorn, Paul (August 19, 2021). «Intel Architecture Day 2021: Alder Lake Chips, Golden Cove and Gracemont Cores». Tom’s Hardware. Retrieved August 21, 2021.
- ^ Cutress, Ian; Frumusanu, Andrei. «The Intel 12th Gen Core i9-12900K Review: Hybrid Performance Brings Hybrid Complexity». www.anandtech.com. Retrieved November 5, 2021.
- ^ «LLVM 3.9 Release Notes — LLVM 3.9 documentation». releases.llvm.org. Retrieved April 3, 2017.
- ^ «GCC 4.9 Release Series — Changes, New Features, and Fixes – GNU Project — Free Software Foundation (FSF)». gcc.gnu.org. Retrieved April 3, 2017.
- ^ «Intel® Parallel Studio XE 2015 Composer Edition C++ Release Notes | Intel® Software». software.intel.com. Retrieved April 3, 2017.
- ^ «Microsoft Visual Studio 2017 Supports Intel® AVX-512». July 11, 2017.
- ^ «AMD Zen 5 Compiler Support Posted For GCC — Confirms New AVX Features & More». www.phoronix.com. Retrieved February 10, 2024.
- ^ Bonshor, Gavin (July 25, 2023). «Intel Unveils AVX10 and APX Instruction Sets: Unifying AVX-512 For Hybrid Architectures». AnandTech. Retrieved August 21, 2024.
- ^ Mann, Tobias (August 15, 2023). «Intel’s AVX10 promises benefits of AVX-512 without baggage». www.theregister.com. Retrieved August 20, 2023.
- ^ Larabel, Michael (March 19, 2025). «Intel AVX10 Drops Optional 512-bit: No AVX10 256-bit Only E-Cores In The Future». Phoronix. Retrieved March 19, 2025.
- ^ «The Converged Vector ISA: Intel® Advanced Vector Extensions 10 Technical Paper». Intel.
- ^ a b c «Intel® Advanced Vector Extensions 10 (Intel® AVX10) Architecture Specification». Intel.
- ^ Larabel, Michael (October 23, 2024). «Intel Preps GCC Compiler For New AMX & ISA Features Ahead Of Diamond Rapids». Phoronix. Retrieved October 23, 2024.
- ^ «Intel® Advanced Performance Extensions (Intel® APX) Architecture Specification». Intel.
- ^ Robinson, Dan (July 26, 2023). «Intel discloses x86 and vector instructions for future chips». www.theregister.com. Retrieved August 20, 2023.
- ^ «Linux RAID». LWN. February 17, 2013. Archived from the original on April 15, 2013.
- ^ «Comparison of BSAFE cryptographic library implementations». July 25, 2023.
- ^ «Improving OpenSSL Performance». May 26, 2015. Retrieved February 28, 2017.
- ^ «OpenSSL 3.0.0 release notes». GitHub. September 7, 2021.
- ^ Jaroš, Milan; Strakoš, Petr; Říha, Lubomír (May 28, 2022). «Rendering in Blender using AVX-512 Vectorization» (PDF). Intel eXtreme Performance Users Group. Technical University of Ostrava. Retrieved October 28, 2022.
- ^ «MASSIVE X Requires AVX Compatible Processor». Native Instruments. Retrieved November 29, 2019.
- ^ «dav1d: performance and completion of the first release». November 21, 2018. Retrieved November 22, 2018.
- ^ «dav1d 0.6.0 release notes». March 6, 2020.
- ^ «SVT-AV1 0.7.0 release notes». September 26, 2019.
- ^ «ArcGIS Data Store 11.2 System Requirements». ArcGIS Enterprise. Retrieved January 24, 2024.
- ^ «Prime95 release notes». Retrieved July 10, 2022.
- ^ «Einstein@Home Applications».
- ^ «Tensorflow 1.6». GitHub.
- ^ New in Version 19.0 – EmEditor (Text Editor)
- ^ «Hardware requirements for Microsoft Teams». Microsoft. Retrieved April 17, 2020.
- ^ «Reduce background noise in Teams meetings». Microsoft Support. Retrieved January 5, 2021.
- ^ Langdale, Geoff; Lemire, Daniel (2019). «Parsing Gigabytes of JSON per Second». The VLDB Journal. 28 (6): 941–960. arXiv:1902.08318. doi:10.1007/s00778-019-00578-5. S2CID 67856679.
- ^ «simdjson 2.1.0 release notes». GitHub. June 30, 2022.
- ^ Larabel, Michael (October 6, 2023). «OpenJDK Merges Intel’s x86-simd-sort For Speeding Up Data Sorting 7~15x». Phoronix.
- ^ Larabel, Michael (July 7, 2022). «Tesseract OCR 5.2 Engine Finds Success With AVX-512F». Phoronix.
- ^ a b Lemire, Daniel (September 7, 2018). «AVX-512: when and how to use these new instructions». Daniel Lemire’s blog.
- ^ BeeOnRope. «SIMD instructions lowering CPU frequency». Stack Overflow.
- ^ a b Downs, Travis (August 19, 2020). «Ice Lake AVX-512 Downclocking». Performance Matters blog.
- ^ «x86 — AVX 512 vs AVX2 performance for simple array processing loops». Stack Overflow.
- ^ «Intel® Extreme Tuning Utility (Intel® XTU) Guide to Overclocking : Advanced Tuning». Intel. Retrieved July 18, 2021.
See image in linked section, where AVX2 ratio has been set to 0.
- Intel Intrinsics Guide
- x86 Assembly Language Reference Manual
Введение
Новый набор SIMD инструкций для x86-процессоров Intel AVX был представлен публике ещё в марте 2008 года. И хотя реализации этих инструкций в железе ждать ещё полгода, спецификацию AVX уже можно считать устоявшейся, а поддержка набора инструкций AVX добавлена в новые версии компиляторов и ассемблеров. В данной статье рассмотрены практические вопросы оптимизации для Intel AVX подпрограмм на языках C/C++ и ассемблер.
Набор команд AVX
Все команды AVX, а также некоторые другие команды, описаны в справочнике, который можно найти на сайте Intel, посвященному AVX. В некотором смысле, набор команд AVX представляет собой расширение наборов команд SSE, которые уже поддерживаются всеми современными процессорами. В частности, AVX расширяет изначально 128-битные регистры SSE до 256 бит. Новые 256-битные регистры обозначаются как ymm0-ymm15 (для 32-битной программы доступны только ymm0-ymm7); при этом 128-битные SSE регистры xmm0-xmm15 ссылаются на младшие 128 бит соответствующего AVX регистра.
Чтобы эффективно работать с новыми 256-битными регистрами, в AVX было добавлено несметное количество инструкций. Однако, большинство из них представляет собой лишь немного изменённые версии уже знакомых нам инструкций SSE.
Так, каждая инструкция из SSE (а также SSE2, SSE3, SSSE3, SSE4.1, SSE4.2 и AES-NI) имеет в AVX свой аналог с префиксом v. Кроме префикса, такие AVX-инстукции отличаются от своих SSE-собратьев тем, что могут иметь три операнда: первый операнд указывает, куда писать результат, а остальные два — откуда брать данные. Трёхоперандные инструкции хороши тем, что во-первых позволяют избавиться от лишних операций копирования регистров в коде, а во-вторых упрощают написание хороших оптимизирующих компиляторов. SSE2-код
movdqa xmm2, xmm0
punpcklbw xmm0, xmm1
punpckhbw xmm2, xmm1
может быть переписан с AVX как
vpunpckhbw xmm2, xmm0, xmm1.
vpunpcklbw xmm0, xmm0, xmm1
При этом команды с префиксом v зануляют старшие 128 бит того AVX регистра, в который они пишут. Например, инструкция vpaddw xmm0, xmm1, xmm2 занулит старшие 128-бит регистра ymm0.
Кроме того, некоторые SSE-инструкции были расширены в AVX для работы с 256-битными регистрами. К таким инструкциям относятся все команды, работающие с числами с плавающей точкой (как одинарной, так и двойной точности). Например следующий AVX код
vmovapd ymm0, [esi]
vmulpd ymm0, ymm0, [edx]
vmovapd [edi], ymm0
обрабатывает сразу 4 double.
Вдобавок, AVX включает в себя некоторые новые инструкции
- vbroadcastss/vbroadcastsd/vbroadcastf128 — заполнение всего AVX регистра одним и тем же загруженным значением
- vmaskmovps/vmaskmovpd — условная загрузка/сохранение float/double чисел в AVX регистр в зависимости от знака чисел в другом AVX регистре
- vzeroupper — обнуление старших 128 бит всех AVX регистров
- vzeroall — полное обнуление всех AVX регистров
- vinsertf128/vextractf128 — вставка/получение любой 128-битной части 256-битного AVX регистра
- vperm2f128 — перестановка 128-битных частей 256-битного AVX регистра. Параметр перестановки задаётся статически.
- vpermilps/vpermilpd — перестановка float/double чисел внутри 128-битных частей 256-битного AVX регистра. При этом параметры перестановки берутся из другого AVX регистра.
- vldmxcsr/vstmxcsr — загрузка/сохранение управляющих параметров AVX (куда ж без этого!)
- xsaveopt — получение подсказки о том, какие AVX-регистры содержат данные. Эта команда сделана для разработчиков ОС и помогает им ускорить переключение контекста.
Использование AVX в ассемблерном коде
На сегодня AVX поддерживается всеми популярными ассемблерами для x86:
- GAS (GNU Assembler) — начиная с версии binutils 2.19.50.0.1, но лучше использовать 2.19.51.0.1, которая поддерживает более позднюю спецификацию AVX
- MASM — начиная с версии 10 (входит в Visual Studio 2010)
- NASM — начиная с версии 2.03, но лучше использовать последнюю версию
- YASM — начиная с версии 0.70, но лучше использовать последнюю версию
Определение поддержки AVX системой
Первое, что нужно сделать перед использованием AVX — убедиться, что система его поддерживает. В отличие от разных версий SSE, для использования AVX требуется его поддержка не только процессором, но и операционной системой (ведь она должна теперь сохранять верхние 128-бит AVX регистров при переключении контекста). К счастью, разработчики AVX предусмотрели способ узнать о поддержке этого набора инструкций операционной системой. ОС сохраняет/восстанавливает контекст AVX с помощью специальных инструкций XSAVE/XRSTOR, а конфигурируются эти команды с помощью расширенных контрольных регистров (extended control register). На сегодня есть только один такой регистр — XCR0, он же XFEATURE_ENABLED_MASK. Получить его значение можно, записав в ecx номер регистра (для XCR0 это, естественно, 0) и вызвав команду XGETBV. 64-битное значение регистра будет сохранено в паре регистров edx:eax. Выставленный нулевой бит регистра XFEATURE_ENABLED_MASK означает, что команда XSAVE сохраняет состояние FPU-регистров (впрочем, этот бит всегда выставлен), выставленный первый бит — сохранение SSE-регистров (младшие 128 бит AVX регистра), а выставленный второй бит — сохранение старших 128 бит AVX регистра. Т.о. чтобы быть уверенным, что система сохраняет состояние AVX регистров при переключении контекстов, нужно убедиться, что в регистре XFEATURE_ENABLED_MASK выставлены биты 1 и 2. Однако, это ещё не всё: прежде, чем вызывать команду XGETBV, нужно убедиться, что ОС действительно использует инструкции XSAVE/XRSTOR для управления контекстами. Делается это с помощью вызова инструкции CPUID с параметром eax = 1: если ОС включила управление сохранением/восстановлением контекста с помощью инструкций XSAVE/XRSTOR, то после выполениния CPUID в 27-ом бите регистра ecx будет единица. Вдобавок, неплохо бы проверить, что сам процессор поддерживает набор инструкций AVX. Делается это аналогично: вызвать CPUID с eax = 1 и убедиться, что после этого в 28-ом бите регистра ecx находится единица. Всё вышесказанное можно выразить следующим кодом (скопированном, с небольшими изменениями, из Intel AVX Reference):
; extern "C" int isAvxSupported()
_isAvxSupported:
xor eax, eax
cpuid
cmp eax, 1 ; Поддерживает ли CPUID параметр eax = 1?
jb not_supported
mov eax, 1
cpuid
and ecx, 018000000h ; Проверяем, что установлены биты 27 (ОС использует XSAVE/XRSTOR)
cmp ecx, 018000000h ; и 28 (поддержка AVX процессором)
jne not_supported
xor ecx, ecx ; Номер регистра XFEATURE_ENABLED_MASK/XCR0 есть 0
xgetbv ; Регистр XFEATURE_ENABLED_MASK теперь в edx:eax
and eax, 110b
cmp eax, 110b ; Убеждаемся, что ОС сохраняет AVX регистры при переключении контекста
jne not_supported
mov eax, 1
ret
not_supported:
xor eax, eax
ret
Использование AVX-инструкций
Теперь, когда вы знаете, когда можно использовать AVX-инструкции, самое время перейти к их использованию. Программирование под AVX мало отличается от программирования под другие наборы инструкций, но нужно учесть следующие особенности:
- Крайне нежелательно смешивать SSE- и AVX-инструкции (в том числе AVX-аналоги SSE-инструкций). Чтобы перейти от выполнения AVX-инструкций к SSE-инструкциям процессор сохраняет в специальном кэше верхние 128 бит AVX регистров, на что может уйти полсотни тактов. Когда после SSE-инструкций процессор снова вернётся к выполнению AVX-инструкций, он восстановит верхние 128 бит AVX регистров, на что уйдёт ещё полсотни тактов. Поэтому смешивание SSE и AVX инструкций приведёт к заметному снижению производительности. Если вам нужна какая-то команда из SSE в AVX-коде, воспользуйтесь её AVX-аналогом с префиксом v.
- Сохранения верхней части AVX регистров при переходе к SSE-коду можно избежать, если занулить верхние 128 бит AVX регистров с помощью команды vzeroupper или vzeroall. Несмотря на то, что эти команды зануляют все AVX регистры, они работают очень быстро. Правилом хорошего тона будет использовать одну из этих команд перед выходом из подпрограммы, использующей AVX.
- Команды загрузки/сохранения выровненных данных vmovaps/vmovapd/vmovdqa требуют, чтобы данные были выровнены на 16 байт, даже если сама команда загружает 32 байта.
- На Windows x64 подпрограмма не должна изменять регистры xmm6-xmm15. Т.о., если вы используете эти регистры (или соответствующие им регистры ymm6-ymm15), вы должны сохранить их в стеке в начале подпрограммы и восстановить из стека перед выходом из подпрограммы.
- Ядро Sandy Bridge будет способно запускать на выполнение две 256-битные AVX-команды с плавающей точкой каждый такт (одно умножение и одно сложение) благодаря расширению исполнительных устройств до 256 бит. Ядро Bulldozer будет иметь два универсальных 128-битных исполнительных устройства для команд с плавающей точкой, что позволит ему выполнять одну 256-битную AVX-команду за такт (умножение, сложение либо совмещённое умножение и сложение (fused multiply-add); при использовании последней операции можно надеяться на такую же производительность, как и у Sandy Bridge).
Теперь вы знаете всё, чтобы писать код с использованием AVX. Например, такой:
; extern "C" double _vec4_dot_avx( double a[4], double b[4] )
_vec4_dot_avx:
%ifdef X86
mov eax, [esp + 8 + 0] ; eax = a
mov edx, [esp + 8 + 8] ; edx = b
vmovupd ymm0, [eax] ; ymm0 = *a
vmovupd ymm1, [edx] ; ymm1 = *b
%else
vmovupd ymm0, [rcx] ; ymm0 = *a
vmovupd ymm1, [rdx] ; ymm1 = *b
%endif
vmulpd ymm0, ymm0, ymm1 ; ymm0 = ( a3 * b3, a2 * b2, a1 * b1, a0 * b0 )
vperm2f128 ymm1, ymm0, ymm0, 010000001b ; ymm1 = ( +0.0, +0.0, a3 * b3, a2 * b2 )
vaddpd xmm0, xmm0, xmm1 ; ymm0 = ( +0.0, +0.0, a1 * b1 + a3 * b3, a0 * b0 + a2 * b2 )
vxorpd xmm1, xmm1, xmm1 ; ymm1 = ( +0.0, +0.0, +0.0, +0.0 )
vhaddpd xmm0, xmm0, xmm1 ; ymm0 = ( +0.0, +0.0, +0.0, a0 * b0 + a1 * b1 + a2 * b2 + a3 * b3 )
%ifdef X86 ; На 32-битной архитектуре возвращаемые числа с плавающей точкой должны быть в st(0)
sub esp, 8
vmovsd [esp], xmm0
vzeroall ; Содержимое SSE-регистров не важно: зануляем полностью
fld qword [esp]
add esp, 8
%else
vzeroupper ; В xmm0 содержится возвращаемое значение, поэтому зануляем только верхние 128 бит
%endif
ret
Тестирование AVX кода
Чтобы убедиться в работоспособности AVX кода лучше написать к нему Unit-тесты. Однако встаёт вопрос: как запустить эти Unit-тесты, если ни один ныне продаваемый процессор не поддерживает AVX? В этом вам поможет специальная утилита от Intel — Software Development Emulator (SDE). Всё, что умеет SDE — это запускать программы, на лету эмулируя новые наборы инструкций. Разумеется, производительность при этом будет далека от таковой на реальном железе, но проверить корректность работы программы таким образом можно. Использовать SDE проще простого: если у вас есть unit-тест для AVX кода в файле avx-unit-test.exe и его нужно запускать с параметром «Hello, AVX!», то вам просто нужно запустить SDE с параметрами
sde -- avx-unit-test.exe "Hello, AVX!"
При запуске программы SDE сэмулирует не только AVX инструкции, но также и инструкции XGETBV и CPUID, так что если вы используете предложенный ранее метод для детектирования поддержки AVX, запущенная под SDE программа решит, что AVX действительно поддерживается. Кроме AVX, SDE (вернее, JIT-компилятор pin, на котором SDE построен) умеет эмулировать SSE3, SSSE3, SSE4.1, SSE4.2, SSE4a, AES-NI, XSAVE, POPCNT и PCLMULQDQ инструкции, так что даже очень старый процессор не помешает вам разрабатывать софт под новые наборы инструкций.
Оценка производительности AVX кода
Некоторое представление о производительности AVX кода можно получить с помощью другой утилиты от Intel — Intel Architecture Code Analyzer (IACA). IACA позволяет оценить время выполнения линейного участка кода (если встречаются команды условных переходов, IACA считает, что переход не происходит). Чтобы использовать IACA, нужно сначала пометить специальными маркерами участки кода, которые вы хотите проанализировать. Маркеры выглядят следующим образом:
; Начало участка кода, который надо проанализировать
%macro IACA_START 0
mov ebx, 111
db 0x64, 0x67, 0x90
%endmacro
; Конец участка кода, который надо проанализировать
%macro IACA_END 0
mov ebx, 222
db 0x64, 0x67, 0x90
%endmacro
Теперь следует окружить этими макросами тот участок кода, который вы хотите проанализировать
IACA_START
vmovups ymm0, [ecx]
vbroadcastss ymm1, [edx]
vmulps ymm0, ymm0, ymm1
vmovups [ecx], ymm0
vzeroupper
IACA_END
Скомпилированный с этими макросами объектный файл нужно скормить IACA:
iaca -32 -arch AVX -cp DATA_DEPENDENCY -mark 0 -o avx-sample.txt avx-sample.obj
Параметры для IACA нужно понимать так
- -32 — означает, что входной объектный файл (MS COFF) содержит 32-битный код. Для 64-битного кода нужно указывать -64. Если на вход IACA подаётся не объектный файл (.obj), а исполняемый модуль (.exe или .dll), то этот аргумент можно не указывать.
- -arch AVX — показывает IACA, что нужно анализировать производительность этого кода на будущем процессоре Intel с поддержкой AVX (т.е. Sandy Bridge). Другие возможные значения: -arch nehalem и -arch westmere.
- -cp DATA_DEPENDENCY просит IACA показать, какие инструкции находятся на критическом путе для данных (т.е. какие инструкции нужно соптимизировать, чтобы результат работы этого кода вычислялся быстрее). Другое возможное значение: -cp PERFORMANCE просит IACA показать, какие инструкции «затыкают» конвеер процессора.
- -mark 0 говорит IACA проанализировать все помеченные маркерами участки кода. Если задать -mark n, IACA будет анализировать только n-ый размеченный участок кода.
- -o avx-sample задаёт имя файла, в который будут записаны результаты анализа. Можно опустить этот параметр, тогда результаты анализа будут выведены в консоль.
Результат запуска IACA приведён ниже:
Intel(R) Architecture Code Analyzer Version - 1.1.3
Analyzed File - avx-sample.obj
Binary Format - 32Bit
Architecture - Intel(R) AVX
*******************************************************************
Intel(R) Architecture Code Analyzer Mark Number 1
*******************************************************************
Analysis Report
---------------
Total Throughput: 2 Cycles; Throughput Bottleneck: FrontEnd, Port2_ALU, Port2_DATA, Port4
Total number of Uops bound to ports: 6
Data Dependency Latency: 14 Cycles; Performance Latency: 15 Cycles
Port Binding in cycles:
-------------------------------------------------------
| Port | 0 - DV | 1 | 2 - D | 3 - D | 4 | 5 |
-------------------------------------------------------
| Cycles | 1 | 0 | 0 | 2 | 2 | 1 | 1 | 2 | 1 |
-------------------------------------------------------
N - port number, DV - Divider pipe (on port 0), D - Data fetch pipe (on ports 2 and 3)
CP - on a critical Data Dependency Path
N - number of cycles port was bound
X - other ports that can be used by this instructions
F - Macro Fusion with the previous instruction occurred
^ - Micro Fusion happened
* - instruction micro-ops not bound to a port
@ - Intel(R) AVX to Intel(R) SSE code switch, dozens of cycles penalty is expected
! - instruction not supported, was not accounted in Analysis
| Num of | Ports pressure in cycles | |
| Uops | 0 - DV | 1 | 2 - D | 3 - D | 4 | 5 | |
------------------------------------------------------------
| 1 | | | | 1 | 2 | X | X | | | CP | vmovups ymm0, ymmword ptr [ecx]
| 2^ | | | | X | X | 1 | 1 | | 1 | | vbroadcastss ymm1, dword ptr [edx]
| 1 | 1 | | | | | | | | | CP | vmulps ymm0, ymm0, ymm1
| 2^ | | | | 1 | | X | | 2 | | CP | vmovups ymmword ptr [ecx], ymm0
| 0* | | | | | | | | | | | vzeroupper
Самыми важными метриками здесь являются Total Throughput и Data Dependency Latency. Если код, который вы оптимизируете, это небольшая подпрограмма, и в программе есть зависимость по данным от её результата, то вам нужно стараться сделать Data Dependency Latency как можно меньше. В качестве примера может служить приведённый выше листинг подпрограммы vec4_dot_avx. Если же оптимизируемый код — это часть цикла, обрабатывающего большой массив элементов, то ваша задача — уменьшать Total Throughput (вообще-то эта метрика должна была бы называться Reciprocal Throughput, ну да ладно).
Использование AVX в коде на C/C++
Поддержка AVX реализована в следующих популярных компиляторах:
- Microsoft C/C++ Compiler начиная с версии 16 (входит в Visual Studio 2010)
- Intel C++ Compiler начиная с версии 11.1
- GCC начиная с версии 4.4
Для использования 256-битных инструкций AVX в дистрибутив этих компиляторов включен новый заголовочный файл immintrin.h с описанием соответствующих intrinsic-функций. Включение этого заголовочного файла автоматически влечёт за собой включение заголовочных файлов всех SSE-intrinsic’ов. Что касается 128-битных инструкций AVX, то для них нет ни только отдельных хидеров, но и отдельных intrinsics-функций. Вместо этого для них используются intrinsic-функции для SSEx-инструкций, а тип инструкций (SSE или AVX), в которые будут компилироваться вызовы этих intrinsic-функций задаётся в параметрах компилятора. Это означает, что смешать SSE и AVX формы 128-битных инструкций в одном компилируемом файле не получится, и если вы хотите иметь и SSE, и AVX версии функций, то вам придётся писать их в разных компилируемых файлах (и компилировать эти файлы с разными параметрами). Параметры компиляции, которые включают компиляцию SSEx intrinsic-функций в AVX инструкции следующие:
- /arch:AVX — для Microsoft C/C++ Compiler и Intel C++ Compiler под Windows
- -mavx — для GCC и Intel C++ Compiler под Linux
- /QxAVX — для Intel C++ Compiler
- /QaxAVX — для Intel C++ Compiler
Следует иметь в виду, что данные команды не только изменяют поведение SSEx intrinsic-функций, но и разрешают компилятору генерировать AVX инструкции при компиляции обычного C/C++ кода (/QaxAVX говорит Интеловскому компилятору сгенерировать две версии кода — с AVX инструкциями и с базовыми x86 инструкциями).
Чтобы со всеми этими intrinsic’ами было проще разобраться, Intel сделал интерактивный справочник — Intel Intrinsic Guide, который включает в себя описание всех intrinsic-функций, которые поддерживаются интеловскими процессорами. Для тех инструкций, которые уже реализованы в железе, указаны также latency и throughput. Скачать этот справочник можно с сайта Intel AVX (есть версии для Windows, Linux и Mac OS X).
Определение поддержки AVX системой
В принципе, для распознавания поддержки AVX системой можно использовать приведённый ранее ассемблерный код, переписав его на inline-ассемблере, либо просто прилинковав собранный ассемблером объектный файл. Однако, если использование inline-ассемблера невозможно (например, из-за coding guidelines, либо потому, что компилятор его не поддерживает, как в случае Microsoft C/C++ Compiler’а для Windows x64), то you are in deep shit. Проблема в том, что intrinsic-функции для инструкции xgetbv не существует! Таким образом, задача разбивается на две части: проверить, что процессор поддерживает AVX (это можно сделать кроссплатформенно) и проверить, что ОС поддерживает AVX (тут уж придётся писать свой код для каждой ОС).
Проверить, что процессор поддерживает AVX можно используя всё ту же инструкцию CPUID, для которой есть intrinsic-функция void __cpuid( int cpuInfo[4], int infoType ). Параметр infoType задаёт значение регистра eax перед вызовом CPUID, а cpuInfo после выполнения функции будет содежать регистры eax, ebx, ecx, edx (именно в таком порядке). Т.о. получаем следующий код:
int isAvxSupportedByCpu() {
int cpuInfo[4];
__cpuid( cpuInfo, 0 );
if( cpuInfo[0] != 0 ) {
__cpuid( cpuInfo, 1 );
return cpuInfo[3] & 0x10000000; // Возвращаем ноль, если 28-ой бит в ecx сброшен
} else {
return 0; // Процессор не поддерживает получение информации о поддерживаемых наборах инструкций
}
}
С поддержкой со стороны ОС сложнее. AVX на сегодня поддерживается следующими ОС:
- Windows 7
- Windows Server 2008 R2
- Linux с ядром 2.6.30 и выше
В Windows была добавлена возможность узнать о поддержке операционкой новых наборов инструкций в виде функции GetEnabledExtendedFeatures из kernel32.dll. К сожалению, эта функция документирована чуть менее, чем никак. Но кое-какую информацию о ней раздобыть всё же можно. Эта функция описана в файле WinBase.h из Platform SDK:
WINBASEAPI
DWORD64
WINAPI
GetEnabledExtendedFeatures(
__in DWORD64 FeatureMask
);
Значения для параметра FeatureMask можно найти в хидере WinNT.h:
//
// Known extended CPU state feature IDs
//
#define XSTATE_LEGACY_FLOATING_POINT 0
#define XSTATE_LEGACY_SSE 1
#define XSTATE_GSSE 2
#define XSTATE_MASK_LEGACY_FLOATING_POINT (1i64 << (XSTATE_LEGACY_FLOATING_POINT))
#define XSTATE_MASK_LEGACY_SSE (1i64 << (XSTATE_LEGACY_SSE))
#define XSTATE_MASK_LEGACY (XSTATE_MASK_LEGACY_FLOATING_POINT | XSTATE_MASK_LEGACY_SSE)
#define XSTATE_MASK_GSSE (1i64 << (XSTATE_GSSE))
#define MAXIMUM_XSTATE_FEATURES 64
Нетрудно заметить, что маски XSTATE_MASK_* соответствуют аналогичным битам регистра XFEATURE_ENABLED_MASK.
В дополнение к этому, в Windows DDK есть описание функции RtlGetEnabledExtendedFeatures и констант XSTATE_MASK_XXX, как две капли воды похожих на GetEnabledExtendedFeatures и XSTATE_MASK_* из WinNT.h. Т.о. для определения поддержки AVX со стороны Windows можно воспользоваться следующим кодом:
int isAvxSupportedByWindows() {
const DWORD64 avxFeatureMask = XSTATE_MASK_LEGACY_SSE | XSTATE_MASK_GSSE;
return GetEnabledExtendedFeatures( avxFeatureMask ) == avxFeatureMask;
}
Если ваша программа должна работать не только в Windows 7 и Windows 2008 R2, то функцию GetEnabledExtendedFeatures нужно подгружать динамически из kernel32.dll, т.к. в других версиях Windows этой функции нет.
В Linux, насколько мне известно, нет отдельной функции, чтобы узнать о поддержке AVX со стороны ОС. Но вы можете воспользоваться тем фактом, что поддержка AVX было добавлена в ядро 2.6.30. Тогда остаётся только проверить, что версия ядра не меньше этого значения. Узнать версию ядра можно с помощью функции uname.
Использование AVX-инструкций
Написание AVX-кода с использованием intrinsic-функций не вызовет у вас затруднений, если вы когда-либо использовали MMX или SSE посредством intrinsic’ов. Единственное, о чём нужно позаботиться дополнительно, это вызвать функцию _mm256_zeroupper() в конце подпрограммы (как нетрудно догадаться, эта intrinsic-функция генерирует инструкцию vzeroupper). Например, приведённая выше ассемблерная подпрограмма vec4_dot_avx может быть переписана на intrinsic’ах так:
double vec4_dot_avx( double a[4], double b[4] ) {
// mmA = a
const __m256d mmA = _mm256_loadu_pd( a );
// mmB = b
const __m256d mmB = _mm256_loadu_pd( b );
// mmAB = ( a3 * b3, a2 * b2, a1 * b1, a0 * b0 )
const __m256d mmAB = _mm256_mul_pd( mmA, mmB );
// mmABHigh = ( +0.0, +0.0, a3 * b3, a2 * b2 )
const __m256d mmABHigh = _mm256_permute2f128_pd( mmAB, mmAB, 0x81 );
// mmSubSum = ( +0.0, +0.0, a1 * b1 + a3 * b3, a0 * b0 + a2 * b2 )
const __m128d mmSubSum = _mm_add_pd(
_mm256_castpd256_pd128( mmAB ),
_mm256_castpd256_pd128( mmABHigh )
);
// mmSum = ( +0.0, +0.0, +0.0, a0 * b0 + a1 * b1 + a2 * b2 + a3 * b3 )
const __m128d mmSum = _mm_hadd_pd( mmSubSum, _mm_setzero_pd() );
const double result = _mm_cvtsd_f64( mmSum );
_mm256_zeroupper();
return result;
}
Тестирование AVX кода
Если вы используете набор инструкций AVX посредством intrinsic-функций, то, кроме запуска этого кода под эмулятором SDE, у вас есть ещё одна возможность — использовать специальный заголовочный файл, эмулирующий 256-битные AVX intrinsic-функции через intrinsic-функции SSE1-SSE4.2. В этом случае у вас получится исполняемый файл, который можно запустить на процессорах Nehalem и Westmere, что, конечно, быстрее эмулятора. Однако учтите, что таким методом не получиться обнаружить ошибки генерации AVX-кода компилятором (а они вполне могут быть).
Оценка производительности AVX кода
Использование IACA для анализа производительности AVX кода, созданного C/C++ компилятором из intrinsic-функций почти ничем не отличается от анализа ассемблерного кода. В дистрибутиве IACA можно найти заголовочный файл iacaMarks.h, в котором описаны макросы-маркеры IACA_START и IACA_END. Ими нужно пометить анализируемые участки кода. В коде подпрограммы маркер IACA_END должен находиться до оператора return, иначе компилятор «соптимизирует», выкинув код маркера. Макросы IACA_START/IACA_END используют inline-ассемблер, который не поддерживается Microsoft C/C++ Compiler для Windows x64, поэтому если для него нужно использовать специальные варианты макросов — IACA_VC64_START и IACA_VC64_END.
Заключение
В этой статье было продемонстрировано, как разрабатывать программы с использованием набора инструкций AVX. Надеюсь, что это знание поможет вам радовать своих пользователей программами, которые используют возможности компьютера на все сто процентов!
Упражнение
Приведённый код подпрограммы vec4_dot_avx не является оптимальным с точки зрения производительности. Попробуйте переписать её более оптимально. Какая у вас получалась Data Dependency Latency?
AVX (Advanced Vector Extensions) — это набор инструкций, разработанных компанией Intel, который предназначен для ускорения выполнения операций с векторными данными. Векторные данные представляют собой набор элементов, которые могут быть обработаны одновременно с помощью одной инструкции. Это особенно полезно для задач, которые требуют обработки больших объемов данных параллельно.
Основные характеристики Intel AVX:
1. Ширина вектора: Intel AVX позволяет обрабатывать векторы с шириной 256 бит. Это означает, что каждая инструкция может обрабатывать одновременно 8 элементов по 32 бита или 4 элемента по 64 бита. Ширина вектора увеличивает производительность, так как позволяет выполнять операции над несколькими данными одновременно.
2. Поддержка различных типов данных: Intel AVX поддерживает операции над различными типами данных, включая целочисленные, с плавающей запятой и даже операции смешанных типов данных. Это позволяет эффективно обрабатывать широкий спектр задач, включая математические вычисления, обработку изображений, аудио и видео.
3. Улучшенные инструкции: Intel AVX включает в себя множество новых инструкций, которые расширяют возможности процессора. Некоторые из них включают инструкции для выполнения сложных математических операций, операций с плавающей запятой, обработки строковых данных, обработки данных в формате двоично-полиномиального кода (BCH) и других.
4. Повышение производительности: Использование Intel AVX позволяет значительно увеличить производительность при выполнении операций с векторными данными. Это особенно полезно для задач, которые могут быть распараллелены и выполняются одновременно над большим количеством данных. Процессоры с поддержкой Intel AVX могут значительно ускорить выполнение задач, таких как обработка изображений и видео, научные вычисления, симуляции и другие.
5. Обратная совместимость: Intel AVX обеспечивает обратную совместимость с предыдущими версиями SSE (Streaming SIMD Extensions). Это означает, что программы, написанные для SSE, могут использовать инструкции Intel AVX без изменений. Это позволяет программистам постепенно внедрять и оптимизировать свои приложения для использования Intel AVX, не изменяя существующий код.
Технологии современных процессоров: AVX2 (часть 3)
Пройдите тест, узнайте какой профессии подходите
При использовании TensorFlow, особенно после первоначальной установки, может возникнуть ситуация, когда при попытке запуска кода появляется следующее
Если хотите прокачаться в IT и освоить новую профессию с нуля, пройдите курсы онлайн-университета Skypro. Например, «Аналитик данных», «Инженер по тестированию», «Веб-разработчик». Программы актуальные, соответствуют требованиям работодателей к новичкам. Соберете портфолио и найдете высокооплачиваемую работу: в этом поможет центр карьеры.
При использовании TensorFlow, особенно после первоначальной установки, может возникнуть ситуация, когда при попытке запуска кода появляется следующее сообщение:
Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
Это сообщение хоть и звучит сложно, на самом деле не является ошибкой. AVX (Advanced Vector Extensions) и AVX2 — это расширения набора инструкций процессора, которые позволяют увеличить производительность при выполнении операций с векторами и матрицами.
Однако, бинарные файлы TensorFlow, которые можно скачать и установить, обычно не поддерживают эти инструкции. Это сделано для обеспечения совместимости с большим количеством процессоров, включая те, которые не поддерживают AVX и AVX2.
В результате, при запуске кода TensorFlow на процессоре, который поддерживает AVX или AVX2, появляется упомянутое сообщение. Оно просто информирует, что TensorFlow может работать быстрее, если бы был скомпилирован с поддержкой этих инструкций.
Для того чтобы TensorFlow использовал AVX и AVX2, необходимо его скомпилировать из исходного кода с соответствующими параметрами. Это немного сложнее, чем просто скачать и установить готовый пакет, и может потребовать некоторых знаний и опыта работы с компиляторами.
Однако, важно отметить, что использование AVX и AVX2 может привести к незначительному увеличению производительности. В большинстве случаев разница в скорости работы не будет заметна. Поэтому, если не требуется максимальная производительность, можно просто игнорировать это сообщение.
Пройдите обучение IT-профессиям с нуля с гарантией новой работы в онлайн-университете Skypro. В программах курсов — только актуальная информация и навыки, которые ценятся работодателями. Все гарантии честно прописаны в договоре. Средняя зарплата выпускников — 72 000 ₽, а специалисты центра карьеры будут сопровождать до тех пор, пока вы не найдете работу по новой профессии.
