Parallel Thread Execution ISA Version 8.5
The programming guide to using PTX (Parallel Thread Execution) and ISA (Instruction Set Architecture).
1. Introduction
This document describes PTX, a low-level parallel thread execution virtual machine and instruction set architecture (ISA). PTX exposes the GPU as a data-parallel computing device.
1.1. Scalable Data-Parallel Computing using GPUs
Driven by the insatiable market demand for real-time, high-definition 3D graphics, the programmable GPU has evolved into a highly parallel, multithreaded, many-core processor with tremendous computational horsepower and very high memory bandwidth. The GPU is especially well-suited to address problems that can be expressed as data-parallel computations - the same program is executed on many data elements in parallel - with high arithmetic intensity - the ratio of arithmetic operations to memory operations. Because the same program is executed for each data element, there is a lower requirement for sophisticated flow control; and because it is executed on many data elements and has high arithmetic intensity, the memory access latency can be hidden with calculations instead of big data caches.
Data-parallel processing maps data elements to parallel processing threads. Many applications that process large data sets can use a data-parallel programming model to speed up the computations. In 3D rendering large sets of pixels and vertices are mapped to parallel threads. Similarly, image and media processing applications such as post-processing of rendered images, video encoding and decoding, image scaling, stereo vision, and pattern recognition can map image blocks and pixels to parallel processing threads. In fact, many algorithms outside the field of image rendering and processing are accelerated by data-parallel processing, from general signal processing or physics simulation to computational finance or computational biology.
PTX defines a virtual machine and ISA for general purpose parallel thread execution. PTX programs are translated at install time to the target hardware instruction set. The PTX-to-GPU translator and driver enable NVIDIA GPUs to be used as programmable parallel computers.
1.2. Goals of PTX
PTX provides a stable programming model and instruction set for general purpose parallel programming. It is designed to be efficient on NVIDIA GPUs supporting the computation features defined by the NVIDIA Tesla architecture. High level language compilers for languages such as CUDA and C/C++ generate PTX instructions, which are optimized for and translated to native target-architecture instructions.
The goals for PTX include the following:
Provide a stable ISA that spans multiple GPU generations.
Achieve performance in compiled applications comparable to native GPU performance.
Provide a machine-independent ISA for C/C++ and other compilers to target.
Provide a code distribution ISA for application and middleware developers.
Provide a common source-level ISA for optimizing code generators and translators, which map PTX to specific target machines.
Facilitate hand-coding of libraries, performance kernels, and architecture tests.
Provide a scalable programming model that spans GPU sizes from a single unit to many parallel units.
1.3. PTX ISA Version 8.5
PTX ISA version 8.5 introduces the following new features:
Adds support for
mma.sp::ordered_metadata
instruction.
1.4. Document Structure
The information in this document is organized into the following Chapters:
Programming Model outlines the programming model.
PTX Machine Model gives an overview of the PTX virtual machine model.
Syntax describes the basic syntax of the PTX language.
State Spaces, Types, and Variables describes state spaces, types, and variable declarations.
Instruction Operands describes instruction operands.
Abstracting the ABI describes the function and call syntax, calling convention, and PTX support for abstracting the Application Binary Interface (ABI).
Instruction Set describes the instruction set.
Special Registers lists special registers.
Directives lists the assembly directives supported in PTX.
Release Notes provides release notes for PTX ISA versions 2.x and beyond.
References
-
754-2008 IEEE Standard for Floating-Point Arithmetic. ISBN 978-0-7381-5752-8, 2008.
-
The OpenCL Specification, Version: 1.1, Document Revision: 44, June 1, 2011.
-
CUDA Programming Guide.
https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html
-
CUDA Dynamic Parallelism Programming Guide.
https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#cuda-dynamic-parallelism
-
CUDA Atomicity Requirements.
https://nvidia.github.io/cccl/libcudacxx/extended_api/memory_model.html#atomicity
-
PTX Writers Guide to Interoperability.
https://docs.nvidia.com/cuda/ptx-writers-guide-to-interoperability/index.html
2. Programming Model
2.1. A Highly Multithreaded Coprocessor
The GPU is a compute device capable of executing a very large number of threads in parallel. It operates as a coprocessor to the main CPU, or host: In other words, data-parallel, compute-intensive portions of applications running on the host are off-loaded onto the device.
More precisely, a portion of an application that is executed many times, but independently on different data, can be isolated into a kernel function that is executed on the GPU as many different threads. To that effect, such a function is compiled to the PTX instruction set and the resulting kernel is translated at install time to the target GPU instruction set.
2.2. Thread Hierarchy
The batch of threads that executes a kernel is organized as a grid. A grid consists of either cooperative thread arrays or clusters of cooperative thread arrays as described in this section and illustrated in Figure 1 and Figure 2. Cooperative thread arrays (CTAs) implement CUDA thread blocks and clusters implement CUDA thread block clusters.
2.2.1. Cooperative Thread Arrays
The Parallel Thread Execution (PTX) programming model is explicitly parallel: a PTX program specifies the execution of a given thread of a parallel thread array. A cooperative thread array, or CTA, is an array of threads that execute a kernel concurrently or in parallel.
Threads within a CTA can communicate with each other. To coordinate the communication of the threads within the CTA, one can specify synchronization points where threads wait until all threads in the CTA have arrived.
Each thread has a unique thread identifier within the CTA. Programs use a data parallel
decomposition to partition inputs, work, and results across the threads of the CTA. Each CTA thread
uses its thread identifier to determine its assigned role, assign specific input and output
positions, compute addresses, and select work to perform. The thread identifier is a three-element
vector tid
, (with elements tid.x
, tid.y
, and tid.z
) that specifies the thread’s
position within a 1D, 2D, or 3D CTA. Each thread identifier component ranges from zero up to the
number of thread ids in that CTA dimension.
Each CTA has a 1D, 2D, or 3D shape specified by a three-element vector ntid
(with elements
ntid.x
, ntid.y
, and ntid.z
). The vector ntid
specifies the number of threads in each
CTA dimension.
Threads within a CTA execute in SIMT (single-instruction, multiple-thread) fashion in groups called
warps. A warp is a maximal subset of threads from a single CTA, such that the threads execute
the same instructions at the same time. Threads within a warp are sequentially numbered. The warp
size is a machine-dependent constant. Typically, a warp has 32 threads. Some applications may be
able to maximize performance with knowledge of the warp size, so PTX includes a run-time immediate
constant, WARP_SZ
, which may be used in any instruction where an immediate operand is allowed.
2.2.2. Cluster of Cooperative Thread Arrays
Cluster is a group of CTAs that run concurrently or in parallel and can synchronize and communicate with each other via shared memory. The executing CTA has to make sure that the shared memory of the peer CTA exists before communicating with it via shared memory and the peer CTA hasn’t exited before completing the shared memory operation.
Threads within the different CTAs in a cluster can synchronize and communicate with each other via
shared memory. Cluster-wide barriers can be used to synchronize all the threads within the
cluster. Each CTA in a cluster has a unique CTA identifier within its cluster
(cluster_ctaid). Each cluster of CTAs has 1D, 2D or 3D shape specified by the parameter
cluster_nctaid. Each CTA in the cluster also has a unique CTA identifier (cluster_ctarank)
across all dimensions. The total number of CTAs across all the dimensions in the cluster is
specified by cluster_nctarank. Threads may read and use these values through predefined, read-only
special registers %cluster_ctaid
, %cluster_nctaid
, %cluster_ctarank
,
%cluster_nctarank
.
Cluster level is applicable only on target architecture sm_90
or higher. Specifying cluster
level during launch time is optional. If the user specifies the cluster dimensions at launch time
then it will be treated as explicit cluster launch, otherwise it will be treated as implicit cluster
launch with default dimension 1x1x1. PTX provides read-only special register
%is_explicit_cluster
to differentiate between explicit and implicit cluster launch.
2.2.3. Grid of Clusters
There is a maximum number of threads that a CTA can contain and a maximum number of CTAs that a cluster can contain. However, clusters with CTAs that execute the same kernel can be batched together into a grid of clusters, so that the total number of threads that can be launched in a single kernel invocation is very large. This comes at the expense of reduced thread communication and synchronization, because threads in different clusters cannot communicate and synchronize with each other.
Each cluster has a unique cluster identifier (clusterid) within a grid of clusters. Each grid of
clusters has a 1D, 2D , or 3D shape specified by the parameter nclusterid. Each grid also has a
unique temporal grid identifier (gridid). Threads may read and use these values through
predefined, read-only special registers %tid
, %ntid
, %clusterid
, %nclusterid
, and
%gridid
.
Each CTA has a unique identifier (ctaid) within a grid. Each grid of CTAs has 1D, 2D, or 3D shape
specified by the parameter nctaid. Thread may use and read these values through predefined,
read-only special registers %ctaid
and %nctaid
.
Each kernel is executed as a batch of threads organized as a grid of clusters consisting of CTAs
where cluster is optional level and is applicable only for target architectures sm_90
and
higher. Figure 1 shows a grid consisting of CTAs and
Figure 2 shows a grid consisting of clusters.
Grids may be launched with dependencies between one another - a grid may be a dependent grid and/or a prerequisite grid. To understand how grid dependencies may be defined, refer to the section on CUDA Graphs in the Cuda Programming Guide.
2.3. Memory Hierarchy
PTX threads may access data from multiple state spaces during their execution as illustrated by
Figure 3 where cluster level is introduced from
target architecture sm_90
onwards. Each thread has a private local memory. Each thread block
(CTA) has a shared memory visible to all threads of the block and to all active blocks in the
cluster and with the same lifetime as the block. Finally, all threads have access to the same global
memory.
There are additional state spaces accessible by all threads: the constant, param, texture, and surface state spaces. Constant and texture memory are read-only; surface memory is readable and writable. The global, constant, param, texture, and surface state spaces are optimized for different memory usages. For example, texture memory offers different addressing modes as well as data filtering for specific data formats. Note that texture and surface memory is cached, and within the same kernel call, the cache is not kept coherent with respect to global memory writes and surface memory writes, so any texture fetch or surface read to an address that has been written to via a global or a surface write in the same kernel call returns undefined data. In other words, a thread can safely read some texture or surface memory location only if this memory location has been updated by a previous kernel call or memory copy, but not if it has been previously updated by the same thread or another thread from the same kernel call.
The global, constant, and texture state spaces are persistent across kernel launches by the same application.
Both the host and the device maintain their own local memory, referred to as host memory and device memory, respectively. The device memory may be mapped and read or written by the host, or, for more efficient transfer, copied from the host memory through optimized API calls that utilize the device’s high-performance Direct Memory Access (DMA) engine.
3. PTX Machine Model
3.1. A Set of SIMT Multiprocessors
The NVIDIA GPU architecture is built around a scalable array of multithreaded Streaming Multiprocessors (SMs). When a host program invokes a kernel grid, the blocks of the grid are enumerated and distributed to multiprocessors with available execution capacity. The threads of a thread block execute concurrently on one multiprocessor. As thread blocks terminate, new blocks are launched on the vacated multiprocessors.
A multiprocessor consists of multiple Scalar Processor (SP) cores, a multithreaded instruction unit, and on-chip shared memory. The multiprocessor creates, manages, and executes concurrent threads in hardware with zero scheduling overhead. It implements a single-instruction barrier synchronization. Fast barrier synchronization together with lightweight thread creation and zero-overhead thread scheduling efficiently support very fine-grained parallelism, allowing, for example, a low granularity decomposition of problems by assigning one thread to each data element (such as a pixel in an image, a voxel in a volume, a cell in a grid-based computation).
To manage hundreds of threads running several different programs, the multiprocessor employs an architecture we call SIMT (single-instruction, multiple-thread). The multiprocessor maps each thread to one scalar processor core, and each scalar thread executes independently with its own instruction address and register state. The multiprocessor SIMT unit creates, manages, schedules, and executes threads in groups of parallel threads called warps. (This term originates from weaving, the first parallel thread technology.) Individual threads composing a SIMT warp start together at the same program address but are otherwise free to branch and execute independently.
When a multiprocessor is given one or more thread blocks to execute, it splits them into warps that get scheduled by the SIMT unit. The way a block is split into warps is always the same; each warp contains threads of consecutive, increasing thread IDs with the first warp containing thread 0.
At every instruction issue time, the SIMT unit selects a warp that is ready to execute and issues the next instruction to the active threads of the warp. A warp executes one common instruction at a time, so full efficiency is realized when all threads of a warp agree on their execution path. If threads of a warp diverge via a data-dependent conditional branch, the warp serially executes each branch path taken, disabling threads that are not on that path, and when all paths complete, the threads converge back to the same execution path. Branch divergence occurs only within a warp; different warps execute independently regardless of whether they are executing common or disjointed code paths.
SIMT architecture is akin to SIMD (Single Instruction, Multiple Data) vector organizations in that a single instruction controls multiple processing elements. A key difference is that SIMD vector organizations expose the SIMD width to the software, whereas SIMT instructions specify the execution and branching behavior of a single thread. In contrast with SIMD vector machines, SIMT enables programmers to write thread-level parallel code for independent, scalar threads, as well as data-parallel code for coordinated threads. For the purposes of correctness, the programmer can essentially ignore the SIMT behavior; however, substantial performance improvements can be realized by taking care that the code seldom requires threads in a warp to diverge. In practice, this is analogous to the role of cache lines in traditional code: Cache line size can be safely ignored when designing for correctness but must be considered in the code structure when designing for peak performance. Vector architectures, on the other hand, require the software to coalesce loads into vectors and manage divergence manually.
How many blocks a multiprocessor can process at once depends on how many registers per thread and how much shared memory per block are required for a given kernel since the multiprocessor’s registers and shared memory are split among all the threads of the batch of blocks. If there are not enough registers or shared memory available per multiprocessor to process at least one block, the kernel will fail to launch.
A set of SIMT multiprocessors with on-chip shared memory.
3.2. Independent Thread Scheduling
On architectures prior to Volta, warps used a single program counter shared amongst all 32 threads in the warp together with an active mask specifying the active threads of the warp. As a result, threads from the same warp in divergent regions or different states of execution cannot signal each other or exchange data, and algorithms requiring fine-grained sharing of data guarded by locks or mutexes can easily lead to deadlock, depending on which warp the contending threads come from.
Starting with the Volta architecture, Independent Thread Scheduling allows full concurrency between threads, regardless of warp. With Independent Thread Scheduling, the GPU maintains execution state per thread, including a program counter and call stack, and can yield execution at a per-thread granularity, either to make better use of execution resources or to allow one thread to wait for data to be produced by another. A schedule optimizer determines how to group active threads from the same warp together into SIMT units. This retains the high throughput of SIMT execution as in prior NVIDIA GPUs, but with much more flexibility: threads can now diverge and reconverge at sub-warp granularity.
Independent Thread Scheduling can lead to a rather different set of threads participating in the executed code than intended if the developer made assumptions about warp-synchronicity of previous hardware architectures. In particular, any warp-synchronous code (such as synchronization-free, intra-warp reductions) should be revisited to ensure compatibility with Volta and beyond. See the section on Compute Capability 7.x in the Cuda Programming Guide for further details.
4. Syntax
PTX programs are a collection of text source modules (files). PTX source modules have an assembly-language style syntax with instruction operation codes and operands. Pseudo-operations specify symbol and addressing management. The ptxas optimizing backend compiler optimizes and assembles PTX source modules to produce corresponding binary object files.
4.1. Source Format
Source modules are ASCII text. Lines are separated by the newline character (\n
).
All whitespace characters are equivalent; whitespace is ignored except for its use in separating tokens in the language.
The C preprocessor cpp may be used to process PTX source modules. Lines beginning with #
are
preprocessor directives. The following are common preprocessor directives:
#include
, #define
, #if
, #ifdef
, #else
, #endif
, #line
, #file
C: A Reference Manual by Harbison and Steele provides a good description of the C preprocessor.
PTX is case sensitive and uses lowercase for keywords.
Each PTX module must begin with a .version
directive specifying the PTX language version,
followed by a .target
directive specifying the target architecture assumed. See PTX Module
Directives for a more information on these directives.
4.3. Statements
A PTX statement is either a directive or an instruction. Statements begin with an optional label and end with a semicolon.
Examples
.reg .b32 r1, r2;
.global .f32 array[N];
start: mov.b32 r1, %tid.x;
shl.b32 r1, r1, 2; // shift thread id by 2 bits
ld.global.b32 r2, array[r1]; // thread[tid] gets array[tid]
add.f32 r2, r2, 0.5; // add 1/2
4.3.1. Directive Statements
Directive keywords begin with a dot, so no conflict is possible with user-defined identifiers. The directives in PTX are listed in Table 1 and described in State Spaces, Types, and Variables and Directives.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4.3.2. Instruction Statements
Instructions are formed from an instruction opcode followed by a comma-separated list of zero or
more operands, and terminated with a semicolon. Operands may be register variables, constant
expressions, address expressions, or label names. Instructions have an optional guard predicate
which controls conditional execution. The guard predicate follows the optional label and precedes
the opcode, and is written as @p
, where p
is a predicate register. The guard predicate may
be optionally negated, written as @!p
.
The destination operand is first, followed by source operands.
Instruction keywords are listed in Table 2. All instruction keywords are reserved tokens in PTX.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4.4. Identifiers
User-defined identifiers follow extended C++ rules: they either start with a letter followed by zero or more letters, digits, underscore, or dollar characters; or they start with an underscore, dollar, or percentage character followed by one or more letters, digits, underscore, or dollar characters:
followsym: [a-zA-Z0-9_$]
identifier: [a-zA-Z]{followsym}* | {[_$%]{followsym}+
PTX does not specify a maximum length for identifiers and suggests that all implementations support a minimum length of at least 1024 characters.
Many high-level languages such as C and C++ follow similar rules for identifier names, except that the percentage sign is not allowed. PTX allows the percentage sign as the first character of an identifier. The percentage sign can be used to avoid name conflicts, e.g., between user-defined variable names and compiler-generated names.
PTX predefines one constant and a small number of special registers that begin with the percentage sign, listed in Table 3.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4.5. Constants
PTX supports integer and floating-point constants and constant expressions. These constants may be
used in data initialization and as operands to instructions. Type checking rules remain the same for
integer, floating-point, and bit-size types. For predicate-type data and instructions, integer
constants are allowed and are interpreted as in C, i.e., zero values are False
and non-zero
values are True
.
4.5.1. Integer Constants
Integer constants are 64-bits in size and are either signed or unsigned, i.e., every integer
constant has type .s64
or .u64
. The signed/unsigned nature of an integer constant is needed
to correctly evaluate constant expressions containing operations such as division and ordered
comparisons, where the behavior of the operation depends on the operand types. When used in an
instruction or data initialization, each integer constant is converted to the appropriate size based
on the data or instruction type at its use.
Integer literals may be written in decimal, hexadecimal, octal, or binary notation. The syntax
follows that of C. Integer literals may be followed immediately by the letter U
to indicate that
the literal is unsigned.
hexadecimal literal: 0[xX]{hexdigit}+U?
octal literal: 0{octal digit}+U?
binary literal: 0[bB]{bit}+U?
decimal literal {nonzero-digit}{digit}*U?
Integer literals are non-negative and have a type determined by their magnitude and optional type
suffix as follows: literals are signed (.s64
) unless the value cannot be fully represented in
.s64
or the unsigned suffix is specified, in which case the literal is unsigned (.u64
).
The predefined integer constant WARP_SZ
specifies the number of threads per warp for the target
platform; to date, all target architectures have a WARP_SZ
value of 32.
4.5.2. Floating-Point Constants
Floating-point constants are represented as 64-bit double-precision values, and all floating-point constant expressions are evaluated using 64-bit double precision arithmetic. The only exception is the 32-bit hex notation for expressing an exact single-precision floating-point value; such values retain their exact 32-bit single-precision value and may not be used in constant expressions. Each 64-bit floating-point constant is converted to the appropriate floating-point size based on the data or instruction type at its use.
Floating-point literals may be written with an optional decimal point and an optional signed exponent. Unlike C and C++, there is no suffix letter to specify size; literals are always represented in 64-bit double-precision format.
PTX includes a second representation of floating-point constants for specifying the exact machine
representation using a hexadecimal constant. To specify IEEE 754 double-precision floating point
values, the constant begins with 0d
or 0D
followed by 16 hex digits. To specify IEEE 754
single-precision floating point values, the constant begins with 0f
or 0F
followed by 8 hex
digits.
0[fF]{hexdigit}{8} // single-precision floating point
0[dD]{hexdigit}{16} // double-precision floating point
Example
mov.f32 $f3, 0F3f800000; // 1.0
4.5.3. Predicate Constants
In PTX, integer constants may be used as predicates. For predicate-type data initializers and
instruction operands, integer constants are interpreted as in C, i.e., zero values are False
and
non-zero values are True
.
4.5.4. Constant Expressions
In PTX, constant expressions are formed using operators as in C and are evaluated using rules similar to those in C, but simplified by restricting types and sizes, removing most casts, and defining full semantics to eliminate cases where expression evaluation in C is implementation dependent.
Constant expressions are formed from constant literals, unary plus and minus, basic arithmetic
operators (addition, subtraction, multiplication, division), comparison operators, the conditional
ternary operator ( ?:
), and parentheses. Integer constant expressions also allow unary logical
negation (!
), bitwise complement (~
), remainder (%
), shift operators (<<
and
>>
), bit-type operators (&
, |
, and ^
), and logical operators (&&
, ||
).
Constant expressions in PTX do not support casts between integer and floating-point.
Constant expressions are evaluated using the same operator precedence as in C. Table 4 gives operator precedence and associativity. Operator precedence is highest for unary operators and decreases with each line in the chart. Operators on the same line have the same precedence and are evaluated right-to-left for unary operators and left-to-right for binary operators.
Kind |
Operator Symbols |
Operator Names |
Associates |
---|---|---|---|
Primary |
|
parenthesis |
n/a |
Unary |
|
plus, minus, negation, complement |
right |
|
casts |
right |
|
Binary |
|
multiplication, division, remainder |
left |
|
addition, subtraction |
||
|
shifts |
||
|
ordered comparisons |
||
|
equal, not equal |
||
|
bitwise AND |
||
|
bitwise XOR |
||
|
bitwise OR |
||
|
logical AND |
||
|
logical OR |
||
Ternary |
|
conditional |
right |
4.5.5. Integer Constant Expression Evaluation
Integer constant expressions are evaluated at compile time according to a set of rules that
determine the type (signed .s64
versus unsigned .u64
) of each sub-expression. These rules
are based on the rules in C, but they’ve been simplified to apply only to 64-bit integers, and
behavior is fully defined in all cases (specifically, for remainder and shift operators).
-
Literals are signed unless unsigned is needed to prevent overflow, or unless the literal uses a
U
suffix. For example:42
,0x1234
,0123
are signed.0xfabc123400000000
,42U
,0x1234U
are unsigned.
-
Unary plus and minus preserve the type of the input operand. For example:
+123
,-1
,-(-42)
are signed.-1U
,-0xfabc123400000000
are unsigned.
Unary logical negation (
!
) produces a signed result with value0
or1
.Unary bitwise complement (
~
) interprets the source operand as unsigned and produces an unsigned result.Some binary operators require normalization of source operands. This normalization is known as the usual arithmetic conversions and simply converts both operands to unsigned type if either operand is unsigned.
Addition, subtraction, multiplication, and division perform the usual arithmetic conversions and produce a result with the same type as the converted operands. That is, the operands and result are unsigned if either source operand is unsigned, and is otherwise signed.
Remainder (
%
) interprets the operands as unsigned. Note that this differs from C, which allows a negative divisor but defines the behavior to be implementation dependent.Left and right shift interpret the second operand as unsigned and produce a result with the same type as the first operand. Note that the behavior of right-shift is determined by the type of the first operand: right shift of a signed value is arithmetic and preserves the sign, and right shift of an unsigned value is logical and shifts in a zero bit.
AND (
&
), OR (|
), and XOR (^
) perform the usual arithmetic conversions and produce a result with the same type as the converted operands.AND_OP (
&&
), OR_OP (||
), Equal (==
), and Not_Equal (!=
) produce a signed result. The result value is 0 or 1.Ordered comparisons (
<
,<=
,>
,>=
) perform the usual arithmetic conversions on source operands and produce a signed result. The result value is0
or1
.Casting of expressions to signed or unsigned is supported using (
.s64
) and (.u64
) casts.For the conditional operator (
? :
) , the first operand must be an integer, and the second and third operands are either both integers or both floating-point. The usual arithmetic conversions are performed on the second and third operands, and the result type is the same as the converted type.
4.5.6. Summary of Constant Expression Evaluation Rules
Table 5 contains a summary of the constant expression evaluation rules.
Kind |
Operator |
Operand Types |
Operand Interpretation |
Result Type |
---|---|---|---|---|
Primary |
|
any type |
same as source |
same as source |
constant literal |
n/a |
n/a |
|
|
Unary |
|
any type |
same as source |
same as source |
|
integer |
zero or non-zero |
|
|
|
integer |
|
|
|
Cast |
|
integer |
|
|
|
integer |
|
|
|
Binary |
|
|
|
|
integer |
use usual conversions |
converted type |
||
|
|
|
|
|
integer |
use usual conversions |
|
||
|
|
|
|
|
integer |
use usual conversions |
|
||
|
integer |
|
|
|
|
integer |
1st unchanged, 2nd is |
same as 1st operand |
|
|
integer |
|
|
|
|
integer |
zero or non-zero |
|
|
Ternary |
|
|
same as sources |
|
|
use usual conversions |
converted type |
5. State Spaces, Types, and Variables
While the specific resources available in a given target GPU will vary, the kinds of resources will be common across platforms, and these resources are abstracted in PTX through state spaces and data types.
5.1. State Spaces
A state space is a storage area with particular characteristics. All variables reside in some state space. The characteristics of a state space include its size, addressability, access speed, access rights, and level of sharing between threads.
The state spaces defined in PTX are a byproduct of parallel programming and graphics programming. The list of state spaces is shown in Table 6,and properties of state spaces are shown in Table 7.
Name |
Description |
---|---|
|
Registers, fast. |
|
Special registers. Read-only; pre-defined; platform-specific. |
|
Shared, read-only memory. |
|
Global memory, shared by all threads. |
|
Local memory, private to each thread. |
|
Kernel parameters, defined per-grid; or Function or local parameters, defined per-thread. |
|
Addressable memory, defined per CTA, accessible to all threads in the cluster throughout the lifetime of the CTA that defines it. |
|
Global texture memory (deprecated). |
Name |
Addressable |
Initializable |
Access |
Sharing |
---|---|---|---|---|
|
No |
No |
R/W |
per-thread |
|
No |
No |
RO |
per-CTA |
|
Yes |
Yes1 |
RO |
per-grid |
|
Yes |
Yes1 |
R/W |
Context |
|
Yes |
No |
R/W |
per-thread |
|
Yes2 |
No |
RO |
per-grid |
|
Restricted3 |
No |
R/W |
per-thread |
|
Yes |
No |
R/W |
per-cluster5 |
|
No4 |
Yes, via driver |
RO |
Context |
Notes: 1 Variables in 2 Accessible only via the 3 Accessible via 4 Accessible only via the 5 Visible to the owning CTA and other active CTAs in the cluster. |
5.1.1. Register State Space
Registers (.reg
state space) are fast storage locations. The number of registers is limited, and
will vary from platform to platform. When the limit is exceeded, register variables will be spilled
to memory, causing changes in performance. For each architecture, there is a recommended maximum
number of registers to use (see the CUDA Programming Guide for details).
Registers may be typed (signed integer, unsigned integer, floating point, predicate) or
untyped. Register size is restricted; aside from predicate registers which are 1-bit, scalar
registers have a width of 8-, 16-, 32-, 64-, or 128-bits, and vector registers have a width of
16-, 32-, 64-, or 128-bits. The most common use of 8-bit registers is with ld
, st
, and cvt
instructions, or as elements of vector tuples.
Registers differ from the other state spaces in that they are not fully addressable, i.e., it is not
possible to refer to the address of a register. When compiling to use the Application Binary
Interface (ABI), register variables are restricted to function scope and may not be declared at
module scope. When compiling legacy PTX code (ISA versions prior to 3.0) containing module-scoped
.reg
variables, the compiler silently disables use of the ABI. Registers may have alignment
boundaries required by multi-word loads and stores.
5.1.2. Special Register State Space
The special register (.sreg
) state space holds predefined, platform-specific registers, such as
grid, cluster, CTA, and thread parameters, clock counters, and performance monitoring registers. All
special registers are predefined.
5.1.3. Constant State Space
The constant (.const
) state space is a read-only memory initialized by the host. Constant memory
is accessed with a ld.const
instruction. Constant memory is restricted in size, currently
limited to 64 KB which can be used to hold statically-sized constant variables. There is an
additional 640 KB of constant memory, organized as ten independent 64 KB regions. The driver may
allocate and initialize constant buffers in these regions and pass pointers to the buffers as kernel
function parameters. Since the ten regions are not contiguous, the driver must ensure that constant
buffers are allocated so that each buffer fits entirely within a 64 KB region and does not span a
region boundary.
Statically-sized constant variables have an optional variable initializer; constant variables with no explicit initializer are initialized to zero by default. Constant buffers allocated by the driver are initialized by the host, and pointers to such buffers are passed to the kernel as parameters. See the description of kernel parameter attributes in Kernel Function Parameter Attributes for more details on passing pointers to constant buffers as kernel parameters.
5.1.3.1. Banked Constant State Space (deprecated)
Previous versions of PTX exposed constant memory as a set of eleven 64 KB banks, with explicit bank numbers required for variable declaration and during access.
Prior to PTX ISA version 2.2, the constant memory was organized into fixed size banks. There were
eleven 64 KB banks, and banks were specified using the .const[bank]
modifier, where bank
ranged from 0 to 10. If no bank number was given, bank zero was assumed.
By convention, bank zero was used for all statically-sized constant variables. The remaining banks were used to declare incomplete constant arrays (as in C, for example), where the size is not known at compile time. For example, the declaration
.extern .const[2] .b32 const_buffer[];
resulted in const_buffer
pointing to the start of constant bank two. This pointer could then be
used to access the entire 64 KB constant bank. Multiple incomplete array variables declared in the
same bank were aliased, with each pointing to the start address of the specified constant bank.
To access data in contant banks 1 through 10, the bank number was required in the state space of the load instruction. For example, an incomplete array in bank 2 was accessed as follows:
.extern .const[2] .b32 const_buffer[];
ld.const[2].b32 %r1, [const_buffer+4]; // load second word
In PTX ISA version 2.2, we eliminated explicit banks and replaced the incomplete array representation of driver-allocated constant buffers with kernel parameter attributes that allow pointers to constant buffers to be passed as kernel parameters.
5.1.4. Global State Space
The global (.global
) state space is memory that is accessible by all threads in a context. It is
the mechanism by which threads in different CTAs, clusters, and grids can communicate. Use
ld.global
, st.global
, and atom.global
to access global variables.
Global variables have an optional variable initializer; global variables with no explicit initializer are initialized to zero by default.
5.1.5. Local State Space
The local state space (.local
) is private memory for each thread to keep its own data. It is
typically standard memory with cache. The size is limited, as it must be allocated on a per-thread
basis. Use ld.local
and st.local
to access local variables.
When compiling to use the Application Binary Interface (ABI), .local
state-space variables
must be declared within function scope and are allocated on the stack. In implementations that do
not support a stack, all local memory variables are stored at fixed addresses, recursive function
calls are not supported, and .local
variables may be declared at module scope. When compiling
legacy PTX code (ISA versions prior to 3.0) containing module-scoped .local
variables, the
compiler silently disables use of the ABI.
5.1.6. Parameter State Space
The parameter (.param
) state space is used (1) to pass input arguments from the host to the
kernel, (2a) to declare formal input and return parameters for device functions called from within
kernel execution, and (2b) to declare locally-scoped byte array variables that serve as function
call arguments, typically for passing large structures by value to a function. Kernel function
parameters differ from device function parameters in terms of access and sharing (read-only versus
read-write, per-kernel versus per-thread). Note that PTX ISA versions 1.x supports only kernel
function parameters in .param space; device function parameters were previously restricted to the
register state space. The use of parameter state space for device function parameters was introduced
in PTX ISA version 2.0 and requires target architecture sm_20
or higher. Additional sub-qualifiers
::entry
or ::func
can be specified on instructions with .param
state space to indicate
whether the address refers to kernel function parameter or device function parameter. If no
sub-qualifier is specified with the .param
state space, then the default sub-qualifier is specific
to and dependent on the exact instruction. For example, st.param
is equivalent to st.param::func
whereas isspacep.param
is equivalent to isspacep.param::entry
. Refer to the instruction
description for more details on default sub-qualifier assumption.
Note
The location of parameter space is implementation specific. For example, in some implementations
kernel parameters reside in global memory. No access protection is provided between parameter and
global space in this case. Though the exact location of the kernel parameter space is
implementation specific, the kernel parameter space window is always contained within the global
space window. Similarly, function parameters are mapped to parameter passing registers and/or
stack locations based on the function calling conventions of the Application Binary Interface
(ABI). Therefore, PTX code should make no assumptions about the relative locations or ordering
of .param
space variables.
5.1.6.1. Kernel Function Parameters
Each kernel function definition includes an optional list of parameters. These parameters are
addressable, read-only variables declared in the .param
state space. Values passed from the host
to the kernel are accessed through these parameter variables using ld.param
instructions. The
kernel parameter variables are shared across all CTAs from all clusters within a grid.
The address of a kernel parameter may be moved into a register using the mov
instruction. The
resulting address is in the .param
state space and is accessed using ld.param
instructions.
Example
.entry foo ( .param .b32 N, .param .align 8 .b8 buffer[64] )
{
.reg .u32 %n;
.reg .f64 %d;
ld.param.u32 %n, [N];
ld.param.f64 %d, [buffer];
...
Example
.entry bar ( .param .b32 len )
{
.reg .u32 %ptr, %n;
mov.u32 %ptr, len;
ld.param.u32 %n, [%ptr];
...
Kernel function parameters may represent normal data values, or they may hold addresses to objects in constant, global, local, or shared state spaces. In the case of pointers, the compiler and runtime system need information about which parameters are pointers, and to which state space they point. Kernel parameter attribute directives are used to provide this information at the PTX level. See Kernel Function Parameter Attributes for a description of kernel parameter attribute directives.
Note
The current implementation does not allow creation of generic pointers to constant variables
(cvta.const
) in programs that have pointers to constant buffers passed as kernel parameters.
5.1.6.2. Kernel Function Parameter Attributes
Kernel function parameters may be declared with an optional .ptr attribute to indicate that a
parameter is a pointer to memory, and also indicate the state space and alignment of the memory
being pointed to. Kernel Parameter Attribute: .ptr
describes the .ptr
kernel parameter attribute.
5.1.6.3. Kernel Parameter Attribute: .ptr
.ptr
Kernel parameter alignment attribute.
Syntax
.param .type .ptr .space .align N varname
.param .type .ptr .align N varname
.space = { .const, .global, .local, .shared };
Description
Used to specify the state space and, optionally, the alignment of memory pointed to by a pointer type kernel parameter. The alignment value N, if present, must be a power of two. If no state space is specified, the pointer is assumed to be a generic address pointing to one of const, global, local, or shared memory. If no alignment is specified, the memory pointed to is assumed to be aligned to a 4 byte boundary.
Spaces between .ptr
, .space
, and .align
may be eliminated to improve readability.
PTX ISA Notes
Introduced in PTX ISA version 2.2.
Support for generic addressing of .const space added in PTX ISA version 3.1.
Target ISA Notes
Supported on all target architectures.
Examples
.entry foo ( .param .u32 param1,
.param .u32 .ptr.global.align 16 param2,
.param .u32 .ptr.const.align 8 param3,
.param .u32 .ptr.align 16 param4 // generic address
// pointer
) { .. }
5.1.6.4. Device Function Parameters
PTX ISA version 2.0 extended the use of parameter space to device function parameters. The most
common use is for passing objects by value that do not fit within a PTX register, such as C
structures larger than 8 bytes. In this case, a byte array in parameter space is used. Typically,
the caller will declare a locally-scoped .param
byte array variable that represents a flattened
C structure or union. This will be passed by value to a callee, which declares a .param
formal
parameter having the same size and alignment as the passed argument.
Example
// pass object of type struct { double d; int y; };
.func foo ( .reg .b32 N, .param .align 8 .b8 buffer[12] )
{
.reg .f64 %d;
.reg .s32 %y;
ld.param.f64 %d, [buffer];
ld.param.s32 %y, [buffer+8];
...
}
// code snippet from the caller
// struct { double d; int y; } mystruct; is flattened, passed to foo
...
.reg .f64 dbl;
.reg .s32 x;
.param .align 8 .b8 mystruct;
...
st.param.f64 [mystruct+0], dbl;
st.param.s32 [mystruct+8], x;
call foo, (4, mystruct);
...
See the section on function call syntax for more details.
Function input parameters may be read via ld.param
and function return parameters may be written
using st.param
; it is illegal to write to an input parameter or read from a return parameter.
Aside from passing structures by value, .param
space is also required whenever a formal
parameter has its address taken within the called function. In PTX, the address of a function input
parameter may be moved into a register using the mov
instruction. Note that the parameter will
be copied to the stack if necessary, and so the address will be in the .local
state space and is
accessed via ld.local
and st.local
instructions. It is not possible to use mov
to get
the address of or a locally-scoped .param
space variable. Starting PTX ISA version 6.0, it is
possible to use mov
instruction to get address of return parameter of device function.
Example
// pass array of up to eight floating-point values in buffer
.func foo ( .param .b32 N, .param .b32 buffer[32] )
{
.reg .u32 %n, %r;
.reg .f32 %f;
.reg .pred %p;
ld.param.u32 %n, [N];
mov.u32 %r, buffer; // forces buffer to .local state space
Loop:
setp.eq.u32 %p, %n, 0;
@%p: bra Done;
ld.local.f32 %f, [%r];
...
add.u32 %r, %r, 4;
sub.u32 %n, %n, 1;
bra Loop;
Done:
...
}
5.1.8. Texture State Space (deprecated)
The texture (.tex
) state space is global memory accessed via the texture instruction. It is
shared by all threads in a context. Texture memory is read-only and cached, so accesses to texture
memory are not coherent with global memory stores to the texture image.
The GPU hardware has a fixed number of texture bindings that can be accessed within a single kernel
(typically 128). The .tex directive will bind the named texture memory variable to a hardware
texture identifier, where texture identifiers are allocated sequentially beginning with
zero. Multiple names may be bound to the same physical texture identifier. An error is generated if
the maximum number of physical resources is exceeded. The texture name must be of type .u32
or
.u64
.
Physical texture resources are allocated on a per-kernel granularity, and .tex
variables are
required to be defined in the global scope.
Texture memory is read-only. A texture’s base address is assumed to be aligned to a 16 byte boundary.
Example
.tex .u32 tex_a; // bound to physical texture 0
.tex .u32 tex_c, tex_d; // both bound to physical texture 1
.tex .u32 tex_d; // bound to physical texture 2
.tex .u32 tex_f; // bound to physical texture 3
Note
Explicit declarations of variables in the texture state space is deprecated, and programs should
instead reference texture memory through variables of type .texref
. The .tex
directive is
retained for backward compatibility, and variables declared in the .tex
state space are
equivalent to module-scoped .texref
variables in the .global
state space.
For example, a legacy PTX definitions such as
.tex .u32 tex_a;
is equivalent to:
.global .texref tex_a;
See Texture Sampler and Surface Types for the
description of the .texref
type and Texture Instructions
for its use in texture instructions.
5.2. Types
5.2.1. Fundamental Types
In PTX, the fundamental types reflect the native data types supported by the target architectures. A fundamental type specifies both a basic type and a size. Register variables are always of a fundamental type, and instructions operate on these types. The same type-size specifiers are used for both variable definitions and for typing instructions, so their names are intentionally short.
Table 8 lists the fundamental type specifiers for each basic type:
Basic Type |
Fundamental Type Specifiers |
---|---|
Signed integer |
|
Unsigned integer |
|
Floating-point |
|
Bits (untyped) |
|
Predicate |
|
Most instructions have one or more type specifiers, needed to fully specify instruction behavior. Operand types and sizes are checked against instruction types for compatibility.
Two fundamental types are compatible if they have the same basic type and are the same size. Signed and unsigned integer types are compatible if they have the same size. The bit-size type is compatible with any fundamental type having the same size.
In principle, all variables (aside from predicates) could be declared using only bit-size types, but typed variables enhance program readability and allow for better operand type checking.
5.2.2. Restricted Use of Sub-Word Sizes
The .u8
, .s8
, and .b8
instruction types are restricted to ld
, st
, and cvt
instructions. The .f16
floating-point type is allowed only in conversions to and from .f32
,
.f64
types, in half precision floating point instructions and texture fetch instructions. The
.f16x2
floating point type is allowed only in half precision floating point arithmetic
instructions and texture fetch instructions.
For convenience, ld
, st
, and cvt
instructions permit source and destination data
operands to be wider than the instruction-type size, so that narrow values may be loaded, stored,
and converted using regular-width registers. For example, 8-bit or 16-bit values may be held
directly in 32-bit or 64-bit registers when being loaded, stored, or converted to other types and
sizes.
5.2.3. Alternate Floating-Point Data Formats
The fundamental floating-point types supported in PTX have implicit bit representations that
indicate the number of bits used to store exponent and mantissa. For example, the .f16
type
indicates 5 bits reserved for exponent and 10 bits reserved for mantissa. In addition to the
floating-point representations assumed by the fundamental types, PTX allows the following alternate
floating-point data formats:
-
bf16
data format: -
This data format is a 16-bit floating point format with 8 bits for exponent and 7 bits for mantissa. A register variable containing
bf16
data must be declared with.b16
type. -
e4m3
data format: -
This data format is an 8-bit floating point format with 4 bits for exponent and 3 bits for mantissa. The
e4m3
encoding does not support infinity andNaN
values are limited to0x7f
and0xff
. A register variable containinge4m3
value must be declared using bit-size type. -
e5m2
data format: -
This data format is an 8-bit floating point format with 5 bits for exponent and 2 bits for mantissa. A register variable containing
e5m2
value must be declared using bit-size type. -
tf32
data format: -
This data format is a special 32-bit floating point format supported by the matrix multiply-and-accumulate instructions, with the same range as
.f32
and reduced precision (>=10 bits). The internal layout oftf32
format is implementation defined. PTX facilitates conversion from single precision.f32
type totf32
format. A register variable containingtf32
data must be declared with.b32
type.
Alternate data formats cannot be used as fundamental types. They are supported as source or destination formats by certain instructions.
5.2.4. Packed Data Types
Certain PTX instructions operate on two sets of inputs in parallel, and produce two outputs. Such instructions can use the data stored in a packed format. PTX supports packing two values of the same scalar data type into a single, larger value. The packed value is considered as a value of a packed data type. In this section we describe the packed data types supported in PTX.
5.2.4.1. Packed Floating Point Data Types
PTX supports the following four variants of packed floating point data types:
.f16x2
packed type containing two.f16
floating point values..bf16x2
packed type containing two.bf16
alternate floating point values..e4m3x2
packed type containing two.e4m3
alternate floating point values..e5m2x2
packed type containing two.e5m2
alternate floating point values.
.f16x2
is supported as a fundamental type. .bf16x2
, .e4m3x2
and .e5m2x2
cannot be
used as fundamental types - they are supported as instruction types on certain instructions. A
register variable containing .bf16x2
data must be declared with .b32
type. A register
variable containing .e4m3x2
or .e5m2x2
data must be declared with .b16
type.
5.2.4.2. Packed Integer Data Types
PTX supports two variants of packed integer data types: .u16x2
and .s16x2
. The packed data
type consists of two .u16
or .s16
values. A register variable containing .u16x2
or
.s16x2
data must be declared with .b32
type. Packed integer data types cannot be used as
fundamental types. They are supported as instruction types on certain instructions.
5.3. Texture Sampler and Surface Types
PTX includes built-in opaque types for defining texture, sampler, and surface descriptor variables. These types have named fields similar to structures, but all information about layout, field ordering, base address, and overall size is hidden to a PTX program, hence the term opaque. The use of these opaque types is limited to:
Variable definition within global (module) scope and in kernel entry parameter lists.
Static initialization of module-scope variables using comma-delimited static assignment expressions for the named members of the type.
Referencing textures, samplers, or surfaces via texture and surface load/store instructions (
tex
,suld
,sust
,sured
).Retrieving the value of a named member via query instructions (
txq
,suq
).Creating pointers to opaque variables using
mov
, e.g.,mov.u64 reg, opaque_var;
. The resulting pointer may be stored to and loaded from memory, passed as a parameter to functions, and de-referenced by texture and surface load, store, and query instructions, but the pointer cannot otherwise be treated as an address, i.e., accessing the pointer withld
andst
instructions, or performing pointer arithmetic will result in undefined results.Opaque variables may not appear in initializers, e.g., to initialize a pointer to an opaque variable.
Note
Indirect access to textures and surfaces using pointers to opaque variables is supported
beginning with PTX ISA version 3.1 and requires target sm_20
or later.
Indirect access to textures is supported only in unified texture mode (see below).
The three built-in types are .texref
, .samplerref
, and .surfref
. For working with
textures and samplers, PTX has two modes of operation. In the unified mode, texture and sampler
information is accessed through a single .texref
handle. In the independent mode, texture and
sampler information each have their own handle, allowing them to be defined separately and combined
at the site of usage in the program. In independent mode, the fields of the .texref
type that
describe sampler properties are ignored, since these properties are defined by .samplerref
variables.
Table 9 and
Table 10 list the named members
of each type for unified and independent texture modes. These members and their values have
precise mappings to methods and values defined in the texture HW
class as well as
exposed values via the API.
Member |
.texref values |
.surfref values |
---|---|---|
|
in elements |
|
|
in elements |
|
|
in elements |
|
|
|
|
|
|
|
|
|
N/A |
|
|
N/A |
|
|
N/A |
|
as number of textures in a texture array |
as number of surfaces in a surface array |
|
as number of levels in a mipmapped texture |
N/A |
|
as number of samples in a multi-sample texture |
N/A |
|
N/A |
|
5.3.1. Texture and Surface Properties
Fields width
, height
, and depth
specify the size of the texture or surface in number of
elements in each dimension.
The channel_data_type
and channel_order
fields specify these properties of the texture or
surface using enumeration types corresponding to the source language API. For example, see Channel
Data Type and Channel Order Fields for
the OpenCL enumeration types currently supported in PTX.
5.3.2. Sampler Properties
The normalized_coords
field indicates whether the texture or surface uses normalized coordinates
in the range [0.0, 1.0) instead of unnormalized coordinates in the range [0, N). If no value is
specified, the default is set by the runtime system based on the source language.
The filter_mode
field specifies how the values returned by texture reads are computed based on
the input texture coordinates.
The addr_mode_{0,1,2}
fields define the addressing mode in each dimension, which determine how
out-of-range coordinates are handled.
See the CUDA C++ Programming Guide for more details of these properties.
Member |
.samplerref values |
.texref values |
.surfref values |
---|---|---|---|
|
N/A |
in elements |
|
|
N/A |
in elements |
|
|
N/A |
in elements |
|
|
N/A |
|
|
|
N/A |
|
|
|
N/A |
|
N/A |
|
|
N/A |
N/A |
|
|
ignored |
N/A |
|
|
N/A |
N/A |
|
N/A |
as number of textures in a texture array |
as number of surfaces in a surface array |
|
N/A |
as number of levels in a mipmapped texture |
N/A |
|
N/A |
as number of samples in a multi-sample texture |
N/A |
|
N/A |
N/A |
|
In independent texture mode, the sampler properties are carried in an independent .samplerref
variable, and these fields are disabled in the .texref
variables. One additional sampler
property, force_unnormalized_coords
, is available in independent texture mode.
The force_unnormalized_coords
field is a property of .samplerref
variables that allows the
sampler to override the texture header normalized_coords
property. This field is defined only in
independent texture mode. When True
, the texture header setting is overridden and unnormalized
coordinates are used; when False
, the texture header setting is used.
The force_unnormalized_coords
property is used in compiling OpenCL; in OpenCL, the property of
normalized coordinates is carried in sampler headers. To compile OpenCL to PTX, texture headers are
always initialized with normalized_coords
set to True, and the OpenCL sampler-based
normalized_coords
flag maps (negated) to the PTX-level force_unnormalized_coords
flag.
Variables using these types may be declared at module scope or within kernel entry parameter
lists. At module scope, these variables must be in the .global
state space. As kernel
parameters, these variables are declared in the .param
state space.
Example
.global .texref my_texture_name;
.global .samplerref my_sampler_name;
.global .surfref my_surface_name;
When declared at module scope, the types may be initialized using a list of static expressions assigning values to the named members.
Example
.global .texref tex1;
.global .samplerref tsamp1 = { addr_mode_0 = clamp_to_border,
filter_mode = nearest
};
5.3.3. Channel Data Type and Channel Order Fields
The channel_data_type
and channel_order
fields have enumeration types corresponding to the
source language API. Currently, OpenCL is the only source language that defines these
fields. Table 12 and
Table 11 show the
enumeration values defined in OpenCL version 1.0 for channel data type and channel order.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5.4. Variables
In PTX, a variable declaration describes both the variable’s type and its state space. In addition to fundamental types, PTX supports types for simple aggregate objects such as vectors and arrays.
5.4.1. Variable Declarations
All storage for data is specified with variable declarations. Every variable must reside in one of the state spaces enumerated in the previous section.
A variable declaration names the space in which the variable resides, its type and size, its name, an optional array size, an optional initializer, and an optional fixed address for the variable.
Predicate variables may only be declared in the register state space.
Examples
.global .u32 loc;
.reg .s32 i;
.const .f32 bias[] = {-1.0, 1.0};
.global .u8 bg[4] = {0, 0, 0, 0};
.reg .v4 .f32 accel;
.reg .pred p, q, r;
5.4.2. Vectors
Limited-length vector types are supported. Vectors of length 2 and 4 of any non-predicate
fundamental type can be declared by prefixing the type with .v2
or .v4
. Vectors must be
based on a fundamental type, and they may reside in the register space. Vectors cannot exceed
128-bits in length; for example, .v4 .f64
is not allowed. Three-element vectors may be
handled by using a .v4
vector, where the fourth element provides padding. This is a common case
for three-dimensional grids, textures, etc.
Examples
.global .v4 .f32 V; // a length-4 vector of floats
.shared .v2 .u16 uv; // a length-2 vector of unsigned ints
.global .v4 .b8 v; // a length-4 vector of bytes
By default, vector variables are aligned to a multiple of their overall size (vector length times base-type size), to enable vector load and store instructions which require addresses aligned to a multiple of the access size.
5.4.3. Array Declarations
Array declarations are provided to allow the programmer to reserve space. To declare an array, the variable name is followed with dimensional declarations similar to fixed-size array declarations in C. The size of each dimension is a constant expression.
Examples
.local .u16 kernel[19][19];
.shared .u8 mailbox[128];
The size of the array specifies how many elements should be reserved. For the declaration of array kernel above, 19*19 = 361 halfwords are reserved, for a total of 722 bytes.
When declared with an initializer, the first dimension of the array may be omitted. The size of the first array dimension is determined by the number of elements in the array initializer.
Examples
.global .u32 index[] = { 0, 1, 2, 3, 4, 5, 6, 7 };
.global .s32 offset[][2] = { {-1, 0}, {0, -1}, {1, 0}, {0, 1} };
Array index has eight elements, and array offset is a 4x2 array.
5.4.4. Initializers
Declared variables may specify an initial value using a syntax similar to C/C++, where the variable name is followed by an equals sign and the initial value or values for the variable. A scalar takes a single value, while vectors and arrays take nested lists of values inside of curly braces (the nesting matches the dimensionality of the declaration).
As in C, array initializers may be incomplete, i.e., the number of initializer elements may be less than the extent of the corresponding array dimension, with remaining array locations initialized to the default value for the specified array type.
Examples
.const .f32 vals[8] = { 0.33, 0.25, 0.125 };
.global .s32 x[3][2] = { {1,2}, {3} };
is equivalent to
.const .f32 vals[8] = { 0.33, 0.25, 0.125, 0.0, 0.0, 0.0, 0.0, 0.0 };
.global .s32 x[3][2] = { {1,2}, {3,0}, {0,0} };
Currently, variable initialization is supported only for constant and global state spaces. Variables in constant and global state spaces with no explicit initializer are initialized to zero by default. Initializers are not allowed in external variable declarations.
Variable names appearing in initializers represent the address of the variable; this can be used to
statically initialize a pointer to a variable. Initializers may also contain var+offset
expressions, where offset is a byte offset added to the address of var. Only variables in
.global
or .const
state spaces may be used in initializers. By default, the resulting
address is the offset in the variable’s state space (as is the case when taking the address of a
variable with a mov
instruction). An operator, generic()
, is provided to create a generic
address for variables used in initializers.
Starting PTX ISA version 7.1, an operator mask()
is provided, where mask
is an integer
immediate. The only allowed expressions in the mask()
operator are integer constant expression
and symbol expression representing address of variable. The mask()
operator extracts n
consecutive bits from the expression used in initializers and inserts these bits at the lowest
position of the initialized variable. The number n
and the starting position of the bits to be
extracted is specified by the integer immediate mask
. PTX ISA version 7.1 only supports
extracting a single byte starting at byte boundary from the address of the variable. PTX ISA version
7.3 supports Integer constant expression as an operand in the mask()
operator.
Supported values for mask
are: 0xFF, 0xFF00, 0XFF0000, 0xFF000000, 0xFF00000000, 0xFF0000000000,
0xFF000000000000, 0xFF00000000000000.
Examples
.const .u32 foo = 42;
.global .u32 bar[] = { 2, 3, 5 };
.global .u32 p1 = foo; // offset of foo in .const space
.global .u32 p2 = generic(foo); // generic address of foo
// array of generic-address pointers to elements of bar
.global .u32 parr[] = { generic(bar), generic(bar)+4,
generic(bar)+8 };
// examples using mask() operator are pruned for brevity
.global .u8 addr[] = {0xff(foo), 0xff00(foo), 0xff0000(foo), ...};
.global .u8 addr2[] = {0xff(foo+4), 0xff00(foo+4), 0xff0000(foo+4),...}
.global .u8 addr3[] = {0xff(generic(foo)), 0xff00(generic(foo)),...}
.global .u8 addr4[] = {0xff(generic(foo)+4), 0xff00(generic(foo)+4),...}
// mask() operator with integer const expression
.global .u8 addr5[] = { 0xFF(1000 + 546), 0xFF00(131187), ...};
Note
PTX 3.1 redefines the default addressing for global variables in initializers, from generic
addresses to offsets in the global state space. Legacy PTX code is treated as having an implicit
generic()
operator for each global variable used in an initializer. PTX 3.1 code should
either include explicit generic()
operators in initializers, use cvta.global
to form
generic addresses at runtime, or load from the non-generic address using ld.global
.
Device function names appearing in initializers represent the address of the first instruction in the function; this can be used to initialize a table of function pointers to be used with indirect calls. Beginning in PTX ISA version 3.1, kernel function names can be used as initializers e.g. to initialize a table of kernel function pointers, to be used with CUDA Dynamic Parallelism to launch kernels from GPU. See the CUDA Dynamic Parallelism Programming Guide for details.
Labels cannot be used in initializers.
Variables that hold addresses of variables or functions should be of type .u8
or .u32
or
.u64
.
Type .u8
is allowed only if the mask()
operator is used.
Initializers are allowed for all types except .f16
, .f16x2
and .pred
.
Examples
.global .s32 n = 10;
.global .f32 blur_kernel[][3]
= {{.05,.1,.05},{.1,.4,.1},{.05,.1,.05}};
.global .u32 foo[] = { 2, 3, 5, 7, 9, 11 };
.global .u64 ptr = generic(foo); // generic address of foo[0]
.global .u64 ptr = generic(foo)+8; // generic address of foo[2]
5.4.5. Alignment
Byte alignment of storage for all addressable variables can be specified in the variable
declaration. Alignment is specified using an optional .align
byte-count specifier immediately
following the state-space specifier. The variable will be aligned to an address which is an integer
multiple of byte-count. The alignment value byte-count must be a power of two. For arrays, alignment
specifies the address alignment for the starting address of the entire array, not for individual
elements.
The default alignment for scalar and array variables is to a multiple of the base-type size. The default alignment for vector variables is to a multiple of the overall vector size.
Examples
// allocate array at 4-byte aligned address. Elements are bytes.
.const .align 4 .b8 bar[8] = {0,0,0,0,2,0,0,0};
Note that all PTX instructions that access memory require that the address be aligned to a multiple
of the access size. The access size of a memory instruction is the total number of bytes accessed in
memory. For example, the access size of ld.v4.b32
is 16 bytes, while the access size of
atom.f16x2
is 4 bytes.
5.4.6. Parameterized Variable Names
Since PTX supports virtual registers, it is quite common for a compiler frontend to generate a large number of register names. Rather than require explicit declaration of every name, PTX supports a syntax for creating a set of variables having a common prefix string appended with integer suffixes.
For example, suppose a program uses a large number, say one hundred, of .b32
variables, named
%r0
, %r1
, …, %r99
. These 100 register variables can be declared as follows:
.reg .b32 %r<100>; // declare %r0, %r1, ..., %r99
This shorthand syntax may be used with any of the fundamental types and with any state space, and may be preceded by an alignment specifier. Array variables cannot be declared this way, nor are initializers permitted.
5.4.7. Variable Attributes
Variables may be declared with an optional .attribute
directive which allows specifying special
attributes of variables. Keyword .attribute
is followed by attribute specification inside
parenthesis. Multiple attributes are separated by comma.
Variable and Function Attribute Directive: .attribute describes the .attribute
directive.
5.4.8. Variable and Function Attribute Directive: .attribute
.attribute
Variable and function attributes
Description
Used to specify special attributes of a variable or a function.
The following attributes are supported.
.managed
-
.managed
attribute specifies that variable will be allocated at a location in unified virtual memory environment where host and other devices in the system can reference the variable directly. This attribute can only be used with variables in .global state space. See the CUDA UVM-Lite Programming Guide for details. .unified
-
.unified
attribute specifies that function has the same memory address on the host and on other devices in the system. Integer constantsuuid1
anduuid2
respectively specify upper and lower 64 bits of the unique identifier associated with the function or the variable. This attribute can only be used on device functions or on variables in the.global
state space. Variables with.unified
attribute are read-only and must be loaded by specifying.unified
qualifier on the address operand ofld
instruction, otherwise the behavior is undefined.
PTX ISA Notes
Introduced in PTX ISA version 4.0.
Support for function attributes introduced in PTX ISA version 8.0.
Target ISA Notes
.managed
attribute requiressm_30
or higher..unified
attribute requiressm_90
or higher.
Examples
.global .attribute(.managed) .s32 g;
.global .attribute(.managed) .u64 x;
.global .attribute(.unified(19,95)) .f32 f;
.func .attribute(.unified(0xAB, 0xCD)) bar() { ... }
5.5. Tensors
A tensor is a multi-dimensional matrix structure in the memory. Tensor is defined by the following properties:
Dimensionality
Dimension sizes across each dimension
Individual element types
Tensor stride across each dimension
PTX supports instructions which can operate on the tensor data. PTX Tensor instructions include:
Copying data between global and shared memories
Reducing the destination tensor data with the source.
The Tensor data can be operated on by various wmma.mma
, mma
and wgmma.mma_async
instructions.
PTX Tensor instructions treat the tensor data in the global memory as a multi-dimensional structure and treat the data in the shared memory as a linear data.
5.5.1. Tensor Dimension, size and format
Tensors can have dimensions: 1D, 2D, 3D, 4D or 5D.
Each dimension has a size which represents the number of elements along the dimension. The elements can have one the following types:
Bit-sized type:
.b32
,.b64
Integer:
.u8
,.u16
,.u32
,.s32
,.u64
,.s64
Floating point and alternate floating point:
.f16
,.bf16
,.tf32
,.f32
,.f64
(rounded to nearest even).
Tensor can have padding at the end in each of the dimensions to provide alignment for the data in the subsequent dimensions. Tensor stride can be used to specify the amount of padding in each dimension.
5.5.2. Tensor Access Modes
Tensor data can be accessed in two modes:
-
Tiled mode:
In tiled mode, the source multi-dimensional tensor layout is preserved at the destination.
-
Im2col mode:
In im2col mode, the elements in the Bounding Box of the source tensor are rearranged into columns at the destination. Refer here for more details.
5.5.3. Tiled Mode
This section talks about how Tensor and Tensor access work in tiled mode.
5.5.3.1. Bounding Box
A tensor can be accessed in chunks known as Bounding Box. The Bounding Box has the same dimensionality as the tensor they are accessing into. Size of each bounding Box must be a multiple of 16 bytes. The address of the bounding Box must also be aligned to 16 bytes.
Bounding Box has the following access properties:
Bounding Box dimension sizes
Out of boundary access mode
Traversal strides
The tensor-coordinates, specified in the PTX tensor instructions, specify the starting offset of the bounding box. Starting offset of the bounding box along with the rest of the bounding box information together are used to determine the elements which are to be accessed.
5.5.3.2. Traversal-Stride
While the Bounding Box is iterating the tensor across a dimension, the traversal stride specifies the exact number of elements to be skipped. If no jump over is required, default value of 1 must be specified.
The traversal stride in dimension 0 can be used for the Interleave layout. For non-interleaved layout, the traversal stride in dimension 0 must always be 1.
Figure 5 illustrates tensor, tensor size, tensor stride, Bounding Box size and traversal stride.
5.5.3.3. Out of Boundary Access
PTX Tensor operation can detect and handle the case when the Bounding Box crosses the tensor boundary in any dimension. There are 2 modes:
-
Zero fill mode:
Elements in the Bounding Box which fall outside of the tensor boundary are set to 0.
-
OOB-NaN
fill mode:Elements in the Bounding Box which fall outside of the tensor boundary are set to a special NaN called
OOB-NaN
.
Figure 6 shows an example of the out of boundary access.
5.5.4. Im2col mode
Im2col mode supports the following tensor dimensions : 3D, 4D and 5D. In this mode, the tensor data is treated as a batch of images with the following properties:
N : number of images in the batch
D, H, W : size of a 3D image (depth, height and width)
C: channels per image element
The above properties are associated with 3D, 4D and 5D tensors as follows:
Dimension |
N/D/H/W/C applicability |
---|---|
3D |
NWC |
4D |
NHWC |
5D |
NDHWC |
5.5.4.1. Bounding Box
In im2col mode, the Bounding Box is defined in DHW space. Boundaries along other dimensions are specified by Pixels-per-Column and Channels-per-Pixel parameters as described below.
The dimensionality of the Bounding Box is two less than the tensor dimensionality.
The following properties describe how to access of the elements in im2col mode:
Bounding-Box Lower-Corner
Bounding-Box Upper-Corner
Pixels-per-Column
Channels-per-Pixel
Bounding-box Lower-Corner and Bounding-box Upper-Corner specify the two opposite corners of the Bounding Box in the DHW space. Bounding-box Lower-Corner specifies the corner with the smallest coordinate and Bounding-box Upper-Corner specifies the corner with the largest coordinate.
Bounding-box Upper- and Lower-Corners are 16-bit signed values whose limits varies across the dimensions and are as shown below:
3D |
4D |
5D |
|
---|---|---|---|
Upper- / Lower- Corner sizes |
[-215, 215-1] |
[-27, 27-1] |
[-24, 24-1] |
Figure 7 and Figure 8 show the Upper-Corners and Lower-Corners.
The Bounding-box Upper- and Lower- Corners specify only the boundaries and not the number of elements to be accessed. Pixels-per-Column specifies the number of elements to be accessed in the NDHW space.
Channels-per-Pixel specifies the number of elements to access across the C dimension.
The tensor coordinates, specified in the PTX tensor instructions, behaves differently in different dimensions:
Across N and C dimensions: specify the starting offsets along the dimension, similar to the tiled mode.
Across DHW dimensions: specify the location of the convolution filter base in the tensor space. The filter corner location must be within the bounding box.
The im2col offsets, specified in the PTX tensor instructions in im2col mode, are added to the filter base coordinates to determine the starting location in the tensor space from where the elements are accessed.
The size of the im2col offsets varies across the dimensions and their valid ranges are as shown below:
3D |
4D |
5D |
|
---|---|---|---|
im2col offsets range |
[0, 216-1] |
[0, 28-1] |
[0, 25-1] |
Following are some examples of the im2col mode accesses:
-
Example 1 (Figure 9):
Tensor Size[0] = 64 Tensor Size[1] = 9 Tensor Size[2] = 14 Tensor Size[3] = 64 Pixels-per-Column = 64 channels-per-pixel = 8 Bounding-Box Lower-Corner W = -1 Bounding-Box Lower-Corner H = -1 Bounding-Box Upper-Corner W = -1 Bounding-Box Upper-Corner H = -1. tensor coordinates = (7, 7, 4, 0) im2col offsets : (0, 0)
-
Example 2 (Figure 10):
Tensor Size[0] = 64 Tensor Size[1] = 9 Tensor Size[2] = 14 Tensor Size[3] = 64 Pixels-per-Column = 64 channels-per-pixel = 8 Bounding-Box Lower-Corner W = 0 Bounding-Box Lower-Corner H = 0 Bounding-Box Upper-Corner W = -2 Bounding-Box Upper-Corner H = -2 tensor coordinates = (7, 7, 4, 0) im2col offsets: (2, 2)
5.5.4.2. Traversal Stride
The traversal stride, in im2col mode, does not impact the total number of elements (or pixels) being accessed unlike the tiled mode. Pixels-per-Column determines the total number of elements being accessed, in im2col mode.
The number of elements traversed along the D, H and W dimensions is strided by the traversal stride for that dimension.
The following example with Figure 11 illustrates accesse with traversal-strides:
Tensor Size[0] = 64
Tensor Size[1] = 8
Tensor Size[2] = 14
Tensor Size[3] = 64
Traversal Stride = 2
Pixels-per-Column = 32
channels-per-pixel = 16
Bounding-Box Lower-Corner W = -1
Bounding-Box Lower-Corner H = -1
Bounding-Box Upper-Corner W = -1
Bounding-Box Upper-Corner H = -1.
Tensor coordinates in the instruction = (7, 7, 5, 0)
Im2col offsets in the instruction : (1, 1)
5.5.4.3. Out of Boundary Access
In im2col mode, when the number of requested pixels in NDHW space specified by Pixels-per-Column exceeds the number of available pixels in the image batch then out-of-bounds access is performed.
Similar to tiled mode, zero fill or OOB-NaN
fill can be performed based on the Fill-Mode
specified.
5.5.5. Interleave layout
Tensor can be interleaved and the following interleave layouts are supported:
No interleave (NDHWC)
8 byte interleave (NC/8DHWC8) : C8 utilizes 16 bytes in memory assuming 2B per channel.
16 byte interleave (NC/16HWC16) : C16 utilizes 32 bytes in memory assuming 4B per channel.
The C information is organized in slices where sequential C elements are grouped in 16 byte or 32 byte quantities.
If the total number of channels is not a multiple of the number of channels per slice, then the last slice must be padded with zeros to make it complete 16B or 32B slice.
Interleaved layouts are supported only for the dimensionalities : 3D, 4D and 5D.
5.5.6. Swizzling Modes
The layout of the data in the shared memory can be different to that of global memory, for access performance reasons. The following describes various swizzling modes:
-
No swizzle mode:
There is no swizzling in this mode and the destination data layout is exactly similar to the source data layout.
0
1
2
3
4
5
6
7
0
1
2
3
4
5
6
7
… Pattern repeats …
-
32 byte swizzle mode:
The following table, where each elements (numbered cell) is 16 byte and the starting address is 256 bytes aligned, shows the pattern of the destination data layout:
0
1
2
3
4
5
6
7
1
0
3
2
5
4
7
6
… Pattern repeats …
An example of the 32 byte swizzle mode for NC/(32B)HWC(32B) tensor of 1x2x10x10xC16 dimension, with the innermost dimension holding slice of 16 channels with 2 byte/channel, is shown in Figure 12.
Figure 13 shows the two fragments of the tensor : one for C/(32B) = 0 and another for C/(32B) = 1.
Figure 14 shows the destination data layout with 32 byte swizzling.
-
64 byte swizzle mode:
The following table, where each elements (numbered cell) is 16 byte and the starting address is 512 bytes aligned, shows the pattern of the destination data layout:
0
1
2
3
4
5
6
7
1
0
3
2
5
4
7
6
2
3
0
1
6
7
4
5
3
2
1
0
7
6
5
4
… Pattern repeats …
An example of the 64 byte swizzle mode for NHWC tensor of 1x10x10x64 dimension, with 2 bytes / channel and 32 channels, is shown in Figure 15.
Each colored cell represents 8 channels. Figure 16 shows the source data layout.
Figure 17 shows the destination data layout with 64 byte swizzling.
-
128 byte swizzle mode:
The following table, where each elements (numbered cell) is 16 byte and the starting address is 1024 bytes aligned, shows the pattern of the destination data layout:
0
1
2
3
4
5
6
7
1
0
3
2
5
4
7
6
2
3
0
1
6
7
4
5
3
2
1
0
7
6
5
4
4
5
6
7
0
1
2
3
5
4
7
6
1
0
3
2
6
7
4
5
2
3
0
1
… Pattern repeats …
An example of the 128 byte swizzle mode for NHWC tensor of 1x10x10x64 dimension, with 2 bytes / channel and 64 channels, is shown in Figure 18.
Each colored cell represents 8 channels. Figure 19 shows the source data layout.
Figure 20 shows the destination data layout with 128 byte swizzling.
5.5.7. Tensor-map
The tensor-map is a 128-byte opaque object either in .const
space or .param
(kernel function
parameter) space or .global
space which describes the tensor properties and the access properties
of the tensor data described in previous sections.
Tensor-Map can be created using CUDA APIs. Refer to CUDA programming guide for more details.
6. Instruction Operands
6.1. Operand Type Information
All operands in instructions have a known type from their declarations. Each operand type must be compatible with the type determined by the instruction template and instruction type. There is no automatic conversion between types.
The bit-size type is compatible with every type having the same size. Integer types of a common size are compatible with each other. Operands having type different from but compatible with the instruction type are silently cast to the instruction type.
6.2. Source Operands
The source operands are denoted in the instruction descriptions by the names a
, b
, and
c
. PTX describes a load-store machine, so operands for ALU instructions must all be in variables
declared in the .reg
register state space. For most operations, the sizes of the operands must
be consistent.
The cvt
(convert) instruction takes a variety of operand types and sizes, as its job is to
convert from nearly any data type to any other data type (and size).
The ld
, st
, mov
, and cvt
instructions copy data from one location to
another. Instructions ld
and st
move data from/to addressable state spaces to/from
registers. The mov
instruction copies data between registers.
Most instructions have an optional predicate guard that controls conditional execution, and a few
instructions have additional predicate source operands. Predicate operands are denoted by the names
p
, q
, r
, s
.
6.3. Destination Operands
PTX instructions that produce a single result store the result in the field denoted by d
(for
destination) in the instruction descriptions. The result operand is a scalar or vector variable in
the register state space.
6.4. Using Addresses, Arrays, and Vectors
Using scalar variables as operands is straightforward. The interesting capabilities begin with addresses, arrays, and vectors.
6.4.1. Addresses as Operands
All the memory instructions take an address operand that specifies the memory location being accessed. This addressable operand is one of:
[var]
-
the name of an addressable variable
var
. [reg]
-
an integer or bit-size type register
reg
containing a byte address. [reg+immOff]
-
a sum of register
reg
containing a byte address plus a constant integer byte offset (signed, 32-bit). [var+immOff]
-
a sum of address of addressable variable
var
containing a byte address plus a constant integer byte offset (signed, 32-bit). [immAddr]
-
an immediate absolute byte address (unsigned, 32-bit).
var[immOff]
-
an array element as described in Arrays as Operands.
The register containing an address may be declared as a bit-size type or integer type.
The access size of a memory instruction is the total number of bytes accessed in memory. For
example, the access size of ld.v4.b32
is 16 bytes, while the access size of atom.f16x2
is 4
bytes.
The address must be naturally aligned to a multiple of the access size. If an address is not properly aligned, the resulting behavior is undefined. For example, among other things, the access may proceed by silently masking off low-order address bits to achieve proper rounding, or the instruction may fault.
The address size may be either 32-bit or 64-bit. 128-bit adresses are not supported. Addresses are zero-extended to the specified width as needed, and truncated if the register width exceeds the state space address width for the target architecture.
Address arithmetic is performed using integer arithmetic and logical instructions. Examples include pointer arithmetic and pointer comparisons. All addresses and address computations are byte-based; there is no support for C-style pointer arithmetic.
The mov
instruction can be used to move the address of a variable into a pointer. The address is
an offset in the state space in which the variable is declared. Load and store operations move data
between registers and locations in addressable state spaces. The syntax is similar to that used in
many assembly languages, where scalar variables are simply named and addresses are de-referenced by
enclosing the address expression in square brackets. Address expressions include variable names,
address registers, address register plus byte offset, and immediate address expressions which
evaluate at compile-time to a constant address.
Here are a few examples:
.shared .u16 x;
.reg .u16 r0;
.global .v4 .f32 V;
.reg .v4 .f32 W;
.const .s32 tbl[256];
.reg .b32 p;
.reg .s32 q;
ld.shared.u16 r0,[x];
ld.global.v4.f32 W, [V];
ld.const.s32 q, [tbl+12];
mov.u32 p, tbl;
6.4.1.1. Generic Addressing
If a memory instruction does not specify a state space, the operation is performed using generic
addressing. The state spaces .const
, Kernel Function Parameters (.param
), .local
and .shared
are modeled as
windows within the generic address space. Each window is defined by a window base and a window size
that is equal to the size of the corresponding state space. A generic address maps to global
memory unless it falls within the window for const
, local
, or shared
memory. The Kernel
Function Parameters (.param
) window is contained
within the .global
window. Within each window, a generic address maps to an address in the
underlying state space by subtracting the window base from the generic address.
6.4.2. Arrays as Operands
Arrays of all types can be declared, and the identifier becomes an address constant in the space where the array is declared. The size of the array is a constant in the program.
Array elements can be accessed using an explicitly calculated byte address, or by indexing into the array using square-bracket notation. The expression within square brackets is either a constant integer, a register variable, or a simple register with constant offset expression, where the offset is a constant expression that is either added or subtracted from a register variable. If more complicated indexing is desired, it must be written as an address calculation prior to use. Examples are:
ld.global.u32 s, a[0];
ld.global.u32 s, a[N-1];
mov.u32 s, a[1]; // move address of a[1] into s
6.4.3. Vectors as Operands
Vector operands are supported by a limited subset of instructions, which include mov
, ld
,
st
, atom
, red
and tex
. Vectors may also be passed as arguments to called functions.
Vector elements can be extracted from the vector with the suffixes .x
, .y
, .z
and
.w
, as well as the typical color fields .r
, .g
, .b
and .a
.
A brace-enclosed list is used for pattern matching to pull apart vectors.
.reg .v4 .f32 V;
.reg .f32 a, b, c, d;
mov.v4.f32 {a,b,c,d}, V;
Vector loads and stores can be used to implement wide loads and stores, which may improve memory performance. The registers in the load/store operations can be a vector, or a brace-enclosed list of similarly typed scalars. Here are examples:
ld.global.v4.f32 {a,b,c,d}, [addr+16];
ld.global.v2.u32 V2, [addr+8];
Elements in a brace-enclosed vector, say {Ra, Rb, Rc, Rd}, correspond to extracted elements as follows:
Ra = V.x = V.r
Rb = V.y = V.g
Rc = V.z = V.b
Rd = V.w = V.a
6.4.4. Labels and Function Names as Operands
Labels and function names can be used only in bra
/brx.idx
and call
instructions
respectively. Function names can be used in mov
instruction to get the address of the function
into a register, for use in an indirect call.
Beginning in PTX ISA version 3.1, the mov
instruction may be used to take the address of kernel
functions, to be passed to a system call that initiates a kernel launch from the GPU. This feature
is part of the support for CUDA Dynamic Parallelism. See the CUDA Dynamic Parallelism Programming
Guide for details.
6.5. Type Conversion
All operands to all arithmetic, logic, and data movement instruction must be of the same type and size, except for operations where changing the size and/or type is part of the definition of the instruction. Operands of different sizes or types must be converted prior to the operation.
6.5.1. Scalar Conversions
Table 13 shows what
precision and format the cvt instruction uses given operands of differing types. For example, if a
cvt.s32.u16
instruction is given a u16
source operand and s32
as a destination operand,
the u16
is zero-extended to s32
.
Conversions to floating-point that are beyond the range of floating-point numbers are represented
with the maximum floating-point value (IEEE 754 Inf for f32
and f64
, and ~131,000 for
f16
).
Destination Format |
||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
s8 |
s16 |
s32 |
s64 |
u8 |
u16 |
u32 |
u64 |
f16 |
f32 |
f64 |
||
Source Format |
s8 |
– |
sext |
sext |
sext |
– |
sext |
sext |
sext |
s2f |
s2f |
s2f |
s16 |
chop1 |
– |
sext |
sext |
chop1 |
– |
sext |
sext |
s2f |
s2f |
s2f |
|
s32 |
chop1 |
chop1 |
– |
sext |
chop1 |
chop1 |
– |
sext |
s2f |
s2f |
s2f |
|
s64 |
chop1 |
chop1 |
chop |
– |
chop1 |
chop1 |
chop |
– |
s2f |
s2f |
s2f |
|
u8 |
– |
zext |
zext |
zext |
– |
zext |
zext |
zext |
u2f |
u2f |
u2f |
|
u16 |
chop1 |
– |
zext |
zext |
chop1 |
– |
zext |
zext |
u2f |
u2f |
u2f |
|
u32 |
chop1 |
chop1 |
– |
zext |
chop1 |
chop1 |
– |
zext |
u2f |
u2f |
u2f |
|
u64 |
chop1 |
chop1 |
chop |
– |
chop1 |
chop1 |
chop |
– |
u2f |
u2f |
u2f |
|
f16 |
f2s |
f2s |
f2s |
f2s |
f2u |
f2u |
f2u |
f2u |
– |
f2f |
f2f |
|
f32 |
f2s |
f2s |
f2s |
f2s |
f2u |
f2u |
f2u |
f2u |
f2f |
– |
f2f |
|
f64 |
f2s |
f2s |
f2s |
f2s |
f2u |
f2u |
f2u |
f2u |
f2f |
f2f |
– |
|
Notes |
sext = sign-extend; zext = zero-extend; chop = keep only low bits that fit; s2f = signed-to-float; f2s = float-to-signed; u2f = unsigned-to-float; f2u = float-to-unsigned; f2f = float-to-float. 1 If the destination register is wider than the destination format, the result is extended to the destination register width after chopping. The type of extension (sign or zero) is based on the destination format. For example, cvt.s16.u32 targeting a 32-bit register first chops to 16-bit, then sign-extends to 32-bit. |
6.5.2. Rounding Modifiers
Conversion instructions may specify a rounding modifier. In PTX, there are four integer rounding modifiers and four floating-point rounding modifiers. Table 14 and Table 15 summarize the rounding modifiers.
Modifier |
Description |
---|---|
|
mantissa LSB rounds to nearest even |
|
mantissa LSB rounds to nearest, ties away from zero |
|
mantissa LSB rounds towards zero |
|
mantissa LSB rounds towards negative infinity |
|
mantissa LSB rounds towards positive infinity |
Modifier |
Description |
---|---|
|
round to nearest integer, choosing even integer if source is equidistant between two integers. |
|
round to nearest integer in the direction of zero |
|
round to nearest integer in direction of negative infinity |
|
round to nearest integer in direction of positive infinity |
6.6. Operand Costs
Operands from different state spaces affect the speed of an operation. Registers are fastest, while global memory is slowest. Much of the delay to memory can be hidden in a number of ways. The first is to have multiple threads of execution so that the hardware can issue a memory operation and then switch to other execution. Another way to hide latency is to issue the load instructions as early as possible, as execution is not blocked until the desired result is used in a subsequent (in time) instruction. The register in a store operation is available much more quickly. Table 16 gives estimates of the costs of using different kinds of memory.
Space |
Time |
Notes |
---|---|---|
Register |
0 |
|
Shared |
0 |
|
Constant |
0 |
Amortized cost is low, first access is high |
Local |
> 100 clocks |
|
Parameter |
0 |
|
Immediate |
0 |
|
Global |
> 100 clocks |
|
Texture |
> 100 clocks |
|
Surface |
> 100 clocks |
7. Abstracting the ABI
Rather than expose details of a particular calling convention, stack layout, and Application Binary
Interface (ABI), PTX provides a slightly higher-level abstraction and supports multiple ABI
implementations. In this section, we describe the features of PTX needed to achieve this hiding of
the ABI. These include syntax for function definitions, function calls, parameter passing, support
for variadic functions (varargs
), and memory allocated on the stack (alloca
).
Refer to PTX Writers Guide to Interoperability for details on generating PTX compliant with Application Binary Interface (ABI) for the CUDA® architecture.
7.1. Function Declarations and Definitions
In PTX, functions are declared and defined using the .func
directive. A function declaration
specifies an optional list of return parameters, the function name, and an optional list of input
parameters; together these specify the function’s interface, or prototype. A function definition
specifies both the interface and the body of the function. A function must be declared or defined
prior to being called.
The simplest function has no parameters or return values, and is represented in PTX as follows:
.func foo
{
...
ret;
}
...
call foo;
...
Here, execution of the call
instruction transfers control to foo
, implicitly saving the
return address. Execution of the ret
instruction within foo
transfers control to the
instruction following the call.
Scalar and vector base-type input and return parameters may be represented simply as register variables. At the call, arguments may be register variables or constants, and return values may be placed directly into register variables. The arguments and return variables at the call must have type and size that match the callee’s corresponding formal parameters.
Example
.func (.reg .u32 %res) inc_ptr ( .reg .u32 %ptr, .reg .u32 %inc )
{
add.u32 %res, %ptr, %inc;
ret;
}
...
call (%r1), inc_ptr, (%r1,4);
...
When using the ABI, .reg
state space parameters must be at least 32-bits in size. Subword scalar
objects in the source language should be promoted to 32-bit registers in PTX, or use .param
state space byte arrays described next.
Objects such as C structures and unions are flattened into registers or byte arrays in PTX and are
represented using .param
space memory. For example, consider the following C structure, passed
by value to a function:
struct {
double dbl;
char c[4];
};
In PTX, this structure will be flattened into a byte array. Since memory accesses are required to be
aligned to a multiple of the access size, the structure in this example will be a 12 byte array with
8 byte alignment so that accesses to the .f64
field are aligned. The .param
state space is
used to pass the structure by value:
Example
.func (.reg .s32 out) bar (.reg .s32 x, .param .align 8 .b8 y[12])
{
.reg .f64 f1;
.reg .b32 c1, c2, c3, c4;
...
ld.param.f64 f1, [y+0];
ld.param.b8 c1, [y+8];
ld.param.b8 c2, [y+9];
ld.param.b8 c3, [y+10];
ld.param.b8 c4, [y+11];
...
... // computation using x,f1,c1,c2,c3,c4;
}
{
.param .b8 .align 8 py[12];
...
st.param.b64 [py+ 0], %rd;
st.param.b8 [py+ 8], %rc1;
st.param.b8 [py+ 9], %rc2;
st.param.b8 [py+10], %rc1;
st.param.b8 [py+11], %rc2;
// scalar args in .reg space, byte array in .param space
call (%out), bar, (%x, py);
...
In this example, note that .param
space variables are used in two ways. First, a .param
variable y
is used in function definition bar to represent a formal parameter. Second, a
.param
variable py
is declared in the body of the calling function and used to set up the
structure being passed to bar.
The following is a conceptual way to think about the .param
state space use in device functions.
For a caller,
The
.param
state space is used to set values that will be passed to a called function and/or to receive return values from a called function. Typically, a.param
byte array is used to collect together fields of a structure being passed by value.
For a callee,
The
.param
state space is used to receive parameter values and/or pass return values back to the caller.
The following restrictions apply to parameter passing.
For a caller,
Arguments may be
.param
variables,.reg
variables, or constants.In the case of
.param
space formal parameters that are byte arrays, the argument must also be a.param
space byte array with matching type, size, and alignment. A.param
argument must be declared within the local scope of the caller.In the case of
.param
space formal parameters that are base-type scalar or vector variables, the corresponding argument may be either a.param
or.reg
space variable with matching type and size, or a constant that can be represented in the type of the formal parameter.In the case of
.reg
space formal parameters, the corresponding argument may be either a.param
or.reg
space variable of matching type and size, or a constant that can be represented in the type of the formal parameter.In the case of
.reg
space formal parameters, the register must be at least 32-bits in size.All
st.param
instructions used for passing arguments to function call must immediately precede the correspondingcall
instruction andld.param
instruction used for collecting return value must immediately follow thecall
instruction without any control flow alteration.st.param
andld.param
instructions used for argument passing cannot be predicated. This enables compiler optimization and ensures that the.param
variable does not consume extra space in the caller’s frame beyond that needed by the ABI. The.param
variable simply allows a mapping to be made at the call site between data that may be in multiple locations (e.g., structure being manipulated by caller is located in registers and memory) to something that can be passed as a parameter or return value to the callee.
For a callee,
Input and return parameters may be
.param
variables or.reg
variables.Parameters in
.param
memory must be aligned to a multiple of 1, 2, 4, 8, or 16 bytes.Parameters in the
.reg
state space must be at least 32-bits in size.The
.reg
state space can be used to receive and return base-type scalar and vector values, including sub-word size objects when compiling in non-ABI mode. Supporting the.reg
state space provides legacy support.
Note that the choice of .reg
or .param
state space for parameter passing has no impact on
whether the parameter is ultimately passed in physical registers or on the stack. The mapping of
parameters to physical registers and stack locations depends on the ABI definition and the order,
size, and alignment of parameters.
7.1.1. Changes from PTX ISA Version 1.x
In PTX ISA version 1.x, formal parameters were restricted to .reg state space, and there was no support for array parameters. Objects such as C structures were flattened and passed or returned using multiple registers. PTX ISA version 1.x supports multiple return values for this purpose.
Beginning with PTX ISA version 2.0, formal parameters may be in either .reg
or .param
state
space, and .param
space parameters support arrays. For targets sm_20
or higher, PTX
restricts functions to a single return value, and a .param
byte array should be used to return
objects that do not fit into a register. PTX continues to support multiple return registers for
sm_1x
targets.
Note
PTX implements a stack-based ABI only for targets sm_20
or higher.
PTX ISA versions prior to 3.0 permitted variables in .reg
and .local
state spaces to be
defined at module scope. When compiling to use the ABI, PTX ISA version 3.0 and later disallows
module-scoped .reg
and .local
variables and restricts their use to within function
scope. When compiling without use of the ABI, module-scoped .reg
and .local
variables are
supported as before. When compiling legacy PTX code (ISA versions prior to 3.0) containing
module-scoped .reg
or .local
variables, the compiler silently disables use of the ABI.
7.2. Variadic Functions
Note
Support for variadic functions which was unimplemented has been removed from the spec.
PTX version 6.0 supports passing unsized array parameter to a function which can be used to implement variadic functions.
Refer to Kernel and Function Directives: .func for details
7.3. Alloca
PTX provides alloca
instruction for allocating storage at runtime on the per-thread local memory
stack. The allocated stack memory can be accessed with ld.local
and st.local
instructions
using the pointer returned by alloca
.
In order to facilitate deallocation of memory allocated with alloca
, PTX provides two additional
instructions: stacksave
which allows reading the value of stack pointer in a local variable, and
stackrestore
which can restore the stack pointer with the saved value.
alloca
, stacksave
, and stackrestore
instructions are described in Stack Manipulation
Instructions.
- Preview Feature:
-
Stack manipulation instructions
alloca
,stacksave
andstackrestore
are preview features in PTX ISA version 7.3. All details are subject to change with no guarantees of backward compatibility on future PTX ISA versions or SM architectures.
8. Memory Consistency Model
In multi-threaded executions, the side-effects of memory operations performed by each thread become visible to other threads in a partial and non-identical order. This means that any two operations may appear to happen in no order, or in different orders, to different threads. The axioms introduced by the memory consistency model specify exactly which contradictions are forbidden between the orders observed by different threads.
In the absence of any constraint, each read operation returns the value committed by some write operation to the same memory location, including the initial write to that memory location. The memory consistency model effectively constrains the set of such candidate writes from which a read operation can return a value.
8.1. Scope and applicability of the model
The constraints specified under this model apply to PTX programs with any PTX ISA version number,
running on sm_70
or later architectures.
The memory consistency model does not apply to texture (including ld.global.nc
) and surface
accesses.
8.1.1. Limitations on atomicity at system scope
When communicating with the host CPU, certain strong operations with system scope may not be performed atomically on some systems. For more details on atomicity guarantees to host memory, see the CUDA Atomicity Requirements.
8.2. Memory operations
The fundamental storage unit in the PTX memory model is a byte, consisting of 8 bits. Each state space available to a PTX program is a sequence of contiguous bytes in memory. Every byte in a PTX state space has a unique address relative to all threads that have access to the same state space.
Each PTX memory instruction specifies an address operand and a data type. The address operand contains a virtual address that gets converted to a physical address during memory access. The physical address and the size of the data type together define a physical memory location, which is the range of bytes starting from the physical address and extending up to the size of the data type in bytes.
The memory consistency model specification uses the terms “address” or “memory address” to indicate a virtual address, and the term “memory location” to indicate a physical memory location.
Each PTX memory instruction also specifies the operation — either a read, a write or an atomic read-modify-write — to be performed on all the bytes in the corresponding memory location.
8.2.1. Overlap
Two memory locations are said to overlap when the starting address of one location is within the range of bytes constituting the other location. Two memory operations are said to overlap when they specify the same virtual address and the corresponding memory locations overlap. The overlap is said to be complete when both memory locations are identical, and it is said to be partial otherwise.
8.2.2. Aliases
Two distinct virtual addresses are said to be aliases if they map to the same memory location.
8.2.3. Multimem Addresses
A multimem address is a virtual address which points to multiple distinct memory locations across devices.
Only multimem.* operations are valid on multimem addresses. That is, the behavior of accessing a multimem address in any other memory operation is undefined.
8.2.4. Memory Operations on Vector Data Types
The memory consistency model relates operations executed on memory locations with scalar data types, which have a maximum size and alignment of 64 bits. Memory operations with a vector data type are modelled as a set of equivalent memory operations with a scalar data type, executed in an unspecified order on the elements in the vector.
8.2.5. Memory Operations on Packed Data Types
A packed data type consists of two values of the same scalar data type, as described in Packed Data Types. These values are accessed in adjacent memory locations. A memory operation on a packed data type is modelled as a pair of equivalent memory operations on the scalar data type, executed in an unspecified order on each element of the packed data.
8.2.6. Initialization
Each byte in memory is initialized by a hypothetical write W0 executed before starting any thread in the program. If the byte is included in a program variable, and that variable has an initial value, then W0 writes the corresponding initial value for that byte; else W0 is assumed to have written an unknown but constant value to the byte.
8.3. State spaces
The relations defined in the memory consistency model are independent of state spaces. In
particular, causality order closes over all memory operations across all the state spaces. But the
side-effect of a memory operation in one state space can be observed directly only by operations
that also have access to the same state space. This further constrains the synchronizing effect of a
memory operation in addition to scope. For example, the synchronizing effect of the PTX instruction
ld.relaxed.shared.sys
is identical to that of ld.relaxed.shared.cluster
, since no thread
outside the same cluster can execute an operation that accesses the same memory location.
8.4. Operation types
For simplicity, the rest of the document refers to the following operation types, instead of mentioning specific instructions that give rise to them.
Operation Type |
Instruction/Operation |
---|---|
atomic operation |
|
read operation |
All variants of |
write operation |
All variants of |
memory operation |
A read or write operation. |
volatile operation |
An instruction with |
acquire operation |
A memory operation with |
release operation |
A memory operation with |
mmio operation |
An |
memory fence operation |
A |
proxy fence operation |
A |
strong operation |
A memory fence operation, or a memory operation with a |
weak operation |
An |
synchronizing operation |
A |
8.4.1. mmio Operation
An mmio operation is a memory operation with .mmio
qualifier specified. It is usually performed
on a memory location which is mapped to the control registers of peer I/O devices. It can also be
used for communication between threads but has poor performance relative to non-mmio operations.
The semantic meaning of mmio operations cannot be defined precisely as it is defined by the underlying I/O device. For formal specification of semantics of mmio operation from Memory Consistency Model perspective, it is equivalent to the semantics of a strong operation. But it follows a few implementation-specific properties, if it meets the CUDA atomicity requirements at the specified scope:
Writes are always performed and are never combined within the scope specified.
-
Reads are always performed, and are not forwarded, prefetched, combined, or allowed to hit any cache within the scope specified.
As an exception, in some implementations, the surrounding locations may also be loaded. In such cases the amount of data loaded is implementation specific and varies between 32 and 128 bytes in size.
8.5. Scope
Each strong operation must specify a scope, which is the set of threads that may interact directly with that operation and establish any of the relations described in the memory consistency model. There are four scopes:
Scope |
Description |
---|---|
|
The set of all threads executing in the same CTA as the current thread. |
|
The set of all threads executing in the same cluster as the current thread. |
|
The set of all threads in the current program executing on the same compute device as the current thread. This also includes other kernel grids invoked by the host program on the same compute device. |
|
The set of all threads in the current program, including all kernel grids invoked by the host program on all compute devices, and all threads constituting the host program itself. |
Note that the warp is not a scope; the CTA is the smallest collection of threads that qualifies as a scope in the memory consistency model.
8.6. Proxies
A memory proxy, or a proxy is an abstract label applied to a method of memory access. When two memory operations use distinct methods of memory access, they are said to be different proxies.
Memory operations as defined in Operation types use generic method of memory access, i.e. a generic proxy. Other operations such as textures and surfaces all use distinct methods of memory access, also distinct from the generic method.
A proxy fence is required to synchronize memory operations across different proxies. Although virtual aliases use the generic method of memory access, since using distinct virtual addresses behaves as if using different proxies, they require a proxy fence to establish memory ordering.
8.7. Morally strong operations
Two operations are said to be morally strong relative to each other if they satisfy all of the following conditions:
The operations are related in program order (i.e, they are both executed by the same thread), or each operation is strong and specifies a scope that includes the thread executing the other operation.
Both operations are performed via the same proxy.
If both are memory operations, then they overlap completely.
Most (but not all) of the axioms in the memory consistency model depend on relations between morally strong operations.
8.7.1. Conflict and Data-races
Two overlapping memory operations are said to conflict when at least one of them is a write.
Two conflicting memory operations are said to be in a data-race if they are not related in causality order and they are not morally strong.
8.7.2. Limitations on Mixed-size Data-races
A data-race between operations that overlap completely is called a uniform-size data-race, while a data-race between operations that overlap partially is called a mixed-size data-race.
The axioms in the memory consistency model do not apply if a PTX program contains one or more mixed-size data-races. But these axioms are sufficient to describe the behavior of a PTX program with only uniform-size data-races.
Atomicity of mixed-size RMW operations
In any program with or without mixed-size data-races, the following property holds for every pair of overlapping atomic operations A1 and A2 such that each specifies a scope that includes the other: Either the read-modify-write operation specified by A1 is performed completely before A2 is initiated, or vice versa. This property holds irrespective of whether the two operations A1 and A2 overlap partially or completely.
8.8. Release and Acquire Patterns
Some sequences of instructions give rise to patterns that participate in memory synchronization as described later. The release pattern makes prior operations from the current thread1 visible to some operations from other threads. The acquire pattern makes some operations from other threads visible to later operations from the current thread.
A release pattern on a location M consists of one of the following:
-
A release operation on M
E.g.:
st.release [M];
oratom.acq_rel [M];
ormbarrier.arrive.release [M];
-
Or a release operation on M followed by a strong write on M in program order
E.g.:
st.release [M]
;st.relaxed [M];
-
Or a memory fence followed by a strong write on M in program order
E.g.:
fence; st.relaxed [M];
Any memory synchronization established by a release pattern only affects operations occurring in program order before the first instruction in that pattern.
An acquire pattern on a location M consists of one of the following:
-
An acquire operation on M
E.g.:
ld.acquire [M];
oratom.acq_rel [M];
ormbarrier.test_wait.acquire [M];
-
Or a strong read on M followed by an acquire operation on M in program order
E.g.:
ld.relaxed [M]; ld.acquire [M];
-
Or a strong read on M followed by a memory fence in program order
E.g.:
ld.relaxed [M]; fence;
Any memory synchronization established by an acquire pattern only affects operations occurring in program order after the last instruction in that pattern.
1 For both release and acquire patterns, this effect is further extended to operations in other threads through the transitive nature of causality order.
8.9. Ordering of memory operations
The sequence of operations performed by each thread is captured as program order while memory synchronization across threads is captured as causality order. The visibility of the side-effects of memory operations to other memory operations is captured as communication order. The memory consistency model defines contradictions that are disallowed between communication order on the one hand, and causality order and program order on the other.
8.9.1. Program Order
The program order relates all operations performed by a thread to the order in which a sequential processor will execute instructions in the corresponding PTX source. It is a transitive relation that forms a total order over the operations performed by the thread, but does not relate operations from different threads.
8.9.1.1. Asynchronous Operations
Some PTX instructions (all variants of cp.async
, cp.async.bulk
, cp.reduce.async.bulk
,
wgmma.mma_async
) perform operations that are asynchronous to the thread that executed the
instruction. These asynchronous operations are ordered after prior instructions in the same thread
(except in the case of wgmma.mma_async
), but they are not part of the program order for that
thread. Instead, they provide weaker ordering guarantees as documented in the instruction
description.
For example, the loads and stores performed as part of a cp.async
are ordered with respect to
each other, but not to those of any other cp.async
instructions initiated by the same thread,
nor any other instruction subsequently issued by the thread with the exception of
cp.async.commit_group
or cp.async.mbarrier.arrive
. The asynchronous mbarrier arrive-on operation
performed by a cp.async.mbarrier.arrive
instruction is ordered with respect to the memory
operations performed by all prior cp.async
operations initiated by the same thread, but not to
those of any other instruction issued by the thread. The implicit mbarrier complete-tx
operation that is part of all variants of cp.async.bulk
and cp.reduce.async.bulk
instructions is ordered only with respect to the memory operations performed by the same
asynchronous instruction, and in particular it does not transitively establish ordering with respect
to prior instructions from the issuing thread.
8.9.2. Observation Order
Observation order relates a write W to a read R through an optional sequence of atomic read-modify-write operations.
A write W precedes a read R in observation order if:
R and W are morally strong and R reads the value written by W, or
For some atomic operation Z, W precedes Z and Z precedes R in observation order.
8.9.3. Fence-SC Order
The Fence-SC order is an acyclic partial order, determined at runtime, that relates every pair of morally strong fence.sc operations.
8.9.4. Memory synchronization
Synchronizing operations performed by different threads synchronize with each other at runtime as described here. The effect of such synchronization is to establish causality order across threads.
A fence.sc operation X synchronizes with a fence.sc operation Y if X precedes Y in the Fence-SC order.
A bar{.cta}.sync or bar{.cta}.red or bar{.cta}.arrive operation synchronizes with a bar{.cta}.sync or bar{.cta}.red operation executed on the same barrier.
A
barrier.cluster.arrive
operation synchronizes with abarrier.cluster.wait
operation.A release pattern X synchronizes with an acquire pattern Y, if a write operation in X precedes a read operation in Y in observation order, and the first operation in X and the last operation in Y are morally strong.
API synchronization
A synchronizes relation can also be established by certain CUDA APIs.
Completion of a task enqueued in a CUDA stream synchronizes with the start of the following task in the same stream, if any.
For purposes of the above, recording or waiting on a CUDA event in a stream, or causing a cross-stream barrier to be inserted due to
cudaStreamLegacy
, enqueues tasks in the associated streams even if there are no direct side effects. An event record task synchronizes with matching event wait tasks, and a barrier arrival task synchronizes with matching barrier wait tasks.Start of a CUDA kernel synchronizes with start of all threads in the kernel. End of all threads in a kernel synchronize with end of the kernel.
Start of a CUDA graph synchronizes with start of all source nodes in the graph. Completion of all sink nodes in a CUDA graph synchronizes with completion of the graph. Completion of a graph node synchronizes with start of all nodes with a direct dependency.
Start of a CUDA API call to enqueue a task synchronizes with start of the task.
Completion of the last task queued to a stream, if any, synchronizes with return from
cudaStreamSynchronize
. Completion of the most recently queued matching event record task, if any, synchronizes with return fromcudaEventSynchronize
. Synchronizing a CUDA device or context behaves as if synchronizing all streams in the context, including ones that have been destroyed.Returning
cudaSuccess
from an API to query a CUDA handle, such as a stream or event, behaves the same as return from the matching synchronization API.
In addition to establishing a synchronizes relation, the CUDA API synchronization mechanisms above also participate in proxy-preserved base causality order.
8.9.5. Causality Order
Causality order captures how memory operations become visible across threads through synchronizing operations. The axiom “Causality” uses this order to constrain the set of write operations from which a read operation may read a value.
Relations in the causality order primarily consist of relations in Base causality order1 , which is a transitive order, determined at runtime.
Base causality order
An operation X precedes an operation Y in base causality order if:
X precedes Y in program order, or
X synchronizes with Y, or
-
For some operation Z,
X precedes Z in program order and Z precedes Y in base causality order, or
X precedes Z in base causality order and Z precedes Y in program order, or
X precedes Z in base causality order and Z precedes Y in base causality order.
Proxy-preserved base causality order
A memory operation X precedes a memory operation Y in proxy-preserved base causality order if X precedes Y in base causality order, and:
X and Y are performed to the same address, using the generic proxy, or
X and Y are performed to the same address, using the same proxy, and by the same thread block, or
X and Y are aliases and there is an alias proxy fence along the base causality path from X to Y.
Causality order
Causality order combines base causality order with some non-transitive relations as follows:
An operation X precedes an operation Y in causality order if:
X precedes Y in proxy-preserved base causality order, or
For some operation Z, X precedes Z in observation order, and Z precedes Y in proxy-preserved base causality order.
1 The transitivity of base causality order accounts for the “cumulativity” of synchronizing operations.
8.9.6. Coherence Order
There exists a partial transitive order that relates overlapping write operations, determined at runtime, called the coherence order1. Two overlapping write operations are related in coherence order if they are morally strong or if they are related in causality order. Two overlapping writes are unrelated in coherence order if they are in a data-race, which gives rise to the partial nature of coherence order.
1 Coherence order cannot be observed directly since it consists entirely of write operations. It may be observed indirectly by its use in constraining the set of candidate writes that a read operation may read from.
8.9.7. Communication Order
The communication order is a non-transitive order, determined at runtime, that relates write operations to other overlapping memory operations.
A write W precedes an overlapping read R in communication order if R returns the value of any byte that was written by W.
A write W precedes a write W’ in communication order if W precedes W’ in coherence order.
A read R precedes an overlapping write W in communication order if, for any byte accessed by both R and W, R returns the value written by a write W’ that precedes W in coherence order.
Communication order captures the visibility of memory operations — when a memory operation X1 precedes a memory operation X2 in communication order, X1 is said to be visible to X2.
8.10. Axioms
8.10.1. Coherence
If a write W precedes an overlapping write W’ in causality order, then W must precede W’ in coherence order.
8.10.2. Fence-SC
Fence-SC order cannot contradict causality order. For a pair of morally strong fence.sc operations F1 and F2, if F1 precedes F2 in causality order, then F1 must precede F2 in Fence-SC order.
8.10.3. Atomicity
Single-Copy Atomicity
Conflicting morally strong operations are performed with single-copy atomicity. When a read R and a write W are morally strong, then the following two communications cannot both exist in the same execution, for the set of bytes accessed by both R and W:
R reads any byte from W.
R reads any byte from any write W’ which precedes W in coherence order.
Atomicity of read-modify-write (RMW) operations
When an atomic operation A and a write W overlap and are morally strong, then the following two communications cannot both exist in the same execution, for the set of bytes accessed by both A and W:
A reads any byte from a write W’ that precedes W in coherence order.
A follows W in coherence order.
Litmus Test 1:
.global .u32 x = 0;
|
|
T1 |
T2 |
A1: atom.sys.inc.u32 %r0, [x];
|
A2: atom.sys.inc.u32 %r0, [x];
|
FINAL STATE: x == 2
|
Atomicity is guaranteed when the operations are morally strong.
Litmus Test 2:
.global .u32 x = 0;
|
|
T1 |
T2 (In a different CTA) |
A1: atom.cta.inc.u32 %r0, [x];
|
A2: atom.gpu.inc.u32 %r0, [x];
|
FINAL STATE: x == 1 OR x == 2
|
Atomicity is not guaranteed if the operations are not morally strong.
8.10.4. No Thin Air
Values may not appear “out of thin air”: an execution cannot speculatively produce a value in such a way that the speculation becomes self-satisfying through chains of instruction dependencies and inter-thread communication. This matches both programmer intuition and hardware reality, but is necessary to state explicitly when performing formal analysis.
Litmus Test: Load Buffering
.global .u32 x = 0;
.global .u32 y = 0;
|
|
T1 |
T2 |
A1: ld.global.u32 %r0, [x];
B1: st.global.u32 [y], %r0;
|
A2: ld.global.u32 %r1, [y];
B2: st.global.u32 [x], %r1;
|
FINAL STATE: x == 0 AND y == 0
|
The litmus test known as “LB” (Load Buffering) checks such forbidden values that may arise out of thin air. Two threads T1 and T2 each read from a first variable and copy the observed result into a second variable, with the first and second variable exchanged between the threads. If each variable is initially zero, the final result shall also be zero. If A1 reads from B2 and A2 reads from B1, then values passing through the memory operations in this example form a cycle: A1->B1->A2->B2->A1. Only the values x == 0 and y == 0 are allowed to satisfy this cycle. If any of the memory operations in this example were to speculatively associate a different value with the corresponding memory location, then such a speculation would become self-fulfilling, and hence forbidden.
8.10.5. Sequential Consistency Per Location
Within any set of overlapping memory operations that are pairwise morally strong, communication order cannot contradict program order, i.e., a concatenation of program order between overlapping operations and morally strong relations in communication order cannot result in a cycle. This ensures that each program slice of overlapping pairwise morally strong operations is strictly sequentially-consistent.
Litmus Test: CoRR
.global .u32 x = 0;
|
|
T1 |
T2 |
W1: st.global.relaxed.sys.u32 [x], 1;
|
R1: ld.global.relaxed.sys.u32 %r0, [x];
R2: ld.global.relaxed.sys.u32 %r1, [x];
|
IF %r0 == 1 THEN %r1 == 1
|
The litmus test “CoRR” (Coherent Read-Read), demonstrates one consequence of this guarantee. A thread T1 executes a write W1 on a location x, and a thread T2 executes two (or an infinite sequence of) reads R1 and R2 on the same location x. No other writes are executed on x, except the one modelling the initial value. The operations W1, R1 and R2 are pairwise morally strong. If R1 reads from W1, then the subsequent read R2 must also observe the same value. If R2 observed the initial value of x instead, then this would form a sequence of morally-strong relations R2->W1->R1 in communication order that contradicts the program order R1->R2 in thread T2. Hence R2 cannot read the initial value of x in such an execution.
8.10.6. Causality
Relations in communication order cannot contradict causality order. This constrains the set of candidate write operations that a read operation may read from:
If a read R precedes an overlapping write W in causality order, then R cannot read from W.
If a write W precedes an overlapping read R in causality order, then for any byte accessed by both R and W, R cannot read from any write W’ that precedes W in coherence order.
Litmus Test: Message Passing
.global .u32 data = 0;
.global .u32 flag = 0;
|
|
T1 |
T2 |
W1: st.global.u32 [data], 1;
F1: fence.sys;
W2: st.global.relaxed.sys.u32 [flag], 1;
|
R1: ld.global.relaxed.sys.u32 %r0, [flag];
F2: fence.sys;
R2: ld.global.u32 %r1, [data];
|
IF %r0 == 1 THEN %r1 == 1
|
The litmus test known as “MP” (Message Passing) represents the essence of typical synchronization algorithms. A vast majority of useful programs can be reduced to sequenced applications of this pattern.
Thread T1 first writes to a data variable and then to a flag variable while a second thread T2 first reads from the flag variable and then from the data variable. The operations on the flag are morally strong and the memory operations in each thread are separated by a fence, and these fences are morally strong.
If R1 observes W2, then the release pattern “F1; W2” synchronizes with the acquire pattern “R1; F2”. This establishes the causality order W1 -> F1 -> W2 -> R1 -> F2 -> R2. Then axiom causality guarantees that R2 cannot read from any write that precedes W1 in coherence order. In the absence of any other writes in this example, R2 must read from W1.
Litmus Test: CoWR
// These addresses are aliases
.global .u32 data_alias_1;
.global .u32 data_alias_2;
|
T1 |
W1: st.global.u32 [data_alias_1], 1;
F1: fence.proxy.alias;
R1: ld.global.u32 %r1, [data_alias_2];
|
%r1 == 1
|
Virtual aliases require an alias proxy fence along the synchronization path.
Litmus Test: Store Buffering
The litmus test known as “SB” (Store Buffering) demonstrates the sequential consistency enforced
by the fence.sc
. A thread T1 writes to a first variable, and then reads the value of a second
variable, while a second thread T2 writes to the second variable and then reads the value of the
first variable. The memory operations in each thread are separated by fence.
sc instructions,
and these fences are morally strong.
.global .u32 x = 0;
.global .u32 y = 0;
|
|
T1 |
T2 |
W1: st.global.u32 [x], 1;
F1: fence.sc.sys;
R1: ld.global.u32 %r0, [y];
|
W2: st.global.u32 [y], 1;
F2: fence.sc.sys;
R2: ld.global.u32 %r1, [x];
|
%r0 == 1 OR %r1 == 1
|
In any execution, either F1 precedes F2 in Fence-SC order, or vice versa. If F1 precedes F2 in
Fence-SC order, then F1 synchronizes with F2. This establishes the causality order in W1 -> F1
-> F2 -> R2. Axiom causality ensures that R2 cannot read from any write that precedes W1 in
coherence order. In the absence of any other write to that variable, R2 must read from
W1. Similarly, in the case where F2 precedes F1 in Fence-SC order, R1 must read from W2. If each
fence.sc
in this example were replaced by a fence.acq_rel
instruction, then this outcome is
not guaranteed. There may be an execution where the write from each thread remains unobserved from
the other thread, i.e., an execution is possible, where both R1 and R2 return the initial value “0”
for variables y and x respectively.
9. Instruction Set
9.1. Format and Semantics of Instruction Descriptions
This section describes each PTX instruction. In addition to the name and the format of the instruction, the semantics are described, followed by some examples that attempt to show several possible instantiations of the instruction.
9.2. PTX Instructions
PTX instructions generally have from zero to four operands, plus an optional guard predicate
appearing after an @
symbol to the left of the opcode
:
@p opcode;
@p opcode a;
@p opcode d, a;
@p opcode d, a, b;
@p opcode d, a, b, c;
For instructions that create a result value, the d
operand is the destination operand, while
a
, b
, and c
are source operands.
The setp
instruction writes two destination registers. We use a |
symbol to separate
multiple destination registers.
setp.lt.s32 p|q, a, b; // p = (a < b); q = !(a < b);
For some instructions the destination operand is optional. A bit bucket operand denoted with an
underscore (_
) may be used in place of a destination register.
9.3. Predicated Execution
In PTX, predicate registers are virtual and have .pred
as the type specifier. So, predicate
registers can be declared as
.reg .pred p, q, r;
All instructions have an optional guard predicate which controls conditional execution of the
instruction. The syntax to specify conditional execution is to prefix an instruction with @{!}p
,
where p
is a predicate variable, optionally negated. Instructions without a guard predicate are
executed unconditionally.
Predicates are most commonly set as the result of a comparison performed by the setp
instruction.
As an example, consider the high-level code
if (i < n)
j = j + 1;
This can be written in PTX as
setp.lt.s32 p, i, n; // p = (i < n)
@p add.s32 j, j, 1; // if i < n, add 1 to j
To get a conditional branch or conditional function call, use a predicate to control the execution of the branch or call instructions. To implement the above example as a true conditional branch, the following PTX instruction sequence might be used:
setp.lt.s32 p, i, n; // compare i to n
@!p bra L1; // if False, branch over
add.s32 j, j, 1;
L1: ...
9.3.1. Comparisons
9.3.1.1. Integer and Bit-Size Comparisons
The signed integer comparisons are the traditional eq
(equal), ne
(not-equal), lt
(less-than), le
(less-than-or-equal), gt
(greater-than), and ge
(greater-than-or-equal). The unsigned comparisons are eq
, ne
, lo
(lower), ls
(lower-or-same), hi
(higher), and hs
(higher-or-same). The bit-size comparisons are eq
and ne
; ordering comparisons are not defined for bit-size types.
Table 19 shows the operators for signed integer, unsigned integer, and bit-size types.
Meaning |
Signed Operator |
Unsigned Operator |
Bit-Size Operator |
---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
n/a |
|
|
|
n/a |
|
|
|
n/a |
|
|
|
n/a |
9.3.1.2. Floating Point Comparisons
The ordered floating-point comparisons are eq
, ne
, lt
, le
, gt
, and ge
. If
either operand is NaN
, the result is
False
. Table 20 lists the floating-point
comparison operators.
Meaning |
Floating-Point Operator |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
To aid comparison operations in the presence of NaN
values, unordered floating-point comparisons
are provided: equ
, neu
, ltu
, leu
, gtu
, and geu
. If both operands are numeric
values (not NaN
), then the comparison has the same result as its ordered counterpart. If either
operand is NaN
, then the result of the comparison is True
.
Table 21 lists the floating-point
comparison operators accepting NaN
values.
Meaning |
Floating-Point Operator |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
To test for NaN
values, two operators num
(numeric
) and nan
(isNaN
) are
provided. num
returns True
if both operands are numeric values (not NaN
), and nan
returns True
if either operand is
NaN
. Table 22 lists the
floating-point comparison operators testing for NaN
values.
Meaning |
Floating-Point Operator |
---|---|
|
|
|
|
9.3.2. Manipulating Predicates
Predicate values may be computed and manipulated using the following instructions: and
, or
,
xor
, not
, and mov
.
There is no direct conversion between predicates and integer values, and no direct way to load or
store predicate register values. However, setp
can be used to generate a predicate from an
integer, and the predicate-based select (selp
) instruction can be used to generate an integer
value based on the value of a predicate; for example:
selp.u32 %r1,1,0,%p; // convert predicate to 32-bit value
9.4. Type Information for Instructions and Operands
Typed instructions must have a type-size modifier. For example, the add
instruction requires
type and size information to properly perform the addition operation (signed, unsigned, float,
different sizes), and this information must be specified as a suffix to the opcode.
Example
.reg .u16 d, a, b;
add.u16 d, a, b; // perform a 16-bit unsigned add
Some instructions require multiple type-size modifiers, most notably the data conversion instruction
cvt
. It requires separate type-size modifiers for the result and source, and these are placed in
the same order as the operands. For example:
.reg .u16 a;
.reg .f32 d;
cvt.f32.u16 d, a; // convert 16-bit unsigned to 32-bit float
In general, an operand’s type must agree with the corresponding instruction-type modifier. The rules for operand and instruction type conformance are as follows:
Bit-size types agree with any type of the same size.
Signed and unsigned integer types agree provided they have the same size, and integer operands are silently cast to the instruction type if needed. For example, an unsigned integer operand used in a signed integer instruction will be treated as a signed integer by the instruction.
Floating-point types agree only if they have the same size; i.e., they must match exactly.
Table 23 summarizes these type checking rules.
Operand Type |
|||||
---|---|---|---|---|---|
.bX |
.sX |
.uX |
.fX |
||
Instruction Type |
.bX |
okay |
okay |
okay |
okay |
.sX |
okay |
okay |
okay |
invalid |
|
.uX |
okay |
okay |
okay |
invalid |
|
.fX |
okay |
invalid |
invalid |
okay |
Note
Some operands have their type and size defined independently from the instruction type-size. For
example, the shift amount operand for left and right shift instructions always has type .u32
,
while the remaining operands have their type and size determined by the instruction type.
Example
// 64-bit arithmetic right shift; shift amount 'b' is .u32
shr.s64 d,a,b;
9.4.1. Operand Size Exceeding Instruction-Type Size
For convenience, ld
, st
, and cvt
instructions permit source and destination data
operands to be wider than the instruction-type size, so that narrow values may be loaded, stored,
and converted using regular-width registers. For example, 8-bit or 16-bit values may be held
directly in 32-bit or 64-bit registers when being loaded, stored, or converted to other types and
sizes. The operand type checking rules are relaxed for bit-size and integer (signed and unsigned)
instruction types; floating-point instruction types still require that the operand type-size matches
exactly, unless the operand is of bit-size type.
When a source operand has a size that exceeds the instruction-type size, the source data is truncated (chopped) to the appropriate number of bits specified by the instruction type-size.
Table 24
summarizes the relaxed type-checking rules for source operands. Note that some combinations may
still be invalid for a particular instruction; for example, the cvt
instruction does not support
.bX
instruction types, so those rows are invalid for cvt
.
Source Operand Type |
|||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b8 |
b16 |
b32 |
b64 |
b128 |
s8 |
s16 |
s32 |
s64 |
u8 |
u16 |
u32 |
u64 |
f16 |
f32 |
f64 |
||
Instruction Type |
b8 |
– |
chop |
chop |
chop |
chop |
– |
chop |
chop |
chop |
– |
chop |
chop |
chop |
chop |
chop |
chop |
b16 |
inv |
– |
chop |
chop |
chop |
inv |
– |
chop |
chop |
inv |
– |
chop |
chop |
– |
chop |
chop |
|
b32 |
inv |
inv |
– |
chop |
chop |
inv |
inv |
– |
chop |
inv |
inv |
– |
chop |
inv |
– |
chop |
|
b64 |
inv |
inv |
inv |
– |
chop |
inv |
inv |
inv |
– |
inv |
inv |
inv |
– |
inv |
inv |
– |
|
b128 |
inv |
inv |
inv |
inv |
– |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
|
s8 |
– |
chop |
chop |
chop |
chop |
– |
chop |
chop |
chop |
– |
chop |
chop |
chop |
inv |
inv |
inv |
|
s16 |
inv |
– |
chop |
chop |
chop |
inv |
– |
chop |
chop |
inv |
– |
chop |
chop |
inv |
inv |
inv |
|
s32 |
inv |
inv |
– |
chop |
chop |
inv |
inv |
– |
chop |
inv |
inv |
– |
chop |
inv |
inv |
inv |
|
s64 |
inv |
inv |
inv |
– |
chop |
inv |
inv |
inv |
– |
inv |
inv |
inv |
– |
inv |
inv |
inv |
|
u8 |
– |
chop |
chop |
chop |
chop |
– |
chop |
chop |
chop |
– |
chop |
chop |
chop |
inv |
inv |
inv |
|
u16 |
inv |
– |
chop |
chop |
chop |
inv |
– |
chop |
chop |
inv |
– |
chop |
chop |
inv |
inv |
inv |
|
u32 |
inv |
inv |
– |
chop |
chop |
inv |
inv |
– |
chop |
inv |
inv |
– |
chop |
inv |
inv |
inv |
|
u64 |
inv |
inv |
inv |
– |
chop |
inv |
inv |
inv |
– |
inv |
inv |
inv |
– |
inv |
inv |
inv |
|
f16 |
inv |
– |
chop |
chop |
chop |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
– |
inv |
inv |
|
f32 |
inv |
inv |
– |
chop |
chop |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
– |
inv |
|
f64 |
inv |
inv |
inv |
– |
chop |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
– |
|
Notes |
chop = keep only low bits that fit; “–” = allowed, but no conversion needed; inv = invalid, parse error.
|
When a destination operand has a size that exceeds the instruction-type size, the destination data is zero- or sign-extended to the size of the destination register. If the corresponding instruction type is signed integer, the data is sign-extended; otherwise, the data is zero-extended.
Table 25 summarizes the relaxed type-checking rules for destination operands.
Destination Operand Type |
|||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b8 |
b16 |
b32 |
b64 |
b128 |
s8 |
s16 |
s32 |
s64 |
u8 |
u16 |
u32 |
u64 |
f16 |
f32 |
f64 |
||
Instruction Type |
b8 |
– |
zext |
zext |
zext |
zext |
– |
zext |
zext |
zext |
– |
zext |
zext |
zext |
zext |
zext |
zext |
b16 |
inv |
– |
zext |
zext |
zext |
inv |
– |
zext |
zext |
inv |
– |
zext |
zext |
– |
zext |
zext |
|
b32 |
inv |
inv |
– |
zext |
zext |
inv |
inv |
– |
zext |
inv |
inv |
– |
zext |
inv |
– |
zext |
|
b64 |
inv |
inv |
inv |
– |
zext |
inv |
inv |
inv |
– |
inv |
inv |
inv |
– |
inv |
inv |
– |
|
b128 |
inv |
inv |
inv |
inv |
– |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
|
s8 |
– |
sext |
sext |
sext |
sext |
– |
sext |
sext |
sext |
– |
sext |
sext |
sext |
inv |
inv |
inv |
|
s16 |
inv |
– |
sext |
sext |
sext |
inv |
– |
sext |
sext |
inv |
– |
sext |
sext |
inv |
inv |
inv |
|
s32 |
inv |
inv |
– |
sext |
sext |
inv |
inv |
– |
sext |
inv |
inv |
– |
sext |
inv |
inv |
inv |
|
s64 |
inv |
inv |
inv |
– |
sext |
inv |
inv |
inv |
– |
inv |
inv |
inv |
– |
inv |
inv |
inv |
|
u8 |
– |
zext |
zext |
zext |
zext |
– |
zext |
zext |
zext |
– |
zext |
zext |
zext |
inv |
inv |
inv |
|
u16 |
inv |
– |
zext |
zext |
zext |
inv |
– |
zext |
zext |
inv |
– |
zext |
zext |
inv |
inv |
inv |
|
u32 |
inv |
inv |
– |
zext |
zext |
inv |
inv |
– |
zext |
inv |
inv |
– |
zext |
inv |
inv |
inv |
|
u64 |
inv |
inv |
inv |
– |
zext |
inv |
inv |
inv |
– |
inv |
inv |
inv |
– |
inv |
inv |
inv |
|
f16 |
inv |
– |
zext |
zext |
zext |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
– |
inv |
inv |
|
f32 |
inv |
inv |
– |
zext |
zext |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
– |
inv |
|
f64 |
inv |
inv |
inv |
– |
zext |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
inv |
– |
|
Notes |
sext = sign-extend; zext = zero-extend; “–” = allowed, but no conversion needed; inv = invalid, parse error.
|
9.5. Divergence of Threads in Control Constructs
Threads in a CTA execute together, at least in appearance, until they come to a conditional control construct such as a conditional branch, conditional function call, or conditional return. If threads execute down different control flow paths, the threads are called divergent. If all of the threads act in unison and follow a single control flow path, the threads are called uniform. Both situations occur often in programs.
A CTA with divergent threads may have lower performance than a CTA with uniformly executing threads,
so it is important to have divergent threads re-converge as soon as possible. All control constructs
are assumed to be divergent points unless the control-flow instruction is marked as uniform, using
the .uni
suffix. For divergent control flow, the optimizing code generator automatically
determines points of re-convergence. Therefore, a compiler or code author targeting PTX can ignore
the issue of divergent threads, but has the opportunity to improve performance by marking branch
points as uniform when the compiler or author can guarantee that the branch point is non-divergent.
9.6. Semantics
The goal of the semantic description of an instruction is to describe the results in all cases in as simple language as possible. The semantics are described using C, until C is not expressive enough.
9.6.1. Machine-Specific Semantics of 16-bit Code
A PTX program may execute on a GPU with either a 16-bit or a 32-bit data path. When executing on a 32-bit data path, 16-bit registers in PTX are mapped to 32-bit physical registers, and 16-bit computations are promoted to 32-bit computations. This can lead to computational differences between code run on a 16-bit machine versus the same code run on a 32-bit machine, since the promoted computation may have bits in the high-order half-word of registers that are not present in 16-bit physical registers. These extra precision bits can become visible at the application level, for example, by a right-shift instruction.
At the PTX language level, one solution would be to define semantics for 16-bit code that is consistent with execution on a 16-bit data path. This approach introduces a performance penalty for 16-bit code executing on a 32-bit data path, since the translated code would require many additional masking instructions to suppress extra precision bits in the high-order half-word of 32-bit registers.
Rather than introduce a performance penalty for 16-bit code running on 32-bit GPUs, the semantics of 16-bit instructions in PTX is machine-specific. A compiler or programmer may chose to enforce portable, machine-independent 16-bit semantics by adding explicit conversions to 16-bit values at appropriate points in the program to guarantee portability of the code. However, for many performance-critical applications, this is not desirable, and for many applications the difference in execution is preferable to limiting performance.
9.7. Instructions
All PTX instructions may be predicated. In the following descriptions, the optional guard predicate is omitted from the syntax.
9.7.1. Integer Arithmetic Instructions
Integer arithmetic instructions operate on the integer types in register and constant immediate forms. The integer arithmetic instructions are:
add
sub
mul
mad
mul24
mad24
sad
div
rem
abs
neg
min
max
popc
clz
bfind
fns
brev
bfe
bfi
bmsk
szext
dp4a
dp2a
9.7.1.1. Integer Arithmetic Instructions: add
add
Add two values.
Syntax
add.type d, a, b;
add{.sat}.s32 d, a, b; // .sat applies only to .s32
.type = { .u16, .u32, .u64,
.s16, .s32, .s64,
.u16x2, .s16x2 };
Description
Performs addition and writes the resulting value into a destination register.
For .u16x2
, .s16x2
instruction types, forms input vectors by half word values from source
operands. Half-word operands are then added in parallel to produce .u16x2
, .s16x2
result in
destination.
Operands d
, a
and b
have type .type
. For instruction types .u16x2
, .s16x2
,
operands d
, a
and b
have type .b32
.
Semantics
if (type == u16x2 || type == s16x2) {
iA[0] = a[0:15];
iA[1] = a[16:31];
iB[0] = b[0:15];
iB[1] = b[16:31];
for (i = 0; i < 2; i++) {
d[i] = iA[i] + iB[i];
}
} else {
d = a + b;
}
Notes
Saturation modifier:
- .sat
-
limits result to
MININT..MAXINT
(no overflow) for the size of the operation. Applies only to.s32
type.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
add.u16x2
and add.s16x2
introduced in PTX ISA version 8.0.
Target ISA Notes
Supported on all target architectures.
add.u16x2
and add.s16x2
require sm_90
or higher.
Examples
@p add.u32 x,y,z;
add.sat.s32 c,c,1;
add.u16x2 u,v,w;
9.7.1.2. Integer Arithmetic Instructions: sub
sub
Subtract one value from another.
Syntax
sub.type d, a, b;
sub{.sat}.s32 d, a, b; // .sat applies only to .s32
.type = { .u16, .u32, .u64,
.s16, .s32, .s64 };
Description
Performs subtraction and writes the resulting value into a destination register.
Semantics
d = a - b;
Notes
Saturation modifier:
.sat
-
limits result to
MININT..MAXINT
(no overflow) for the size of the operation. Applies only to.s32
type.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
Supported on all target architectures.
Examples
sub.s32 c,a,b;
9.7.1.3. Integer Arithmetic Instructions: mul
mul
Multiply two values.
Syntax
mul.mode.type d, a, b;
.mode = { .hi, .lo, .wide };
.type = { .u16, .u32, .u64,
.s16, .s32, .s64 };
Description
Compute the product of two values.
Semantics
t = a * b;
n = bitwidth of type;
d = t; // for .wide
d = t<2n-1..n>; // for .hi variant
d = t<n-1..0>; // for .lo variant
Notes
The type of the operation represents the types of the a
and b
operands. If .hi
or
.lo
is specified, then d
is the same size as a
and b
, and either the upper or lower
half of the result is written to the destination register. If .wide
is specified, then d
is
twice as wide as a
and b
to receive the full result of the multiplication.
The .wide
suffix is supported only for 16- and 32-bit integer types.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
Supported on all target architectures.
Examples
mul.wide.s16 fa,fxs,fys; // 16*16 bits yields 32 bits
mul.lo.s16 fa,fxs,fys; // 16*16 bits, save only the low 16 bits
mul.wide.s32 z,x,y; // 32*32 bits, creates 64 bit result
9.7.1.4. Integer Arithmetic Instructions: mad
mad
Multiply two values, optionally extract the high or low half of the intermediate result, and add a third value.
Syntax
mad.mode.type d, a, b, c;
mad.hi.sat.s32 d, a, b, c;
.mode = { .hi, .lo, .wide };
.type = { .u16, .u32, .u64,
.s16, .s32, .s64 };
Description
Multiplies two values, optionally extracts the high or low half of the intermediate result, and adds a third value. Writes the result into a destination register.
Semantics
t = a * b;
n = bitwidth of type;
d = t + c; // for .wide
d = t<2n-1..n> + c; // for .hi variant
d = t<n-1..0> + c; // for .lo variant
Notes
The type of the operation represents the types of the a
and b
operands. If .hi or .lo is
specified, then d
and c
are the same size as a
and b
, and either the upper or lower
half of the result is written to the destination register. If .wide
is specified, then d
and
c
are twice as wide as a
and b
to receive the result of the multiplication.
The .wide
suffix is supported only for 16-bit and 32-bit integer types.
Saturation modifier:
.sat
-
limits result to
MININT..MAXINT
(no overflow) for the size of the operation.Applies only to
.s32
type in.hi
mode.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
Supported on all target architectures.
Examples
@p mad.lo.s32 d,a,b,c;
mad.lo.s32 r,p,q,r;
9.7.1.5. Integer Arithmetic Instructions: mul24
mul24
Multiply two 24-bit integer values.
Syntax
mul24.mode.type d, a, b;
.mode = { .hi, .lo };
.type = { .u32, .s32 };
Description
Compute the product of two 24-bit integer values held in 32-bit source registers, and return either the high or low 32-bits of the 48-bit result.
Semantics
t = a * b;
d = t<47..16>; // for .hi variant
d = t<31..0>; // for .lo variant
Notes
Integer multiplication yields a result that is twice the size of the input operands, i.e., 48-bits.
mul24.hi
performs a 24x24-bit multiply and returns the high 32 bits of the 48-bit result.
mul24.lo
performs a 24x24-bit multiply and returns the low 32 bits of the 48-bit result.
All operands are of the same type and size.
mul24.hi
may be less efficient on machines without hardware support for 24-bit multiply.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
Supported on all target architectures.
Examples
mul24.lo.s32 d,a,b; // low 32-bits of 24x24-bit signed multiply.
9.7.1.6. Integer Arithmetic Instructions: mad24
mad24
Multiply two 24-bit integer values and add a third value.
Syntax
mad24.mode.type d, a, b, c;
mad24.hi.sat.s32 d, a, b, c;
.mode = { .hi, .lo };
.type = { .u32, .s32 };
Description
Compute the product of two 24-bit integer values held in 32-bit source registers, and add a third, 32-bit value to either the high or low 32-bits of the 48-bit result. Return either the high or low 32-bits of the 48-bit result.
Semantics
t = a * b;
d = t<47..16> + c; // for .hi variant
d = t<31..0> + c; // for .lo variant
Notes
Integer multiplication yields a result that is twice the size of the input operands, i.e., 48-bits.
mad24.hi
performs a 24x24-bit multiply and adds the high 32 bits of the 48-bit result to a third
value.
mad24.lo
performs a 24x24-bit multiply and adds the low 32 bits of the 48-bit result to a third
value.
All operands are of the same type and size.
Saturation modifier:
.sat
-
limits result of 32-bit signed addition to
MININT..MAXINT
(no overflow). Applies only to.s32
type in .hi mode.
mad24.hi
may be less efficient on machines without hardware support for 24-bit multiply.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
Supported on all target architectures.
Examples
mad24.lo.s32 d,a,b,c; // low 32-bits of 24x24-bit signed multiply.
9.7.1.7. Integer Arithmetic Instructions: sad
sad
Sum of absolute differences.
Syntax
sad.type d, a, b, c;
.type = { .u16, .u32, .u64,
.s16, .s32, .s64 };
Description
Adds the absolute value of a-b
to c
and writes the resulting value into d
.
Semantics
d = c + ((a<b) ? b-a : a-b);
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
Supported on all target architectures.
Examples
sad.s32 d,a,b,c;
sad.u32 d,a,b,d; // running sum
9.7.1.8. Integer Arithmetic Instructions: div
div
Divide one value by another.
Syntax
div.type d, a, b;
.type = { .u16, .u32, .u64,
.s16, .s32, .s64 };
Description
Divides a
by b
, stores result in d
.
Semantics
d = a / b;
Notes
Division by zero yields an unspecified, machine-specific value.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
Supported on all target architectures.
Examples
div.s32 b,n,i;
9.7.1.9. Integer Arithmetic Instructions: rem
rem
The remainder of integer division.
Syntax
rem.type d, a, b;
.type = { .u16, .u32, .u64,
.s16, .s32, .s64 };
Description
Divides a
by b
, store the remainder in d
.
Semantics
d = a % b;
Notes
The behavior for negative numbers is machine-dependent and depends on whether divide rounds towards zero or negative infinity.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
Supported on all target architectures.
Examples
rem.s32 x,x,8; // x = x%8;
9.7.1.10. Integer Arithmetic Instructions: abs
abs
Absolute value.
Syntax
abs.type d, a;
.type = { .s16, .s32, .s64 };
Description
Take the absolute value of a
and store it in d
.
Semantics
d = |a|;
Notes
Only for signed integers.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
Supported on all target architectures.
Examples
abs.s32 r0,a;
9.7.1.11. Integer Arithmetic Instructions: neg
neg
Arithmetic negate.
Syntax
neg.type d, a;
.type = { .s16, .s32, .s64 };
Description
Negate the sign of a and store the result in d.
Semantics
d = -a;
Notes
Only for signed integers.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
Supported on all target architectures.
Examples
neg.s32 r0,a;
9.7.1.12. Integer Arithmetic Instructions: min
min
Find the minimum of two values.
Syntax
min.atype d, a, b;
min{.relu}.btype d, a, b;
.atype = { .u16, .u32, .u64,
.u16x2, .s16, .s64 };
.btype = { .s16x2, .s32 };
Description
Store the minimum of a
and b
in d
.
For .u16x2
, .s16x2
instruction types, forms input vectors by half word values from source
operands. Half-word operands are then processed in parallel to produce .u16x2
, .s16x2
result
in destination.
Operands d
, a
and b
have the same type as the instruction type. For instruction types
.u16x2
, .s16x2
, operands d
, a
and b
have type .b32
.
Semantics
if (type == u16x2 || type == s16x2) {
iA[0] = a[0:15];
iA[1] = a[16:31];
iB[0] = b[0:15];
iB[1] = b[16:31];
for (i = 0; i < 2; i++) {
d[i] = (iA[i] < iB[i]) ? iA[i] : iB[i];
}
} else {
d = (a < b) ? a : b; // Integer (signed and unsigned)
}
Notes
Signed and unsigned differ.
- Saturation modifier:
-
min.relu.{s16x2, s32}
clamps the result to 0 if negative.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
min.u16x2
, min{.relu}.s16x2
and min.relu.s32
introduced in PTX ISA version 8.0.
Target ISA Notes
Supported on all target architectures.
min.u16x2
, min{.relu}.s16x2
and min.relu.s32
require sm_90
or higher.
Examples
min.s32 r0,a,b;
@p min.u16 h,i,j;
min.s16x2.relu u,v,w;
9.7.1.13. Integer Arithmetic Instructions: max
max
Find the maximum of two values.
Syntax
max.atype d, a, b;
max{.relu}.btype d, a, b;
.atype = { .u16, .u32, .u64,
.u16x2, .s16, .s64 };
.btype = { .s16x2, .s32 };
Description
Store the maximum of a
and b
in d
.
For .u16x2
, .s16x2
instruction types, forms input vectors by half word values from source
operands. Half-word operands are then processed in parallel to produce .u16x2
, .s16x2
result
in destination.
Operands d
, a
and b
have the same type as the instruction type. For instruction types
.u16x2
, .s16x2
, operands d
, a
and b
have type .b32
.
Semantics
if (type == u16x2 || type == s16x2) {
iA[0] = a[0:15];
iA[1] = a[16:31];
iB[0] = b[0:15];
iB[1] = b[16:31];
for (i = 0; i < 2; i++) {
d[i] = (iA[i] > iB[i]) ? iA[i] : iB[i];
}
} else {
d = (a > b) ? a : b; // Integer (signed and unsigned)
}
Notes
Signed and unsigned differ.
- Saturation modifier:
-
max.relu.{s16x2, s32}
clamps the result to 0 if negative.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
max.u16x2
, max{.relu}.s16x2
and max.relu.s32
introduced in PTX ISA version 8.0.
Target ISA Notes
Supported on all target architectures.
max.u16x2
, max{.relu}.s16x2
and max.relu.s32
require sm_90
or higher.
Examples
max.u32 d,a,b;
max.s32 q,q,0;
max.relu.s16x2 t,t,u;
9.7.1.14. Integer Arithmetic Instructions: popc
popc
Population count.
Syntax
popc.type d, a;
.type = { .b32, .b64 };
Description
Count the number of one bits in a
and place the resulting population count in 32-bit
destination register d
. Operand a
has the instruction type and destination d
has type
.u32
.
Semantics
.u32 d = 0;
while (a != 0) {
if (a & 0x1) d++;
a = a >> 1;
}
PTX ISA Notes
Introduced in PTX ISA version 2.0.
Target ISA Notes
popc
requires sm_20
or higher.
Examples
popc.b32 d, a;
popc.b64 cnt, X; // cnt is .u32
9.7.1.15. Integer Arithmetic Instructions: clz
clz
Count leading zeros.
Syntax
clz.type d, a;
.type = { .b32, .b64 };
Description
Count the number of leading zeros in a
starting with the most-significant bit and place the
result in 32-bit destination register d
. Operand a
has the instruction type, and destination
d
has type .u32
. For .b32
type, the number of leading zeros is between 0 and 32,
inclusively. For.b64
type, the number of leading zeros is between 0 and 64, inclusively.
Semantics
.u32 d = 0;
if (.type == .b32) { max = 32; mask = 0x80000000; }
else { max = 64; mask = 0x8000000000000000; }
while (d < max && (a&mask == 0) ) {
d++;
a = a << 1;
}
PTX ISA Notes
Introduced in PTX ISA version 2.0.
Target ISA Notes
clz
requires sm_20
or higher.
Examples
clz.b32 d, a;
clz.b64 cnt, X; // cnt is .u32
9.7.1.16. Integer Arithmetic Instructions: bfind
bfind
Find most significant non-sign bit.
Syntax
bfind.type d, a;
bfind.shiftamt.type d, a;
.type = { .u32, .u64,
.s32, .s64 };
Description
Find the bit position of the most significant non-sign bit in a
and place the result in
d
. Operand a
has the instruction type, and destination d
has type .u32
. For unsigned
integers, bfind
returns the bit position of the most significant 1
. For signed integers,
bfind
returns the bit position of the most significant 0
for negative inputs and the most
significant 1
for non-negative inputs.
If .shiftamt
is specified, bfind
returns the shift amount needed to left-shift the found bit
into the most-significant bit position.
bfind
returns 0xffffffff
if no non-sign bit is found.
Semantics
msb = (.type==.u32 || .type==.s32) ? 31 : 63;
// negate negative signed inputs
if ( (.type==.s32 || .type==.s64) && (a & (1<<msb)) ) {
a = ~a;
}
.u32 d = 0xffffffff;
for (.s32 i=msb; i>=0; i--) {
if (a & (1<<i)) { d = i; break; }
}
if (.shiftamt && d != 0xffffffff) { d = msb - d; }
PTX ISA Notes
Introduced in PTX ISA version 2.0.
Target ISA Notes
bfind
requires sm_20
or higher.
Examples
bfind.u32 d, a;
bfind.shiftamt.s64 cnt, X; // cnt is .u32
9.7.1.17. Integer Arithmetic Instructions: fns
fns
Find the n-th set bit
Syntax
fns.b32 d, mask, base, offset;
Description
Given a 32-bit value mask
and an integer value base
(between 0 and 31), find the n-th (given
by offset) set bit in mask
from the base
bit, and store the bit position in d
. If not
found, store 0xffffffff in d
.
Operand mask
has a 32-bit type. Operand base
has .b32
, .u32
or .s32
type. Operand offset has .s32
type. Destination d
has type .b32.
Operand base
must be <= 31, otherwise behavior is undefined.
Semantics
d = 0xffffffff;
if (offset == 0) {
if (mask[base] == 1) {
d = base;
}
} else {
pos = base;
count = |offset| - 1;
inc = (offset > 0) ? 1 : -1;
while ((pos >= 0) && (pos < 32)) {
if (mask[pos] == 1) {
if (count == 0) {
d = pos;
break;
} else {
count = count – 1;
}
}
pos = pos + inc;
}
}
PTX ISA Notes
Introduced in PTX ISA version 6.0.
Target ISA Notes
fns
requires sm_30
or higher.
Examples
fns.b32 d, 0xaaaaaaaa, 3, 1; // d = 3
fns.b32 d, 0xaaaaaaaa, 3, -1; // d = 3
fns.b32 d, 0xaaaaaaaa, 2, 1; // d = 3
fns.b32 d, 0xaaaaaaaa, 2, -1; // d = 1
9.7.1.18. Integer Arithmetic Instructions: brev
brev
Bit reverse.
Syntax
brev.type d, a;
.type = { .b32, .b64 };
Description
Perform bitwise reversal of input.
Semantics
msb = (.type==.b32) ? 31 : 63;
for (i=0; i<=msb; i++) {
d[i] = a[msb-i];
}
PTX ISA Notes
Introduced in PTX ISA version 2.0.
Target ISA Notes
brev
requires sm_20
or higher.
Examples
brev.b32 d, a;
9.7.1.19. Integer Arithmetic Instructions: bfe
bfe
Bit Field Extract.
Syntax
bfe.type d, a, b, c;
.type = { .u32, .u64,
.s32, .s64 };
Description
Extract bit field from a
and place the zero or sign-extended result in d
. Source b
gives
the bit field starting bit position, and source c
gives the bit field length in bits.
Operands a
and d
have the same type as the instruction type. Operands b
and c
are
type .u32
, but are restricted to the 8-bit value range 0..255
.
The sign bit of the extracted field is defined as:
-
.u32
,.u64
: -
zero
-
.s32
,.s64
: -
msb
of input a if the extracted field extends beyond themsb
of amsb
of extracted field, otherwise
If the bit field length is zero, the result is zero.
The destination d
is padded with the sign bit of the extracted field. If the start position is
beyond the msb
of the input, the destination d
is filled with the replicated sign bit of the
extracted field.
Semantics
msb = (.type==.u32 || .type==.s32) ? 31 : 63;
pos = b & 0xff; // pos restricted to 0..255 range
len = c & 0xff; // len restricted to 0..255 range
if (.type==.u32 || .type==.u64 || len==0)
sbit = 0;
else
sbit = a[min(pos+len-1,msb)];
d = 0;
for (i=0; i<=msb; i++) {
d[i] = (i<len && pos+i<=msb) ? a[pos+i] : sbit;
}
PTX ISA Notes
Introduced in PTX ISA version 2.0.
Target ISA Notes
bfe
requires sm_20
or higher.
Examples
bfe.b32 d,a,start,len;
9.7.1.20. Integer Arithmetic Instructions: bfi
bfi
Bit Field Insert.
Syntax
bfi.type f, a, b, c, d;
.type = { .b32, .b64 };
Description
Align and insert a bit field from a
into b
, and place the result in f
. Source c
gives the starting bit position for the insertion, and source d
gives the bit field length in
bits.
Operands a
, b
, and f
have the same type as the instruction type. Operands c
and
d
are type .u32
, but are restricted to the 8-bit value range 0..255
.
If the bit field length is zero, the result is b
.
If the start position is beyond the msb of the input, the result is b
.
Semantics
msb = (.type==.b32) ? 31 : 63;
pos = c & 0xff; // pos restricted to 0..255 range
len = d & 0xff; // len restricted to 0..255 range
f = b;
for (i=0; i<len && pos+i<=msb; i++) {
f[pos+i] = a[i];
}
PTX ISA Notes
Introduced in PTX ISA version 2.0.
Target ISA Notes
bfi
requires sm_20
or higher.
Examples
bfi.b32 d,a,b,start,len;
9.7.1.21. Integer Arithmetic Instructions: szext
szext
Sign-extend or Zero-extend.
Syntax
szext.mode.type d, a, b;
.mode = { .clamp, .wrap };
.type = { .u32, .s32 };
Description
Sign-extends or zero-extends an N-bit value from operand a
where N is specified in operand
b
. The resulting value is stored in the destination operand d
.
For the .s32
instruction type, the value in a
is treated as an N-bit signed value and the
most significant bit of this N-bit value is replicated up to bit 31. For the .u32
instruction
type, the value in a
is treated as an N-bit unsigned number and is zero-extended to 32
bits. Operand b
is an unsigned 32-bit value.
If the value of N is 0, then the result of szext
is 0. If the value of N is 32 or higher, then
the result of szext
depends upon the value of the .mode
qualifier as follows:
If
.mode
is.clamp
, then the result is the same as the source operanda
.If
.mode
is.wrap
, then the result is computed using the wrapped value of N.
Semantics
b1 = b & 0x1f;
too_large = (b >= 32 && .mode == .clamp) ? true : false;
mask = too_large ? 0 : (~0) << b1;
sign_pos = (b1 - 1) & 0x1f;
if (b1 == 0 || too_large || .type != .s32) {
sign_bit = false;
} else {
sign_bit = (a >> sign_pos) & 1;
}
d = (a & ~mask) | (sign_bit ? mask | 0);
PTX ISA Notes
Introduced in PTX ISA version 7.6.
Target ISA Notes
szext
requires sm_70
or higher.
Examples
szext.clamp.s32 rd, ra, rb;
szext.wrap.u32 rd, 0xffffffff, 0; // Result is 0.
9.7.1.22. Integer Arithmetic Instructions: bmsk
bmsk
Bit Field Mask.
Syntax
bmsk.mode.b32 d, a, b;
.mode = { .clamp, .wrap };
Description
Generates a 32-bit mask starting from the bit position specified in operand a
, and of the width
specified in operand b
. The generated bitmask is stored in the destination operand d
.
The resulting bitmask is 0 in the following cases:
When the value of
a
is 32 or higher and.mode
is.clamp
.When either the specified value of
b
or the wrapped value ofb
(when.mode
is specified as.wrap
) is 0.
Semantics
a1 = a & 0x1f;
mask0 = (~0) << a1;
b1 = b & 0x1f;
sum = a1 + b1;
mask1 = (~0) << sum;
sum-overflow = sum >= 32 ? true : false;
bit-position-overflow = false;
bit-width-overflow = false;
if (.mode == .clamp) {
if (a >= 32) {
bit-position-overflow = true;
mask0 = 0;
}
if (b >= 32) {
bit-width-overflow = true;
}
}
if (sum-overflow || bit-position-overflow || bit-width-overflow) {
mask1 = 0;
} else if (b1 == 0) {
mask1 = ~0;
}
d = mask0 & ~mask1;
Notes
The bitmask width specified by operand b
is limited to range 0..32
in .clamp
mode and to
range 0..31
in .wrap
mode.
PTX ISA Notes
Introduced in PTX ISA version 7.6.
Target ISA Notes
bmsk
requires sm_70
or higher.
Examples
bmsk.clamp.b32 rd, ra, rb;
bmsk.wrap.b32 rd, 1, 2; // Creates a bitmask of 0x00000006.
9.7.1.23. Integer Arithmetic Instructions: dp4a
dp4a
Four-way byte dot product-accumulate.
Syntax
dp4a.atype.btype d, a, b, c;
.atype = .btype = { .u32, .s32 };
Description
Four-way byte dot product which is accumulated in 32-bit result.
Operand a
and b
are 32-bit inputs which hold 4 byte inputs in packed form for dot product.
Operand c
has type .u32
if both .atype
and .btype
are .u32
else operand c
has type .s32
.
Semantics
d = c;
// Extract 4 bytes from a 32bit input and sign or zero extend
// based on input type.
Va = extractAndSignOrZeroExt_4(a, .atype);
Vb = extractAndSignOrZeroExt_4(b, .btype);
for (i = 0; i < 4; ++i) {
d += Va[i] * Vb[i];
}
PTX ISA Notes
Introduced in PTX ISA version 5.0.
Target ISA Notes
Requires sm_61
or higher.
Examples
dp4a.u32.u32 d0, a0, b0, c0;
dp4a.u32.s32 d1, a1, b1, c1;
9.7.1.24. Integer Arithmetic Instructions: dp2a
dp2a
Two-way dot product-accumulate.
Syntax
dp2a.mode.atype.btype d, a, b, c;
.atype = .btype = { .u32, .s32 };
.mode = { .lo, .hi };
Description
Two-way 16-bit to 8-bit dot product which is accumulated in 32-bit result.
Operand a
and b
are 32-bit inputs. Operand a
holds two 16-bits inputs in packed form and
operand b
holds 4 byte inputs in packed form for dot product.
Depending on the .mode
specified, either lower half or upper half of operand b
will be used
for dot product.
Operand c
has type .u32
if both .atype
and .btype
are .u32
else operand c
has type .s32
.
Semantics
d = c;
// Extract two 16-bit values from a 32-bit input and sign or zero extend
// based on input type.
Va = extractAndSignOrZeroExt_2(a, .atype);
// Extract four 8-bit values from a 32-bit input and sign or zer extend
// based on input type.
Vb = extractAndSignOrZeroExt_4(b, .btype);
b_select = (.mode == .lo) ? 0 : 2;
for (i = 0; i < 2; ++i) {
d += Va[i] * Vb[b_select + i];
}
PTX ISA Notes
Introduced in PTX ISA version 5.0.
Target ISA Notes
Requires sm_61
or higher.
Examples
dp2a.lo.u32.u32 d0, a0, b0, c0;
dp2a.hi.u32.s32 d1, a1, b1, c1;
9.7.2. Extended-Precision Integer Arithmetic Instructions
Instructions add.cc
, addc
, sub.cc
, subc
, mad.cc
and madc
reference an
implicitly specified condition code register (CC
) having a single carry flag bit (CC.CF
)
holding carry-in/carry-out or borrow-in/borrow-out. These instructions support extended-precision
integer addition, subtraction, and multiplication. No other instructions access the condition code,
and there is no support for setting, clearing, or testing the condition code. The condition code
register is not preserved across calls and is mainly intended for use in straight-line code
sequences for computing extended-precision integer addition, subtraction, and multiplication.
The extended-precision arithmetic instructions are:
add.cc
,addc
sub.cc
,subc
mad.cc
,madc
9.7.2.1. Extended-Precision Arithmetic Instructions: add.cc
add.cc
Add two values with carry-out.
Syntax
add.cc.type d, a, b;
.type = { .u32, .s32, .u64, .s64 };
Description
Performs integer addition and writes the carry-out value into the condition code register.
Semantics
d = a + b;
carry-out written to CC.CF
Notes
No integer rounding modifiers.
No saturation.
Behavior is the same for unsigned and signed integers.
PTX ISA Notes
32-bit add.cc
introduced in PTX ISA version 1.2.
64-bit add.cc
introduced in PTX ISA version 4.3.
Target ISA Notes
32-bit add.cc
is supported on all target architectures.
64-bit add.cc
requires sm_20
or higher.
Examples
@p add.cc.u32 x1,y1,z1; // extended-precision addition of
@p addc.cc.u32 x2,y2,z2; // two 128-bit values
@p addc.cc.u32 x3,y3,z3;
@p addc.u32 x4,y4,z4;
9.7.2.2. Extended-Precision Arithmetic Instructions: addc
addc
Add two values with carry-in and optional carry-out.
Syntax
addc{.cc}.type d, a, b;
.type = { .u32, .s32, .u64, .s64 };
Description
Performs integer addition with carry-in and optionally writes the carry-out value into the condition code register.
Semantics
d = a + b + CC.CF;
if .cc
specified, carry-out written to CC.CF
Notes
No integer rounding modifiers.
No saturation.
Behavior is the same for unsigned and signed integers.
PTX ISA Notes
32-bit addc
introduced in PTX ISA version 1.2.
64-bit addc
introduced in PTX ISA version 4.3.
Target ISA Notes
32-bit addc
is supported on all target architectures.
64-bit addc
requires sm_20
or higher.
Examples
@p add.cc.u32 x1,y1,z1; // extended-precision addition of
@p addc.cc.u32 x2,y2,z2; // two 128-bit values
@p addc.cc.u32 x3,y3,z3;
@p addc.u32 x4,y4,z4;
9.7.2.3. Extended-Precision Arithmetic Instructions: sub.cc
sub.cc
Subtract one value from another, with borrow-out.
Syntax
sub.cc.type d, a, b;
.type = { .u32, .s32, .u64, .s64 };
Description
Performs integer subtraction and writes the borrow-out value into the condition code register.
Semantics
d = a - b;
borrow-out written to CC.CF
Notes
No integer rounding modifiers.
No saturation.
Behavior is the same for unsigned and signed integers.
PTX ISA Notes
32-bit sub.cc
introduced in PTX ISA version 1.2.
64-bit sub.cc
introduced in PTX ISA version 4.3.
Target ISA Notes
32-bit sub.cc
is supported on all target architectures.
64-bit sub.cc
requires sm_20
or higher.
Examples
@p sub.cc.u32 x1,y1,z1; // extended-precision subtraction
@p subc.cc.u32 x2,y2,z2; // of two 128-bit values
@p subc.cc.u32 x3,y3,z3;
@p subc.u32 x4,y4,z4;
9.7.2.4. Extended-Precision Arithmetic Instructions: subc
subc
Subtract one value from another, with borrow-in and optional borrow-out.
Syntax
subc{.cc}.type d, a, b;
.type = { .u32, .s32, .u64, .s64 };
Description
Performs integer subtraction with borrow-in and optionally writes the borrow-out value into the condition code register.
Semantics
d = a - (b + CC.CF);
if .cc
specified, borrow-out written to CC.CF
Notes
No integer rounding modifiers.
No saturation.
Behavior is the same for unsigned and signed integers.
PTX ISA Notes
32-bit subc
introduced in PTX ISA version 1.2.
64-bit subc
introduced in PTX ISA version 4.3.
Target ISA Notes
32-bit subc
is supported on all target architectures.
64-bit subc
requires sm_20
or higher.
Examples
@p sub.cc.u32 x1,y1,z1; // extended-precision subtraction
@p subc.cc.u32 x2,y2,z2; // of two 128-bit values
@p subc.cc.u32 x3,y3,z3;
@p subc.u32 x4,y4,z4;
9.7.2.5. Extended-Precision Arithmetic Instructions: mad.cc
mad.cc
Multiply two values, extract high or low half of result, and add a third value with carry-out.
Syntax
mad{.hi,.lo}.cc.type d, a, b, c;
.type = { .u32, .s32, .u64, .s64 };
Description
Multiplies two values, extracts either the high or low part of the result, and adds a third value. Writes the result to the destination register and the carry-out from the addition into the condition code register.
Semantics
t = a * b;
d = t<63..32> + c; // for .hi variant
d = t<31..0> + c; // for .lo variant
carry-out from addition is written to CC.CF
Notes
Generally used in combination with madc
and addc
to implement extended-precision multi-word
multiplication. See madc
for an example.
PTX ISA Notes
32-bit mad.cc
introduced in PTX ISA version 3.0.
64-bit mad.cc
introduced in PTX ISA version 4.3.
Target ISA Notes
Requires target sm_20
or higher.
Examples
@p mad.lo.cc.u32 d,a,b,c;
mad.lo.cc.u32 r,p,q,r;
9.7.2.6. Extended-Precision Arithmetic Instructions: madc
madc
Multiply two values, extract high or low half of result, and add a third value with carry-in and optional carry-out.
Syntax
madc{.hi,.lo}{.cc}.type d, a, b, c;
.type = { .u32, .s32, .u64, .s64 };
Description
Multiplies two values, extracts either the high or low part of the result, and adds a third value along with carry-in. Writes the result to the destination register and optionally writes the carry-out from the addition into the condition code register.
Semantics
t = a * b;
d = t<63..32> + c + CC.CF; // for .hi variant
d = t<31..0> + c + CC.CF; // for .lo variant
if .cc
specified, carry-out from addition is written to CC.CF
Notes
Generally used in combination with mad.cc
and addc
to implement extended-precision
multi-word multiplication. See example below.
PTX ISA Notes
32-bit madc
introduced in PTX ISA version 3.0.
64-bit madc
introduced in PTX ISA version 4.3.
Target ISA Notes
Requires target sm_20
or higher.
Examples
// extended-precision multiply: [r3,r2,r1,r0] = [r5,r4] * [r7,r6]
mul.lo.u32 r0,r4,r6; // r0=(r4*r6).[31:0], no carry-out
mul.hi.u32 r1,r4,r6; // r1=(r4*r6).[63:32], no carry-out
mad.lo.cc.u32 r1,r5,r6,r1; // r1+=(r5*r6).[31:0], may carry-out
madc.hi.u32 r2,r5,r6,0; // r2 =(r5*r6).[63:32]+carry-in,
// no carry-out
mad.lo.cc.u32 r1,r4,r7,r1; // r1+=(r4*r7).[31:0], may carry-out
madc.hi.cc.u32 r2,r4,r7,r2; // r2+=(r4*r7).[63:32]+carry-in,
// may carry-out
addc.u32 r3,0,0; // r3 = carry-in, no carry-out
mad.lo.cc.u32 r2,r5,r7,r2; // r2+=(r5*r7).[31:0], may carry-out
madc.hi.u32 r3,r5,r7,r3; // r3+=(r5*r7).[63:32]+carry-in
9.7.3. Floating-Point Instructions
Floating-point instructions operate on .f32
and .f64
register operands and constant
immediate values. The floating-point instructions are:
testp
copysign
add
sub
mul
fma
mad
div
abs
neg
min
max
rcp
sqrt
rsqrt
sin
cos
lg2
ex2
tanh
Instructions that support rounding modifiers are IEEE-754 compliant. Double-precision instructions
support subnormal inputs and results. Single-precision instructions support subnormal inputs and
results by default for sm_20
and subsequent targets, and flush subnormal inputs and results to
sign-preserving zero for sm_1x
targets. The optional .ftz
modifier on single-precision
instructions provides backward compatibility with sm_1x
targets by flushing subnormal inputs and
results to sign-preserving zero regardless of the target architecture.
Single-precision add
, sub
, mul
, and mad
support saturation of results to the range
[0.0, 1.0], with NaN
s being flushed to positive zero. NaN
payloads are supported for
double-precision instructions (except for rcp.approx.ftz.f64
and rsqrt.approx.ftz.f64
, which
maps input NaN
s to a canonical NaN
). Single-precision instructions return an unspecified
NaN
. Note that future implementations may support NaN
payloads for single-precision
instructions, so PTX programs should not rely on the specific single-precision NaN
s being
generated.
Table 26 summarizes floating-point instructions in PTX.
Instruction |
.rn |
.rz |
.rm |
.rp |
.ftz |
.sat |
Notes |
---|---|---|---|---|---|---|---|
|
x |
x |
x |
x |
x |
x |
If no rounding modifier is specified,
default is |
|
x |
x |
x |
x |
n/a |
n/a |
If no rounding modifier is specified,
default is |
|
n/a |
n/a |
n/a |
n/a |
x |
x |
No rounding modifier. |
|
x |
x |
x |
x |
x |
x |
|
|
x |
x |
x |
x |
n/a |
n/a |
|
|
n/a |
n/a |
n/a |
n/a |
x |
n/a |
No rounding modifier. |
|
n/a |
n/a |
n/a |
n/a |
x |
n/a |
n/a |
|
n/a |
n/a |
n/a |
n/a |
x |
n/a |
|
|
x |
x |
x |
x |
x |
n/a |
|
|
x |
x |
x |
x |
n/a |
n/a |
|
|
n/a |
n/a |
n/a |
n/a |
x |
n/a |
|
|
n/a |
n/a |
n/a |
n/a |
n/a |
n/a |
|
|
n/a |
n/a |
n/a |
n/a |
x |
n/a |
|
|
n/a |
n/a |
n/a |
n/a |
n/a |
n/a |
|
|
n/a |
n/a |
n/a |
n/a |
x |
n/a |
|
|
n/a |
n/a |
n/a |
n/a |
x |
n/a |
|
|
n/a |
n/a |
n/a |
n/a |
n/a |
n/a |
|
9.7.3.1. Floating Point Instructions: testp
testp
Test floating-point property.
Syntax
testp.op.type p, a; // result is .pred
.op = { .finite, .infinite,
.number, .notanumber,
.normal, .subnormal };
.type = { .f32, .f64 };
Description
testp
tests common properties of floating-point numbers and returns a predicate value of 1
if True
and 0
if False
.
testp.finite
-
True
if the input is not infinite orNaN
testp.infinite
-
True
if the input is positive or negative infinity testp.number
-
True
if the input is notNaN
testp.notanumber
-
True
if the input isNaN
testp.normal
-
True
if the input is a normal number (notNaN
, not infinity) testp.subnormal
-
True
if the input is a subnormal number (notNaN
, not infinity)
As a special case, positive and negative zero are considered normal numbers.
PTX ISA Notes
Introduced in PTX ISA version 2.0.
Target ISA Notes
Requires sm_20
or higher.
Examples
testp.notanumber.f32 isnan, f0;
testp.infinite.f64 p, X;
9.7.3.2. Floating Point Instructions: copysign
copysign
Copy sign of one input to another.
Syntax
copysign.type d, a, b;
.type = { .f32, .f64 };
Description
Copy sign bit of a
into value of b
, and return the result as d
.
PTX ISA Notes
Introduced in PTX ISA version 2.0.
Target ISA Notes
Requires sm_20
or higher.
Examples
copysign.f32 x, y, z;
copysign.f64 A, B, C;
9.7.3.3. Floating Point Instructions: add
add
Add two values.
Syntax
add{.rnd}{.ftz}{.sat}.f32 d, a, b;
add{.rnd}.f64 d, a, b;
.rnd = { .rn, .rz, .rm, .rp };
Description
Performs addition and writes the resulting value into a destination register.
Semantics
d = a + b;
Notes
Rounding modifiers:
.rn
-
mantissa LSB rounds to nearest even
.rz
-
mantissa LSB rounds towards zero
.rm
-
mantissa LSB rounds towards negative infinity
.rp
-
mantissa LSB rounds towards positive infinity
The default value of rounding modifier is .rn
. Note that an add
instruction with an explicit
rounding modifier is treated conservatively by the code optimizer. An add
instruction with no
rounding modifier defaults to round-to-nearest-even and may be optimized aggressively by the code
optimizer. In particular, mul
/add
sequences with no rounding modifiers may be optimized to
use fused-multiply-add instructions on the target device.
Subnormal numbers:
sm_20+
-
By default, subnormal numbers are supported.
add.ftz.f32
flushes subnormal inputs and results to sign-preserving zero. sm_1x
-
add.f64
supports subnormal numbers.add.f32
flushes subnormal inputs and results to sign-preserving zero.
Saturation modifier:
add.sat.f32
clamps the result to [0.0, 1.0]. NaN
results are flushed to +0.0f
.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
add.f32
supported on all target architectures.
add.f64
requires sm_13
or higher.
Rounding modifiers have the following target requirements:
-
.rn
,.rz
-
available for all targets
-
.rm
,.rp
-
for
add.f64
, requiressm_13
or higher.for
add.f32
, requiressm_20
or higher.
Examples
@p add.rz.ftz.f32 f1,f2,f3;
9.7.3.4. Floating Point Instructions: sub
sub
Subtract one value from another.
Syntax
sub{.rnd}{.ftz}{.sat}.f32 d, a, b;
sub{.rnd}.f64 d, a, b;
.rnd = { .rn, .rz, .rm, .rp };
Description
Performs subtraction and writes the resulting value into a destination register.
Semantics
d = a - b;
Notes
Rounding modifiers:
.rn
-
mantissa LSB rounds to nearest even
.rz
-
mantissa LSB rounds towards zero
.rm
-
mantissa LSB rounds towards negative infinity
.rp
-
mantissa LSB rounds towards positive infinity
The default value of rounding modifier is .rn
. Note that a sub
instruction with an explicit
rounding modifier is treated conservatively by the code optimizer. A sub
instruction with no
rounding modifier defaults to round-to-nearest-even and may be optimized aggressively by the code
optimizer. In particular, mul
/sub
sequences with no rounding modifiers may be optimized to
use fused-multiply-add instructions on the target device.
Subnormal numbers:
sm_20+
-
By default, subnormal numbers are supported.
sub.ftz.f32
flushes subnormal inputs and results to sign-preserving zero. sm_1x
-
sub.f64
supports subnormal numbers.sub.f32
flushes subnormal inputs and results to sign-preserving zero.
Saturation modifier:
sub.sat.f32
clamps the result to [0.0, 1.0]. NaN results are flushed to +0.0f
.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
sub.f32
supported on all target architectures.
sub.f64
requires sm_13
or higher.
Rounding modifiers have the following target requirements:
-
.rn
,.rz
-
available for all targets
-
.rm
,.rp
-
for
sub.f64
, requiressm_13
or higher.for
sub.f32
, requiressm_20
or higher.
Examples
sub.f32 c,a,b;
sub.rn.ftz.f32 f1,f2,f3;
9.7.3.5. Floating Point Instructions: mul
mul
Multiply two values.
Syntax
mul{.rnd}{.ftz}{.sat}.f32 d, a, b;
mul{.rnd}.f64 d, a, b;
.rnd = { .rn, .rz, .rm, .rp };
Description
Compute the product of two values.
Semantics
d = a * b;
Notes
For floating-point multiplication, all operands must be the same size.
Rounding modifiers:
.rn
-
mantissa LSB rounds to nearest even
.rz
-
mantissa LSB rounds towards zero
.rm
-
mantissa LSB rounds towards negative infinity
.rp
-
mantissa LSB rounds towards positive infinity
The default value of rounding modifier is .rn
. Note that a mul
instruction with an explicit
rounding modifier is treated conservatively by the code optimizer. A mul
instruction with no
rounding modifier defaults to round-to-nearest-even and may be optimized aggressively by the code
optimizer. In particular, mul/add
and mul/sub
sequences with no rounding modifiers may be
optimized to use fused-multiply-add instructions on the target device.
Subnormal numbers:
sm_20+
-
By default, subnormal numbers are supported.
mul.ftz.f32
flushes subnormal inputs and results to sign-preserving zero. sm_1x
-
mul.f64
supports subnormal numbers.mul.f32
flushes subnormal inputs and results to sign-preserving zero.
Saturation modifier:
mul.sat.f32
clamps the result to [0.0, 1.0]. NaN
results are flushed to +0.0f
.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
mul.f32
supported on all target architectures.
mul.f64
requires sm_13
or higher.
Rounding modifiers have the following target requirements:
-
.rn
,.rz
-
available for all targets
-
.rm
,.rp
-
for
mul.f64
, requiressm_13
or higher.for
mul.f32
, requiressm_20
or higher.
Examples
mul.ftz.f32 circumf,radius,pi // a single-precision multiply
9.7.3.6. Floating Point Instructions: fma
fma
Fused multiply-add.
Syntax
fma.rnd{.ftz}{.sat}.f32 d, a, b, c;
fma.rnd.f64 d, a, b, c;
.rnd = { .rn, .rz, .rm, .rp };
Description
Performs a fused multiply-add with no loss of precision in the intermediate product and addition.
Semantics
d = a*b + c;
Notes
fma.f32
computes the product of a
and b
to infinite precision and then adds c
to
this product, again in infinite precision. The resulting value is then rounded to single precision
using the rounding mode specified by .rnd
.
fma.f64
computes the product of a
and b
to infinite precision and then adds c
to
this product, again in infinite precision. The resulting value is then rounded to double precision
using the rounding mode specified by .rnd
.
fma.f64
is the same as mad.f64
.
Rounding modifiers (no default):
.rn
-
mantissa LSB rounds to nearest even
.rz
-
mantissa LSB rounds towards zero
.rm
-
mantissa LSB rounds towards negative infinity
.rp
-
mantissa LSB rounds towards positive infinity
Subnormal numbers:
sm_20+
-
By default, subnormal numbers are supported.
fma.ftz.f32
flushes subnormal inputs and results to sign-preserving zero. sm_1x
-
fma.f64
supports subnormal numbers.fma.f32
is unimplemented forsm_1x
targets.
Saturation:
fma.sat.f32
clamps the result to [0.0, 1.0]. NaN
results are flushed to +0.0f
.
PTX ISA Notes
fma.f64
introduced in PTX ISA version 1.4.
fma.f32
introduced in PTX ISA version 2.0.
Target ISA Notes
fma.f32
requires sm_20
or higher.
fma.f64
requires sm_13
or higher.
Examples
fma.rn.ftz.f32 w,x,y,z;
@p fma.rn.f64 d,a,b,c;
9.7.3.7. Floating Point Instructions: mad
mad
Multiply two values and add a third value.
Syntax
mad{.ftz}{.sat}.f32 d, a, b, c; // .target sm_1x
mad.rnd{.ftz}{.sat}.f32 d, a, b, c; // .target sm_20
mad.rnd.f64 d, a, b, c; // .target sm_13 and higher
.rnd = { .rn, .rz, .rm, .rp };
Description
Multiplies two values and adds a third, and then writes the resulting value into a destination register.
Semantics
d = a*b + c;
Notes
For .target sm_20
and higher:
mad.f32
computes the product ofa
andb
to infinite precision and then addsc
to this product, again in infinite precision. The resulting value is then rounded to single precision using the rounding mode specified by.rnd
.mad.f64
computes the product ofa
andb
to infinite precision and then addsc
to this product, again in infinite precision. The resulting value is then rounded to double precision using the rounding mode specified by.rnd
.mad.{f32,f64}
is the same asfma.{f32,f64}
.
For .target sm_1x
:
mad.f32
computes the product ofa
andb
at double precision, and then the mantissa is truncated to 23 bits, but the exponent is preserved. Note that this is different from computing the product withmul
, where the mantissa can be rounded and the exponent will be clamped. The exception formad.f32
is whenc = +/-0.0
,mad.f32
is identical to the result computed using separate mul and add instructions. When JIT-compiled for SM 2.0 devices,mad.f32
is implemented as a fused multiply-add (i.e.,fma.rn.ftz.f32
). In this case,mad.f32
can produce slightly different numeric results and backward compatibility is not guaranteed in this case.mad.f64
computes the product ofa
andb
to infinite precision and then addsc
to this product, again in infinite precision. The resulting value is then rounded to double precision using the rounding mode specified by.rnd
. Unlikemad.f32
, the treatment of subnormal inputs and output follows IEEE 754 standard.mad.f64
is the same asfma.f64
.
Rounding modifiers (no default):
.rn
-
mantissa LSB rounds to nearest even
.rz
-
mantissa LSB rounds towards zero
.rm
-
mantissa LSB rounds towards negative infinity
.rp
-
mantissa LSB rounds towards positive infinity
Subnormal numbers:
sm_20+
-
By default, subnormal numbers are supported.
mad.ftz.f32
flushes subnormal inputs and results to sign-preserving zero. sm_1x
-
mad.f64
supports subnormal numbers.mad.f32
flushes subnormal inputs and results to sign-preserving zero.
Saturation modifier:
mad.sat.f32
clamps the result to [0.0, 1.0]. NaN
results are flushed to +0.0f
.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
In PTX ISA versions 1.4 and later, a rounding modifier is required for mad.f64
.
Legacy mad.f64
instructions having no rounding modifier will map to mad.rn.f64
.
In PTX ISA versions 2.0 and later, a rounding modifier is required for mad.f32
for sm_20
and higher targets.
Errata
mad.f32
requires a rounding modifier for sm_20
and higher targets. However for PTX ISA
version 3.0 and earlier, ptxas does not enforce this requirement and mad.f32
silently defaults
to mad.rn.f32
. For PTX ISA version 3.1, ptxas generates a warning and defaults to
mad.rn.f32
, and in subsequent releases ptxas will enforce the requirement for PTX ISA version
3.2 and later.
Target ISA Notes
mad.f32
supported on all target architectures.
mad.f64
requires sm_13
or higher.
Rounding modifiers have the following target requirements:
.rn
,.rz
,.rm
,.rp
formad.f64
, requiressm_13
or higher..rn
,.rz
,.rm
,.rp
formad.f32
, requiressm_20
or higher.
Examples
@p mad.f32 d,a,b,c;
9.7.3.8. Floating Point Instructions: div
div
Divide one value by another.
Syntax
div.approx{.ftz}.f32 d, a, b; // fast, approximate divide
div.full{.ftz}.f32 d, a, b; // full-range approximate divide
div.rnd{.ftz}.f32 d, a, b; // IEEE 754 compliant rounding
div.rnd.f64 d, a, b; // IEEE 754 compliant rounding
.rnd = { .rn, .rz, .rm, .rp };
Description
Divides a
by b
, stores result in d
.
Semantics
d = a / b;
Notes
Fast, approximate single-precision divides:
div.approx.f32
implements a fast approximation to divide, computed asd = a * (1/b)
. For|b|
in [2-126, 2126], the maximumulp
error is 2. For 2126 <|b|
< 2128, ifa
is infinity,div.approx.f32
returnsNaN
, otherwise it returns 0.div.full.f32
implements a relatively fast, full-range approximation that scales operands to achieve better accuracy, but is not fully IEEE 754 compliant and does not support rounding modifiers. The maximumulp
error is 2 across the full range of inputs.Subnormal inputs and results are flushed to sign-preserving zero. Fast, approximate division by zero creates a value of infinity (with same sign as
a
).
Divide with IEEE 754 compliant rounding:
Rounding modifiers (no default):
.rn
-
mantissa LSB rounds to nearest even
.rz
-
mantissa LSB rounds towards zero
.rm
-
mantissa LSB rounds towards negative infinity
.rp
-
mantissa LSB rounds towards positive infinity
Subnormal numbers:
sm_20+
-
By default, subnormal numbers are supported.
div.ftz.f32
flushes subnormal inputs and results to sign-preserving zero. sm_1x
-
div.f64
supports subnormal numbers.div.f32
flushes subnormal inputs and results to sign-preserving zero.
PTX ISA Notes
div.f32
and div.f64
introduced in PTX ISA version 1.0.
Explicit modifiers .approx
, .full
, .ftz
, and rounding introduced in PTX ISA version 1.4.
For PTX ISA version 1.4 and later, one of .approx
, .full
, or .rnd
is required.
For PTX ISA versions 1.0 through 1.3, div.f32
defaults to div.approx.ftz.f32
, and
div.f64
defaults to div.rn.f64
.
Target ISA Notes
div.approx.f32
and div.full.f32
supported on all target architectures.
div.rnd.f32
requires sm_20
or higher.
div.rn.f64
requires sm_13
or higher, or .target map_f64_to_f32
.
div.{rz,rm,rp}.f64
requires sm_20
or higher.
Examples
div.approx.ftz.f32 diam,circum,3.14159;
div.full.ftz.f32 x, y, z;
div.rn.f64 xd, yd, zd;
9.7.3.9. Floating Point Instructions: abs
abs
Absolute value.
Syntax
abs{.ftz}.f32 d, a;
abs.f64 d, a;
Description
Take the absolute value of a
and store the result in d
.
Semantics
d = |a|;
Notes
Subnormal numbers:
sm_20+
-
By default, subnormal numbers are supported.
abs.ftz.f32
flushes subnormal inputs and results to sign-preserving zero. sm_1x
-
abs.f64
supports subnormal numbers.abs.f32
flushes subnormal inputs and results to sign-preserving zero.
For abs.f32
, NaN
input yields unspecified NaN
. For abs.f64
, NaN
input is passed
through unchanged. Future implementations may comply with the IEEE 754 standard by preserving
payload and modifying only the sign bit.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
abs.f32
supported on all target architectures.
abs.f64
requires sm_13
or higher.
Examples
abs.ftz.f32 x,f0;
9.7.3.10. Floating Point Instructions: neg
neg
Arithmetic negate.
Syntax
neg{.ftz}.f32 d, a;
neg.f64 d, a;
Description
Negate the sign of a
and store the result in d
.
Semantics
d = -a;
Notes
Subnormal numbers:
sm_20+
-
By default, subnormal numbers are supported.
neg.ftz.f32
flushes subnormal inputs and results to sign-preserving zero. sm_1x
-
neg.f64
supports subnormal numbers.neg.f32
flushes subnormal inputs and results to sign-preserving zero.
NaN
inputs yield an unspecified NaN
. Future implementations may comply with the IEEE 754
standard by preserving payload and modifying only the sign bit.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
neg.f32
supported on all target architectures.
neg.f64
requires sm_13
or higher.
Examples
neg.ftz.f32 x,f0;
9.7.3.11. Floating Point Instructions: min
min
Find the minimum of two values.
Syntax
min{.ftz}{.NaN}{.xorsign.abs}.f32 d, a, b;
min.f64 d, a, b;
Description
Store the minimum of a
and b
in d
.
If .NaN
modifier is specified, then the result is canonical NaN
if either of the inputs is
NaN
.
If .abs
modifier is specified, the magnitude of destination operand d
is the minimum of
absolute values of both the input arguments.
If .xorsign
modifier is specified, the sign bit of destination d
is equal to the XOR of the
sign bits of both the inputs.
Modifiers .abs
and .xorsign
must be specified together and .xorsign
considers the sign
bit of both inputs before applying .abs
operation.
If the result of min
is NaN
then the .xorsign
and .abs
modifiers will be ignored.
Semantics
if (.xorsign) {
xorsign = getSignBit(a) ^ getSignBit(b);
if (.abs) {
a = |a|;
b = |b|;
}
}
if (isNaN(a) && isNaN(b)) d = NaN;
else if (.NaN && (isNaN(a) || isNaN(b))) d = NaN;
else if (isNaN(a)) d = b;
else if (isNaN(b)) d = a;
else d = (a < b) ? a : b;
if (.xorsign && !isNaN(d)) {
setSignBit(d, xorsign);
}
Notes
Subnormal numbers:
sm_20+
-
By default, subnormal numbers are supported.
min.ftz.f32
flushes subnormal inputs and results to sign-preserving zero. sm_1x
-
min.f64
supports subnormal numbers.min.f32
flushes subnormal inputs and results to sign-preserving zero.
If values of both inputs are 0.0, then +0.0 > -0.0.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
min.NaN
introduced in PTX ISA version 7.0.
min.xorsign.abs
introduced in PTX ISA version 7.2.
Target ISA Notes
min.f32
supported on all target architectures.
min.f64
requires sm_13
or higher.
min.NaN
requires sm_80
or higher.
min.xorsign.abs
requires sm_86
or higher.
Examples
@p min.ftz.f32 z,z,x;
min.f64 a,b,c;
// fp32 min with .NaN
min.NaN.f32 f0,f1,f2;
// fp32 min with .xorsign.abs
min.xorsign.abs.f32 Rd, Ra, Rb;
9.7.3.12. Floating Point Instructions: max
max
Find the maximum of two values.
Syntax
max{.ftz}{.NaN}{.xorsign.abs}.f32 d, a, b;
max.f64 d, a, b;
Description
Store the maximum of a
and b
in d
.
If .NaN
modifier is specified, the result is canonical NaN
if either of the inputs is
NaN
.
If .abs
modifier is specified, the magnitude of destination operand d
is the maximum of
absolute values of both the input arguments.
If .xorsign
modifier is specified, the sign bit of destination d
is equal to the XOR of the
sign bits of both the inputs.
Modifiers .abs
and .xorsign
must be specified together and .xorsign
considers the sign
bit of both inputs before applying .abs
operation.
If the result of max
is NaN
then the .xorsign
and .abs
modifiers will be ignored.
Semantics
if (.xorsign) {
xorsign = getSignBit(a) ^ getSignBit(b);
if (.abs) {
a = |a|;
b = |b|;
}
}
if (isNaN(a) && isNaN(b)) d = NaN;
else if (.NaN && (isNaN(a) || isNaN(b))) d = NaN;
else if (isNaN(a)) d = b;
else if (isNaN(b)) d = a;
else d = (a > b) ? a : b;
if (.xorsign && !isNaN(d)) {
setSignBit(d, xorsign);
}
Notes
Subnormal numbers:
sm_20+
-
By default, subnormal numbers are supported.
max.ftz.f32
flushes subnormal inputs and results to sign-preserving zero. sm_1x
-
max.f64
supports subnormal numbers.max.f32
flushes subnormal inputs and results to sign-preserving zero.
If values of both inputs are 0.0, then +0.0 > -0.0.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
max.NaN
introduced in PTX ISA version 7.0.
max.xorsign.abs
introduced in PTX ISA version 7.2.
Target ISA Notes
max.f32
supported on all target architectures.
max.f64
requires sm_13
or higher.
max.NaN
requires sm_80
or higher.
max.xorsign.abs
requires sm_86
or higher.
Examples
max.ftz.f32 f0,f1,f2;
max.f64 a,b,c;
// fp32 max with .NaN
max.NaN.f32 f0,f1,f2;
// fp32 max with .xorsign.abs
max.xorsign.abs.f32 Rd, Ra, Rb;
9.7.3.13. Floating Point Instructions: rcp
rcp
Take the reciprocal of a value.
Syntax
rcp.approx{.ftz}.f32 d, a; // fast, approximate reciprocal
rcp.rnd{.ftz}.f32 d, a; // IEEE 754 compliant rounding
rcp.rnd.f64 d, a; // IEEE 754 compliant rounding
.rnd = { .rn, .rz, .rm, .rp };
Description
Compute 1/a
, store result in d
.
Semantics
d = 1 / a;
Notes
Fast, approximate single-precision reciprocal:
rcp.approx.f32
implements a fast approximation to reciprocal. The maximum absolute error is 2-23.0 over the range 1.0-2.0.
Input |
Result |
---|---|
-Inf |
-0.0 |
-subnormal |
-Inf |
-0.0 |
-Inf |
+0.0 |
+Inf |
+subnormal |
+Inf |
+Inf |
+0.0 |
NaN |
NaN |
Reciprocal with IEEE 754 compliant rounding:
Rounding modifiers (no default):
.rn
-
mantissa LSB rounds to nearest even
.rz
-
mantissa LSB rounds towards zero
.rm
-
mantissa LSB rounds towards negative infinity
.rp
-
mantissa LSB rounds towards positive infinity
Subnormal numbers:
sm_20+
-
By default, subnormal numbers are supported.
rcp.ftz.f32
flushes subnormal inputs and results to sign-preserving zero. sm_1x
-
rcp.f64
supports subnormal numbers.rcp.f32
flushes subnormal inputs and results to sign-preserving zero.
PTX ISA Notes
rcp.f32
and rcp.f64
introduced in PTX ISA version 1.0. rcp.rn.f64
and explicit modifiers
.approx
and .ftz
were introduced in PTX ISA version 1.4. General rounding modifiers were
added in PTX ISA version 2.0.
For PTX ISA version 1.4 and later, one of .approx
or .rnd
is required.
For PTX ISA versions 1.0 through 1.3, rcp.f32
defaults to rcp.approx.ftz.f32
, and
rcp.f64
defaults to rcp.rn.f64
.
Target ISA Notes
rcp.approx.f32
supported on all target architectures.
rcp.rnd.f32
requires sm_20
or higher.
rcp.rn.f64
requires sm_13
or higher, or .target map_f64_to_f32.
rcp.{rz,rm,rp}.f64
requires sm_20
or higher.
Examples
rcp.approx.ftz.f32 ri,r;
rcp.rn.ftz.f32 xi,x;
rcp.rn.f64 xi,x;
9.7.3.14. Floating Point Instructions: rcp.approx.ftz.f64
rcp.approx.ftz.f64
Compute a fast, gross approximation to the reciprocal of a value.
Syntax
rcp.approx.ftz.f64 d, a;
Description
Compute a fast, gross approximation to the reciprocal as follows:
extract the most-significant 32 bits of
.f64
operanda
in 1.11.20 IEEE floating-point format (i.e., ignore the least-significant 32 bits ofa
),compute an approximate
.f64
reciprocal of this value using the most-significant 20 bits of the mantissa of operanda
,place the resulting 32-bits in 1.11.20 IEEE floating-point format in the most-significant 32-bits of destination
d
,andzero the least significant 32 mantissa bits of
.f64
destinationd
.
Semantics
tmp = a[63:32]; // upper word of a, 1.11.20 format
d[63:32] = 1.0 / tmp;
d[31:0] = 0x00000000;
Notes
rcp.approx.ftz.f64
implements a fast, gross approximation to reciprocal.
Input a[63:32] |
Result d[63:32] |
---|---|
-Inf |
-0.0 |
-subnormal |
-Inf |
-0.0 |
-Inf |
+0.0 |
+Inf |
+subnormal |
+Inf |
+Inf |
+0.0 |
NaN |
NaN |
Input NaN
s map to a canonical NaN
with encoding 0x7fffffff00000000
.
Subnormal inputs and results are flushed to sign-preserving zero.
PTX ISA Notes
rcp.approx.ftz.f64
introduced in PTX ISA version 2.1.
Target ISA Notes
rcp.approx.ftz.f64
requires sm_20
or higher.
Examples
rcp.ftz.f64 xi,x;
9.7.3.15. Floating Point Instructions: sqrt
sqrt
Take the square root of a value.
Syntax
sqrt.approx{.ftz}.f32 d, a; // fast, approximate square root
sqrt.rnd{.ftz}.f32 d, a; // IEEE 754 compliant rounding
sqrt.rnd.f64 d, a; // IEEE 754 compliant rounding
.rnd = { .rn, .rz, .rm, .rp };
Description
Compute sqrt(a
) and store the result in d
.
Semantics
d = sqrt(a);
Notes
sqrt.approx.f32
implements a fast approximation to square root.
Input |
Result |
---|---|
-Inf |
NaN |
-normal |
NaN |
-subnormal |
-0.0 |
-0.0 |
-0.0 |
+0.0 |
+0.0 |
+subnormal |
+0.0 |
+Inf |
+Inf |
NaN |
NaN |
Square root with IEEE 754 compliant rounding:
Rounding modifiers (no default):
.rn
-
mantissa LSB rounds to nearest even
.rz
-
mantissa LSB rounds towards zero
.rm
-
mantissa LSB rounds towards negative infinity
.rp
-
mantissa LSB rounds towards positive infinity
Subnormal numbers:
sm_20+
-
By default, subnormal numbers are supported.
sqrt.ftz.f32
flushes subnormal inputs and results to sign-preserving zero. sm_1x
-
sqrt.f64
supports subnormal numbers.sqrt.f32
flushes subnormal inputs and results to sign-preserving zero.
PTX ISA Notes
sqrt.f32
and sqrt.f64
introduced in PTX ISA version 1.0. sqrt.rn.f64
and explicit
modifiers .approx
and .ftz
were introduced in PTX ISA version 1.4. General rounding
modifiers were added in PTX ISA version 2.0.
For PTX ISA version 1.4 and later, one of .approx
or .rnd
is required.
For PTX ISA versions 1.0 through 1.3, sqrt.f32
defaults to sqrt.approx.ftz.f32
, and
sqrt.f64
defaults to sqrt.rn.f64
.
Target ISA Notes
sqrt.approx.f32
supported on all target architectures.
sqrt.rnd.f32
requires sm_20
or higher.
sqrt.rn.f64
requires sm_13
or higher, or .target map_f64_to_f32
.
sqrt.{rz,rm,rp}.f64
requires sm_20
or higher.
Examples
sqrt.approx.ftz.f32 r,x;
sqrt.rn.ftz.f32 r,x;
sqrt.rn.f64 r,x;
9.7.3.16. Floating Point Instructions: rsqrt
rsqrt
Take the reciprocal of the square root of a value.
Syntax
rsqrt.approx{.ftz}.f32 d, a;
rsqrt.approx.f64 d, a;
Description
Compute 1/sqrt(a)
and store the result in d
.
Semantics
d = 1/sqrt(a);
Notes
rsqrt.approx
implements an approximation to the reciprocal square root.
Input |
Result |
---|---|
-Inf |
NaN |
-normal |
NaN |
-subnormal |
-Inf |
-0.0 |
-Inf |
+0.0 |
+Inf |
+subnormal |
+Inf |
+Inf |
+0.0 |
NaN |
NaN |
The maximum absolute error for rsqrt.f32
is 2-22.4 over the range 1.0-4.0.
Subnormal numbers:
sm_20+
-
By default, subnormal numbers are supported.
rsqrt.ftz.f32
flushes subnormal inputs and results to sign-preserving zero. sm_1x
-
rsqrt.f64
supports subnormal numbers.rsqrt.f32
flushes subnormal inputs and results to sign-preserving zero.
Note that rsqrt.approx.f64
is emulated in software and are relatively slow.
PTX ISA Notes
rsqrt.f32
and rsqrt.f64
were introduced in PTX ISA version 1.0. Explicit modifiers
.approx
and .ftz
were introduced in PTX ISA version 1.4.
For PTX ISA version 1.4 and later, the .approx
modifier is required.
For PTX ISA versions 1.0 through 1.3, rsqrt.f32
defaults to rsqrt.approx.ftz.f32
, and
rsqrt.f64
defaults to rsqrt.approx.f64
.
Target ISA Notes
rsqrt.f32
supported on all target architectures.
rsqrt.f64
requires sm_13
or higher.
Examples
rsqrt.approx.ftz.f32 isr, x;
rsqrt.approx.f64 ISR, X;
9.7.3.17. Floating Point Instructions: rsqrt.approx.ftz.f64
rsqrt.approx.ftz.f64
Compute an approximation of the square root reciprocal of a value.
Syntax
rsqrt.approx.ftz.f64 d, a;
Description
Compute a double-precision (.f64
) approximation of the square root reciprocal of a value. The
least significant 32 bits of the double-precision (.f64
) destination d
are all zeros.
Semantics
tmp = a[63:32]; // upper word of a, 1.11.20 format
d[63:32] = 1.0 / sqrt(tmp);
d[31:0] = 0x00000000;
Notes
rsqrt.approx.ftz.f64
implements a fast approximation of the square root reciprocal of a value.
Input |
Result |
---|---|
-Inf |
NaN |
-subnormal |
-Inf |
-0.0 |
-Inf |
+0.0 |
+Inf |
+subnormal |
+Inf |
+Inf |
+0.0 |
NaN |
NaN |
Input NaN
s map to a canonical NaN
with encoding 0x7fffffff00000000
.
Subnormal inputs and results are flushed to sign-preserving zero.
PTX ISA Notes
rsqrt.approx.ftz.f64
introduced in PTX ISA version 4.0.
Target ISA Notes
rsqrt.approx.ftz.f64
requires sm_20
or higher.
Examples
rsqrt.approx.ftz.f64 xi,x;
9.7.3.18. Floating Point Instructions: sin
sin
Find the sine of a value.
Syntax
sin.approx{.ftz}.f32 d, a;
Description
Find the sine of the angle a
(in radians).
Semantics
d = sin(a);
Notes
sin.approx.f32
implements a fast approximation to sine.
Input |
Result |
---|---|
-Inf |
NaN |
-subnormal |
-0.0 |
-0.0 |
-0.0 |
+0.0 |
+0.0 |
+subnormal |
+0.0 |
+Inf |
NaN |
NaN |
NaN |
The maximum absolute error is 2-20.9 in quadrant 00.
Subnormal numbers:
sm_20+
-
By default, subnormal numbers are supported.
sin.ftz.f32
flushes subnormal inputs and results to sign-preserving zero. sm_1x
-
Subnormal inputs and results to sign-preserving zero.
PTX ISA Notes
sin.f32
introduced in PTX ISA version 1.0. Explicit modifiers .approx
and .ftz
introduced in PTX ISA version 1.4.
For PTX ISA version 1.4 and later, the .approx modifier is required.
For PTX ISA versions 1.0 through 1.3, sin.f32
defaults to sin.approx.ftz.f32
.
Target ISA Notes
Supported on all target architectures.
Examples
sin.approx.ftz.f32 sa, a;
9.7.3.19. Floating Point Instructions: cos
cos
Find the cosine of a value.
Syntax
cos.approx{.ftz}.f32 d, a;
Description
Find the cosine of the angle a
(in radians).
Semantics
d = cos(a);
Notes
cos.approx.f32
implements a fast approximation to cosine.
Input |
Result |
---|---|
-Inf |
NaN |
-subnormal |
+1.0 |
-0.0 |
+1.0 |
+0.0 |
+1.0 |
+subnormal |
+1.0 |
+Inf |
NaN |
NaN |
NaN |
The maximum absolute error is 2-20.9 in quadrant 00.
Subnormal numbers:
sm_20+
-
By default, subnormal numbers are supported.
cos.ftz.f32
flushes subnormal inputs and results to sign-preserving zero. sm_1x
-
Subnormal inputs and results to sign-preserving zero.
PTX ISA Notes
cos.f32
introduced in PTX ISA version 1.0. Explicit modifiers .approx
and .ftz
introduced in PTX ISA version 1.4.
For PTX ISA version 1.4 and later, the .approx
modifier is required.
For PTX ISA versions 1.0 through 1.3, cos.f32
defaults to cos.approx.ftz.f32
.
Target ISA Notes
Supported on all target architectures.
Examples
cos.approx.ftz.f32 ca, a;
9.7.3.20. Floating Point Instructions: lg2
lg2
Find the base-2 logarithm of a value.
Syntax
lg2.approx{.ftz}.f32 d, a;
Description
Determine the log2 of a
.
Semantics
d = log(a) / log(2);
Notes
lg2.approx.f32
implements a fast approximation to log2(a).
Input |
Result |
---|---|
-Inf |
NaN |
-subnormal |
-Inf |
-0.0 |
-Inf |
+0.0 |
-Inf |
+subnormal |
-Inf |
+Inf |
+Inf |
NaN |
NaN |
The maximum absolute error is 2-22.6 for mantissa.
Subnormal numbers:
sm_20+
-
By default, subnormal numbers are supported.
lg2.ftz.f32
flushes subnormal inputs and results to sign-preserving zero. sm_1x
-
Subnormal inputs and results to sign-preserving zero.
PTX ISA Notes
lg2.f32
introduced in PTX ISA version 1.0. Explicit modifiers .approx
and .ftz
introduced in PTX ISA version 1.4.
For PTX ISA version 1.4 and later, the .approx
modifier is required.
For PTX ISA versions 1.0 through 1.3, lg2.f32
defaults to lg2.approx.ftz.f32
.
Target ISA Notes
Supported on all target architectures.
Examples
lg2.approx.ftz.f32 la, a;
9.7.3.21. Floating Point Instructions: ex2
ex2
Find the base-2 exponential of a value.
Syntax
ex2.approx{.ftz}.f32 d, a;
Description
Raise 2 to the power a
.
Semantics
d = 2 ^ a;
Notes
ex2.approx.f32
implements a fast approximation to 2a.
Input |
Result |
---|---|
-Inf |
+0.0 |
-subnormal |
+1.0 |
-0.0 |
+1.0 |
+0.0 |
+1.0 |
+subnormal |
+1.0 |
+Inf |
+Inf |
NaN |
NaN |
The maximum absolute error is 2-22.5 for fraction in the primary range.
Subnormal numbers:
sm_20+
-
By default, subnormal numbers are supported.
ex2.ftz.f32
flushes subnormal inputs and results to sign-preserving zero. sm_1x
-
Subnormal inputs and results to sign-preserving zero.
PTX ISA Notes
ex2.f32
introduced in PTX ISA version 1.0. Explicit modifiers .approx
and .ftz
introduced in PTX ISA version 1.4.
For PTX ISA version 1.4 and later, the .approx
modifier is required.
For PTX ISA versions 1.0 through 1.3, ex2.f32
defaults to ex2.approx.ftz.f32
.
Target ISA Notes
Supported on all target architectures.
Examples
ex2.approx.ftz.f32 xa, a;
9.7.3.22. Floating Point Instructions: tanh
tanh
Find the hyperbolic tangent of a value (in radians)
Syntax
tanh.approx.f32 d, a;
Description
Take hyperbolic tangent value of a
.
The operands d
and a
are of type .f32
.
Semantics
d = tanh(a);
Notes
tanh.approx.f32
implements a fast approximation to FP32 hyperbolic-tangent.
Results of tanh
for various corner-case inputs are as follows:
Input |
Result |
---|---|
-Inf |
-1.0 |
-subnormal |
Same as input |
-0.0 |
-0.0 |
+0.0 |
+0.0 |
+subnormal |
Same as input |
+Inf |
1.0 |
NaN |
NaN |
The subnormal numbers are supported.
Note
The subnormal inputs gets passed through to the output since the value of tanh(x)
for small
values of x
is approximately the same as x
.
PTX ISA Notes
Introduced in PTX ISA version 7.0.
Target ISA Notes
Requires sm_75
or higher.
Examples
tanh.approx.f32 sa, a;
9.7.4. Half Precision Floating-Point Instructions
Half precision floating-point instructions operate on .f16
and .f16x2
register operands. The
half precision floating-point instructions are:
add
sub
mul
fma
neg
abs
min
max
tanh
ex2
Half-precision add
, sub
, mul
, and fma
support saturation of results to the range
[0.0, 1.0], with NaN
s being flushed to positive zero. Half-precision instructions return an
unspecified NaN
.
9.7.4.1. Half Precision Floating Point Instructions: add
add
Add two values.
Syntax
add{.rnd}{.ftz}{.sat}.f16 d, a, b;
add{.rnd}{.ftz}{.sat}.f16x2 d, a, b;
add{.rnd}.bf16 d, a, b;
add{.rnd}.bf16x2 d, a, b;
.rnd = { .rn };
Description
Performs addition and writes the resulting value into a destination register.
For .f16x2
and .bf16x2
instruction type, forms input vectors by half word values from source
operands. Half-word operands are then added in parallel to produce .f16x2
or .bf16x2
result
in destination.
For .f16
instruction type, operands d
, a
and b
have .f16
or .b16
type. For
.f16x2
instruction type, operands d
, a
and b
have .b32
type. For .bf16
instruction type, operands d
, a
, b
have .b16
type. For .bf16x2
instruction type,
operands d
, a
, b
have .b32
type.
Semantics
if (type == f16 || type == bf16) {
d = a + b;
} else if (type == f16x2 || type == bf16x2) {
fA[0] = a[0:15];
fA[1] = a[16:31];
fB[0] = b[0:15];
fB[1] = b[16:31];
for (i = 0; i < 2; i++) {
d[i] = fA[i] + fB[i];
}
}
Notes
Rounding modifiers:
.rn
-
mantissa LSB rounds to nearest even
The default value of rounding modifier is .rn
. Note that an add
instruction with an explicit
rounding modifier is treated conservatively by the code optimizer. An add
instruction with no
rounding modifier defaults to round-to-nearest-even and may be optimized aggressively by the code
optimizer. In particular, mul
/add
sequences with no rounding modifiers may be optimized to
use fused-multiply-add instructions on the target device.
- Subnormal numbers:
-
By default, subnormal numbers are supported.
add.ftz.{f16, f16x2}
flushes subnormal inputs and results to sign-preserving zero. - Saturation modifier:
-
add.sat.{f16, f16x2}
clamps the result to [0.0, 1.0].NaN
results are flushed to+0.0f
.
PTX ISA Notes
Introduced in PTX ISA version 4.2.
add{.rnd}.bf16
and add{.rnd}.bf16x2
introduced in PTX ISA version 7.8.
Target ISA Notes
Requires sm_53
or higher.
add{.rnd}.bf16
and add{.rnd}.bf16x2
requires sm_90
or higher.
Examples
// scalar f16 additions
add.f16 d0, a0, b0;
add.rn.f16 d1, a1, b1;
add.bf16 bd0, ba0, bb0;
add.rn.bf16 bd1, ba1, bb1;
// SIMD f16 addition
cvt.rn.f16.f32 h0, f0;
cvt.rn.f16.f32 h1, f1;
cvt.rn.f16.f32 h2, f2;
cvt.rn.f16.f32 h3, f3;
mov.b32 p1, {h0, h1}; // pack two f16 to 32bit f16x2
mov.b32 p2, {h2, h3}; // pack two f16 to 32bit f16x2
add.f16x2 p3, p1, p2; // SIMD f16x2 addition
// SIMD bf16 addition
cvt.rn.bf16x2.f32 p4, f4, f5; // Convert two f32 into packed bf16x2
cvt.rn.bf16x2.f32 p5, f6, f7; // Convert two f32 into packed bf16x2
add.bf16x2 p6, p4, p5; // SIMD bf16x2 addition
// SIMD fp16 addition
ld.global.b32 f0, [addr]; // load 32 bit which hold packed f16x2
ld.global.b32 f1, [addr + 4]; // load 32 bit which hold packed f16x2
add.f16x2 f2, f0, f1; // SIMD f16x2 addition
ld.global.b32 f3, [addr + 8]; // load 32 bit which hold packed bf16x2
ld.global.b32 f4, [addr + 12]; // load 32 bit which hold packed bf16x2
add.bf16x2 f5, f3, f4; // SIMD bf16x2 addition
9.7.4.2. Half Precision Floating Point Instructions: sub
sub
Subtract two values.
Syntax
sub{.rnd}{.ftz}{.sat}.f16 d, a, b;
sub{.rnd}{.ftz}{.sat}.f16x2 d, a, b;
sub{.rnd}.bf16 d, a, b;
sub{.rnd}.bf16x2 d, a, b;
.rnd = { .rn };
Description
Performs subtraction and writes the resulting value into a destination register.
For .f16x2
and .bf16x2
instruction type, forms input vectors by half word values from source
operands. Half-word operands are then subtracted in parallel to produce .f16x2
or .bf16x2
result in destination.
For .f16
instruction type, operands d
, a
and b
have .f16
or .b16
type. For
.f16x2
instruction type, operands d
, a
and b
have .b32
type. For .bf16
instruction type, operands d
, a
, b
have .b16
type. For .bf16x2
instruction type,
operands d
, a
, b
have .b32
type.
Semantics
if (type == f16 || type == bf16) {
d = a - b;
} else if (type == f16x2 || type == bf16x2) {
fA[0] = a[0:15];
fA[1] = a[16:31];
fB[0] = b[0:15];
fB[1] = b[16:31];
for (i = 0; i < 2; i++) {
d[i] = fA[i] - fB[i];
}
}
Notes
Rounding modifiers:
.rn
-
mantissa LSB rounds to nearest even
The default value of rounding modifier is .rn
. Note that a sub
instruction with an explicit
rounding modifier is treated conservatively by the code optimizer. A sub
instruction with no
rounding modifier defaults to round-to-nearest-even and may be optimized aggressively by the code
optimizer. In particular, mul
/sub
sequences with no rounding modifiers may be optimized to
use fused-multiply-add instructions on the target device.
- Subnormal numbers:
-
By default, subnormal numbers are supported.
sub.ftz.{f16, f16x2}
flushes subnormal inputs and results to sign-preserving zero. - Saturation modifier:
-
sub.sat.{f16, f16x2}
clamps the result to [0.0, 1.0].NaN
results are flushed to+0.0f
.
PTX ISA Notes
Introduced in PTX ISA version 4.2.
sub{.rnd}.bf16
and sub{.rnd}.bf16x2
introduced in PTX ISA version 7.8.
Target ISA Notes
Requires sm_53
or higher.
sub{.rnd}.bf16
and sub{.rnd}.bf16x2
requires sm_90
or higher.
Examples
// scalar f16 subtractions
sub.f16 d0, a0, b0;
sub.rn.f16 d1, a1, b1;
sub.bf16 bd0, ba0, bb0;
sub.rn.bf16 bd1, ba1, bb1;
// SIMD f16 subtraction
cvt.rn.f16.f32 h0, f0;
cvt.rn.f16.f32 h1, f1;
cvt.rn.f16.f32 h2, f2;
cvt.rn.f16.f32 h3, f3;
mov.b32 p1, {h0, h1}; // pack two f16 to 32bit f16x2
mov.b32 p2, {h2, h3}; // pack two f16 to 32bit f16x2
sub.f16x2 p3, p1, p2; // SIMD f16x2 subtraction
// SIMD bf16 subtraction
cvt.rn.bf16x2.f32 p4, f4, f5; // Convert two f32 into packed bf16x2
cvt.rn.bf16x2.f32 p5, f6, f7; // Convert two f32 into packed bf16x2
sub.bf16x2 p6, p4, p5; // SIMD bf16x2 subtraction
// SIMD fp16 subtraction
ld.global.b32 f0, [addr]; // load 32 bit which hold packed f16x2
ld.global.b32 f1, [addr + 4]; // load 32 bit which hold packed f16x2
sub.f16x2 f2, f0, f1; // SIMD f16x2 subtraction
// SIMD bf16 subtraction
ld.global.b32 f3, [addr + 8]; // load 32 bit which hold packed bf16x2
ld.global.b32 f4, [addr + 12]; // load 32 bit which hold packed bf16x2
sub.bf16x2 f5, f3, f4; // SIMD bf16x2 subtraction
9.7.4.3. Half Precision Floating Point Instructions: mul
mul
Multiply two values.
Syntax
mul{.rnd}{.ftz}{.sat}.f16 d, a, b;
mul{.rnd}{.ftz}{.sat}.f16x2 d, a, b;
mul{.rnd}.bf16 d, a, b;
mul{.rnd}.bf16x2 d, a, b;
.rnd = { .rn };
Description
Performs multiplication and writes the resulting value into a destination register.
For .f16x2
and .bf16x2
instruction type, forms input vectors by half word values from source
operands. Half-word operands are then multiplied in parallel to produce .f16x2
or .bf16x2
result in destination.
For .f16
instruction type, operands d
, a
and b
have .f16
or .b16
type. For
.f16x2
instruction type, operands d
, a
and b
have .b32
type. For .bf16
instruction type, operands d
, a
, b
have .b16
type. For .bf16x2
instruction type,
operands d
, a
, b
have .b32
type.
Semantics
if (type == f16 || type == bf16) {
d = a * b;
} else if (type == f16x2 || type == bf16x2) {
fA[0] = a[0:15];
fA[1] = a[16:31];
fB[0] = b[0:15];
fB[1] = b[16:31];
for (i = 0; i < 2; i++) {
d[i] = fA[i] * fB[i];
}
}
Notes
Rounding modifiers:
.rn
-
mantissa LSB rounds to nearest even
The default value of rounding modifier is .rn
. Note that a mul
instruction with an explicit
rounding modifier is treated conservatively by the code optimizer. A mul
instruction with no
rounding modifier defaults to round-to-nearest-even and may be optimized aggressively by the code
optimizer. In particular, mul
/add
and mul/sub
sequences with no rounding modifiers may
be optimized to use fused-multiply-add instructions on the target device.
- Subnormal numbers:
-
By default, subnormal numbers are supported.
mul.ftz.{f16, f16x2}
flushes subnormal inputs and results to sign-preserving zero. - Saturation modifier:
-
mul.sat.{f16, f16x2}
clamps the result to [0.0, 1.0].NaN
results are flushed to+0.0f
.
PTX ISA Notes
Introduced in PTX ISA version 4.2.
mul{.rnd}.bf16
and mul{.rnd}.bf16x2
introduced in PTX ISA version 7.8.
Target ISA Notes
Requires sm_53
or higher.
mul{.rnd}.bf16
and mul{.rnd}.bf16x2
requires sm_90
or higher.
Examples
// scalar f16 multiplications
mul.f16 d0, a0, b0;
mul.rn.f16 d1, a1, b1;
mul.bf16 bd0, ba0, bb0;
mul.rn.bf16 bd1, ba1, bb1;
// SIMD f16 multiplication
cvt.rn.f16.f32 h0, f0;
cvt.rn.f16.f32 h1, f1;
cvt.rn.f16.f32 h2, f2;
cvt.rn.f16.f32 h3, f3;
mov.b32 p1, {h0, h1}; // pack two f16 to 32bit f16x2
mov.b32 p2, {h2, h3}; // pack two f16 to 32bit f16x2
mul.f16x2 p3, p1, p2; // SIMD f16x2 multiplication
// SIMD bf16 multiplication
cvt.rn.bf16x2.f32 p4, f4, f5; // Convert two f32 into packed bf16x2
cvt.rn.bf16x2.f32 p5, f6, f7; // Convert two f32 into packed bf16x2
mul.bf16x2 p6, p4, p5; // SIMD bf16x2 multiplication
// SIMD fp16 multiplication
ld.global.b32 f0, [addr]; // load 32 bit which hold packed f16x2
ld.global.b32 f1, [addr + 4]; // load 32 bit which hold packed f16x2
mul.f16x2 f2, f0, f1; // SIMD f16x2 multiplication
// SIMD bf16 multiplication
ld.global.b32 f3, [addr + 8]; // load 32 bit which hold packed bf16x2
ld.global.b32 f4, [addr + 12]; // load 32 bit which hold packed bf16x2
mul.bf16x2 f5, f3, f4; // SIMD bf16x2 multiplication
9.7.4.4. Half Precision Floating Point Instructions: fma
fma
Fused multiply-add
Syntax
fma.rnd{.ftz}{.sat}.f16 d, a, b, c;
fma.rnd{.ftz}{.sat}.f16x2 d, a, b, c;
fma.rnd{.ftz}.relu.f16 d, a, b, c;
fma.rnd{.ftz}.relu.f16x2 d, a, b, c;
fma.rnd{.relu}.bf16 d, a, b, c;
fma.rnd{.relu}.bf16x2 d, a, b, c;
fma.rnd.oob.{relu}.type d, a, b, c;
.rnd = { .rn };
Description
Performs a fused multiply-add with no loss of precision in the intermediate product and addition.
For .f16x2
and .bf16x2
instruction type, forms input vectors by half word values from source
operands. Half-word operands are then operated in parallel to produce .f16x2
or .bf16x2
result in destination.
For .f16
instruction type, operands d
, a
, b
and c
have .f16
or .b16
type. For .f16x2
instruction type, operands d
, a
, b
and c
have .b32
type. For .bf16
instruction type, operands d
, a
, b
and c
have .b16
type. For
.bf16x2
instruction type, operands d
, a
, b
and c
have .b32
type.
Semantics
if (type == f16 || type == bf16) {
d = a * b + c;
} else if (type == f16x2 || type == bf16x2) {
fA[0] = a[0:15];
fA[1] = a[16:31];
fB[0] = b[0:15];
fB[1] = b[16:31];
fC[0] = c[0:15];
fC[1] = c[16:31];
for (i = 0; i < 2; i++) {
d[i] = fA[i] * fB[i] + fC[i];
}
}
Notes
Rounding modifiers (default is .rn
):
.rn
-
mantissa LSB rounds to nearest even
- Subnormal numbers:
-
By default, subnormal numbers are supported.
fma.ftz.{f16, f16x2}
flushes subnormal inputs and results to sign-preserving zero. - Saturation modifier:
-
fma.sat.{f16, f16x2}
clamps the result to [0.0, 1.0].NaN
results are flushed to+0.0f
.fma.relu.{f16, f16x2, bf16, bf16x2}
clamps the result to 0 if negative.NaN
result is converted to canonicalNaN
. - Out Of Bounds modifier:
-
fma.oob.{f16, f16x2, bf16, bf16x2}
clamps the result to 0 if either of the operands isOOB NaN
(defined under Tensors) value. The test for the specialNaN
value and resultant forcing of the result to +0.0 is performed independently for each of the two SIMD operations.
PTX ISA Notes
Introduced in PTX ISA version 4.2.
fma.relu.{f16, f16x2}
and fma{.relu}.{bf16, bf16x2}
introduced in PTX ISA version 7.0.
Support for modifier .oob
introduced in PTX ISA version 8.1.
Target ISA Notes
Requires sm_53
or higher.
fma.relu.{f16, f16x2}
and fma{.relu}.{bf16, bf16x2}
require sm_80
or higher.
fma{.oob}.{f16, f16x2, bf16, bf16x2}
requires sm_90
or higher.
Examples
// scalar f16 fused multiply-add
fma.rn.f16 d0, a0, b0, c0;
fma.rn.f16 d1, a1, b1, c1;
fma.rn.relu.f16 d1, a1, b1, c1;
fma.rn.oob.f16 d1, a1, b1, c1;
fma.rn.oob.relu.f16 d1, a1, b1, c1;
// scalar bf16 fused multiply-add
fma.rn.bf16 d1, a1, b1, c1;
fma.rn.relu.bf16 d1, a1, b1, c1;
fma.rn.oob.bf16 d1, a1, b1, c1;
fma.rn.oob.relu.bf16 d1, a1, b1, c1;
// SIMD f16 fused multiply-add
cvt.rn.f16.f32 h0, f0;
cvt.rn.f16.f32 h1, f1;
cvt.rn.f16.f32 h2, f2;
cvt.rn.f16.f32 h3, f3;
mov.b32 p1, {h0, h1}; // pack two f16 to 32bit f16x2
mov.b32 p2, {h2, h3}; // pack two f16 to 32bit f16x2
fma.rn.f16x2 p3, p1, p2, p2; // SIMD f16x2 fused multiply-add
fma.rn.relu.f16x2 p3, p1, p2, p2; // SIMD f16x2 fused multiply-add with relu saturation mode
fma.rn.oob.f16x2 p3, p1, p2, p2; // SIMD f16x2 fused multiply-add with oob modifier
fma.rn.oob.relu.f16x2 p3, p1, p2, p2; // SIMD f16x2 fused multiply-add with oob modifier and relu saturation mode
// SIMD fp16 fused multiply-add
ld.global.b32 f0, [addr]; // load 32 bit which hold packed f16x2
ld.global.b32 f1, [addr + 4]; // load 32 bit which hold packed f16x2
fma.rn.f16x2 f2, f0, f1, f1; // SIMD f16x2 fused multiply-add
// SIMD bf16 fused multiply-add
fma.rn.bf16x2 f2, f0, f1, f1; // SIMD bf16x2 fused multiply-add
fma.rn.relu.bf16x2 f2, f0, f1, f1; // SIMD bf16x2 fused multiply-add with relu saturation mode
fma.rn.oob.bf16x2 f2, f0, f1, f1; // SIMD bf16x2 fused multiply-add with oob modifier
fma.rn.oob.relu.bf16x2 f2, f0, f1, f1; // SIMD bf16x2 fused multiply-add with oob modifier and relu saturation mode
9.7.4.5. Half Precision Floating Point Instructions: neg
neg
Arithmetic negate.
Syntax
neg{.ftz}.f16 d, a;
neg{.ftz}.f16x2 d, a;
neg.bf16 d, a;
neg.bf16x2 d, a;
Description
Negate the sign of a
and store the result in d
.
For .f16x2
and .bf16x2
instruction type, forms input vector by extracting half word values
from the source operand. Half-word operands are then negated in parallel to produce .f16x2
or
.bf16x2
result in destination.
For .f16
instruction type, operands d
and a
have .f16
or .b16
type. For
.f16x2
instruction type, operands d
and a
have .b32
type. For .bf16
instruction
type, operands d
and a
have .b16
type. For .bf16x2
instruction type, operands d
and a
have .b32
type.
Semantics
if (type == f16 || type == bf16) {
d = -a;
} else if (type == f16x2 || type == bf16x2) {
fA[0] = a[0:15];
fA[1] = a[16:31];
for (i = 0; i < 2; i++) {
d[i] = -fA[i];
}
}
Notes
- Subnormal numbers:
-
By default, subnormal numbers are supported.
neg.ftz.{f16, f16x2}
flushes subnormal inputs and results to sign-preserving zero.
NaN
inputs yield an unspecified NaN
. Future implementations may comply with the IEEE 754
standard by preserving payload and modifying only the sign bit.
PTX ISA Notes
Introduced in PTX ISA version 6.0.
neg.bf16
and neg.bf16x2
introduced in PTX ISA 7.0.
Target ISA Notes
Requires sm_53
or higher.
neg.bf16
and neg.bf16x2
requires architecture sm_80
or higher.
Examples
neg.ftz.f16 x,f0;
neg.bf16 x,b0;
neg.bf16x2 x1,b1;
9.7.4.6. Half Precision Floating Point Instructions: abs
abs
Absolute value
Syntax
abs{.ftz}.f16 d, a;
abs{.ftz}.f16x2 d, a;
abs.bf16 d, a;
abs.bf16x2 d, a;
Description
Take absolute value of a
and store the result in d
.
For .f16x2
and .bf16x2
instruction type, forms input vector by extracting half word values
from the source operand. Absolute values of half-word operands are then computed in parallel to
produce .f16x2
or .bf16x2
result in destination.
For .f16
instruction type, operands d
and a
have .f16
or .b16
type. For
.f16x2
instruction type, operands d
and a
have .f16x2
or .b32
type. For
.bf16
instruction type, operands d
and a
have .b16
type. For .bf16x2
instruction
type, operands d
and a
have .b32
type.
Semantics
if (type == f16 || type == bf16) {
d = |a|;
} else if (type == f16x2 || type == bf16x2) {
fA[0] = a[0:15];
fA[1] = a[16:31];
for (i = 0; i < 2; i++) {
d[i] = |fA[i]|;
}
}
Notes
- Subnormal numbers:
-
By default, subnormal numbers are supported.
abs.ftz.{f16, f16x2}
flushes subnormal inputs and results to sign-preserving zero.
NaN
inputs yield an unspecified NaN
. Future implementations may comply with the IEEE 754
standard by preserving payload and modifying only the sign bit.
PTX ISA Notes
Introduced in PTX ISA version 6.5.
abs.bf16
and abs.bf16x2
introduced in PTX ISA 7.0.
Target ISA Notes
Requires sm_53
or higher.
abs.bf16
and abs.bf16x2
requires architecture sm_80
or higher.
Examples
abs.ftz.f16 x,f0;
abs.bf16 x,b0;
abs.bf16x2 x1,b1;
9.7.4.7. Half Precision Floating Point Instructions: min
min
Find the minimum of two values.
Syntax
min{.ftz}{.NaN}{.xorsign.abs}.f16 d, a, b;
min{.ftz}{.NaN}{.xorsign.abs}.f16x2 d, a, b;
min{.NaN}{.xorsign.abs}.bf16 d, a, b;
min{.NaN}{.xorsign.abs}.bf16x2 d, a, b;
Description
Store the minimum of a
and b
in d
.
For .f16x2
and .bf16x2
instruction types, input vectors are formed with half-word values
from source operands. Half-word operands are then processed in parallel to store .f16x2
or
.bf16x2
result in destination.
For .f16
instruction type, operands d
and a
have .f16
or .b16
type. For
.f16x2
instruction type, operands d
and a
have .f16x2
or .b32
type. For
.bf16
instruction type, operands d
and a
have .b16
type. For .bf16x2
instruction
type, operands d
and a
have .b32
type.
If .NaN
modifier is specified, then the result is canonical NaN
if either of the inputs is
NaN
.
If .abs
modifier is specified, the magnitude of destination operand d
is the minimum of
absolute values of both the input arguments.
If .xorsign
modifier is specified, the sign bit of destination d
is equal to the XOR of the
sign bits of both the inputs.
Modifiers .abs
and .xorsign
must be specified together and .xorsign
considers the sign
bit of both inputs before applying .abs
operation.
If the result of min
is NaN
then the .xorsign
and .abs
modifiers will be ignored.
Semantics
if (type == f16 || type == bf16) {
if (.xorsign) {
xorsign = getSignBit(a) ^ getSignBit(b);
if (.abs) {
a = |a|;
b = |b|;
}
}
if (isNaN(a) && isNaN(b)) d = NaN;
if (.NaN && (isNaN(a) || isNaN(b))) d = NaN;
else if (isNaN(a)) d = b;
else if (isNaN(b)) d = a;
else d = (a < b) ? a : b;
if (.xorsign && !isNaN(d)) {
setSignBit(d, xorsign);
}
} else if (type == f16x2 || type == bf16x2) {
fA[0] = a[0:15];
fA[1] = a[16:31];
fB[0] = b[0:15];
fB[1] = b[16:31];
for (i = 0; i < 2; i++) {
if (.xorsign) {
xorsign = getSignBit(fA[i]) ^ getSignBit(fB[i]);
if (.abs) {
fA[i] = |fA[i]|;
fB[i] = |fB[i]|;
}
}
if (isNaN(fA[i]) && isNaN(fB[i])) d[i] = NaN;
if (.NaN && (isNaN(fA[i]) || isNaN(fB[i]))) d[i] = NaN;
else if (isNaN(fA[i])) d[i] = fB[i];
else if (isNaN(fB[i])) d[i] = fA[i];
else d[i] = (fA[i] < fB[i]) ? fA[i] : fB[i];
if (.xorsign && !isNaN(d[i])) {
setSignBit(d[i], xorsign);
}
}
}
Notes
- Subnormal numbers:
-
By default, subnormal numbers are supported.
min.ftz.{f16, f16x2}
flushes subnormal inputs and results to sign-preserving zero.
If values of both inputs are 0.0, then +0.0 > -0.0.
PTX ISA Notes
Introduced in PTX ISA version 7.0.
min.xorsign
introduced in PTX ISA version 7.2.
Target ISA Notes
Requires sm_80
or higher.
min.xorsign.abs
support requires sm_86
or higher.
Examples
min.ftz.f16 h0,h1,h2;
min.f16x2 b0,b1,b2;
// SIMD fp16 min with .NaN
min.NaN.f16x2 b0,b1,b2;
min.bf16 h0, h1, h2;
// SIMD bf16 min with NaN
min.NaN.bf16x2 b0, b1, b2;
// scalar bf16 min with xorsign.abs
min.xorsign.abs.bf16 Rd, Ra, Rb
9.7.4.8. Half Precision Floating Point Instructions: max
max
Find the maximum of two values.
Syntax
max{.ftz}{.NaN}{.xorsign.abs}.f16 d, a, b;
max{.ftz}{.NaN}{.xorsign.abs}.f16x2 d, a, b;
max{.NaN}{.xorsign.abs}.bf16 d, a, b;
max{.NaN}{.xorsign.abs}.bf16x2 d, a, b;
Description
Store the maximum of a
and b
in d
.
For .f16x2
and .bf16x2
instruction types, input vectors are formed with half-word values
from source operands. Half-word operands are then processed in parallel to store .f16x2
or
.bf16x2
result in destination.
For .f16
instruction type, operands d
and a
have .f16
or .b16
type. For
.f16x2
instruction type, operands d
and a
have .f16x2
or .b32
type. For
.bf16
instruction type, operands d
and a
have .b16
type. For .bf16x2
instruction
type, operands d
and a
have .b32
type.
If .NaN
modifier is specified, the result is canonical NaN
if either of the inputs is
NaN
.
If .abs
modifier is specified, the magnitude of destination operand d
is the maximum of
absolute values of both the input arguments.
If .xorsign
modifier is specified, the sign bit of destination d
is equal to the XOR of the
sign bits of both the inputs.
Modifiers .abs
and .xorsign
must be specified together and .xorsign
considers the sign
bit of both inputs before applying .abs
operation.
If the result of max
is NaN
then the .xorsign
and .abs
modifiers will be ignored.
Semantics
if (type == f16 || type == bf16) {
if (.xorsign) {
xorsign = getSignBit(a) ^ getSignBit(b);
if (.abs) {
a = |a|;
b = |b|;
}
}
if (isNaN(a) && isNaN(b)) d = NaN;
if (.NaN && (isNaN(a) || isNaN(b))) d = NaN;
else if (isNaN(a)) d = b;
else if (isNaN(b)) d = a;
else d = (a > b) ? a : b;
if (.xorsign && !isNaN(d)) {
setSignBit(d, xorsign);
}
} else if (type == f16x2 || type == bf16x2) {
fA[0] = a[0:15];
fA[1] = a[16:31];
fB[0] = b[0:15];
fB[1] = b[16:31];
for (i = 0; i < 2; i++) {
if (.xorsign) {
xorsign = getSignBit(fA[i]) ^ getSignBit(fB[i]);
if (.abs) {
fA[i] = |fA[i]|;
fB[i] = |fB[i]|;
}
}
if (isNaN(fA[i]) && isNaN(fB[i])) d[i] = NaN;
if (.NaN && (isNaN(fA[i]) || isNaN(fB[i]))) d[i] = NaN;
else if (isNaN(fA[i])) d[i] = fB[i];
else if (isNaN(fB[i])) d[i] = fA[i];
else d[i] = (fA[i] > fB[i]) ? fA[i] : fB[i];
if (.xorsign && !isNaN(fA[i])) {
setSignBit(d[i], xorsign);
}
}
}
Notes
- Subnormal numbers:
-
By default, subnormal numbers are supported.
max.ftz.{f16, f16x2}
flushes subnormal inputs and results to sign-preserving zero.
If values of both inputs are 0.0, then +0.0 > -0.0.
PTX ISA Notes
Introduced in PTX ISA version 7.0.
max.xorsign.abs
introduced in PTX ISA version 7.2.
Target ISA Notes
Requires sm_80
or higher.
max.xorsign.abs
support requires sm_86
or higher.
Examples
max.ftz.f16 h0,h1,h2;
max.f16x2 b0,b1,b2;
// SIMD fp16 max with NaN
max.NaN.f16x2 b0,b1,b2;
// scalar f16 max with xorsign.abs
max.xorsign.abs.f16 Rd, Ra, Rb;
max.bf16 h0, h1, h2;
// scalar bf16 max and NaN
max.NaN.bf16x2 b0, b1, b2;
// SIMD bf16 max with xorsign.abs
max.xorsign.abs.bf16x2 Rd, Ra, Rb;
9.7.4.9. Half Precision Floating Point Instructions: tanh
tanh
Find the hyperbolic tangent of a value (in radians)
Syntax
tanh.approx.type d, a;
.type = {.f16, .f16x2, .bf16, .bf16x2}
Description
Take hyperbolic tangent value of a
.
The type of operands d
and a
are as specified by .type
.
For .f16x2
or .bf16x2
instruction type, each of the half-word operands are operated in
parallel and the results are packed appropriately into a .f16x2
or .bf16x2
.
Semantics
if (.type == .f16 || .type == .bf16) {
d = tanh(a)
} else if (.type == .f16x2 || .type == .bf16x2) {
fA[0] = a[0:15];
fA[1] = a[16:31];
d[0] = tanh(fA[0])
d[1] = tanh(fA[1])
}
Notes
tanh.approx.{f16, f16x2, bf16, bf16x2}
implements an approximate hyperbolic tangent in the
target format.
Results of tanh
for various corner-case inputs are as follows:
Input |
Result |
---|---|
-Inf |
-1.0 |
-0.0 |
-0.0 |
+0.0 |
+0.0 |
+Inf |
1.0 |
NaN |
NaN |
The maximum absolute error for .f16
type is 2-10.987. The maximum absolute error for .bf16
type is 2-8.
The subnormal numbers are supported.
PTX ISA Notes
Introduced in PTX ISA version 7.0.
tanh.approx.{bf16/bf16x2}
introduced in PTX ISA version 7.8.
Target ISA Notes
Requires sm_75
or higher.
tanh.approx.{bf16/bf16x2}
requires sm_90
or higher.
Examples
tanh.approx.f16 h1, h0;
tanh.approx.f16x2 hd1, hd0;
tanh.approx.bf16 b1, b0;
tanh.approx.bf16x2 hb1, hb0;
9.7.4.10. Half Precision Floating Point Instructions: ex2
ex2
Find the base-2 exponent of input.
Syntax
ex2.approx.atype d, a;
ex2.approx.ftz.btype d, a;
.atype = { .f16, .f16x2}
.btype = { .bf16, .bf16x2}
Description
Raise 2 to the power a
.
The type of operands d
and a
are as specified by .type
.
For .f16x2
or .bf16x2
instruction type, each of the half-word operands are operated in
parallel and the results are packed appropriately into a .f16x2
or .bf16x2
.
Semantics
if (.type == .f16 || .type == .bf16) {
d = 2 ^ a
} else if (.type == .f16x2 || .type == .bf16x2) {
fA[0] = a[0:15];
fA[1] = a[16:31];
d[0] = 2 ^ fA[0]
d[1] = 2 ^ fA[1]
}
Notes
ex2.approx.{f16, f16x2, bf16, bf16x2}
implement a fast approximation to 2a.
For the .f16
type, subnormal inputs are supported. ex2.approx.ftz.bf16
flushes subnormal
inputs and results to sign-preserving zero.
Results of ex2.approx.ftz.bf16
for various corner-case inputs are as follows:
Input |
Result |
---|---|
-Inf |
+0.0 |
-subnormal |
+1.0 |
-0.0 |
+1.0 |
+0.0 |
+1.0 |
+subnormal |
+1.0 |
+Inf |
+Inf |
NaN |
NaN |
Results of ex2.approx.f16
for various corner-case inputs are as follows:
Input |
Result |
---|---|
-Inf |
+0.0 |
-0.0 |
+1.0 |
+0.0 |
+1.0 |
+Inf |
+Inf |
NaN |
NaN |
The maximum relative error for .f16
type is 2-9.9. The maximum relative error for .bf16
type
is 2-7.
PTX ISA Notes
Introduced in PTX ISA version 7.0.
ex2.approx.ftz.{bf16/bf16x2}
introduced in PTX ISA version 7.8.
Target ISA Notes
Requires sm_75
or higher.
ex2.approx.ftz.{bf16/bf16x2}
requires sm_90
or higher.
Examples
ex2.approx.f16 h1, h0;
ex2.approx.f16x2 hd1, hd0;
ex2.approx.ftz.bf16 b1, b2;
ex2.approx.ftz.bf16x2 hb1, hb2;
9.7.5. Comparison and Selection Instructions
The comparison select instructions are:
set
setp
selp
slct
As with single-precision floating-point instructions, the set
, setp
, and slct
instructions support subnormal numbers for sm_20
and higher targets and flush single-precision
subnormal inputs to sign-preserving zero for sm_1x
targets. The optional .ftz
modifier
provides backward compatibility with sm_1x
targets by flushing subnormal inputs and results to
sign-preserving zero regardless of the target architecture.
9.7.5.1. Comparison and Selection Instructions: set
set
Compare two numeric values with a relational operator, and optionally combine this result with a predicate value by applying a Boolean operator.
Syntax
set.CmpOp{.ftz}.dtype.stype d, a, b;
set.CmpOp.BoolOp{.ftz}.dtype.stype d, a, b, {!}c;
.CmpOp = { eq, ne, lt, le, gt, ge, lo, ls, hi, hs,
equ, neu, ltu, leu, gtu, geu, num, nan };
.BoolOp = { and, or, xor };
.dtype = { .u32, .s32, .f32 };
.stype = { .b16, .b32, .b64,
.u16, .u32, .u64,
.s16, .s32, .s64,
.f32, .f64 };
Description
Compares two numeric values and optionally combines the result with another predicate value by
applying a Boolean operator. If this result is True
, 1.0f
is written for floating-point
destination types, and 0xffffffff
is written for integer destination types. Otherwise,
0x00000000
is written.
Operand d
has type .dtype
; operands a
and b
have type .stype
; operand c
has
type .pred
.
Semantics
t = (a CmpOp b) ? 1 : 0;
if (isFloat(dtype))
d = BoolOp(t, c) ? 1.0f : 0x00000000;
else
d = BoolOp(t, c) ? 0xffffffff : 0x00000000;
Integer Notes
The signed and unsigned comparison operators are eq
, ne
, lt
, le
, gt
, ge
.
For unsigned values, the comparison operators lo
, ls
, hi
, and hs
for lower,
lower-or-same, higher, and higher-or-same may be used instead of lt
, le
, gt
, ge
,
respectively.
The untyped, bit-size comparisons are eq
and ne
.
Floating Point Notes
The ordered comparisons are eq
, ne
, lt
, le
, gt
, ge
. If either operand is NaN
, the result is False
.
To aid comparison operations in the presence of NaN
values, unordered versions are included:
equ
, neu
, ltu
, leu
, gtu
, geu
. If both operands are numeric values (not
NaN
), then these comparisons have the same result as their ordered counterparts. If either
operand is NaN
, then the result of these comparisons is True
.
num
returns True
if both operands are numeric values (not NaN
), and nan
returns
True
if either operand is NaN
.
Subnormal numbers:
sm_20+
-
By default, subnormal numbers are supported.
set.ftz.dtype.f32
flushes subnormal inputs to sign-preserving zero. sm_1x
-
set.dtype.f64
supports subnormal numbers.set.dtype.f32
flushes subnormal inputs to sign-preserving zero.
Modifier .ftz
applies only to .f32
comparisons.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
set
with .f64
source type requires sm_13
or higher.
Examples
@p set.lt.and.f32.s32 d,a,b,r;
set.eq.u32.u32 d,i,n;
9.7.5.2. Comparison and Selection Instructions: setp
setp
Compare two numeric values with a relational operator, and (optionally) combine this result with a predicate value by applying a Boolean operator.
Syntax
setp.CmpOp{.ftz}.type p[|q], a, b;
setp.CmpOp.BoolOp{.ftz}.type p[|q], a, b, {!}c;
.CmpOp = { eq, ne, lt, le, gt, ge, lo, ls, hi, hs,
equ, neu, ltu, leu, gtu, geu, num, nan };
.BoolOp = { and, or, xor };
.type = { .b16, .b32, .b64,
.u16, .u32, .u64,
.s16, .s32, .s64,
.f32, .f64 };
Description
Compares two values and combines the result with another predicate value by applying a Boolean operator. This result is written to the first destination operand. A related value computed using the complement of the compare result is written to the second destination operand.
Applies to all numeric types. Operands a
and b
have type .type
; operands p
, q
,
and c
have type .pred
. The sink symbol ‘_’ may be used in place of any one of the
destination operands.
Semantics
t = (a CmpOp b) ? 1 : 0;
p = BoolOp(t, c);
q = BoolOp(!t, c);
Integer Notes
The signed and unsigned comparison operators are eq
, ne
, lt
, le
, gt
, ge
.
For unsigned values, the comparison operators lo
, ls
, hi
, and hs
for lower,
lower-or-same, higher, and higher-or-same may be used instead of lt
, le
, gt
, ge
,
respectively.
The untyped, bit-size comparisons are eq
and ne
.
Floating Point Notes
The ordered comparisons are eq
, ne
, lt
, le
, gt
, ge
. If either operand is NaN
, the result is False
.
To aid comparison operations in the presence of NaN
values, unordered versions are included:
equ
, neu
, ltu
, leu
, gtu
, geu
. If both operands are numeric values (not
NaN
), then these comparisons have the same result as their ordered counterparts. If either
operand is NaN
, then the result of these comparisons is True
.
num
returns True
if both operands are numeric values (not NaN
), and nan
returns
True
if either operand is NaN
.
Subnormal numbers:
sm_20+
-
By default, subnormal numbers are supported.
setp.ftz.dtype.f32
flushes subnormal inputs to sign-preserving zero. sm_1x
-
setp.dtype.f64
supports subnormal numbers.setp.dtype.f32
flushes subnormal inputs to sign-preserving zero.
Modifier .ftz
applies only to .f32
comparisons.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
setp
with .f64
source type requires sm_13
or higher.
Examples
setp.lt.and.s32 p|q,a,b,r;
@q setp.eq.u32 p,i,n;
9.7.5.3. Comparison and Selection Instructions: selp
selp
Select between source operands, based on the value of the predicate source operand.
Syntax
selp.type d, a, b, c;
.type = { .b16, .b32, .b64,
.u16, .u32, .u64,
.s16, .s32, .s64,
.f32, .f64 };
Description
Conditional selection. If c
is True
, a
is stored in d
, b
otherwise. Operands
d
, a
, and b
must be of the same type. Operand c
is a predicate.
Semantics
d = (c == 1) ? a : b;
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
selp.f64
requires sm_13
or higher.
Examples
selp.s32 r0,r,g,p;
@q selp.f32 f0,t,x,xp;
9.7.5.4. Comparison and Selection Instructions: slct
slct
Select one source operand, based on the sign of the third operand.
Syntax
slct.dtype.s32 d, a, b, c;
slct{.ftz}.dtype.f32 d, a, b, c;
.dtype = { .b16, .b32, .b64,
.u16, .u32, .u64,
.s16, .s32, .s64,
.f32, .f64 };
Description
Conditional selection. If c
≥ 0, a
is stored in d
, otherwise b
is stored in
d
. Operands d
, a
, and b
are treated as a bitsize type of the same width as the first
instruction type; operand c
must match the second instruction type (.s32
or .f32
). The
selected input is copied to the output without modification.
Semantics
d = (c >= 0) ? a : b;
Floating Point Notes
For .f32
comparisons, negative zero equals zero.
Subnormal numbers:
sm_20+
-
By default, subnormal numbers are supported.
slct.ftz.dtype.f32
flushes subnormal values of operandc
to sign-preserving zero, and operanda
is selected. sm_1x
-
slct.dtype.f32
flushes subnormal values of operandc
to sign-preserving zero, and operanda
is selected.
Modifier .ftz
applies only to .f32
comparisons.
If operand c
is NaN
, the comparison is unordered and operand b
is selected.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
slct.f64
requires sm_13
or higher.
Examples
slct.u32.s32 x, y, z, val;
slct.ftz.u64.f32 A, B, C, fval;
9.7.6. Half Precision Comparison Instructions
The comparison instructions are:
set
setp
9.7.6.1. Half Precision Comparison Instructions: set
set
Compare two numeric values with a relational operator, and optionally combine this result with a predicate value by applying a Boolean operator.
Syntax
set.CmpOp{.ftz}.f16.stype d, a, b;
set.CmpOp.BoolOp{.ftz}.f16.stype d, a, b, {!}c;
set.CmpOp.bf16.stype d, a, b;
set.CmpOp.BoolOp.bf16.stype d, a, b, {!}c;
set.CmpOp{.ftz}.dtype.f16 d, a, b;
set.CmpOp.BoolOp{.ftz}.dtype.f16 d, a, b, {!}c;
.dtype = { .u16, .s16, .u32, .s32}
set.CmpOp.dtype.bf16 d, a, b;
set.CmpOp.BoolOp.dtype.bf16 d, a, b, {!}c;
.dtype = { .u16, .s16, .u32, .s32}
set.CmpOp{.ftz}.dtype.f16x2 d, a, b;
set.CmpOp.BoolOp{.ftz}.dtype.f16x2 d, a, b, {!}c;
.dtype = { .f16x2, .u32, .s32}
set.CmpOp.dtype.bf16x2 d, a, b;
set.CmpOp.BoolOp.dtype.bf16x2 d, a, b, {!}c;
.dtype = { .bf16x2, .u32, .s32}
.CmpOp = { eq, ne, lt, le, gt, ge,
equ, neu, ltu, leu, gtu, geu, num, nan };
.BoolOp = { and, or, xor };
.stype = { .b16, .b32, .b64,
.u16, .u32, .u64,
.s16, .s32, .s64,
.f16, .f32, .f64};
Description
Compares two numeric values and optionally combines the result with another predicate value by applying a Boolean operator.
Result of this computation is written in destination register in the following way:
-
If result is
True
,0xffffffff
is written for destination types.u32
/.s32
.0xffff
is written for destination types.u16
/.s16
.1.0
in target precision floating point format is written for destination type.f16
,.bf16
.
-
If result is
False
,0x0
is written for all integer destination types.0.0
in target precision floating point format is written for destination type.f16
,.bf16
.
If the source type is .f16x2
or .bf16x2
then result of individual operations are packed in
the 32-bit destination operand.
Operand c
has type .pred
.
Semantics
if (stype == .f16x2 || stype == .bf16x2) {
fA[0] = a[0:15];
fA[1] = a[16:31];
fB[0] = b[0:15];
fB[1] = b[16:31];
t[0] = (fA[0] CmpOp fB[0]) ? 1 : 0;
t[1] = (fA[1] CmpOp fB[1]) ? 1 : 0;
if (dtype == .f16x2 || stype == .bf16x2) {
for (i = 0; i < 2; i++) {
d[i] = BoolOp(t[i], c) ? 1.0 : 0.0;
}
} else {
for (i = 0; i < 2; i++) {
d[i] = BoolOp(t[i], c) ? 0xffff : 0;
}
}
} else if (dtype == .f16 || stype == .bf16) {
t = (a CmpOp b) ? 1 : 0;
d = BoolOp(t, c) ? 1.0 : 0.0;
} else { // Integer destination type
trueVal = (isU16(dtype) || isS16(dtype)) ? 0xffff : 0xffffffff;
t = (a CmpOp b) ? 1 : 0;
d = BoolOp(t, c) ? trueVal : 0;
}
Floating Point Notes
The ordered comparisons are eq
, ne
, lt
, le
, gt
, ge
. If either operand is
NaN
, the result is False
.
To aid comparison operations in the presence of NaN
values, unordered versions are included:
equ
, neu
, ltu
, leu
, gtu
, geu
. If both operands are numeric values (not
NaN
), then these comparisons have the same result as their ordered counterparts. If either
operand is NaN
, then the result of these comparisons is True
.
num
returns True
if both operands are numeric values (not NaN
), and nan
returns
True
if either operand is NaN
.
- Subnormal numbers:
-
By default, subnormal numbers are supported.
When
.ftz
modifier is specified then subnormal inputs and results are flushed to sign preserving zero.
PTX ISA Notes
Introduced in PTX ISA version 4.2.
set.{u16, u32, s16, s32}.f16
and set.{u32, s32}.f16x2
are introduced in PTX ISA version 6.5.
set.{u16, u32, s16, s32}.bf16
, set.{u32, s32, bf16x2}.bf16x2
,
set.bf16.{s16,u16,f16,b16,s32,u32,f32,b32,s64,u64,f64,b64}
are introduced in PTX ISA version
7.8.
Target ISA Notes
Requires sm_53
or higher.
set.{u16, u32, s16, s32}.bf16
, set.{u32, s32, bf16x2}.bf16x2
,
set.bf16.{s16,u16,f16,b16,s32,u32,f32,b32,s64,u64,f64,b64}
require sm_90
or higher.
Examples
set.lt.and.f16.f16 d,a,b,r;
set.eq.f16x2.f16x2 d,i,n;
set.eq.u32.f16x2 d,i,n;
set.lt.and.u16.f16 d,a,b,r;
set.ltu.or.bf16.f16 d,u,v,s;
set.equ.bf16x2.bf16x2 d,j,m;
set.geu.s32.bf16x2 d,j,m;
set.num.xor.s32.bf16 d,u,v,s;
9.7.6.2. Half Precision Comparison Instructions: setp
setp
Compare two numeric values with a relational operator, and optionally combine this result with a predicate value by applying a Boolean operator.
Syntax
setp.CmpOp{.ftz}.f16 p, a, b;
setp.CmpOp.BoolOp{.ftz}.f16 p, a, b, {!}c;
setp.CmpOp{.ftz}.f16x2 p|q, a, b;
setp.CmpOp.BoolOp{.ftz}.f16x2 p|q, a, b, {!}c;
setp.CmpOp.bf16 p, a, b;
setp.CmpOp.BoolOp.bf16 p, a, b, {!}c;
setp.CmpOp.bf16x2 p|q, a, b;
setp.CmpOp.BoolOp.bf16x2 p|q, a, b, {!}c;
.CmpOp = { eq, ne, lt, le, gt, ge,
equ, neu, ltu, leu, gtu, geu, num, nan };
.BoolOp = { and, or, xor };
Description
Compares two values and combines the result with another predicate value by applying a Boolean operator. This result is written to the destination operand.
Operand c
, p
and q
has type .pred
.
For instruction type .f16
, operands a
and b
have type .b16
or .f16
.
For instruction type .f16x2
, operands a
and b
have type .b32
.
For instruction type .bf16
, operands a
and b
have type .b16
.
For instruction type .bf16x2
, operands a
and b
have type .b32
.
Semantics
if (type == .f16 || type == .bf16) {
t = (a CmpOp b) ? 1 : 0;
p = BoolOp(t, c);
} else if (type == .f16x2 || type == .bf16x2) {
fA[0] = a[0:15];
fA[1] = a[16:31];
fB[0] = b[0:15];
fB[1] = b[16:31];
t[0] = (fA[0] CmpOp fB[0]) ? 1 : 0;
t[1] = (fA[1] CmpOp fB[1]) ? 1 : 0;
p = BoolOp(t[0], c);
q = BoolOp(t[1], c);
}
Floating Point Notes
The ordered comparisons are eq
, ne
, lt
, le
, gt
, ge
. If either operand is
NaN
, the result is False
.
To aid comparison operations in the presence of NaN
values, unordered versions are included:
equ
, neu
, ltu
, leu
, gtu
, geu
. If both operands are numeric values (not
NaN
), then these comparisons have the same result as their ordered counterparts. If either
operand is NaN
, then the result of these comparisons is True
.
num
returns True
if both operands are numeric values (not NaN
), and nan
returns
True
if either operand is NaN
.
- Subnormal numbers:
-
By default, subnormal numbers are supported.
setp.ftz.{f16,f16x2}
flushes subnormal inputs to sign-preserving zero.
PTX ISA Notes
Introduced in PTX ISA version 4.2.
setp.{bf16/bf16x2}
introduced in PTX ISA version 7.8.
Target ISA Notes
Requires sm_53
or higher.
setp.{bf16/bf16x2}
requires sm_90
or higher.
Examples
setp.lt.and.f16x2 p|q,a,b,r;
@q setp.eq.f16 p,i,n;
setp.gt.or.bf16x2 u|v,c,d,s;
@q setp.eq.bf16 u,j,m;
9.7.7. Logic and Shift Instructions
The logic and shift instructions are fundamentally untyped, performing bit-wise operations on
operands of any type, provided the operands are of the same size. This permits bit-wise operations
on floating point values without having to define a union to access the bits. Instructions and
,
or
, xor
, and not
also operate on predicates.
The logical shift instructions are:
and
or
xor
not
cnot
lop3
shf
shl
shr
9.7.7.1. Logic and Shift Instructions: and
and
Bitwise AND.
Syntax
and.type d, a, b;
.type = { .pred, .b16, .b32, .b64 };
Description
Compute the bit-wise and operation for the bits in a
and b
.
Semantics
d = a & b;
Notes
The size of the operands must match, but not necessarily the type.
Allowed types include predicate registers.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
Supported on all target architectures.
Examples
and.b32 x,q,r;
and.b32 sign,fpvalue,0x80000000;
9.7.7.2. Logic and Shift Instructions: or
or
Biwise OR.
Syntax
or.type d, a, b;
.type = { .pred, .b16, .b32, .b64 };
Description
Compute the bit-wise or operation for the bits in a
and b
.
Semantics
d = a | b;
Notes
The size of the operands must match, but not necessarily the type.
Allowed types include predicate registers.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
Supported on all target architectures.
Examples
or.b32 mask mask,0x00010001
or.pred p,q,r;
9.7.7.3. Logic and Shift Instructions: xor
xor
Bitwise exclusive-OR (inequality).
Syntax
xor.type d, a, b;
.type = { .pred, .b16, .b32, .b64 };
Description
Compute the bit-wise exclusive-or operation for the bits in a
and b
.
Semantics
d = a ^ b;
Notes
The size of the operands must match, but not necessarily the type.
Allowed types include predicate registers.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
Supported on all target architectures.
Examples
xor.b32 d,q,r;
xor.b16 d,x,0x0001;
9.7.7.4. Logic and Shift Instructions: not
not
Bitwise negation; one’s complement.
Syntax
not.type d, a;
.type = { .pred, .b16, .b32, .b64 };
Description
Invert the bits in a
.
Semantics
d = ~a;
Notes
The size of the operands must match, but not necessarily the type.
Allowed types include predicates.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
Supported on all target architectures.
Examples
not.b32 mask,mask;
not.pred p,q;
9.7.7.5. Logic and Shift Instructions: cnot
cnot
C/C++ style logical negation.
Syntax
cnot.type d, a;
.type = { .b16, .b32, .b64 };
Description
Compute the logical negation using C/C++ semantics.
Semantics
d = (a==0) ? 1 : 0;
Notes
The size of the operands must match, but not necessarily the type.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
Supported on all target architectures.
Examples
cnot.b32 d,a;
9.7.7.6. Logic and Shift Instructions: lop3
lop3
Arbitrary logical operation on 3 inputs.
Syntax
lop3.b32 d, a, b, c, immLut;
lop3.BoolOp.b32 d|p, a, b, c, immLut, q;
.BoolOp = { .or , .and };
Description
Compute bitwise logical operation on inputs a
, b
, c
and store the result in destination
d
.
Optionally, .BoolOp
can be specified to compute the predicate result p
by performing a
Boolean operation on the destination operand d
with the predicate q
in the following manner:
p = (d != 0) BoolOp q;
The sink symbol ‘_’ may be used in place of the destination operand d
when .BoolOp
qualifier
is specified.
The logical operation is defined by a look-up table which, for 3 inputs, can be represented as an
8-bit value specified by operand immLut
as described below. immLut
is an integer constant
that can take values from 0 to 255, thereby allowing up to 256 distinct logical operations on inputs
a
, b
, c
.
For a logical operation F(a, b, c)
the value of immLut
can be computed by applying the same
operation to three predefined constant values as follows:
ta = 0xF0;
tb = 0xCC;
tc = 0xAA;
immLut = F(ta, tb, tc);
Examples:
If F = (a & b & c);
immLut = 0xF0 & 0xCC & 0xAA = 0x80
If F = (a | b | c);
immLut = 0xF0 | 0xCC | 0xAA = 0xFE
If F = (a & b & ~c);
immLut = 0xF0 & 0xCC & (~0xAA) = 0x40
If F = ((a & b | c) ^ a);
immLut = (0xF0 & 0xCC | 0xAA) ^ 0xF0 = 0x1A
The following table illustrates computation of immLut
for various logical operations:
ta |
tb |
tc |
Oper 0 (False) |
Oper 1 (ta & tb & tc) |
Oper 2 (ta & tb & ~tc) |
… |
Oper 254 (ta | tb | tc) |
Oper 255 (True) |
---|---|---|---|---|---|---|---|---|
0 |
0 |
0 |
0 |
0 |
0 |
… |
0 |
1 |
0 |
0 |
1 |
0 |
0 |
0 |
1 |
1 |
|
0 |
1 |
0 |
0 |
0 |
0 |
1 |
1 |
|
0 |
1 |
1 |
0 |
0 |
0 |
1 |
1 |
|
1 |
0 |
0 |
0 |
0 |
0 |
1 |
1 |
|
1 |
0 |
1 |
0 |
0 |
0 |
1 |
1 |
|
1 |
1 |
0 |
0 |
0 |
1 |
1 |
1 |
|
1 |
1 |
1 |
0 |
1 |
0 |
1 |
1 |
|
immLut |
0x0 |
0x80 |
0x40 |
… |
0xFE |
0xFF |
Semantics
F = GetFunctionFromTable(immLut); // returns the function corresponding to immLut value
d = F(a, b, c);
if (BoolOp specified) {
p = (d != 0) BoolOp q;
}
PTX ISA Notes
Introduced in PTX ISA version 4.3.
Support for .BoolOp
qualifier introduced in PTX ISA version 8.2.
Target ISA Notes
Requires sm_50
or higher.
Qualifier .BoolOp
requires sm_70
or higher.
Examples
lop3.b32 d, a, b, c, 0x40;
lop3.or.b32 d|p, a, b, c, 0x3f, q;
lop3.and.b32 _|p, a, b, c, 0x3f, q;
9.7.7.7. Logic and Shift Instructions: shf
shf
Funnel shift.
Syntax
shf.l.mode.b32 d, a, b, c; // left shift
shf.r.mode.b32 d, a, b, c; // right shift
.mode = { .clamp, .wrap };
Description
Shift the 64-bit value formed by concatenating operands a
and b
left or right by the amount
specified by the unsigned 32-bit value in c
. Operand b
holds bits 63:32
and operand a
holds bits 31:0
of the 64-bit source value. The source is shifted left or right by the clamped
or wrapped value in c
. For shf.l
, the most-significant 32-bits of the result are written
into d
; for shf.r
, the least-significant 32-bits of the result are written into d
.
Semantics
u32 n = (.mode == .clamp) ? min(c, 32) : c & 0x1f;
switch (shf.dir) { // shift concatenation of [b, a]
case shf.l: // extract 32 msbs
u32 d = (b << n) | (a >> (32-n));
case shf.r: // extract 32 lsbs
u32 d = (b << (32-n)) | (a >> n);
}
Notes
Use funnel shift for multi-word shift operations and for rotate operations. The shift amount is
limited to the range 0..32
in clamp mode and 0..31
in wrap mode, so shifting multi-word
values by distances greater than 32 requires first moving 32-bit words, then using shf
to shift
the remaining 0..31
distance.
To shift data sizes greater than 64 bits to the right, use repeated shf.r
instructions applied
to adjacent words, operating from least-significant word towards most-significant word. At each
step, a single word of the shifted result is computed. The most-significant word of the result is
computed using a shr.{u32,s32}
instruction, which zero or sign fills based on the instruction
type.
To shift data sizes greater than 64 bits to the left, use repeated shf.l
instructions applied to
adjacent words, operating from most-significant word towards least-significant word. At each step, a
single word of the shifted result is computed. The least-significant word of the result is computed
using a shl
instruction.
Use funnel shift to perform 32-bit left or right rotate by supplying the same value for source
arguments a
and b
.
PTX ISA Notes
Introduced in PTX ISA version 3.1.
Target ISA Notes
Requires sm_32
or higher.
Example
shf.l.clamp.b32 r3,r1,r0,16;
// 128-bit left shift; n < 32
// [r7,r6,r5,r4] = [r3,r2,r1,r0] << n
shf.l.clamp.b32 r7,r2,r3,n;
shf.l.clamp.b32 r6,r1,r2,n;
shf.l.clamp.b32 r5,r0,r1,n;
shl.b32 r4,r0,n;
// 128-bit right shift, arithmetic; n < 32
// [r7,r6,r5,r4] = [r3,r2,r1,r0] >> n
shf.r.clamp.b32 r4,r0,r1,n;
shf.r.clamp.b32 r5,r1,r2,n;
shf.r.clamp.b32 r6,r2,r3,n;
shr.s32 r7,r3,n; // result is sign-extended
shf.r.clamp.b32 r1,r0,r0,n; // rotate right by n; n < 32
shf.l.clamp.b32 r1,r0,r0,n; // rotate left by n; n < 32
// extract 32-bits from [r1,r0] starting at position n < 32
shf.r.clamp.b32 r0,r0,r1,n;
9.7.7.8. Logic and Shift Instructions: shl
shl
Shift bits left, zero-fill on right.
Syntax
shl.type d, a, b;
.type = { .b16, .b32, .b64 };
Description
Shift a
left by the amount specified by unsigned 32-bit value in b
.
Semantics
d = a << b;
Notes
Shift amounts greater than the register width N are clamped to N.
The sizes of the destination and first source operand must match, but not necessarily the type. The
b
operand must be a 32-bit value, regardless of the instruction type.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
Supported on all target architectures.
Example
shl.b32 q,a,2;
9.7.7.9. Logic and Shift Instructions: shr
shr
Shift bits right, sign or zero-fill on left.
Syntax
shr.type d, a, b;
.type = { .b16, .b32, .b64,
.u16, .u32, .u64,
.s16, .s32, .s64 };
Description
Shift a
right by the amount specified by unsigned 32-bit value in b
. Signed shifts fill with
the sign bit, unsigned and untyped shifts fill with 0
.
Semantics
d = a >> b;
Notes
Shift amounts greater than the register width N are clamped to N.
The sizes of the destination and first source operand must match, but not necessarily the type. The
b
operand must be a 32-bit value, regardless of the instruction type.
Bit-size types are included for symmetry with shl
.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Target ISA Notes
Supported on all target architectures.
Example
shr.u16 c,a,2;
shr.s32 i,i,1;
shr.b16 k,i,j;
9.7.8. Data Movement and Conversion Instructions
These instructions copy data from place to place, and from state space to state space, possibly
converting it from one format to another. mov
, ld
, ldu
, and st
operate on both
scalar and vector types. The isspacep
instruction is provided to query whether a generic address
falls within a particular state space window. The cvta
instruction converts addresses between
generic
and const
, global
, local
, or shared
state spaces.
Instructions ld
, st
, suld
, and sust
support optional cache operations.
The Data Movement and Conversion Instructions are:
mov
shfl.sync
prmt
ld
ldu
st
st.async
multimem.ld_reduce
,multimem.st
,multimem.red
prefetch
,prefetchu
isspacep
cvta
cvt
cvt.pack
cp.async
cp.async.commit_group
cp.async.wait_group
,cp.async.wait_all
cp.async.bulk
cp.reduce.async.bulk
cp.async.bulk.prefetch
cp.async.bulk.tensor
cp.reduce.async.bulk.tensor
cp.async.bulk.prefetch.tensor
cp.async.bulk.commit_group
cp.async.bulk.wait_group
tensormap.replace
9.7.8.1. Cache Operators
PTX ISA version 2.0 introduced optional cache operators on load and store instructions. The cache
operators require a target architecture of sm_20
or higher.
Cache operators on load or store instructions are treated as performance hints only. The use of a
cache operator on an ld
or st
instruction does not change the memory consistency behavior of
the program.
For sm_20
and higher, the cache operators have the following definitions and behavior.
Operator |
Meaning |
---|---|
|
Cache at all levels, likely to be accessed again. The default load instruction cache operation is ld.ca, which allocates cache lines in all
levels (L1 and L2) with normal eviction policy. Global data is coherent at the L2 level, but
multiple L1 caches are not coherent for global data. If one thread stores to global memory
via one L1 cache, and a second thread loads that address via a second L1 cache with |
|
Cache at global level (cache in L2 and below, not L1). Use |
|
Cache streaming, likely to be accessed once. The |
|
Last use. The compiler/programmer may use |
|
Don’t cache and fetch again (consider cached system memory lines stale, fetch again). The ld.cv load operation applied to a global System Memory address invalidates (discards) a matching L2 line and re-fetches the line on each new load. |
Operator |
Meaning |
---|---|
|
Cache write-back all coherent levels. The default store instruction cache operation is If one thread stores to global memory, bypassing its L1 cache, and a second thread in a
different SM later loads from that address via a different L1 cache with The driver must invalidate global L1 cache lines between dependent grids of thread arrays.
Stores by the first grid program are then correctly missed in L1 and fetched by the second grid
program issuing default |
|
Cache at global level (cache in L2 and below, not L1). Use |
|
Cache streaming, likely to be accessed once. The |
|
Cache write-through (to system memory). The |
9.7.8.2. Cache Eviction Priority Hints
PTX ISA version 7.4 adds optional cache eviction priority hints on load and store
instructions. Cache eviction priority requires target architecture sm_70
or higher.
Cache eviction priority on load or store instructions is treated as a performance hint. It is
supported for .global
state space and generic addresses where the address points to .global
state space.
Cache Eviction Priority |
Meaning |
---|---|
|
Cache data with normal eviction priority. This is the default eviction priority. |
|
Data cached with this priority will be first in the eviction priority order and will likely be evicted when cache eviction is required. This priority is suitable for streaming data. |
|
Data cached with this priority will be last in the eviction priority order and will
likely be evicted only after other data with |
|
Do not change eviction priority order as part of this operation. |
|
Do not allocate data to cache. This priority is suitable for streaming data. |
9.7.8.3. Data Movement and Conversion Instructions: mov
mov
Set a register variable with the value of a register variable or an immediate value. Take the non-generic address of a variable in global, local, or shared state space.
Syntax
mov.type d, a;
mov.type d, sreg;
mov.type d, avar; // get address of variable
mov.type d, avar+imm; // get address of variable with offset
mov.u32 d, fname; // get address of device function
mov.u64 d, fname; // get address of device function
mov.u32 d, kernel; // get address of entry function
mov.u64 d, kernel; // get address of entry function
.type = { .pred,
.b16, .b32, .b64,
.u16, .u32, .u64,
.s16, .s32, .s64,
.f32, .f64 };
Description
Write register d
with the value of a
.
Operand a
may be a register, special register, variable with optional offset in an addressable
memory space, or function name.
For variables declared in .const
, .global
, .local
, and .shared
state spaces, mov
places the non-generic address of the variable (i.e., the address of the variable in its state
space) into the destination register. The generic address of a variable in const
, global
,
local
, or shared
state space may be generated by first taking the address within the state
space with mov
and then converting it to a generic address using the cvta
instruction;
alternately, the generic address of a variable declared in const
, global
, local
, or
shared
state space may be taken directly using the cvta
instruction.
Note that if the address of a device function parameter is moved to a register, the parameter will be copied onto the stack and the address will be in the local state space.
Semantics
d = a;
d = sreg;
d = &avar; // address is non-generic; i.e., within the variable's declared state space
d = &avar+imm;
Notes
Although only predicate and bit-size types are required, we include the arithmetic types for the programmer’s convenience: their use enhances program readability and allows additional type checking.
When moving address of a kernel or a device function, only
.u32
or.u64
instruction types are allowed. However, if a signed type is used, it is not treated as a compilation error. The compiler issues a warning in this case.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Taking the address of kernel entry functions requires PTX ISA version 3.1 or later. Kernel function addresses should only be used in the context of CUDA Dynamic Parallelism system calls. See the CUDA Dynamic Parallelism Programming Guide for details.
Target ISA Notes
mov.f64
requires sm_13
or higher.
Taking the address of kernel entry functions requires sm_35
or higher.
Examples
mov.f32 d,a;
mov.u16 u,v;
mov.f32 k,0.1;
mov.u32 ptr, A; // move address of A into ptr
mov.u32 ptr, A[5]; // move address of A[5] into ptr
mov.u32 ptr, A+20; // move address with offset into ptr
mov.u32 addr, myFunc; // get address of device function 'myFunc'
mov.u64 kptr, main; // get address of entry function 'main'
9.7.8.4. Data Movement and Conversion Instructions: mov
mov
Move vector-to-scalar (pack) or scalar-to-vector (unpack).
Syntax
mov.type d, a;
.type = { .b16, .b32, .b64, .b128 };
Description
Write scalar register d
with the packed value of vector register a
, or write vector register
d
with the unpacked values from scalar register a
.
When destination operand d
is a vector register, the sink symbol '_'
may be used for one or
more elements provided that at least one element is a scalar register.
For bit-size types, mov
may be used to pack vector elements into a scalar register or unpack
sub-fields of a scalar register into a vector. Both the overall size of the vector and the size of
the scalar must match the size of the instruction type.
Semantics
// pack two 8-bit elements into .b16
d = a.x | (a.y << 8)
// pack four 8-bit elements into .b32
d = a.x | (a.y << 8) | (a.z << 16) | (a.w << 24)
// pack two 16-bit elements into .b32
d = a.x | (a.y << 16)
// pack four 16-bit elements into .b64
d = a.x | (a.y << 16) | (a.z << 32) | (a.w << 48)
// pack two 32-bit elements into .b64
d = a.x | (a.y << 32)
// pack four 32-bit elements into .b128
d = a.x | (a.y << 32) | (a.z << 64) | (a.w << 96)
// pack two 64-bit elements into .b128
d = a.x | (a.y << 64)
// unpack 8-bit elements from .b16
{ d.x, d.y } = { a[0..7], a[8..15] }
// unpack 8-bit elements from .b32
{ d.x, d.y, d.z, d.w }
{ a[0..7], a[8..15], a[16..23], a[24..31] }
// unpack 16-bit elements from .b32
{ d.x, d.y } = { a[0..15], a[16..31] }
// unpack 16-bit elements from .b64
{ d.x, d.y, d.z, d.w } =
{ a[0..15], a[16..31], a[32..47], a[48..63] }
// unpack 32-bit elements from .b64
{ d.x, d.y } = { a[0..31], a[32..63] }
// unpack 32-bit elements from .b128
{ d.x, d.y, d.z, d.w } =
{ a[0..31], a[32..63], a[64..95], a[96..127] }
// unpack 64-bit elements from .b128
{ d.x, d.y } = { a[0..63], a[64..127] }
PTX ISA Notes
Introduced in PTX ISA version 1.0.
Support for .b128
type introduced in PTX ISA version 8.3.
Target ISA Notes
Supported on all target architectures.
Support for .b128
type requires sm_70
or higher.
Examples
mov.b32 %r1,{a,b}; // a,b have type .u16
mov.b64 {lo,hi}, %x; // %x is a double; lo,hi are .u32
mov.b32 %r1,{x,y,z,w}; // x,y,z,w have type .b8
mov.b32 {r,g,b,a},%r1; // r,g,b,a have type .u8
mov.b64 {%r1, _}, %x; // %x is.b64, %r1 is .b32
mov.b128 {%b1, %b2}, %y; // %y is.b128, %b1 and % b2 are .b64
mov.b128 %y, {%b1, %b2}; // %y is.b128, %b1 and % b2 are .b64
9.7.8.5. Data Movement and Conversion Instructions: shfl (deprecated)
shfl (deprecated)
Register data shuffle within threads of a warp.
Syntax
shfl.mode.b32 d[|p], a, b, c;
.mode = { .up, .down, .bfly, .idx };
Deprecation Note
The shfl
instruction without a .sync
qualifier is deprecated in PTX ISA version 6.0.
Support for this instruction with
.target
lower thansm_70
may be removed in a future PTX ISA version.
Removal Note
Support for shfl
instruction without a .sync
qualifier is removed in PTX ISA version 6.4 for .target
sm_70
or higher.
Description
Exchange register data between threads of a warp.
Each thread in the currently executing warp will compute a source lane index j based on input
operands b
and c
and the mode. If the computed source lane index j is in range, the
thread will copy the input operand a
from lane j into its own destination register d
;
otherwise, the thread will simply copy its own input a
to destination d
. The optional
destination predicate p
is set to True
if the computed source lane is in range, and
otherwise set to False
.
Note that an out of range value of b
may still result in a valid computed source lane index
j. In this case, a data transfer occurs and the destination predicate p
is True.
Note that results are undefined in divergent control flow within a warp, if an active thread sources a register from an inactive thread.
Operand b
specifies a source lane or source lane offset, depending on the mode.
Operand c
contains two packed values specifying a mask for logically splitting warps into
sub-segments and an upper bound for clamping the source lane index.
Semantics
lane[4:0] = [Thread].laneid; // position of thread in warp
bval[4:0] = b[4:0]; // source lane or lane offset (0..31)
cval[4:0] = c[4:0]; // clamp value
mask[4:0] = c[12:8];
// get value of source register a if thread is active and
// guard predicate true, else unpredictable
if (isActive(Thread) && isGuardPredicateTrue(Thread)) {
SourceA[lane] = a;
} else {
// Value of SourceA[lane] is unpredictable for
// inactive/predicated-off threads in warp
}
maxLane = (lane[4:0] & mask[4:0]) | (cval[4:0] & ~mask[4:0]);
minLane = (lane[4:0] & mask[4:0]);
switch (.mode) {
case .up: j = lane - bval; pval = (j >= maxLane); break;
case .down: j = lane + bval; pval = (j <= maxLane); break;
case .bfly: j = lane ^ bval; pval = (j <= maxLane); break;
case .idx: j = minLane | (bval[4:0] & ~mask[4:0]);
pval = (j <= maxLane); break;
}
if (!pval) j = lane; // copy from own lane
d = SourceA[j]; // copy input a from lane j
if (dest predicate selected)
p = pval;
PTX ISA Notes
Introduced in PTX ISA version 3.0.
Deprecated in PTX ISA version 6.0 in favor of shfl.sync
.
Not supported in PTX ISA version 6.4 for .target sm_70
or higher.
Target ISA Notes
shfl
requires sm_30
or higher.
shfl
is not supported on sm_70
or higher starting PTX ISA version 6.4.
Examples
// Warp-level INCLUSIVE PLUS SCAN:
//
// Assumes input in following registers:
// - Rx = sequence value for this thread
//
shfl.up.b32 Ry|p, Rx, 0x1, 0x0;
@p add.f32 Rx, Ry, Rx;
shfl.up.b32 Ry|p, Rx, 0x2, 0x0;
@p add.f32 Rx, Ry, Rx;
shfl.up.b32 Ry|p, Rx, 0x4, 0x0;
@p add.f32 Rx, Ry, Rx;
shfl.up.b32 Ry|p, Rx, 0x8, 0x0;
@p add.f32 Rx, Ry, Rx;
shfl.up.b32 Ry|p, Rx, 0x10, 0x0;
@p add.f32 Rx, Ry, Rx;
// Warp-level INCLUSIVE PLUS REVERSE-SCAN:
//
// Assumes input in following registers:
// - Rx = sequence value for this thread
//
shfl.down.b32 Ry|p, Rx, 0x1, 0x1f;
@p add.f32 Rx, Ry, Rx;
shfl.down.b32 Ry|p, Rx, 0x2, 0x1f;
@p add.f32 Rx, Ry, Rx;
shfl.down.b32 Ry|p, Rx, 0x4, 0x1f;
@p add.f32 Rx, Ry, Rx;
shfl.down.b32 Ry|p, Rx, 0x8, 0x1f;
@p add.f32 Rx, Ry, Rx;
shfl.down.b32 Ry|p, Rx, 0x10, 0x1f;
@p add.f32 Rx, Ry, Rx;
// BUTTERFLY REDUCTION:
//
// Assumes input in following registers:
// - Rx = sequence value for this thread
//
shfl.bfly.b32 Ry, Rx, 0x10, 0x1f; // no predicate dest
add.f32 Rx, Ry, Rx;
shfl.bfly.b32 Ry, Rx, 0x8, 0x1f;
add.f32 Rx, Ry, Rx;
shfl.bfly.b32 Ry, Rx, 0x4, 0x1f;
add.f32 Rx, Ry, Rx;
shfl.bfly.b32 Ry, Rx, 0x2, 0x1f;
add.f32 Rx, Ry, Rx;
shfl.bfly.b32 Ry, Rx, 0x1, 0x1f;
add.f32 Rx, Ry, Rx;
//
// All threads now hold sum in Rx
9.7.8.6. Data Movement and Conversion Instructions: shfl.sync
shfl.sync
Register data shuffle within threads of a warp.
Syntax
shfl.sync.mode.b32 d[|p], a, b, c, membermask;
.mode = { .up, .down, .bfly, .idx };
Description
Exchange register data between threads of a warp.
shfl.sync
will cause executing thread to wait until all non-exited threads corresponding to
membermask
have executed shfl.sync
with the same qualifiers and same membermask
value
before resuming execution.
Operand membermask
specifies a 32-bit integer which is a mask indicating threads participating
in barrier where the bit position corresponds to thread’s laneid
.
shfl.sync
exchanges register data between threads in membermask
.
Each thread in the currently executing warp will compute a source lane index j based on input
operands b
and c
and the mode. If the computed source lane index j is in range, the
thread will copy the input operand a
from lane j into its own destination register d
;
otherwise, the thread will simply copy its own input a
to destination d
. The optional
destination predicate p
is set to True
if the computed source lane is in range, and
otherwise set to False
.
Note that an out of range value of b
may still result in a valid computed source lane index
j. In this case, a data transfer occurs and the destination predicate p
is True.
Note that results are undefined if a thread sources a register from an inactive thread or a thread
that is not in membermask
.
Operand b
specifies a source lane or source lane offset, depending on the mode.
Operand c
contains two packed values specifying a mask for logically splitting warps into
sub-segments and an upper bound for clamping the source lane index.
The behavior of shfl.sync
is undefined if the executing thread is not in the membermask
.
Note
For .target sm_6x
or below, all threads in membermask
must execute the same shfl.sync
instruction in convergence, and only threads belonging to some membermask
can be active when
the shfl.sync
instruction is executed. Otherwise, the behavior is undefined.
Semantics
// wait for all threads in membermask to arrive
wait_for_specified_threads(membermask);
lane[4:0] = [Thread].laneid; // position of thread in warp
bval[4:0] = b[4:0]; // source lane or lane offset (0..31)
cval[4:0] = c[4:0]; // clamp value
segmask[4:0] = c[12:8];
// get value of source register a if thread is active and
// guard predicate true, else unpredictable
if (isActive(Thread) && isGuardPredicateTrue(Thread)) {
SourceA[lane] = a;
} else {
// Value of SourceA[lane] is unpredictable for
// inactive/predicated-off threads in warp
}
maxLane = (lane[4:0] & segmask[4:0]) | (cval[4:0] & ~segmask[4:0]);
minLane = (lane[4:0] & segmask[4:0]);
switch (.mode) {
case .up: j = lane - bval; pval = (j >= maxLane); break;
case .down: j = lane + bval; pval = (j <= maxLane); break;
case .bfly: j = lane ^ bval; pval = (j <= maxLane); break;
case .idx: j = minLane | (bval[4:0] & ~segmask[4:0]);
pval = (j <= maxLane); break;
}
if (!pval) j = lane; // copy from own lane
d = SourceA[j]; // copy input a from lane j
if (dest predicate selected)
p = pval;
PTX ISA Notes
Introduced in PTX ISA version 6.0.
Target ISA Notes
Requires sm_30
or higher.
Examples
shfl.sync.up.b32 Ry|p, Rx, 0x1, 0x0, 0xffffffff;
9.7.8.7. Data Movement and Conversion Instructions: prmt
prmt
Permute bytes from register pair.
Syntax
prmt.b32{.mode} d, a, b, c;
.mode = { .f4e, .b4e, .rc8, .ecl, .ecr, .rc16 };
Description
Pick four arbitrary bytes from two 32-bit registers, and reassemble them into a 32-bit destination register.
In the generic form (no mode specified), the permute control consists of four 4-bit selection
values. The bytes in the two source registers are numbered from 0 to 7: {b, a} = {{b7, b6, b5,
b4}, {b3, b2, b1, b0}}
. For each byte in the target register, a 4-bit selection value is defined.
The 3 lsbs of the selection value specify which of the 8 source bytes should be moved into the
target position. The msb defines if the byte value should be copied, or if the sign (msb of the
byte) should be replicated over all 8 bits of the target position (sign extend of the byte value);
msb=0
means copy the literal value; msb=1
means replicate the sign. Note that the sign
extension is only performed as part of generic form.
Thus, the four 4-bit values fully specify an arbitrary byte permute, as a 16b
permute code.
default mode |
source select |
source select |
source select |
source select |
---|---|---|---|---|
index |
|
|
|
|
The more specialized form of the permute control uses the two lsb’s of operand c
(which is
typically an address pointer) to control the byte extraction.
mode |
selector
|
source |
source |
source |
source |
---|---|---|---|---|---|
|
0 |
3 |
2 |
1 |
0 |
1 |
4 |
3 |
2 |
1 |
|
2 |
5 |
4 |
3 |
2 |
|
3 |
6 |
5 |
4 |
3 |
|
|
0 |
5 |
6 |
7 |
0 |
1 |
6 |
7 |
0 |
1 |
|
2 |
7 |
0 |
1 |
2 |
|
3 |
0 |
1 |
2 |
3 |
|
|
0 |
0 |
0 |
0 |
0 |
1 |
1 |
1 |
1 |
1 |
|
2 |
2 |
2 |
2 |
2 |
|
3 |
3 |
3 |
3 |
3 |
|
|
0 |
3 |
2 |
1 |
0 |
1 |
3 |
2 |
1 |
1 |
|
2 |
3 |
2 |
2 |
2 |
|
3 |
3 |
3 |
3 |
3 |
|
|
0 |
0 |
0 |
0 |
0 |
1 |
1 |
1 |
1 |
0 |
|
2 |
2 |
2 |
1 |
0 |
|
3 |
3 |
2 |
1 |
0 |
|
|
0 |
1 |
0 |
1 |
0 |
1 |
3 |
2 |
3 |
2 |
|
2 |
1 |
0 |
1 |
0 |
|
3 |
3 |
2 |
3 |
2 |
Semantics
tmp64 = (b<<32) | a; // create 8 byte source
if ( ! mode ) {
ctl[0] = (c >> 0) & 0xf;
ctl[1] = (c >> 4) & 0xf;
ctl[2] = (c >> 8) & 0xf;
ctl[3] = (c >> 12) & 0xf;
} else {
ctl[0] = ctl[1] = ctl[2] = ctl[3] = (c >> 0) & 0x3;
}
tmp[07:00] = ReadByte( mode, ctl[0], tmp64 );
tmp[15:08] = ReadByte( mode, ctl[1], tmp64 );
tmp[23:16] = ReadByte( mode, ctl[2], tmp64 );
tmp[31:24] = ReadByte( mode, ctl[3], tmp64 );
PTX ISA Notes
Introduced in PTX ISA version 2.0.
Target ISA Notes
prmt
requires sm_20
or higher.
Examples
prmt.b32 r1, r2, r3, r4;
prmt.b32.f4e r1, r2, r3, r4;
9.7.8.8. Data Movement and Conversion Instructions: ld
ld
Load a register variable from an addressable state space variable.
Syntax
ld{.weak}{.ss}{.cop}{.level::cache_hint}{.level::prefetch_size}{.vec}.type d, [a]{.unified}{, cache-policy};
ld{.weak}{.ss}{.level::eviction_priority}{.level::cache_hint}{.level::prefetch_size}{.vec}.type d, [a]{.unified}{, cache-policy};
ld.volatile{.ss}{.level::prefetch_size}{.vec}.type d, [a];
ld.relaxed.scope{.ss}{.level::eviction_priority}{.level::cache_hint}{.level::prefetch_size}{.vec}.type d, [a]{, cache-policy};
ld.acquire.scope{.ss}{.level::eviction_priority}{.level::cache_hint}{.level::prefetch_size}{.vec}.type d, [a]{, cache-policy};
ld.mmio.relaxed.sys{.global}.type d, [a];
.ss = { .const, .global, .local, .param{::entry, ::func}, .shared{::cta, ::cluster} };
.cop = { .ca, .cg, .cs, .lu, .cv };
.level::eviction_priority = { .L1::evict_normal, .L1::evict_unchanged,
.L1::evict_first, .L1::evict_last, .L1::no_allocate };
.level::cache_hint = { .L2::cache_hint };
.level::prefetch_size = { .L2::64B, .L2::128B, .L2::256B }
.scope = { .cta, .cluster, .gpu, .sys };
.vec = { .v2, .v4 };
.type = { .b8, .b16, .b32, .b64, .b128,
.u8, .u16, .u32, .u64,
.s8, .s16, .s32, .s64,
.f32, .f64 };
Description
Load register variable d
from the location specified by the source address operand a
in
specified state space. If no state space is given, perform the load using Generic Addressing.
If no sub-qualifier is specified with .shared
state space, then ::cta
is assumed by default.
Supported addressing modes for operand a
and alignment requirements are described in Addresses
as Operands
If no sub-qualifier is specified with .param
state space, then :
::func
is assumed when access is inside a device function.::entry
is assumed when accessing kernel function parameters from entry function. Otherwise, when accessing device function parameters or any other.param
variables from entry function::func
is assumed by default.
For ld.param::entry
instruction, operand a must be a kernel parameter address, otherwise behavior
is undefined. For ld.param::func
instruction, operand a must be a device function parameter address,
otherwise behavior is undefined.
Instruction ld.param{::func}
used for reading value returned from device function call cannot be
predicated. See Parameter State Space and
Function Declarations and Definitions for descriptions
of the proper use of ld.param
.
The .relaxed
and .acquire
qualifiers indicate memory synchronization as described in the
Memory Consistency Model. The .scope
qualifier
indicates the set of threads with which an ld.relaxed
or ld.acquire
instruction can directly
synchronize1. The .weak
qualifier indicates a memory instruction with no synchronization.
The effects of this instruction become visible to other threads only when synchronization is established
by other means.
The semantic details of .mmio
qualifier are described in the Memory Consistency Model. Only .sys
thread scope is valid for ld.mmio
operation. The
qualifiers .mmio
and .relaxed
must be specified together.
The .weak
, .volatile
, .relaxed
and .acquire
qualifiers are mutually exclusive. When
none of these is specified, the .weak
qualifier is assumed by default.
An ld.volatile
operation is always performed and it will not be reordered with respect to other
volatile
operations to the same memory location. volatile
and non-volatile load operations
to the same memory location may be reordered. ld.volatile
has the same memory synchronization
semantics as ld.relaxed.sys
.
The qualifiers .volatile
, .relaxed
and .acquire
may be used only with .global
and
.shared
spaces and with generic addressing, where the address points to .global
or
.shared
space. Cache operations are not permitted with these qualifiers. The qualifier .mmio
may be used only with .global
space and with generic addressing, where the address points to
.global
space.
The optional qualifier .unified
must be specified on operand a
if a
is the address of a
variable declared with .unified
attribute as described in Variable and Function Attribute
Directive: .attribute.
The qualifier .level::eviction_priority
specifies the eviction policy that will be used during
memory access.
The .level::prefetch_size
qualifier is a hint to fetch additional data of the specified size
into the respective cache level.The sub-qualifier prefetch_size
can be set to either of 64B
,
128B
, 256B
thereby allowing the prefetch size to be 64 Bytes, 128 Bytes or 256 Bytes
respectively.
The qualifier .level::prefetch_size
may only be used with .global
state space and with
generic addressing where the address points to .global
state space. If the generic address does
not fall within the address window of the global memory, then the prefetching behavior is undefined.
The .level::prefetch_size
qualifier is treated as a performance hint only.
When the optional argument cache-policy
is specified, the qualifier .level::cache_hint
is
required. The 64-bit operand cache-policy
specifies the cache eviction policy that may be used
during the memory access.
The qualifiers .unified
and .level::cache_hint
are only supported for .global
state
space and for generic addressing where the address points to the .global
state space.
cache-policy
is a hint to the cache subsystem and may not always be respected. It is treated as
a performance hint only, and does not change the memory consistency behavior of the program.
1 This synchronization is further extended to other threads through the transitive nature of causality order, as described in the memory consistency model.
Semantics
d = a; // named variable a
d = *(&a+immOff) // variable-plus-offset
d = *a; // register
d = *(a+immOff); // register-plus-offset
d = *(immAddr); // immediate address
Notes
Destination d
must be in the .reg
state space.
A destination register wider than the specified type may be used. The value loaded is sign-extended to the destination register width for signed integers, and is zero-extended to the destination register width for unsigned and bit-size types. See Table 25 for a description of these relaxed type-checking rules.
.f16
data may be loaded using ld.b16
, and then converted to .f32
or .f64
using
cvt
or can be used in half precision floating point instructions.
.f16x2
data may be loaded using ld.b32
and then used in half precision floating point
instructions.
PTX ISA Notes
ld introduced in PTX ISA version 1.0. ld.volatile
introduced in PTX ISA version 1.1.
Generic addressing and cache operations introduced in PTX ISA version 2.0.
Support for scope qualifier, .relaxed
, .acquire
, .weak
qualifiers introduced in PTX ISA
version 6.0.
Support for generic addressing of .const space added in PTX ISA version 3.1.
Support for .level::eviction_priority
, .level::prefetch_size
and .level::cache_hint
qualifiers introduced in PTX ISA version 7.4.
Support for .cluster
scope qualifier introduced in PTX ISA version 7.8.
Support for ::cta
and ::cluster
sub-qualifiers introduced in PTX ISA version 7.8.
Support for .unified
qualifier introduced in PTX ISA version 8.0.
Support for .mmio
qualifier introduced in PTX ISA version 8.2.
Support for ::entry
and ::func
sub-qualifiers on .param
space introduced in PTX ISA
version 8.3.
Support for .b128
type introduced in PTX ISA version 8.3.
Support for .sys
scope with .b128
type introduced in PTX ISA version 8.4.
Target ISA Notes
ld.f64
requires sm_13
or higher.
Support for scope qualifier, .relaxed
, .acquire
, .weak
qualifiers require sm_70
or
higher.
Generic addressing requires sm_20
or higher.
Cache operations require sm_20
or higher.
Support for .level::eviction_priority
qualifier requires sm_70
or higher.
Support for .level::prefetch_size
qualifier requires sm_75
or higher.
Support for .L2::256B
and .L2::cache_hint
qualifiers requires sm_80
or higher.
Support for .cluster
scope qualifier requires sm_90
or higher.
Sub-qualifier ::cta
requires sm_30
or higher.
Sub-qualifier ::cluster
requires sm_90
or higher.
Support for .unified
qualifier requires sm_90
or higher.
Support for .mmio
qualifier requires sm_70
or higher.
Support for .b128
type requires sm_70
or higher.
Examples
ld.global.f32 d,[a];
ld.shared.v4.b32 Q,[p];
ld.const.s32 d,[p+4];
ld.local.b32 x,[p+-8]; // negative offset
ld.local.b64 x,[240]; // immediate address
ld.global.b16 %r,[fs]; // load .f16 data into 32-bit reg
cvt.f32.f16 %r,%r; // up-convert f16 data to f32
ld.global.b32 %r0, [fs]; // load .f16x2 data in 32-bit reg
ld.global.b32 %r1, [fs + 4]; // load .f16x2 data in 32-bit reg
add.rn.f16x2 %d0, %r0, %r1; // addition of f16x2 data
ld.global.relaxed.gpu.u32 %r0, [gbl];
ld.shared.acquire.gpu.u32 %r1, [sh];
ld.global.relaxed.cluster.u32 %r2, [gbl];
ld.shared::cta.acquire.gpu.u32 %r2, [sh + 4];
ld.shared::cluster.u32 %r3, [sh + 8];
ld.global.mmio.relaxed.sys.u32 %r3, [gbl];
ld.global.f32 d,[ugbl].unified;
ld.b32 %r0, [%r1].unified;
ld.global.L1::evict_last.u32 d, [p];
ld.global.L2::64B.b32 %r0, [gbl]; // Prefetch 64B to L2
ld.L2::128B.f64 %r1, [gbl]; // Prefetch 128B to L2
ld.global.L2::256B.f64 %r2, [gbl]; // Prefetch 256B to L2
createpolicy.fractional.L2::evict_last.L2::evict_unchanged.b64 cache-policy, 1;
ld.global.L2::cache_hint.b64 x, [p], cache-policy;
ld.param::entry.b32 %rp1, [kparam1];
ld.global.b128 %r0, [gbl]; // 128-bit load
9.7.8.9. Data Movement and Conversion Instructions: ld.global.nc
ld.global.nc
Load a register variable from global state space via non-coherent cache.
Syntax
ld.global{.cop}.nc{.level::cache_hint}{.level::prefetch_size}.type d, [a]{, cache-policy};
ld.global{.cop}.nc{.level::cache_hint}{.level::prefetch_size}.vec.type d, [a]{, cache-policy};
ld.global.nc{.level::eviction_priority}{.level::cache_hint}{.level::prefetch_size}.type d, [a]{, cache-policy};
ld.global.nc{.level::eviction_priority}{.level::cache_hint}{.level::prefetch_size}.vec.type d, [a]{, cache-policy};
.cop = { .ca, .cg, .cs }; // cache operation
.level::eviction_priority = { .L1::evict_normal, .L1::evict_unchanged,
.L1::evict_first, .L1::evict_last, .L1::no_allocate};
.level::cache_hint = { .L2::cache_hint };
.level::prefetch_size = { .L2::64B, .L2::128B, .L2::256B }
.vec = { .v2, .v4 };
.type = { .b8, .b16, .b32, .b64, .b128,
.u8, .u16, .u32, .u64,
.s8, .s16, .s32, .s64,
.f32, .f64 };
Description
Load register variable d
from the location specified by the source address operand a
in the
global state space, and optionally cache in non-coherent read-only cache.
Note
On some architectures, the texture cache is larger, has higher bandwidth, and longer latency than
the global memory cache. For applications with sufficient parallelism to cover the longer
latency, ld.global.nc
should offer better performance than ld.global
on such
architectures.
The address operand a
may contain a generic address pointing to the
.global
state space. Supported addressing modes for operand a
and alignment requirements are
described in Addresses as Operands
The qualifier .level::eviction_priority
specifies the eviction policy that will be used during
memory access.
The .level::prefetch_size
qualifier is a hint to fetch additional data of the specified size
into the respective cache level.The sub-qualifier prefetch_size
can be set to either of 64B
,
128B
, 256B
thereby allowing the prefetch size to be 64 Bytes, 128 Bytes or 256 Bytes
respectively.
The .level::prefetch_size
qualifier is treated as a performance hint only.
When the optional argument cache-policy
is specified, the qualifier .level::cache_hint
is
required. The 64-bit operand cache-policy
specifies the cache eviction policy that may be used
during the memory access.
cache-policy
is a hint to the cache subsystem and may not always be respected. It is treated as
a performance hint only, and does not change the memory consistency behavior of the program.
Semantics
d = a; // named variable a
d = *(&a+immOff) // variable-plus-offset
d = *a; // register
d = *(a+immOff); // register-plus-offset
d = *(immAddr); // immediate address
Notes
Destination d
must be in the .reg
state space.
A destination register wider than the specified type may be used. The value loaded is sign-extended to the destination register width for signed integers, and is zero-extended to the destination register width for unsigned and bit-size types.
.f16
data may be loaded using ld.b16
, and then converted to .f32
or .f64
using cvt
.
PTX ISA Notes
Introduced in PTX ISA version 3.1.
Support for .level::eviction_priority
, .level::prefetch_size
and .level::cache_hint
qualifiers introduced in PTX ISA version 7.4.
Support for .b128
type introduced in PTX ISA version 8.3.
Target ISA Notes
Requires sm_32
or higher.
Support for .level::eviction_priority
qualifier requires sm_70
or higher.
Support for .level::prefetch_size
qualifier requires sm_75
or higher.
Support for .level::cache_hint
qualifier requires sm_80
or higher.
Support for .b128
type requires sm_70
or higher.
Examples
ld.global.nc.f32 d, [a];
ld.gloal.nc.L1::evict_last.u32 d, [a];
createpolicy.fractional.L2::evict_last.b64 cache-policy, 0.5;
ld.global.nc.L2::cache_hint.f32 d, [a], cache-policy;
ld.global.nc.L2::64B.b32 d, [a]; // Prefetch 64B to L2
ld.global.nc.L2::256B.f64 d, [a]; // Prefetch 256B to L2
ld.global.nc.b128 d, [a];
9.7.8.10. Data Movement and Conversion Instructions: ldu
ldu
Load read-only data from an address that is common across threads in the warp.
Syntax
ldu{.ss}.type d, [a]; // load from address
ldu{.ss}.vec.type d, [a]; // vec load from address
.ss = { .global }; // state space
.vec = { .v2, .v4 };
.type = { .b8, .b16, .b32, .b64, .b128,
.u8, .u16, .u32, .u64,
.s8, .s16, .s32, .s64,
.f32, .f64 };
Description
Load read-only data into register variable d
from the location specified by the source address
operand a
in the global state space, where the address is guaranteed to be the same across all
threads in the warp. If no state space is given, perform the load using Generic Addressing.
Supported addressing modes for operand a
and alignment requirements are described in Addresses
as Operands
Semantics
d = a; // named variable a
d = *(&a+immOff) // variable-plus-offset
d = *a; // register
d = *(a+immOff); // register-plus-offset
d = *(immAddr); // immediate address
Notes
Destination d
must be in the .reg
state space.
A destination register wider than the specified type may be used. The value loaded is sign-extended to the destination register width for signed integers, and is zero-extended to the destination register width for unsigned and bit-size types. See Table 25 for a description of these relaxed type-checking rules.
.f16
data may be loaded using ldu.b16
, and then converted to .f32
or .f64
using
cvt
or can be used in half precision floating point instructions.
.f16x2
data may be loaded using ldu.b32
and then used in half precision floating point
instructions.
PTX ISA Notes
Introduced in PTX ISA version 2.0.
Support for .b128
type introduced in PTX ISA version 8.3.
Target ISA Notes
ldu.f64
requires sm_13
or higher.
Support for .b128
type requires sm_70
or higher.
Examples
ldu.global.f32 d,[a];
ldu.global.b32 d,[p+4];
ldu.global.v4.f32 Q,[p];
ldu.global.b128 d,[a];
9.7.8.11. Data Movement and Conversion Instructions: st
st
Store data to an addressable state space variable.
Syntax
st{.weak}{.ss}{.cop}{.level::cache_hint}{.vec}.type [a], b{, cache-policy};
st{.weak}{.ss}{.level::eviction_priority}{.level::cache_hint}{.vec}.type
[a], b{, cache-policy};
st.volatile{.ss}{.vec}.type [a], b;
st.relaxed.scope{.ss}{.level::eviction_priority}{.level::cache_hint}{.vec}.type
[a], b{, cache-policy};
st.release.scope{.ss}{.level::eviction_priority}{.level::cache_hint}{.vec}.type
[a], b{, cache-policy};
st.mmio.relaxed.sys{.global}.type [a], b;
.ss = { .global, .local, .param{::func}, .shared{::cta, ::cluster} };
.level::eviction_priority = { .L1::evict_normal, .L1::evict_unchanged,
.L1::evict_first, .L1::evict_last, .L1::no_allocate };
.level::cache_hint = { .L2::cache_hint };
.cop = { .wb, .cg, .cs, .wt };
.sem = { .relaxed, .release };
.scope = { .cta, .cluster, .gpu, .sys };
.vec = { .v2, .v4 };
.type = { .b8, .b16, .b32, .b64, .b128,
.u8, .u16, .u32, .u64,
.s8, .s16, .s32, .s64,
.f32, .f64 };
Description
Store the value of operand b
in the location specified by the destination address
operand a
in specified state space. If no state space is given, perform the store using Generic
Addressing. Stores to const memory are illegal.
If no sub-qualifier is specified with .shared
state space, then ::cta
is assumed by default.
Supported addressing modes for operand a
and alignment requirements are described in Addresses
as Operands
If .param
is specified without any sub-qualifiers then it defaults to .param::func
.
Instruction st.param{::func}
used for passing arguments to device function cannot be predicated.
See Parameter State Space and Function Declarations and
Definitions for descriptions of the proper use
of st.param
.
The qualifiers .relaxed
and .release
indicate memory synchronization as described in the
Memory Consistency Model. The .scope
qualifier
indicates the set of threads with which an st.relaxed
or st.release
instruction can directly
synchronize1. The .weak
qualifier indicates a memory instruction with no synchronization.
The effects of this instruction become visible to other threads only when synchronization is established
by other means.
The semantic details of .mmio
qualifier are described in the Memory Consistency Model. Only .sys
thread scope is valid for st.mmio
operation. The
qualifiers .mmio
and .relaxed
must be specified together.
The .weak
, .volatile
, .relaxed
and .release
qualifiers are mutually exclusive. When
none of these is specified, the .weak
qualifier is assumed by default.
An st.volatile
operation is always performed and it will not be reordered with respect to other
volatile
operations to the same memory location. st.volatile
has the same memory
synchronization semantics as st.relaxed.sys
.
The qualifiers .volatile
, .relaxed
and .release
may be used only with .global
and
.shared
spaces and with generic addressing, where the address points to .global
or
.shared
space. Cache operations are not permitted with these qualifiers. The qualifier .mmio
may be used only with .global
space and with generic addressing, where the address points to
.global
space.
The qualifier .level::eviction_priority
specifies the eviction policy that will be used during
memory access.
When the optional argument cache-policy
is specified, the qualifier .level::cache_hint
is
required. The 64-bit operand cache-policy
specifies the cache eviction policy that may be used
during the memory access.
The qualifier .level::cache_hint
is only supported for .global
state space and for generic
addressing where the address points to the .global
state space.
cache-policy
is a hint to the cache subsystem and may not always be respected. It is treated as
a performance hint only, and does not change the memory consistency behavior of the program.
1 This synchronization is further extended to other threads through the transitive nature of causality order, as described in the memory consistency model.
Semantics
d = a; // named variable d
*(&a+immOffset) = b; // variable-plus-offset
*a = b; // register
*(a+immOffset) = b; // register-plus-offset
*(immAddr) = b; // immediate address
Notes
Operand b
must be in the .reg
state space.
A source register wider than the specified type may be used. The lower n
bits corresponding to
the instruction-type width are stored to memory. See
Table 24
for a description of these relaxed type-checking rules.
.f16
data resulting from a cvt
instruction may be stored using st.b16
.
.f16x2
data may be stored using st.b32
.
PTX ISA Notes
st introduced in PTX ISA version 1.0. st.volatile
introduced in PTX ISA version 1.1.
Generic addressing and cache operations introduced in PTX ISA version 2.0.
Support for scope qualifier, .relaxed
, .release
, .weak
qualifiers introduced in PTX ISA
version 6.0.
Support for .level::eviction_priority
and .level::cache_hint
qualifiers introduced in PTX
ISA version 7.4.
Support for .cluster
scope qualifier introduced in PTX ISA version 7.8.
Support for ::cta
and ::cluster
sub-qualifiers introduced in PTX ISA version 7.8.
Support for .mmio
qualifier introduced in PTX ISA version 8.2.
Support for ::func
sub-qualifier on .param
space introduced in PTX ISA version 8.3.
Support for .b128
type introduced in PTX ISA version 8.3.
Support for .sys
scope with .b128
type introduced in PTX ISA version 8.4.
Target ISA Notes
st.f64
requires sm_13
or higher.
Support for scope qualifier, .relaxed
, .release
, .weak
qualifiers require sm_70
or
higher.
Generic addressing requires sm_20
or higher.
Cache operations require sm_20
or higher.
Support for .level::eviction_priority
qualifier requires sm_70
or higher.
Support for .level::cache_hint
qualifier requires sm_80
or higher.
Support for .cluster
scope qualifier requires sm_90
or higher.
Sub-qualifier ::cta
requires sm_30
or higher.
Sub-qualifier ::cluster
requires sm_90
or higher.
Support for .mmio
qualifier requires sm_70
or higher.
Support for .b128
type requires sm_70
or higher.
Examples
st.global.f32 [a],b;
st.local.b32 [q+4],a;
st.global.v4.s32 [p],Q;
st.local.b32 [q+-8],a; // negative offset
st.local.s32 [100],r7; // immediate address
cvt.f16.f32 %r,%r; // %r is 32-bit register
st.b16 [fs],%r; // store lower
st.global.relaxed.sys.u32 [gbl], %r0;
st.shared.release.cta.u32 [sh], %r1;
st.global.relaxed.cluster.u32 [gbl], %r2;
st.shared::cta.release.cta.u32 [sh + 4], %r1;
st.shared::cluster.u32 [sh + 8], %r1;
st.global.mmio.relaxed.sys.u32 [gbl], %r1;
st.global.L1::no_allocate.f32 [p], a;
createpolicy.fractional.L2::evict_last.b64 cache-policy, 0.25;
st.global.L2::cache_hint.b32 [a], b, cache-policy;
st.param::func.b64 [param1], %rp1;
st.global.b128 [a], b; // 128-bit store
9.7.8.12. Data Movement and Conversion Instructions: st.async
st.async
Asynchronous store operation on shared memory.
Syntax
st.async{.weak}{.ss}{.completion_mechanism}{.vec}.type [a], b, [mbar];
.ss = { .shared::cluster };
.type = { .b32, .b64,
.u32, .u64,
.s32, .s64,
.f32, .f64 };
.vec = { .v2, .v4 };
.completion_mechanism = { .mbarrier::complete_tx::bytes };
Description
st.async
is a non-blocking instruction which initiates an asynchronous store operation that
stores the value specified by source operand b
to the destination memory location
specified by operand a
.
The modifier .completion_mechanism
specifies that upon completion of the asynchronous operation,
complete-tx
operation, with completeCount
argument equal to amount of data stored in bytes, will be
performed on the mbarrier object specified by the operand mbar
.
Operand a
represents destination address and must be a register or of the form register +
immOff
as described in Addresses as Operands.
The shared memory addresses of destination operand a
and the mbarrier object mbar
, must
meet all of the following conditions:
They belong to the same CTA.
They are different to the CTA of the executing thread but must be within the same cluster.
Otherwise, the behavior is undefined.
The state space of the address {.ss}
, if specified, is applicable to both operands a
and
mbar
. If not specified, then Generic Addressing is used for
both a
and mbar
. If the generic addresses specified do not fall within the address window of
.shared::cluster
state space, then the behaviour is undefined.
The store operation in st.async
is treated as a weak memory operation and the complete_tx
operation on the mbarrier has .release
semantics at the .cluster
scope as described in the
Memory Consistency Model.
PTX ISA Notes
Introduced in PTX ISA version 8.1.
Target ISA Notes
Requires sm_90
or higher.
Examples
st.async.shared::cluster.mbarrier::complete_tx::bytes.u32 [addr], b, [mbar_addr]
9.7.8.13. Data Movement and Conversion Instructions: multimem.ld_reduce, multimem.st, multimem.red
The multimem.* operations operate on multimem addresses and accesses all of the multiple memory locations which the multimem address points to.
Multimem addresses can only be accessed only by multimem.* operations. Accessing a multimem address
with ld
, st
or any other memory operations results in undefined behavior.
Refer to CUDA programming guide for creation and management of the multimem addresses.
multimem.ld_reduce, multimem.st, multimem.red
Perform memory operations on the multimem address.
Syntax
// Integer type:
multimem.ld_reduce{.ldsem}{.scope}{.ss}.op.type d, [a];
multimem.st{.stsem}{.scope}{.ss}.type [a], b;
multimem.red{.redsem}{.scope}{.ss}.op.type [a], b;
.ss = { .global }
.ldsem = { .weak, .relaxed, .acquire }
.stsem = { .weak, .relaxed, .release }
.redsem = { .relaxed, .release }
.scope = { .cta, .cluster, .gpu, .sys }
.op = { .min, .max, .add, .and, .or, .xor }
.type = { .b32, .b64, .u32, .u64, .s32, .s64 }
// Floating point type:
multimem.ld_reduce{.ldsem}{.scope}{.ss}.op{.acc_prec}{.vec}.type d, [a];
multimem.st{.stsem}{.scope}{.ss}{.vec}.type [a], b;
multimem.red{.redsem}{.scope}{.ss}.redop{.vec}.type [a], b;
.ss = { .global }
.ldsem = { .weak, .relaxed, .acquire }
.stsem = { .weak, .relaxed, .release }
.redsem = { .relaxed, .release }
.scope = { .cta, .cluster, .gpu, .sys }
.op = { .min, .max, .add }
.redop = { .add }
.acc_prec = { .acc::f32 }
.vec = { .v2, .v4, .v8 }
.type= { .f16, .f16x2, .bf16, .bf16x2, .f32, .f64 }
Description
Instruction multimem.ld_reduce
performs the following operations:
load operation on the multimem address
a
, which involves loading of data from all of the multiple memory locations pointed to by the multimem addressa
,reduction operation specified by
.op
on the multiple data loaded from the multimem addressa
.
The result of the reduction operation in returned in register d
.
Instruction multimem.st
performs a store operation of the input operand b
to all the memory
locations pointed to by the multimem address a
.
Instruction multimem.red
performs a reduction operation on all the memory locations pointed to
by the multimem address a
, with operand b
.
Instruction multimem.ld_reduce
performs reduction on the values loaded from all the memory
locations that the multimem address points to. In contrast, the multimem.red
perform reduction
on all the memory locations that the multimem address points to.
Address operand a
must be a multimem address. Otherwise, the behavior is undefined. Supported
addressing modes for operand a and alignment requirements are described in Addresses as Operands.
If no state space is specified then Generic Addressing is
used. If the address specified by a
does not fall within the address window of .global
state
space then the behavior is undefined.
For floating-point type multi- operations, the size of the specified type along with .vec
must
equal either 32-bits or 64-bits or 128-bits. No other combinations of .vec
and type are
allowed. Type .f64
cannot be used with .vec
qualifier.
The following table describes the valid combinations of .op
and base type:
op |
Base type |
---|---|
|
.u32 , .u64 , .s32
.f16 , .f16x2 , .bf16 , .bf16x2
.f32 , .f64
|
|
|
|
.u32 , .s32 , .u64 , .s644
.f16 , .f16x2 , .bf16 , .bf16x2
|
For multimem.ld_reduce
, the default precision of the intermediate accumulation is same as the
specified type. Optionally for .f16
, .f16x2
, .bf16
and .bf16x2
types, .acc::f32
can be specified to change the precision of the intermediate accumulation to .f32
.
Optional qualifiers .ldsem
, .stsem
and .redsem
specify the memory synchronizing effect
of the multimem.ld_reduce
, multimem.st
and multimem.red
respectively, as described in
Memory Consistency Model. If explicit semantics qualifiers
are not specified, then multimem.ld_reduce
and multimem.st
default to .weak
and
multimem.red
defaults to .relaxed
.
The optional .scope
qualifier specifies the set of threads that can directly observe the memory
synchronizing effect of this operation, as described in Memory Consistency Model. If the .scope
qualifier is not specified for
multimem.red
then .sys
scope is assumed by default.
PTX ISA Notes
Introduced in PTX ISA version 8.1.
Support for .acc::f32
qualifier introduced in PTX ISA version 8.2.
Target ISA Notes
Requires sm_90
or higher.
Examples
multimem.ld_reduce.and.b32 val1_b32, [addr1];
multimem.ld_reduce.acquire.gpu.global.add.u32 val2_u32, [addr2];
multimem.st.relaxed.gpu.b32 [addr3], val3_b32;
multimem.st.release.cta.global.u32 [addr4], val4_u32;
multimem.red.relaxed.gpu.max.f64 [addr5], val5_f64;
multimem.red.release.cta.global.add.v4.f32 [addr6], {val6, val7, val8, val9};
multimem.ld_reduce.add.acc::f32.v2.f16x2 {val_10, val_11}, [addr7];
9.7.8.14. Data Movement and Conversion Instructions: prefetch, prefetchu
prefetch, prefetchu
Prefetch line containing a generic address at a specified level of memory hierarchy, in specified state space.
Syntax
prefetch{.space}.level [a]; // prefetch to data cache
prefetch.global.level::eviction_priority [a]; // prefetch to data cache
prefetchu.L1 [a]; // prefetch to uniform cache
prefetch{.tensormap_space}.tensormap [a]; // prefetch the tensormap
.space = { .global, .local };
.level = { .L1, .L2 };
.level::eviction_priority = { .L2::evict_last, .L2::evict_normal };
.tensormap_space = { .const, .param };
Description
The prefetch
instruction brings the cache line containing the specified address in global or
local memory state space into the specified cache level.
If the .tensormap
qualifier is specified then the prefetch
instruction brings the cache line
containing the specified address in the .const
or .param
memory state space for subsequent
use by the cp.async.bulk.tensor
instruction.
If no state space is given, the prefetch
uses Generic Addressing.
Optionally, the eviction priority to be applied on the prefetched cache line can be specified by the
modifier .level::eviction_priority
.
Supported addressing modes for operand a
and alignment requirements are described in Addresses
as Operands
The prefetchu
instruction brings the cache line containing the specified generic address into
the specified uniform cache level.
A prefetch
to a shared memory location performs no operation.
A prefetch
into the uniform cache requires a generic address, and no operation occurs if the
address maps to a const
, local
, or shared
memory location.
PTX ISA Notes
Introduced in PTX ISA version 2.0.
Support for .level::eviction_priority
qualifier introduced in PTX ISA version 7.4.
Support for the .tensormap
qualifier is introduced in PTX ISA version 8.0.
Target ISA Notes
prefetch
and prefetchu
require sm_20
or higher.
Support for .level::eviction_priority
qualifier requires sm_80
or higher.
Support for the .tensormap
qualifier requires sm_90
or higher.
Examples
prefetch.global.L1 [ptr];
prefetch.global.L2::evict_last [ptr];
prefetchu.L1 [addr];
prefetch.global.tensormap [ptr];
9.7.8.15. Data Movement and Conversion Instructions: applypriority
applypriority
Apply the cache eviction priority to the specified address in the specified cache level.
Syntax
applypriority{.global}.level::eviction_priority [a], size;
.level::eviction_priority = { .L2::evict_normal };
Description
The applypriority
instruction applies the cache eviction priority specified by the
.level::eviction_priority
qualifier to the address range [a..a+size)
in the specified cache
level.
If no state space is specified then Generic Addressing is
used. If the specified address does not fall within the address window of .global
state space
then the behavior is undefined.
The operand size
is an integer constant that specifies the amount of data, in bytes, in the
specified cache level on which the priority is to be applied. The only supported value for the
size
operand is 128.
Supported addressing modes for operand a
are described in Addresses as Operands. a
must be aligned to 128 bytes.
If the data pointed to by address a
is not already present in the specified cache level, then
the data will be prefetched before applying the specified priority.
PTX ISA Notes
Introduced in PTX ISA version 7.4.
Target ISA Notes
Requires sm_80
or higher.
Examples
applypriority.global.L2::evict_normal [ptr], 128;
9.7.8.16. Data Movement and Conversion Instructions: discard
discard
Invalidate the data in cache at the specified address and cache level.
Syntax
discard{.global}.level [a], size;
.level = { .L2 };
Description
The discard
instruction invalidates the data at the address range [a .. a + (size - 1)]
in
the cache level specified by the .level
qualifier without writing back the data in the cache to
the memory. Therefore after the discard operation, the data at the address range [a .. a+ (size -
1)]
has undetermined value.
The operand size
is an integer constant that specifies the amount of data, in bytes, in the
cache level specified by the .level
qualifier to be discarded. The only supported value for the
size
operand is 128.
If no state space is specified then Generic Addressing is
used. If the specified address does not fall within the address window of .global
state space
then the behavior is undefined.
Supported addressing modes for address operand a
are described in Addresses as Operands. a
must be aligned to 128 bytes.
PTX ISA Notes
Introduced in PTX ISA version 7.4.
Target ISA Notes
Requires sm_80
or higher.
Examples
discard.global.L2 [ptr], 128;
9.7.8.17. Data Movement and Conversion Instructions: createpolicy
createpolicy
Create a cache eviction policy for the specified cache level.
Syntax
// Range-based policy
createpolicy.range{.global}.level::primary_priority{.level::secondary_priority}.b64
cache-policy, [a], primary-size, total-size;
// Fraction-based policy
createpolicy.fractional.level::primary_priority{.level::secondary_priority}.b64
cache-policy{, fraction};
// Converting the access property from CUDA APIs
createpolicy.cvt.L2.b64 cache-policy, access-property;
.level::primary_priority = { .L2::evict_last, .L2::evict_normal,
.L2::evict_first, .L2::evict_unchanged };
.level::secondary_priority = { .L2::evict_first, .L2::evict_unchanged };
Description
The createpolicy
instruction creates a cache eviction policy for the specified cache level in an
opaque 64-bit register specified by the destination operand cache-policy
. The cache eviction
policy specifies how cache eviction priorities are applied to global memory addresses used in memory
operations with .level::cache_hint
qualifier.
There are two types of cache eviction policies:
-
Range-based policy
The cache eviction policy created using
createpolicy.range
specifies the cache eviction behaviors for the following three address ranges:[a .. a + (primary-size - 1)]
referred to as primary range.[a + primary-size .. a + (total-size - 1)]
referred to as trailing secondary range.[a - (total-size - primary-size) .. (a - 1)]
referred to as preceding secondary range.
When a range-based cache eviction policy is used in a memory operation with
.level::cache_hint
qualifier, the eviction priorities are applied as follows:If the memory address falls in the primary range, the eviction priority specified by
.L2::primary_priority
is applied.If the memory address falls in any of the secondary ranges, the eviction priority specified by
.L2::secondary_priority
is applied.If the memory address does not fall in either of the above ranges, then the applied eviction priority is unspecified.
The 32-bit operand
primary-size
specifies the size, in bytes, of the primary range. The 32-bit operandtotal-size
specifies the combined size, in bytes, of the address range including primary and secondary ranges. The value ofprimary-size
must be less than or equal to the value oftotal-size
. Maximum allowed value oftotal-size
is 4GB.If
.L2::secondary_priority
is not specified, then it defaults to.L2::evict_unchanged
.If no state space is specified then Generic Addressing is used. If the specified address does not fall within the address window of
.global
state space then the behavior is undefined. -
Fraction-based policy
A memory operation with
.level::cache_hint
qualifier can use the fraction-based cache eviction policy to request the cache eviction priority specified by.L2:primary_priority
to be applied to a fraction of cache accesses specified by the 32-bit floating point operandfraction
. The remainder of the cache accesses get the eviction priority specified by.L2::secondary_priority
. This implies that in a memory operation that uses a fraction-based cache policy, the memory access has a probability specified by the operandfraction
of getting the cache eviction priority specified by.L2::primary_priority
.The valid range of values for the operand
fraction
is(0.0,.., 1.0]
. If the operandfraction
is not specified, it defaults to 1.0.If
.L2::secondary_priority
is not specified, then it defaults to.L2::evict_unchanged
.
The access property created using the CUDA APIs can be converted into cache eviction policy by the
instruction createpolicy.cvt
. The source operand access-property
is a 64-bit opaque
register. Refer to CUDA programming guide for more details.
PTX ISA Notes
Introduced in PTX ISA version 7.4.
Target ISA Notes
Requires sm_80
or higher.
Examples
createpolicy.fractional.L2::evict_last.b64 policy, 1.0;
createpolicy.fractional.L2::evict_last.L2::evict_unchanged.b64 policy, 0.5;
createpolicy.range.L2::evict_last.L2::evict_first.b64
policy, [ptr], 0x100000, 0x200000;
// access-prop is created by CUDA APIs.
createpolicy.cvt.L2.b64 policy, access-prop;
9.7.8.18. Data Movement and Conversion Instructions: isspacep
isspacep
Query whether a generic address falls within a specified state space window.
Syntax
isspacep.space p, a; // result is .pred
.space = { const, .global, .local, .shared{::cta, ::cluster}, .param{::entry} };
Description
Write predicate register p
with 1
if generic address a falls within the specified state
space window and with 0
otherwise. Destination p
has type .pred
; the source address
operand must be of type .u32
or .u64
.
isspacep.param{::entry}
returns 1
if the generic address falls within the window of
Kernel Function Parameters, otherwise returns 0
. If .param
is specified without any sub-qualifiers then it defaults to .param::entry
.
isspacep.global
returns 1
for Kernel Function Parameters as .param
window is contained within the .global
window.
If no sub-qualifier is specified with .shared
state space, then ::cta
is assumed by default.
Note
ispacep.shared::cluster
will return 1 for every shared memory address that is accessible to
the threads in the cluster, whereas ispacep.shared::cta
will return 1 only if the address is
of a variable declared in the executing CTA.
PTX ISA Notes
Introduced in PTX ISA version 2.0.
isspacep.const
introduced in PTX ISA version 3.1.
isspacep.param
introduced in PTX ISA version 7.7.
Support for ::cta
and ::cluster
sub-qualifiers introduced in PTX ISA version 7.8.
Support for sub-qualifier ::entry
on .param
space introduced in PTX ISA version 8.3.
Target ISA Notes
isspacep
requires sm_20
or higher.
isspacep.param{::entry}
requires sm_70
or higher.
Sub-qualifier ::cta
requires sm_30
or higher.
Sub-qualifier ::cluster
requires sm_90
or higher.
Examples
isspacep.const iscnst, cptr;
isspacep.global isglbl, gptr;
isspacep.local islcl, lptr;
isspacep.shared isshrd, sptr;
isspacep.param::entry isparam, pptr;
isspacep.shared::cta isshrdcta, sptr;
isspacep.shared::cluster ishrdany sptr;
9.7.8.19. Data Movement and Conversion Instructions: cvta
cvta
Convert address from .const
, Kernel Function Parameters (.param
), .global
, .local
, or .shared
state space to generic, or vice-versa. Take the generic address of a variable declared in
.const
, Kernel Function Parameters (.param
),
.global
, .local
, or .shared
state space.
Syntax
// convert const, global, local, or shared address to generic address
cvta.space.size p, a; // source address in register a
cvta.space.size p, var; // get generic address of var
cvta.space.size p, var+imm; // generic address of var+offset
// convert generic address to const, global, local, or shared address
cvta.to.space.size p, a;
.space = { .const, .global, .local, .shared{::cta, ::cluster}, .param{::entry} };
.size = { .u32, .u64 };
Description
Convert a const
, Kernel Function Parameters
(.param
), global
, local
, or shared
address to a generic address, or vice-versa. The
source and destination addresses must be the same size. Use cvt.u32.u64
or cvt.u64.u32
to
truncate or zero-extend addresses.
For variables declared in .const
, Kernel Function Parameters (.param
), .global
, .local
, or .shared
state space, the generic address of the variable may be taken using cvta
. The source is either a
register or a variable defined in const
, Kernel Function Parameters (.param
), global
, local
, or shared
memory
with an optional offset.
When converting a generic address into a const
, Kernel Function Parameters (.param
), global
, local
, or shared
address, the resulting address is undefined in cases where the generic address does not fall within
the address window of the specified state space. A program may use isspacep
to guard against
such incorrect behavior.
For cvta
with .shared
state space, the address must belong to the space specified by
::cta
or ::cluster
sub-qualifier, otherwise the behavior is undefined. If no sub-qualifier
is specified with .shared
state space, then ::cta
is assumed by default.
If .param
is specified without any sub-qualifiers then it defaults to .param::entry
.
PTX ISA Notes
Introduced in PTX ISA version 2.0.
cvta.const
and cvta.to.const
introduced in PTX ISA version 3.1.
cvta.param
and cvta.to.param
introduced in PTX ISA version 7.7.
Note: The current implementation does not allow generic pointers to const
space variables in
programs that contain pointers to constant buffers passed as kernel parameters.
Support for ::cta
and ::cluster
sub-qualifiers introduced in PTX ISA version 7.8.
Support for sub-qualifier ::entry
on .param
space introduced in PTX ISA version 8.3.
Target ISA Notes
cvta
requires sm_20
or higher.
cvta.param{::entry}
and cvta.to.param{::entry}
requires sm_70
or higher.
Sub-qualifier ::cta
requires sm_30
or higher.
Sub-qualifier ::cluster
requires sm_90
or higher.
Examples
cvta.const.u32 ptr,cvar;
cvta.local.u32 ptr,lptr;
cvta.shared::cta.u32 p,As+4;
cvta.shared::cluster.u32 ptr, As;
cvta.to.global.u32 p,gptr;
cvta.param.u64 ptr,pvar;
cvta.to.param::entry.u64 epptr, ptr;
9.7.8.20. Data Movement and Conversion Instructions: cvt
cvt
Convert a value from one type to another.
Syntax
cvt{.irnd}{.ftz}{.sat}.dtype.atype d, a; // integer rounding
cvt{.frnd}{.ftz}{.sat}.dtype.atype d, a; // fp rounding
cvt.frnd2{.relu}{.satfinite}.f16.f32 d, a;
cvt.frnd2{.relu}{.satfinite}.f16x2.f32 d, a, b;
cvt.frnd2{.relu}{.satfinite}.bf16.f32 d, a;
cvt.frnd2{.relu}{.satfinite}.bf16x2.f32 d, a, b;
cvt.rna{.satfinite}.tf32.f32 d, a;
cvt.frnd2{.relu}.tf32.f32 d, a;
cvt.rn.satfinite{.relu}.f8x2type.f32 d, a, b;
cvt.rn.satfinite{.relu}.f8x2type.f16x2 d, a;
cvt.rn.{.relu}.f16x2.f8x2type d, a;
.irnd = { .rni, .rzi, .rmi, .rpi };
.frnd = { .rn, .rz, .rm, .rp };
.frnd2 = { .rn, .rz };
.dtype = .atype = { .u8, .u16, .u32, .u64,
.s8, .s16, .s32, .s64,
.bf16, .f16, .f32, .f64 };
.f8x2type = { .e4m3x2, .e5m2x2 };
Description
Convert between different types and sizes.
For .f16x2
and .bf16x2
instruction type, two inputs a
and b
of .f32
type are
converted into .f16
or .bf16
type and the converted values are packed in the destination
register d
, such that the value converted from input a
is stored in the upper half of d
and the value converted from input b
is stored in the lower half of d
For .f16x2
instruction type, destination operand d
has .f16x2
or .b32
type. For
.bf16
instruction type, operand d
has .b16
type. For .bf16x2
instruction type,
operand d
has .b32
type. For .tf32
instruction type, operand d
has .b32
type.
When converting to .e4m3x2
/.e5m2x2
data formats, the destination operand d
has .b16
type. When converting two .f32
inputs to .e4m3x2
/.e5m2x2
, each input is converted to the
specified format, and the converted values are packed in the destination operand d
such that the
value converted from input a
is stored in the upper 8 bits of d
and the value converted from
input b
is stored in the lower 8 bits of d
. When converting an .f16x2
input to
.e4m3x2
/ .e5m2x2
, each .f16
input from operand a
is converted to the specified
format. The converted values are packed in the destination operand d
such that the value
converted from the upper 16 bits of input a
is stored in the upper 8 bits of d
and the value
converted from the lower 16 bits of input a
is stored in the lower 8 bits of d
.
When converting from .e4m3x2
/.e5m2x2
to .f16x2
, source operand a
has .b16
type. Each 8-bit input value in operand a
is converted to .f16
type. The converted values
are packed in the destination operand d
such that the value converted from the upper 8 bits of
a
is stored in the upper 16 bits of d
and the value converted from the lower 8 bits of a
is stored in the lower 16 bits of d
.
Rounding modifier is mandatory in all of the following cases:
float-to-float conversions, when destination type is smaller than source type
All float-to-int conversions
All int-to-float conversions
All conversions involving
.f16x2
,.e4m3x2, .e5m2x2,
.bf16x2
and.tf32
instruction types.
.satfinite
modifier is only supported for conversions involving the following types:
.e4m3x2
and.e5m2x2
destination types..satfinite
modifier is mandatory for such conversions..f16
,.bf16
,.f16x2
,.bf16x2
as destination types..tf32
as destination type with rounding mode specified as round to nearest, ties away from zero.
Semantics
if (/* inst type is .f16x2 or .bf16x2 */) {
d[31:16] = convert(a);
d[15:0] = convert(b);
} else {
d = convert(a);
}
Integer Notes
Integer rounding is required for float-to-integer conversions, and for same-size float-to-float conversions where the value is rounded to an integer. Integer rounding is illegal in all other instances.
Integer rounding modifiers:
.rni
-
round to nearest integer, choosing even integer if source is equidistant between two integers
.rzi
-
round to nearest integer in the direction of zero
.rmi
-
round to nearest integer in direction of negative infinity
.rpi
-
round to nearest integer in direction of positive infinity
In float-to-integer conversion, NaN
inputs are converted to 0.
Subnormal numbers:
sm_20+
-
By default, subnormal numbers are supported.
For
cvt.ftz.dtype.f32
float-to-integer conversions andcvt.ftz.f32.f32
float-to-float conversions with integer rounding, subnormal inputs are flushed to sign-preserving zero. Modifier.ftz
can only be specified when either.dtype
or.atype
is.f32
and applies only to single precision (.f32
) inputs and results. sm_1x
-
For
cvt.ftz.dtype.f32
float-to-integer conversions andcvt.ftz.f32.f32
float-to-float conversions with integer rounding, subnormal inputs are flushed to sign-preserving zero. The optional.ftz
modifier may be specified in these cases for clarity.Note: In PTX ISA versions 1.4 and earlier, the
cvt
instruction did not flush single-precision subnormal inputs or results to zero if the destination type size was 64-bits. The compiler will preserve this behavior for legacy PTX code.
Saturation modifier:
.sat
-
For integer destination types,
.sat
limits the result toMININT..MAXINT
for the size of the operation. Note that saturation applies to both signed and unsigned integer types.The saturation modifier is allowed only in cases where the destination type’s value range is not a superset of the source type’s value range; i.e., the
.sat
modifier is illegal in cases where saturation is not possible based on the source and destination types.For float-to-integer conversions, the result is clamped to the destination range by default; i.e,
.sat
is redundant.
Floating Point Notes
Floating-point rounding is required for float-to-float conversions that result in loss of precision, and for integer-to-float conversions. Floating-point rounding is illegal in all other instances.
Floating-point rounding modifiers:
.rn
-
mantissa LSB rounds to nearest even
.rna
-
mantissa LSB rounds to nearest, ties away from zero
.rz
-
mantissa LSB rounds towards zero
.rm
-
mantissa LSB rounds towards negative infinity
.rp
-
mantissa LSB rounds towards positive infinity
A floating-point value may be rounded to an integral value using the integer rounding modifiers (see Integer Notes). The operands must be of the same size. The result is an integral value, stored in floating-point format.
Subnormal numbers:
sm_20+
-
By default, subnormal numbers are supported. Modifier
.ftz
may be specified to flush single-precision subnormal inputs and results to sign-preserving zero. Modifier.ftz
can only be specified when either.dtype
or.atype
is.f32
and applies only to single precision (.f32
) inputs and results. sm_1x
-
Single-precision subnormal inputs and results are flushed to sign-preserving zero. The optional
.ftz
modifier may be specified in these cases for clarity.
Note: In PTX ISA versions 1.4 and earlier, the cvt
instruction did not flush
single-precision subnormal inputs or results to zero if either source or destination type was
.f64
. The compiler will preserve this behavior for legacy PTX code. Specifically, if the PTX
ISA version is 1.4 or earlier, single-precision subnormal inputs and results are flushed to
sign-preserving zero only for cvt.f32.f16
, cvt.f16.f32
, and cvt.f32.f32
instructions.
Saturation modifier:
-
.sat
: -
For floating-point destination types,
.sat
limits the result to the range [0.0, 1.0].NaN
results are flushed to positive zero. Applies to.f16
,.f32
, and.f64
types. -
.relu
: -
For
.f16
,.f16x2
,.bf16
,.bf16x2
,.e4m3x2
,.e5m2x2
and.tf32
destination types,.relu
clamps the result to 0 if negative.NaN
results are converted to canonicalNaN
. -
.satfinite
: -
For
.f16
,.f16x2
,.bf16
,.bf16x2
,.e4m3x2
,.e5m2x2
and.tf32
destination formats, if the input value isNaN
, then the result isNaN
in the specified destination format. If the absolute value of input (ignoring sign) is greater than MAX_NORM of the specified destination format, then the result is sign-preserved MAX_NORM of the destination format.
Notes
A source register wider than the specified type may be used, except when the source operand has
.bf16
or .bf16x2
format. The lower n
bits corresponding to the instruction-type width
are used in the conversion. See Operand Size Exceeding Instruction-Type Size for a description of these relaxed
type-checking rules.
A destination register wider than the specified type may be used, except when the destination
operand has .bf16
, .bf16x2
or .tf32
format. The result of conversion is sign-extended to
the destination register width for signed integers, and is zero-extended to the destination register
width for unsigned, bit-size, and floating-point types. See Operand Size Exceeding Instruction-Type
Size for a description of these relaxed
type-checking rules.
For cvt.f32.bf16
, NaN
input yields unspecified NaN
.
PTX ISA Notes
Introduced in PTX ISA version 1.0.
.relu
modifier and {.f16x2
, .bf16
, .bf16x2
, .tf32
} destination formats
introduced in PTX ISA version 7.0.
cvt.bf16.{u8/s8/u16/s16/u32/s32/u64/s64/f16/f64/bf16}
,
cvt.{u8/s8/u16/s16/u32/s32/u64/s64/f16/f64}.bf16
, and cvt.tf32.f32.{relu}.{rn/rz}
introduced
in PTX ISA 7.8.
cvt
with .e4m3x2
/.e5m2x2
for sm_90
or higher introduced in PTX ISA version 7.8.
cvt.satfinite.{e4m3x2, e5m2x2}.{f32, f16x2}
for sm_90
or higher introduced in PTX ISA version 7.8.
cvt
with .e4m3x2
/.e5m2x2
for sm_89
introduced in PTX ISA version 8.1.
cvt.satfinite.{e4m3x2, e5m2x2}.{f32, f16x2}
for sm_89
introduced in PTX ISA version 8.1.
cvt.satfinite.{f16, bf16, f16x2, bf16x2, tf32}.f32
introduced in PTX ISA version 8.1.
Target ISA Notes
cvt
to or from .f64
requires sm_13
or higher.
.relu
modifier and {.f16x2
, .bf16
, .bf16x2
, .tf32
} destination formats require
sm_80
or higher.
cvt.bf16.{u8/s8/u16/s16/u32/s32/u64/s64/f16/f64/bf16}
,
cvt.{u8/s8/u16/s16/u32/s32/u64/s64/f16/f64}.bf16
, and cvt.tf32.f32.{relu}.{rn/rz}
require
sm_90
or higher.
cvt
with .e4m3x2
/.e5m2x2
requires sm89
or higher.
cvt.satfinite.{e4m3x2, e5m2x2}.{f32, f16x2}
requires sm_89
or higher.
Examples
cvt.f32.s32 f,i;
cvt.s32.f64 j,r; // float-to-int saturates by default
cvt.rni.f32.f32 x,y; // round to nearest int, result is fp
cvt.f32.f32 x,y; // note .ftz behavior for sm_1x targets
cvt.rn.relu.f16.f32 b, f; // result is saturated with .relu saturation mode
cvt.rz.f16x2.f32 b1, f, f1; // convert two fp32 values to packed fp16 outputs
cvt.rn.relu.satfinite.f16x2.f32 b1, f, f1; // convert two fp32 values to packed fp16 outputs with .relu saturation on each output
cvt.rn.bf16.f32 b, f; // convert fp32 to bf16
cvt.rz.relu.satfinite.bf16.f3 2 b, f; // convert fp32 to bf16 with .relu and .satfinite saturation
cvt.rz.satfinite.bf16x2.f32 b1, f, f1; // convert two fp32 values to packed bf16 outputs
cvt.rn.relu.bf16x2.f32 b1, f, f1; // convert two fp32 values to packed bf16 outputs with .relu saturation on each output
cvt.rna.satfinite.tf32.f32 b1, f; // convert fp32 to tf32 format
cvt.rn.relu.tf32.f32 d, a; // convert fp32 to tf32 format
cvt.f64.bf16.rp f, b; // convert bf16 to f64 format
cvt.bf16.f16.rz b, f // convert f16 to bf16 format
cvt.bf16.u64.rz b, u // convert u64 to bf16 format
cvt.s8.bf16.rpi s, b // convert bf16 to s8 format
cvt.bf16.bf16.rpi b1, b2 // convert bf16 to corresponding int represented in bf16 format
cvt.rn.satfinite.e4m3x2.f32 d, a, b; // convert a, b to .e4m3 and pack as .e4m3x2 output
cvt.rn.relu.satfinite.e5m2x2.f16x2 d, a; // unpack a and convert the values to .e5m2 outputs with .relu
// saturation on each output and pack as .e5m2x2
cvt.rn.f16x2.e4m3x2 d, a; // unpack a, convert two .e4m3 values to packed f16x2 output
9.7.8.21. Data Movement and Conversion Instructions: cvt.pack
cvt.pack
Convert two integer values from one integer type to another and pack the results.
Syntax
cvt.pack.sat.convertType.abType d, a, b;
.convertType = { .u16, .s16 }
.abType = { .s32 }
cvt.pack.sat.convertType.abType.cType d, a, b, c;
.convertType = { .u2, .s2, .u4, .s4, .u8, .s8 }
.abType = { .s32 }
.cType = { .b32 }
Description
Convert two 32-bit integers a
and b
into specified type and pack the results into d
.
Destination d
is an unsigned 32-bit integer. Source operands a
and b
are integers of
type .abType
and the source operand c
is an integer of type .cType
.
The inputs a
and b
are converted to values of type specified by .convertType
with
saturation and the results after conversion are packed into lower bits of d
.
If operand c
is specified then remaining bits of d
are copied from lower bits of c
.
Semantics
ta = a < MIN(convertType) ? MIN(convertType) : a;
ta = a > MAX(convertType) ? MAX(convertType) : a;
tb = b < MIN(convertType) ? MIN(convertType) : b;
tb = b > MAX(convertType) ? MAX(convertType) : b;
size = sizeInBits(convertType);
td = tb ;
for (i = size; i <= 2 * size - 1; i++) {
td[i] = ta[i - size];
}
if (isU16(convertType) || isS16(convertType)) {
d = td;
} else {
for (i = 0; i < 2 * size; i++) {
d[i] = td[i];
}
for (i = 2 * size; i <= 31; i++) {
d[i] = c[i - 2 * size];
}
}
.sat
modifier limits the converted values to MIN(convertType)
..MAX(convertedType)
(no
overflow) if the corresponding inputs are not in the range of datatype specified as
.convertType
.
PTX ISA Notes
Introduced in PTX ISA version 6.5.
Target ISA Notes
Requires sm_72
or higher.
Sub byte types (.u4
/.s4
and .u2
/.s2
) requires sm_75
or higher.
Examples
cvt.pack.sat.s16.s32 %r1, %r2, %r3; // 32-bit to 16-bit conversion
cvt.pack.sat.u8.s32.b32 %r4, %r5, %r6, 0; // 32-bit to 8-bit conversion
cvt.pack.sat.u8.s32.b32 %r7, %r8, %r9, %r4; // %r7 = { %r5, %r6, %r8, %r9 }
cvt.pack.sat.u4.s32.b32 %r10, %r12, %r13, %r14; // 32-bit to 4-bit conversion
cvt.pack.sat.s2.s32.b32 %r15, %r16, %r17, %r18; // 32-bits to 2-bit conversion
9.7.8.22. Data Movement and Conversion Instructions: mapa
mapa
Map the address of the shared variable in the target CTA.
Syntax
mapa{.space}.type d, a, b;
// Maps shared memory address in register a into CTA b.
mapa.shared::cluster.type d, a, b;
// Maps shared memory variable into CTA b.
mapa.shared::cluster.type d, sh, b;
// Maps shared memory variable into CTA b.
mapa.shared::cluster.type d, sh + imm, b;
// Maps generic address in register a into CTA b.
mapa.type d, a, b;
.space = { .shared::cluster }
.type = { .u32, .u64 }
Description
Get address in the CTA specified by operand b
which corresponds to the address specified by
operand a
.
Instruction type .type
indicates the type of the destination operand d
and the source
operand a
.
When space is .shared::cluster
, source a
is either a shared memory variable or a register
containing a valid shared memory address and register d
contains a shared memory address. When
the optional qualifier .space
is not specified, both a
and d
are registers containing
generic addresses pointing to shared memory.
b
is a 32-bit integer operand representing the rank of the target CTA.
Destination register d
will hold an address in CTA b
corresponding to operand a
.
PTX ISA Notes
Introduced in PTX ISA version 7.8.
Target ISA Notes
Requires sm_90
or higher.
Examples
mapa.shared::cluster.u64 d1, %reg1, cta;
mapa.shared::cluster.u32 d2, sh, 3;
mapa.u64 d3, %reg2, cta;
9.7.8.23. Data Movement and Conversion Instructions: getctarank
getctarank
Generate the CTA rank of the address.
Syntax
getctarank{.space}.type d, a;
// Get cta rank from source shared memory address in register a.
getctarank.shared::cluster.type d, a;
// Get cta rank from shared memory variable.
getctarank.shared::cluster.type d, var;
// Get cta rank from shared memory variable+offset.
getctarank.shared::cluster.type d, var + imm;
// Get cta rank from generic address of shared memory variable in register a.
getctarank.type d, a;
.space = { .shared::cluster }
.type = { .u32, .u64 }
Description
Write the destination register d
with the rank of the CTA which contains the address specified
in operand a
.
Instruction type .type
indicates the type of source operand a
.
When space is .shared::cluster
, source a
is either a shared memory variable or a register
containing a valid shared memory address. When the optional qualifier .space
is not specified,
a
is a register containing a generic addresses pointing to shared memory. Destination d
is
always a 32-bit register which holds the rank of the CTA.
PTX ISA Notes
Introduced in PTX ISA version 7.8.
Target ISA Notes
Requires sm_90
or higher.
Examples
getctarank.shared::cluster.u32 d1, addr;
getctarank.shared::cluster.u64 d2, sh + 4;
getctarank.u64 d3, src;
9.7.8.24. Data Movement and Conversion Instructions: Asynchronous copy
An asynchronous copy operation performs the underlying operation asynchronously in the background, thus allowing the issuing threads to perform subsequent tasks.
An asynchronous copy operation can be a bulk operation that operates on a large amount of data, or a non-bulk operation that operates on smaller sized data. The amount of data handled by a bulk asynchronous operation must be a multiple of 16 bytes.
9.7.8.24.1. Completion Mechanisms for Asynchronous Copy Operations
A thread must explicitly wait for the completion of an asynchronous copy operation in order to access the result of the operation. Once an asynchronous copy operation is initiated, modifying the source memory location or reading from the destination memory location before the asynchronous operation completes, will cause unpredictable results.
This section describes two asynchronous copy operation completion mechanisms supported in PTX: Async-group mechanism and mbarrier-based mechanism.
Async-group mechanism
When using the async-group completion mechanism, the issuing thread specifies a group of asynchronous operations, called async-group, using a commit operation and tracks the completion of this group using a wait operation. The thread issuing the asynchronous operation must create separate async-groups for bulk and non-bulk asynchronous operations.
A commit operation creates a per-thread async-group containing all prior asynchronous operations initiated by the executing thread but none of the asynchronous operations following the commit operation. A committed asynchronous operation belongs to a single async-group.
When an async-group completes, all the asynchronous operations belonging to that group are complete and the executing thread that initiated the asynchronous operations can read the result of the asynchronous operations. All async-groups committed by an executing thread always complete in the order in which they were committed. There is no ordering between asynchronous operations within an async-group.
A typical pattern of using async-group as the completion mechanism is as follows:
Initiate the asynchronous operations.
Group the asynchronous operations into an async-group using a commit operation.
Wait for the completion of the async-group using the wait operation.
Once the async-group completes, access the results of all asynchronous operations in that async-group.
Mbarrier-based mechanism
A thread can track the completion of one or more asynchronous operations using the current phase of an mbarrier object. When the current phase of the mbarrier object is complete, it implies that all asynchronous operations tracked by this phase are complete, and all threads participating in that mbarrier object can access the result of the asynchronous operations.
The mbarrier object to be used for tracking the completion of an asynchronous operation can be either specified along with the asynchronous operation as part of its syntax, or as a separate operation. For a bulk asynchronous operation, the mbarrier object must be specified in the asynchronous operation, whereas for non-bulk operations, it can be specified after the asynchronous operation.
A typical pattern of using mbarrier-based completion mechanism is as follows:
Initiate the asynchronous operations.
Set up an mbarrier object to track the asynchronous operations in its current phase, either as part of the asynchronous operation or as a separate operation.
Wait for the mbarrier object to complete its current phase using
mbarrier.test_wait
ormbarrier.try_wait
.Once the
mbarrier.test_wait
ormbarrier.try_wait
operation returnsTrue
, access the results of the asynchronous operations tracked by the mbarrier object.
9.7.8.24.2. Async Proxy
The cp{.reduce}.async.bulk
operations are performed in the asynchronous proxy (or async
proxy).
Accessing the same memory location across multiple proxies needs a cross-proxy fence. For the
async proxy, fence.proxy.async
should be used to synchronize memory between generic
proxy and the async proxy.
The completion of a cp{.reduce}.async.bulk
operation is followed by an implicit generic-async
proxy fence. So the result of the asynchronous operation is made visible to the generic proxy as
soon as its completion is observed. Async-group OR mbarrier-based completion mechanism must
be used to wait for the completion of the cp{.reduce}.async.bulk
instructions.
9.7.8.24.3. Data Movement and Conversion Instructions: cp.async
cp.async
Initiates an asynchronous copy operation from one state space to another.
Syntax
cp.async.ca.shared{::cta}.global{.level::cache_hint}{.level::prefetch_size}
[dst], [src], cp-size{, src-size}{, cache-policy} ;
cp.async.cg.shared{::cta}.global{.level::cache_hint}{.level::prefetch_size}
[dst], [src], 16{, src-size}{, cache-policy} ;
cp.async.ca.shared{::cta}.global{.level::cache_hint}{.level::prefetch_size}
[dst], [src], cp-size{, ignore-src}{, cache-policy} ;
cp.async.cg.shared{::cta}.global{.level::cache_hint}{.level::prefetch_size}
[dst], [src], 16{, ignore-src}{, cache-policy} ;
.level::cache_hint = { .L2::cache_hint }
.level::prefetch_size = { .L2::64B, .L2::128B, .L2::256B }
cp-size = { 4, 8, 16 }
Description
cp.async
is a non-blocking instruction which initiates an asynchronous copy operation of data
from the location specified by source address operand src
to the location specified by
destination address operand dst
. Operand src
specifies a location in the global state space
and dst
specifies a location in the shared state space.
Operand cp-size
is an integer constant which specifies the size of data in bytes to be copied to
the destination dst
. cp-size
can only be 4, 8 and 16.
Instruction cp.async
allows optionally specifying a 32-bit integer operand src-size
. Operand
src-size
represents the size of the data in bytes to be copied from src
to dst
and must
be less than cp-size
. In such case, remaining bytes in destination dst
are filled with
zeros. Specifying src-size
larger than cp-size
results in undefined behavior.
The optional and non-immediate predicate argument ignore-src
specifies whether the data from the
source location src
should be ignored completely. If the source data is ignored then zeros will
be copied to destination dst
. If the argument ignore-src
is not specified then it defaults
to False
.
Supported alignment requirements and addressing modes for operand src
and dst
are described
in Addresses as Operands.
The mandatory .async
qualifier indicates that the cp
instruction will initiate the memory
copy operation asynchronously and control will return to the executing thread before the copy
operation is complete. The executing thread can then use cp.async.wait_all
or
cp.async.wait_group
or mbarrier instructions to wait for
completion of the asynchronous copy operation. No other synchronization mechanisms described in
Memory Consistency Model can be used to guarantee the
completion of the asynchronous copy operations.
There is no ordering guarantee between two cp.async
operations if they are not explicitly
synchronized using cp.async.wait_all
or cp.async.wait_group
or mbarrier instructions.
As described in Cache Operators, the .cg
qualifier indicates
caching of data only at global level cache L2 and not at L1 whereas .ca
qualifier indicates
caching of data at all levels including L1 cache. Cache operator are treated as performance hints
only.
cp.async
is treated as a weak memory operation in the Memory Consistency Model.
The .level::prefetch_size
qualifier is a hint to fetch additional data of the specified size
into the respective cache level.The sub-qualifier prefetch_size
can be set to either of 64B
,
128B
, 256B
thereby allowing the prefetch size to be 64 Bytes, 128 Bytes or 256 Bytes
respectively.
The qualifier .level::prefetch_size
may only be used with .global
state space and with
generic addressing where the address points to .global
state space. If the generic address does
not fall within the address window of the global memory, then the prefetching behavior is undefined.
The .level::prefetch_size
qualifier is treated as a performance hint only.
When the optional argument cache-policy
is specified, the qualifier .level::cache_hint
is
required. The 64-bit operand cache-policy
specifies the cache eviction policy that may be used
during the memory access.
The qualifier .level::cache_hint
is only supported for .global
state space and for generic
addressing where the address points to the .global
state space.
cache-policy
is a hint to the cache subsystem and may not always be respected. It is treated as
a performance hint only, and does not change the memory consistency behavior of the program.
PTX ISA Notes
Introduced in PTX ISA version 7.0.
Support for .level::cache_hint
and .level::prefetch_size
qualifiers introduced in PTX ISA
version 7.4.
Support for ignore-src
operand introduced in PTX ISA version 7.5.
Support for sub-qualifier ::cta
introduced in PTX ISA version 7.8.
Target ISA Notes
Requires sm_80
or higher.
Sub-qualifier ::cta
requires sm_30
or higher.
Examples
cp.async.ca.shared.global [shrd], [gbl + 4], 4;
cp.async.ca.shared::cta.global [%r0 + 8], [%r1], 8;
cp.async.cg.shared.global [%r2], [%r3], 16;
cp.async.cg.shared.global.L2::64B [%r2], [%r3], 16;
cp.async.cg.shared.global.L2::128B [%r0 + 16], [%r1], 16;
cp.async.cg.shared.global.L2::256B [%r2 + 32], [%r3], 16;
createpolicy.fractional.L2::evict_last.L2::evict_unchanged.b64 cache-policy, 0.25;
cp.async.ca.shared.global.L2::cache_hint [%r2], [%r1], 4, cache-policy;
cp.async.ca.shared.global [shrd], [gbl], 4, p;
cp.async.cg.shared.global.L2::cache_hint [%r0], [%r2], 16, q, cache-policy;
9.7.8.24.4. Data Movement and Conversion Instructions: cp.async.commit_group
cp.async.commit_group
Commits all prior initiated but uncommitted cp.async
instructions into a cp.async-group.
Syntax
cp.async.commit_group ;
Description
cp.async.commit_group
instruction creates a new cp.async-group per thread and batches all
prior cp.async
instructions initiated by the executing thread but not committed to any
cp.async-group into the new cp.async-group. If there are no uncommitted cp.async
instructions then cp.async.commit_group
results in an empty cp.async-group.
An executing thread can wait for the completion of all cp.async
operations in a cp.async-group
using cp.async.wait_group
.
There is no memory ordering guarantee provided between any two cp.async
operations within the
same cp.async-group. So two or more cp.async
operations within a cp.async-group copying data
to the same location results in undefined behavior.
PTX ISA Notes
Introduced in PTX ISA version 7.0.
Target ISA Notes
Requires sm_80
or higher.
Examples
// Example 1:
cp.async.ca.shared.global [shrd], [gbl], 4;
cp.async.commit_group ; // Marks the end of a cp.async group
// Example 2:
cp.async.ca.shared.global [shrd1], [gbl1], 8;
cp.async.ca.shared.global [shrd1+8], [gbl1+8], 8;
cp.async.commit_group ; // Marks the end of cp.async group 1
cp.async.ca.shared.global [shrd2], [gbl2], 16;
cp.async.cg.shared.global [shrd2+16], [gbl2+16], 16;
cp.async.commit_group ; // Marks the end of cp.async group 2
9.7.8.24.5. Data Movement and Conversion Instructions: cp.async.wait_group / cp.async.wait_all
cp.async.wait_group/cp.async.wait_all
Wait for completion of prior asynchronous copy operations.
Syntax
cp.async.wait_group N;
cp.async.wait_all ;
Description
cp.async.wait_group
instruction will cause executing thread to wait till only N
or fewer of
the most recent cp.async-groups are pending and all the prior cp.async-groups committed by
the executing threads are complete. For example, when N
is 0, the executing thread waits on all
the prior cp.async-groups to complete. Operand N
is an integer constant.
cp.async.wait_all
is equivalent to :
cp.async.commit_group;
cp.async.wait_group 0;
An empty cp.async-group is considered to be trivially complete.
Writes performed by cp.async
operations are made visible to the executing thread only after:
The completion of
cp.async.wait_all
orThe completion of
cp.async.wait_group
on the cp.async-group in which thecp.async
belongs to ormbarrier.test_wait returns
True
on an mbarrier object which is tracking the completion of thecp.async
operation.
There is no ordering between two cp.async
operations that are not synchronized with
cp.async.wait_all
or cp.async.wait_group
or mbarrier objects.
cp.async.wait_group
and cp.async.wait_all
does not provide any ordering and visibility
guarantees for any other memory operation apart from cp.async
.
PTX ISA Notes
Introduced in PTX ISA version 7.0.
Target ISA Notes
Requires sm_80
or higher.
Examples
// Example of .wait_all:
cp.async.ca.shared.global [shrd1], [gbl1], 4;
cp.async.cg.shared.global [shrd2], [gbl2], 16;
cp.async.wait_all; // waits for all prior cp.async to complete
// Example of .wait_group :
cp.async.ca.shared.global [shrd3], [gbl3], 8;
cp.async.commit_group; // End of group 1
cp.async.cg.shared.global [shrd4], [gbl4], 16;
cp.async.commit_group; // End of group 2
cp.async.cg.shared.global [shrd5], [gbl5], 16;
cp.async.commit_group; // End of group 3
cp.async.wait_group 1; // waits for group 1 and group 2 to complete
9.7.8.24.6. Data Movement and Conversion Instructions: cp.async.bulk
cp.async.bulk
Initiates an asynchronous copy operation from one state space to another.
Syntax
cp.async.bulk.dst.src.completion_mechanism{.multicast}{.level::cache_hint}
[dstMem], [srcMem], size, [mbar] {, ctaMask} {, cache-policy}
.dst = { .shared::cluster }
.src = { .global }
.completion_mechanism = { .mbarrier::complete_tx::bytes }
.level::cache_hint = { .L2::cache_hint }
.multicast = { .multicast::cluster }
cp.async.bulk.dst.src.completion_mechanism [dstMem], [srcMem], size, [mbar]
.dst = { .shared::cluster }
.src = { .shared::cta }
.completion_mechanism = { .mbarrier::complete_tx::bytes }
cp.async.bulk.dst.src.completion_mechanism{.level::cache_hint} [dstMem], [srcMem], size{, cache-policy}
.dst = { .global }
.src = { .shared::cta }
.completion_mechanism = { .bulk_group }
.level::cache_hint = { .L2::cache_hint }
Description
cp.async.bulk
is a non-blocking instruction which initiates an asynchronous bulk-copy operation
from the location specified by source address operand srcMem
to the location specified by
destination address operand dstMem
.
The direction of bulk-copy is from the state space specified by the .src
modifier to the state
space specified by the .dst
modifiers.
The 32-bit operand size
specifies the amount of memory to be copied, in terms of number of
bytes. size
must be a multiple of 16. If the value is not a multiple of 16, then the behavior is
undefined. The memory range [dstMem, dstMem + size - 1]
must not overflow the destination memory
space and the memory range [srcMem, srcMem + size - 1]
must not overflow the source memory
space. Otherwise, the behavior is undefined. The addresses dstMem
and srcMem
must be aligned
to 16 bytes.
When the source of the copy is .shared::cta
and the destination is .shared::cluster
, the
destination has to be in the shared memory of a different CTA within the cluster.
The modifier .completion_mechanism
specifies the completion mechanism that is supported on the
instruction variant. The completion mechanisms that are supported for different variants are
summarized in the following table:
Completion mechanism |
|
|
Description |
---|---|---|---|
|
|
|
mbarrier based completion mechanism |
|
|
||
|
|
|
Bulk async-group based completion mechanism |
The modifier .mbarrier::complete_tx::bytes
specifies that the cp.async.bulk
variant uses
mbarrier based completion mechanism. The complete-tx
operation, with completeCount
argument equal to amount of data copied in bytes, will be
performed on the mbarrier object specified by the operand mbar
.
The modifier .bulk_group
specifies that the cp.async.bulk
variant uses bulk async-group
based completion mechanism.
The optional modifier .multicast::cluster
allows copying of data from global memory to shared
memory of multiple CTAs in the cluster. Operand ctaMask
specifies the destination CTAs in the
cluster such that each bit position in the 16-bit ctaMask
operand corresponds to the %ctaid
of the destination CTA. The source data is multicast to the same CTA-relative offset as dstMem
in the shared memory of each destination CTA. The mbarrier signal is also multicast to the same
CTA-relative offset as mbar
in the shared memory of the destination CTA.
When the optional argument cache-policy
is specified, the qualifier .level::cache_hint
is
required. The 64-bit operand cache-policy
specifies the cache eviction policy that may be used
during the memory access.
cache-policy
is a hint to the cache subsystem and may not always be respected. It is treated as
a performance hint only, and does not change the memory consistency behavior of the program. The
qualifier .level::cache_hint
is only supported when at least one of the .src
or .dst
statespaces is .global
state space.
The copy operation in cp.async.bulk
is treated as a weak memory operation and the complete-tx
operation on the mbarrier has .release
semantics at the .cluster
scope as described in the
Memory Consistency Model.
Notes
.multicast::cluster
qualifier is optimized for target architecture sm_90a
and may have
substantially reduced performance on other targets and hence .multicast::cluster
is advised to
be used with .target
sm_90a
.
PTX ISA Notes
Introduced in PTX ISA version 8.0.
Target ISA Notes
Requires sm_90
or higher.
.multicast::cluster
qualifier advised to be used with .target
sm_90a
.
Examples
// .global -> .shared::cluster:
cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes [dstMem], [srcMem], size, [mbar];
cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes.multicast::cluster
[dstMem], [srcMem], size, [mbar], ctaMask;
cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint
[dstMem], [srcMem], size, [mbar], cache-policy;
// .shared::cta -> .shared::cluster (strictly remote):
cp.async.bulk.shared::cluster.shared::cta.mbarrier::complete_tx::bytes [dstMem], [srcMem], size, [mbar];
// .shared::cta -> .global:
cp.async.bulk.global.shared::cta.bulk_group [dstMem], [srcMem], size;
cp.async.bulk.global.shared::cta.bulk_group.L2::cache_hint} [dstMem], [srcMem], size, cache-policy;
9.7.8.24.7. Data Movement and Conversion Instructions: cp.reduce.async.bulk
cp.reduce.async.bulk
Initiates an asynchronous reduction operation.
Syntax
cp.reduce.async.bulk.dst.src.completion_mechanism.redOp.type
[dstMem], [srcMem], size, [mbar]
.dst = { .shared::cluster }
.src = { .shared::cta }
.completion_mechanism = { .mbarrier::complete_tx::bytes }
.redOp= { .and, .or, .xor,
.add, .inc, .dec,
.min, .max }
.type = { .b32, .u32, .s32, .b64, .u64 }
cp.reduce.async.bulk.dst.src.completion_mechanism{.level::cache_hint}.redOp.type
[dstMem], [srcMem], size{, cache-policy}
.dst = { .global }
.src = { .shared::cta }
.completion_mechanism = { .bulk_group }
.level::cache_hint = { .L2::cache_hint }
.redOp= { .and, .or, .xor,
.add, .inc, .dec,
.min, .max }
.type = { .f16, .bf16, .b32, .u32, .s32, .b64, .u64, .s64, .f32, .f64 }
cp.reduce.async.bulk.dst.src.completion_mechanism{.level::cache_hint}.add.noftz.type
[dstMem], [srcMem], size{, cache-policy}
.dst = { .global }
.src = { .shared::cta }
.completion_mechanism = { .bulk_group }
.type = { .f16, .bf16 }
Description
cp.reduce.async.bulk
is a non-blocking instruction which initiates an asynchronous reduction
operation on an array of memory locations specified by the destination address operand dstMem
with the source array whose location is specified by the source address operand srcMem
. The size
of the source and the destination array must be the same and is specified by the operand size
.
Each data element in the destination array is reduced inline with the corresponding data element in
the source array with the reduction operation specified by the modifier .redOp
. The type of each
data element in the source and the destination array is specified by the modifier .type
.
The source address operand srcMem
is located in the state space specified by .src
and the
destination address operand dstMem
is located in the state specified by the .dst
.
The 32-bit operand size
specifies the amount of memory to be copied from the source location and
used in the reduction operation, in terms of number of bytes. size
must be a multiple of 16. If
the value is not a multiple of 16, then the behavior is undefined. The memory range [dstMem,
dstMem + size - 1]
must not overflow the destination memory space and the memory range [srcMem,
srcMem + size - 1]
must not overflow the source memory space. Otherwise, the behavior is
undefined. The addresses dstMem
and srcMem
must be aligned to 16 bytes.
The operations supported by .redOp
are classified as follows:
The bit-size operations are
.and
,.or
, and.xor
.The integer operations are
.add
,.inc
,.dec
,.min
, and.max
. The.inc
and.dec
operations return a result in the range[0..x]
wherex
is the value at the source state space.The floating point operation
.add
rounds to the nearest even. The current implementation ofcp.reduce.async.bulk.add.f32
flushes subnormal inputs and results to sign-preserving zero. Thecp.reduce.async.bulk.add.f16
andcp.reduce.async.bulk.add.bf16
operations require.noftz
qualifier. It preserves input and result subnormals, and does not flush them to zero.
The following table describes the valid combinations of .redOp
and element type:
|
|
Element type |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4.2. Comments
Comments in PTX follow C/C++ syntax, using non-nested
/*
and*/
for comments that may span multiple lines, and using//
to begin a comment that extends up to the next newline character, which terminates the current line. Comments cannot occur within character constants, string literals, or within other comments.Comments in PTX are treated as whitespace.