NVIDIA HPC Fortran Compiler User’s Guide

Preface

This guide is part of a set of manuals that describe how to use the NVIDIA HPC Fortran compiler, NVFORTRAN. The compiler works in conjunction with an assembler, linker, libraries and header files on your target system, and includes a CUDA toolchain, libraries and header files for GPU computing. You can use the NVIDIA HPC Fortran compiler to develop, optimize and parallelize applications for NVIDIA GPUs and x86-64 and Arm Server multicore CPUs.

The NVIDIA HPC Fortran Compiler User’s Guide provides operating instructions for the NVFORTRAN command-line development environment. The NVIDIA HPC Fortran Compiler Reference Guide contains details concerning the NVFORTRAN compiler’s interpretation of the Fortran language standards, implementation of language extensions, and command-line compilation. Users are expected to have previous experience with or knowledge of the Fortran programming language. These guides do not teach the Fortran programming language.

The NVIDIA HPC C and C++ compilers, NVC and NVC++, are described in a companion set of manuals: the NVIDIA HPC C and C++ Compilers User’s Guide and the NVIDIA HPC C and C++ Compilers Reference Guide.

Audience Description

This manual is intended for scientists and engineers using the NVIDIA HPC Fortran compiler. To use this compiler, you should be aware of the role of high-level languages, such as Fortran, as well as parallel programming models such as CUDA, OpenACC and OpenMP in the software development process, and you should have some level of understanding of programming. The NVIDIA HPC Fortran compiler is available for a variety of NVIDIA GPUs and x86-64 and Arm CPU-based platforms and operating systems. You need to be familiar with the basic commands available on your system.

Compatibility and Conformance to Standards

Your system needs to be running a properly installed and configured version of the NVIDIA HPC Fortran compiler. For information on installing the NVIDIA HPC compilers, refer to the Release Notes and Installation Guide included with your software.

The NVIDIA HPC Fortran compiler supports Fortran 2018 language features and selected Fortran 2023 features. Feature availability and limitations are described in this guide and the release notes.

For further information, refer to the following:

  • American National Standard Programming Language FORTRAN, ANSI X3. -1978 (1978).

  • ISO/IEC 1539-1 : 1991, Information technology – Programming Languages – Fortran, Geneva, 1991 (Fortran 90).

  • ISO/IEC 1539-1 : 1997, Information technology – Programming Languages – Fortran, Geneva, 1997 (Fortran 95).

  • ISO/IEC 1539-1 : 2004, Information technology – Programming Languages – Fortran, Geneva, 2004 (Fortran 2003).

  • ISO/IEC 1539-1 : 2010, Information technology – Programming Languages – Fortran, Geneva, 2010 (Fortran 2008).

  • ISO/IEC 1539-1 : 2018, Information technology – Programming Languages – Fortran, Geneva, 2018 (Fortran 2018).

  • ISO/IEC 1539-1:2023, Programming languages – Fortran – Part 1: Base language (Fortran 2023).

  • OpenACC Application Program Interface, Version 2.7, November 2018, http://www.openacc.org.

  • OpenACC Application Programming Interface, Version 3.3, November 2022, https://www.openacc.org.

  • OpenMP Application Program Interface, Version 5.0, November 2018, http://www.openmp.org.

Organization

This guide contains the essential information on how to use the NVIDIA HPC Fortran compiler and is divided into these sections:

Getting Started provides an introduction to the NVIDIA HPC Fortran compiler and describes its use and overall features.

Use Command-line Options provides an overview of the command-line options as well as task-related lists of options.

Multicore CPU Optimization describes multicore CPU optimizations and related compiler options.

Using GPUs gives an overview of the options for programming NVIDIA GPUs and covers topics that affect GPU programming when using one or more of the GPU programming models.

Using OpenACC describes how to use an NVIDIA GPU and gives an introduction to using OpenACC.

Using OpenMP describes how to use OpenMP for multicore CPU programming.

Using Stdpar describes how to use ISO Fortran standard language parallelism (DO CONCURRENT, array intrinsics) for programming an NVIDIA GPU or multicore CPU.

PCAST describes how to use the Parallel Compiler Assisted Testing features of the NVIDIA HPC Fortran compiler. The comparison-directive mode controlled by -Mpcast is not available in this NG beta.

Using MPI describes how to use MPI with the NVIDIA HPC Fortran compiler.

Creating and Using Libraries discusses NVIDIA HPC Fortran compiler support libraries, shared object files, and environment variables that affect the behavior of the compiler.

Environment Variables describes the environment variables that affect the behavior of the NVIDIA HPC Fortran compiler.

Distributing Files – Deployment describes the deployment of your files once you have built, debugged and compiled them successfully.

Inter-language Calling provides examples showing how to place C and C++ language calls in a Fortran program and Fortran language calls in a C or C++ program.

Programming Considerations for 64-Bit Environments discusses issues of which programmers should be aware when targeting 64-bit processors.

Hardware and Software Constraints

This guide describes versions of the NVIDIA HPC Fortran compiler that target NVIDIA GPUs and x86-64 and Arm CPUs. Details concerning environment-specific values and defaults and system-specific features or limitations are presented in the release notes delivered with the NVIDIA HPC compilers.

Conventions

This guide uses the following conventions:

italic

is used for emphasis.

Constant Width

is used for filenames, directories, arguments, options, examples, and for language statements in the text, including assembly language statements.

Bold

is used for commands.

[ item1 ]

in general, square brackets indicate optional items. In this case item1 is optional. In the context of p/t-sets, square brackets are required to specify a p/t-set.

{ item2 | item 3 }

braces indicate that a selection is required. In this case, you must select either item2 or item3.

filename …

an ellipsis indicates repetition. Zero or more of the preceding item may occur. In this example, multiple filenames are allowed.

FORTRAN

Fortran language statements are shown in the text of this guide using a reduced fixed point size.

Terms

The following table lists the NVIDIA HPC Fortran compiler and its corresponding command:

Table 1 NVIDIA HPC Fortran Compiler and Command

Compiler or Tool

Language or Function

Command

NVFORTRAN

ISO/ANSI Fortran

nvfortran

In general, the designation NVFORTRAN is used to refer to the NVIDIA Fortran compiler, and nvfortran is used to refer to the command that invokes the compiler.

Examples of command-line invocation of the compiler in this guide use the nvfortran command, and source code examples are written in Fortran. The NVIDIA HPC C and C++ compilers, NVC and NVC++, have command-line options and features that do not apply to NVFORTRAN, and vice versa; they are documented in the NVIDIA HPC C and C++ Compilers User’s Guide.

There are a wide variety of x86-64 CPUs in use. Most of these CPUs are forward-compatible, but not backward-compatible, meaning that code compiled to target a given processor will not necessarily execute correctly on a previous-generation processor.

A table listing the processor options that the NVIDIA HPC Fortran compiler supports is available in the Release Notes. The table also includes the features utilized by the compiler that distinguish them from a compatibility standpoint.

In this manual, the convention is to use “x86-64” to specify the group of CPUs that are x86-compatible, 64-bit enabled, and run a 64-bit operating system. x86-64 processors can differ in terms of their support for various prefetch, SSE and AVX instructions. Where such distinctions are important with respect to a given compiler option or feature, it is explicitly noted in this manual.

Related Publications

The following documents contain additional information related to the NVIDIA HPC Fortran compiler.

  • System V Application Binary Interface Processor Supplement by AT&T UNIX System Laboratories, Inc. (Prentice Hall, Inc.).

  • System V Application Binary Interface X86-64 Architecture Processor Supplement.

1. Getting Started

This section describes how to use the NVIDIA HPC Fortran compiler.

1.1. Overview

The command used to invoke the compiler, the nvfortran command, is called a compiler driver. The compiler driver controls the following phases of compilation: preprocessing, compiling, assembling, and linking. Once a file is compiled and an executable file is produced, you can execute, debug, or profile the program on your system.

In general, using the NVIDIA HPC Fortran compiler involves three steps:

  1. Produce program source code in a file containing a .f extension or another appropriate extension, as described in Input Files. This program may be one that you have written or one that you are modifying.

  2. Compile the program using the nvfortran command.

  3. Execute, debug, or profile the executable file on your system.

You might also want to deploy your application, though this is not a required step.

The NVIDIA HPC Fortran compiler allows many variations on these general program development steps. These variations include the following:

  • Stop the compilation after preprocessing, compiling or assembling to save and examine intermediate results.

  • Provide options to the driver that control compiler optimization or that specify various features or limitations.

  • Include as input intermediate files such as preprocessor output, compiler output, or assembler output.

1.2. Creating an Example

Let’s look at a simple example of using the NVIDIA Fortran compiler to create, compile, and execute a program that prints:

hello
  1. Create your program. For this example, suppose you enter the following simple Fortran program in the file hello.f:

    print *, "hello"
    end
    
  2. Compile the program. When you created your program, you called it hello.f. In this example, we compile it from a shell command prompt using the default nvfortran driver option. Use the following syntax:

    $ nvfortran hello.f
    

    By default, the executable output is placed in the file a.out. However, you can specify an output file name by using the o option.

    To place the executable output in the file hello, use this command:

    $ nvfortran -o hello hello.f
    
  3. Execute the program. To execute the resulting hello program, simply type the filename at the command prompt and press the Return or Enter key on your keyboard:

    $ hello
    

    Below is the expected output:

    hello
    

1.3. Invoking the Command-level NVIDIA HPC Fortran Compiler

To translate and link a Fortran program, the nvfortran command does the following:

  1. Preprocess the source text file.

  2. Check the syntax of the source text.

  3. Generate an assembly language file.

  4. Pass control to the subsequent assembly and linking steps.

1.3.1. Command-line Syntax

The compiler command-line syntax is:

nvfortran [options] [path]filename [...]

Where:

options

is one or more command-line options, all of which are described in detail in Use Command-line Options.

path

is the pathname to the directory containing the file named by filename. If you do not specify the path for a filename, the compiler uses the current directory. You must specify the path separately for each filename not in the current directory.

filename

is the name of a source file, preprocessed source file, assembly-language file, object file, or library to be processed by the compilation system. You can specify more than one [path]filename.

1.3.2. Command-line Options

The command-line options control various aspects of the compilation process. For a complete alphabetical listing and a description of all the command-line options, refer to Use Command-Line Options.

The following list provides important information about proper use of command-line options.

  • Command-line options and their arguments are case sensitive.

  • The compiler driver recognizes characters preceded by a hyphen (-) as command-line options. For example, the -Mlist option specifies that the compiler creates a listing file.

    Note

    The convention for the text of this manual is to show command-line options using a dash instead of a hyphen; for example, you see -Mlist.

  • The order of options and the filename is flexible. That is, you can place options before and after the filename argument on the command line. However, the placement of some options is significant, such as the -l option, in which the order of the filenames determines the search order.

    Note

    If two or more options contradict each other, the last one in the command line takes precedence.

  • You may write linker options into a text file prefixed with the ‘@’ symbol, e.g. @file, and pass that file to the compiler as an option. The contents of @file are passed to the linker.

    $ echo "foo.o bar.o" > ./option_file.rsp
    $ nvfortran @./option_file.rsp
    

    The above will pass “foo.o bar.o” to the compiler as linker arguments.

1.4. Filename Conventions

The NVIDIA HPC Fortran compiler uses the filenames that you specify on the command line to find and to create input and output files. This section describes the input and output filename conventions for the phases of the compilation process.

1.4.1. Input Files

You can specify assembly-language files, preprocessed source files, Fortran source files, object files, and libraries as inputs on the command line. The compiler driver determines the type of each input file by examining the filename extensions.

The driver uses the following conventions:

filename.f

indicates a Fortran source file.

filename.F

indicates a Fortran source file that can contain macros and preprocessor directives (to be preprocessed).

filename.FOR

indicates a Fortran source file that can contain macros and preprocessor directives (to be preprocessed).

filename.F90

indicates a Fortran 90/95 source file that can contain macros and preprocessor directives (to be preprocessed).

filename.F95

indicates a Fortran 90/95 source file that can contain macros and preprocessor directives (to be preprocessed).

filename.f90

indicates a Fortran 90/95 source file that is in freeform format.

filename.f95

indicates a Fortran 90/95 source file that is in freeform format.

filename.cuf

indicates a Fortran 90/95 source file in free format with CUDA Fortran extensions.

filename.CUF

indicates a Fortran 90/95 source file in free format with CUDA Fortran extensions and that can contain macros and preprocessor directives (to be preprocessed).

filename.s

indicates an assembly-language file.

filename.o

(Linux) indicates an object file.

filename.a

(Linux) indicates a library of object files.

filename.so

(Linux only) indicates a library of shared object files.

The driver passes files with .s extensions to the assembler and files with .o, .so and .a extensions to the linker. Input files with unrecognized extensions, or no extension, are also passed to the linker.

Files with a .F (Capital F) or .FOR suffix are first preprocessed by the Fortran compiler and the output is passed to the compilation phase. The Fortran preprocessor functions like cpp for C programs, but is built in to the Fortran compiler rather than implemented through an invocation of cpp. This design ensures consistency in the preprocessing step regardless of the type or revision of operating system under which you are compiling.

Any input files not needed for a particular phase of processing are not processed. For example, if on the command line you specify an assembly-language file (filename.s) and the -S option to stop before the assembly phase, the compiler takes no action on the assembly language file. Processing stops after compilation and the assembler does not run. In this scenario, the compilation must have been completed in a previous pass which created the .s file. For a complete description of the -S option, refer to Output Files.

In addition to specifying primary input files on the command line, code within other files can be compiled as part of include files using the INCLUDE statement in a Fortran source file or the preprocessor #include directive in Fortran source files that use a .F extension.

When linking a program with a library, the linker extracts only those library components that the program needs. The compiler driver links in several libraries by default. For more information about libraries, refer to Create and Use Libraries.

1.4.2. Output Files

By default, an executable output file produced by the NVIDIA HPC Fortran compiler is placed in the file a.out. As the Hello example shows, you can use the -o option to specify the output file name.

If you use option -F, -S or -c, the compiler produces a file containing the output of the last completed phase for each input file, as specified by the option supplied.

The output file is a preprocessed source file, an assembly-language file, or an unlinked object file respectively. Similarly, the -E option does not produce a file, but displays the preprocessed source file on the standard output. Using any of these options, the -o option is valid only if you specify a single input file. If no errors occur during processing, you can use the files created by these options as input to a future invocation of the nvfortran compiler driver.

The following table lists the stop-after options and the output files that the compiler creates when you use these options. It also indicates the accepted input files.

Table 2 Option Descriptions

Option

Stop After

Input

Output

-E

preprocessing

Source files

preprocessed file to standard out

-F

preprocessing

Source files.

preprocessed file (.f)

-S

compilation

Source files or preprocessed files

assembly-language file (.s)

-c

assembly

Source files, or preprocessed files, or assembly-language files

unlinked object file (.o or .obj)

none

linking

Source files, or preprocessed files, assembly-language files, object files, or libraries

executable file (a.out)

If you specify multiple input files or do not specify an object filename, the compiler uses the input filenames to derive corresponding default output filenames of the following form, where filename is the input filename without its extension:

filename.f

indicates a preprocessed file, if you compiled a Fortran file using the -⁠F option.

filename.lst

indicates a listing file from the -⁠Mlist option.

filename.o or filename.obj

indicates a object file from the -⁠c option.

filename.s

indicates an assembly-language file from the -⁠S option.

Note

Unless you specify otherwise, the destination directory for any output file is the current working directory. If the file exists in the destination directory, the compiler overwrites it.

The following example demonstrates the use of output filename extensions.

$ nvfortran -c proto.f proto1.F

This produces the output files proto.o and proto1.o, which are binary object files. Prior to compilation, the file proto1.F is preprocessed because it has a .F filename extension.

1.5. Fortran Data Types

The NVIDIA Fortran compiler recognizes scalar and aggregate data types. A scalar data type holds a single value, such as the integer value 42 or the real value 112.6. An aggregate data type consists of one or more scalar data type objects, such as an array of integer values.

1.6. Platform-specific considerations

The NVIDIA HPC Fortran compiler is supported on x86-64 and 64-bit Arm multicore CPUs running Linux.

1.7. Site-Specific Customization of the Compiler

If you are using the NVIDIA HPC Fortran compiler and want all your users to have access to specific libraries or other files, there are special files that allow you to customize the compiler for your site.

1.7.1. Use siterc Files

The NVIDIA HPC Fortran compiler command-level driver utilizes a file named siterc to enable site-specific customization of the behavior of the compiler. The siterc file is located in the bin subdirectory of the NVIDIA HPC Compilers installation directory. Using siterc, you can control how the compiler driver invokes the various components in the compilation tool chain.

1.7.2. Using User rc Files

In addition to the siterc file, a user rc file can reside in a given user’s home directory, as specified by the user’s HOME environment variable. You can use this file to control the NVIDIA HPC Fortran compiler. This file is optional.

On Linux, this file is named .mynvfortranrc.

The following examples show how you can use these rc files to tailor a given installation for a particular purpose on Linux_x86_64 targets. The process is similar with obvious substitutions for aarch64 targets.

Table 3 Examples of Using siterc and User rc Files

To do this…

Add the line shown to the indicated file(s)

Make available to all linux compilations the libraries found in /opt/newlibs/64

set SITELIB=/opt/newlibs/64; to /opt/nv/Linux_x86_64/26.11ng-beta/compilers/bin/siterc

Add to all linux compilations a new library path: /opt/local/fast

append SITELIB=/opt/local/fast; to /opt/nv/Linux_x86_64/26.11ng-beta/compilers/bin/siterc

With linux compilations, change -Mmpi to link in /opt/mympi/64/libmpix.a

set MPILIBDIR=/opt/mympi/64; set MPILIBNAME=mpix; to /opt/nv/Linux_x86_64/26.11ng-beta/compilers/bin/siterc

Build a Fortran executable for linux that resolves shared objects in the relative directory ./REDIST

set RPATH=./REDIST; to ~/.mynvfortranrc

1.8. Common Development Tasks

Now that you have a brief introduction to the compiler, let’s look at some common development tasks that you might wish to perform.

  • When you compile code you can specify a number of options on the command line that define specific characteristics related to how the program is compiled and linked, typically enhancing or overriding the default behavior of the compiler. For a list of the most common command line options and information on all the command line options, refer to Use Command-line Options.

  • Code optimization for multicore CPUs allows the compiler to organize your code for efficient execution. While possibly increasing compilation time and making the code more difficult to debug, these techniques typically produce code that runs significantly faster than code that does not use them. For more information on optimization refer to Multicore CPU Optimization.

  • Function inlining, a special type of optimization, replaces a call to a function or a subroutine with the body of the function or subroutine. This process can speed up execution by eliminating parameter passing and the function or subroutine call and return overhead. In addition, function inlining allows the compiler to optimize the function with the rest of the code. However, function inlining may also result in much larger code size with no increase in execution speed. For more information on function inlining, refer to Using Function Inlining.

  • A library is a collection of functions or subprograms used to develop software. Libraries contain “helper” code and data, which provide services to independent programs, allowing code and data to be shared and changed in a modular fashion. The functions and programs in a library are grouped for ease of use and linking. When creating your programs, it is often useful to incorporate standard libraries or proprietary ones. For more information on this topic, refer to Creating and Using Libraries.

  • Environment variables define a set of dynamic values that can affect the way running processes behave on a computer. It is often useful to use these variables to set and pass information that alters the default behavior of the NVIDIA HPC Fortran compiler and the executables which it generates. For more information on these variables, refer to Environment Variables.

  • Deployment, though possibly an infrequent task, can present some unique issues related to concerns of porting the code to other systems. Deployment, in this context, involves distribution of a specific file or set of files that are already compiled and configured. The distribution must occur in such a way that the application executes accurately on another system which may not be configured exactly the same as the system on which the code was created. For more information on what you might need to know to successfully deploy your code, refer to Distributing Files – Deployment.

2. Porting Guide

Practical notes from the NVHPC applications team

2.1. Introduction

In developing NVIDIA’s next-generation CPU Fortran compiler, the NVIDIA high-performance computing (NVHPC) team tried to keep the user experience as a foremost priority. We wanted users to have a smooth transition from the classic nvfortran compiler to the new beta compiler. To help facilitate this experience, we challenged the NVHPC applications team to use the beta compiler and run the entirety of Fortran applications, correctness tests, and benchmarks that we test nightly with classic nvfortran. Then we asked them what they learned, what they wished they knew going in, and what they would want a user to know before picking up the beta. We hoped that our stumbles might lead to new users sprinting while we put together this porting guide.

The NVIDIA HPC Fortran Compiler Reference Guide describes beta nvfortran only. This guide holds the differences from classic nvfortran: the options, language features, directives, preprocessor behavior, runtime conventions and messages that differ between the two compilers.

The following guide is not an all-inclusive outline of every difference between the classic and beta compiler – but we believe it should discuss and highlight issues and differences in the compilers that are likely to be encountered by users. The first confusion that we must confront head on – there are now two compilers that answer to nvfortran:

  • the original, PGI-based compiler (referred to in this document as classic nvfortran),

  • the new Flang-based compiler (referred to as beta nvfortran).

The ultimate goal of beta nvfortran is to give the user a more modern frontend and optimizer, have better compliance with modern Fortran than the classic compiler, generate better diagnostics, and to have a path to long-term evolution from the open-source Flang community, whilst keeping as much of the classic nvfortran user experience as practical and allowing ourselves to have opportunities to introduce even better optimizations for the user.

2.2. How to use this guide

If you just want to try the new compiler on an existing code base, start with the quick-start checklist and then refer to later sections when something surprises you.

  • Classic vs beta: same name, different compiler DNA

  • Optimization levels and floating-point behavior

  • Command-line option differences

  • Stricter front-end diagnostics, and the format of messages

  • Language and data type differences

  • Compiler directive differences

  • Preprocessing and predefined macros

  • Modules and module hashes

  • Runtime environment and ABI differences

  • Stack usage and memory placement

  • Libraries, NVPL, and PIE/linking behavior

  • Build systems and CMake notes

  • Performance expectations and tuning

  • Bonus section: OpenMP

  • How to get help and give feedback

2.3. Quick-start porting checklist

A conservative way to try beta nvfortran on a code base that already builds with classic nvfortran:

  • Start from a clean, working classic nvfortran build. Save the build logs and test outputs – they are your baseline.

  • Switch your environment so that nvfortran refers to the new beta compiler. Keep the source code and build system identical for this first attempt.

  • Compile with the same general optimization level you used with classic, but if you used aggressive optimization flags like -Ofast with classic, consider starting with -O2 under beta and enabling more aggressive options later.

  • Pay attention to the compiler output. Beta nvfortran will:

    • accept many classic -M* flags by mapping them internally to new -f* flags, and accept many standard Flang flags

    • warn about flags it recognizes but has not yet implemented, and continue compiling without them

    • emit an error and stop on flags it does not recognize

    • emit new warnings and errors where your code violates or relies on grey areas of the Fortran standard.

  • Run your existing test suite. Group issues into three buckets:

    • compile-time diagnostics

    • runtime crashes or linking issues, and

    • numerical or performance differences.

  • If you see immediate runtime segmentation faults, first suspect stack limits. Try using the command “ulimit -s unlimited” and re-run.

  • If tests fail numerically at higher optimization levels, try a more conservative configuration while you debug, using new Flang flags to disable possible problematic optimizations. For example: nvfortran -O2 -fno-associative-math -ffp-contract=off … Once you understand the differences and are comfortable with them, you can relax these settings again.

  • If you see a flood of new warnings, resist the urge to disable them immediately. In our experience, many of these warnings point to real issues that other compilers silently ignored.

  • Once you have a clean, validated build, consider re-enabling more aggressive optimizations (for example -O3 or -Ofast where acceptable) and retuning performance as described below.

2.4. Classic vs beta: same name, different compiler DNA.

Both compilers are called nvfortran, but internally they are quite different:

  • classic nvfortran is the long-standing PGI-based compiler with a PGI built front and middle end, that couples to an LLVM-backend.

  • beta nvfortran is a new Flang/LLVM-based compiler that has a Flang-based front end, will have an NVIDIA designed middle for additional optimizations, and couples to an LLVM-backend.

Where possible, the beta compiler accepts familiar classic nvfortran options, often mapping them to new Flang-based -f* options under the hood (for example, -Minline ↔ -finline-functions). The driver also supports many Flang/LLVM options that classic nvfortran never had. The same rule applies to both classic -M* options and Flang-based -f* options:

  • If the beta driver recognizes an option but has not yet implemented it, it warns that the option is not yet implemented, ignores the option, and continues compilation.

  • If the beta driver does not recognize an option at all, it emits an error and ends compilation.

Warning example (the program is built, but without bounds checking):

$ nvfortran test.F90 -o test -Mbounds
nvfortran-Warning-not yet implemented: -Mbounds

Error example (a misspelling of -fno-vectorize):

$ nvfortran test.F90 -o test -fno-vectorise
nvfortran-Error-Unknown switch: -fno-vectorise

This difference in “compiler DNA” has practical consequences that impact numerics, correctness testing, performance, and behavior:

  • inlining and loop-optimization algorithms, behavior and heuristics are different,

  • floating-point transformations are not identical, and

  • diagnostics are generally stricter and more standard-conforming. Another point that should be made – because they are different compilers, a third party library, such as MPI or OpenBLAS, compiled for classic nvfortran will not be compatible with beta nvfortran. This means a user will likely need to build new libraries for applications that need them.

2.4.1. Bundled C/C++ Compiler

The beta nvfortran compiler is bundled with proven compilers, libraries and software tools essential to maximize developer productivity, performance, and portability of HPC applications. The C/C++ compiler packaged with the beta nvfortran is the NVIDIA nvc/nvc++ compiler familiar to users of classic nvfortran. Although the beta nvfortran compiler is based on LLVM Flang, the bundled C/C++ compiler is NOT LLVM Clang. Continue to use build configurations and options for NVIDIA C/C++ (nvc/nvc++). While the C/C++ compilers will silently accept some Flang flags as no-ops, they do not accept Clang flags.

As with all compiler packages, individual components and their versions do change over time. Make sure to consult Release Notes, READMEs and component documentation with each release for the latest changes.

2.4.2. Object files, libraries, and Modulefile Compatibility

Beta nvfortran and classic nvfortran are not ABI compatible. Object and binary files compiled with classic nvfortran cannot be used by beta nvfortran. Similarly, objects and binaries compiled by beta nvfortran cannot be used by classic nvfortran. Linking a classic object into a beta executable typically fails first with a PIE relocation error from the linker; see -fPIE defaults and mixed linking.

Beta nvfortran and classic nvfortran have different modulefile (.mod .smod) formats that are not interoperable. Beta nvfortran uses modulefile format from LLVM Flang. The LLVM Flang modulefiles are text files written as Fortran source, so they are human readable, unlike the classic modulefiles, which are text files in an internal format not meant to be read by people.

Each compiler rejects the other’s modulefiles with a clear message. For example, using the module_a and module_b example from Modules and module hashes, beta nvfortran reading a classic module_a.mod reports:

$ nvfortran -c module_b.F90
error: Semantic errors in module_b.F90
module_b.F90:3:5: error: Cannot read module file for module 'module_a': 'module_a.mod' is not a module file for this compiler
  use module_a
      ^^^^^^^^
...

Classic nvfortran reading a beta module_a.mod reports:

$ nvfortran -c module_b.F90
NVFORTRAN-F-0004-Corrupt or Old Module file ./module_a.mod (module_b.F90: 4)
NVFORTRAN/x86-64 Linux 26.11-0: compilation aborted

As a consequence, it is necessary to build 3rd party libraries with Fortran interfaces for beta nvfortran. The bundled libraries with this beta package are fully compatible with beta nvfortran. Either compiler can interoperate with NVIDIA C/C++ objects and libraries for mixed language applications.

2.5. Optimization levels and floating-point behavior

Classic and beta nvfortran both accept -O0, -O1, -O2, -O3, -O4, -Ofast, and -fast, but the flag combinations they imply are not identical. Only beta nvfortran accepts -Os. The classic descriptions below are approximate; the beta behavior is taken from the current beta documentation.

Option

classic nvfortran

beta nvfortran

Porting notes

-O0

Minimal optimization; mostly for debugging.

Minimal optimization; debug-friendly.

Use when chasing correctness or front-end issues; not representative for performance.

-O

Historically similar to -O1 with basic scalar optimizations.

Alias for -O2 (and implies -finline-functions).

If you used bare -O with classic, expect more aggressive optimization under beta.

-O1

Light optimization; first level that does noticeable work.

Light optimization; basic scalar and simple loop transforms.

Good starting point when debugging numerical differences.

-O2

Common production level; vectorization and loop optimizations. Enables inlining.

Main optimization level; vectorization and aggressive scalar/loop transforms; turns on inlining by default.

Typical first choice for performance/correctness runs under beta.

-O3

More aggressive loop and inlining heuristics; often used via -fast/-Ofast.

Like -O2 plus more aggressive loop transformations; turns on associative math.

Expect more reordering of floating-point operations. Use -fno-associative-math for closer reproducibility.

-O4

Historically a slightly more aggressive variant of -O3.

Alias for -O3.

Under beta there is no behavioral difference between -O3 and -O4.

-fast

Bundle: -O2 -Munroll=c:1 -Mlre -Mautoinline; implies -Mvect=simd -Mflushz -Mcache_align.

Alias for -O3, which implies -fassociative-math.

Unlike classic -fast, beta -fast reassociates floating-point expressions, so results can change. Add -fno-associative-math for closer reproducibility. If you relied on specific -M* flags implied by -fast, add them explicitly when using beta. -Mlre is not yet implemented in beta and is ignored with a warning.

-Ofast

Bundle on top of -O3 that also enables -Mstack_arrays and relaxed FP semantics.

“-O3 -ffast-math -fstack-arrays -frepack-arrays”, plus -fno-protect-parens and -mrecip (approximate reciprocals for division).

Enables aggressive FP transforms, ignores the order set by parentheses, and uses more stack. Use intentionally. Add -fprotect-parens to restore parenthesis ordering. -fno-fast-math does not fully undo -Ofast; see below.

-Os

Not supported (Unknown switch).

Optimize for size (roughly “O2-like” with reduced inlining).

Mainly for libraries or footprint-sensitive components, not most HPC kernels.

For further discussion, we highly recommend that users familiarize themselves with the compiler options of both classic and beta nvfortran using

$ nvfortran --help

And read our documentation on compiler options, shipped with the beta compiler.

2.5.1. Fast-math, associativity, and fused operations

The biggest numerical differences we saw between classic and beta nvfortran came from how aggressively beta uses LLVM’s floating-point optimizations, especially when flags like -Ofast are in play.

Key options to be aware of:

  • -ffast-math – expands to a collection of assumptions (no NaNs, no infinities, associative math, approximate math functions, no signed zeros, and -ffp-contract=fast). Implied by -Ofast. Disabled with -fno-fast-math.

  • -ffp-contract=fast – allows fused floating-point operations (including across statements). Enabled by default; actual fusion starts at -O1 and depends on the target ISA. Can be turned off with -ffp-contract=off.

  • -fassociative-math – allows reassociating floating-point expressions like a+b+c. Implied by -O3 and by -ffast-math. Can be disabled by -fno-associative-math.

  • -frepack-arrays – enables creation of contiguous temporaries for non-contiguous dummy arguments; implied by -Ofast. These temporaries may be placed on the stack if -fstack-arrays is also enabled. Can be disabled with -fno-repack-arrays.

  • -fstack-arrays – allocates automatic and some temporary arrays on the stack instead of the heap; implied by -Ofast. Can be disabled with -fno-stack-arrays.

  • -fprotect-parens – evaluates parenthesized expressions in the order the parentheses specify, as the Fortran standard requires. Enabled by default; -Ofast turns it off (-fno-protect-parens). Add -fprotect-parens after -Ofast to restore it.

Because many of these flags get enabled at higher optimization levels (typically -O2 and above) beta nvfortran can legitimately produce slightly different numerical results than classic nvfortran, even when both compilers are completely correct. This might be particularly visible when you compare bitwise results against golden output from classic nvfortran at high optimization.

Note that -Ofast is more than -O3 -ffast-math -fstack-arrays -frepack-arrays: it also adds -fno-protect-parens and -mrecip, which allows approximate reciprocal instructions for floating-point division. Neither of these is implied by -ffast-math alone.

Adding -fno-fast-math after -Ofast does not give you -O3 behavior back. It removes the -ffast-math assumptions, but:

  • -fno-protect-parens, -mrecip, -fstack-arrays, -frepack-arrays and the faster math-library model of -Ofast remain in effect, and

  • -fassociative-math (normally implied by -O3) is turned off and -ffp-contract is set to off.

The result is neither -O3 nor -Ofast. If you want only part of -Ofast, start from -O3 and add the individual options you need, for example -O3 -fstack-arrays.

2.5.2. A practical validation workflow

In real ports, the following workflow has been robust:

First validate with a more conservative beta configuration that limits re-association and fused operations, for example:

nvfortran -O2 -fno-associative-math -ffp-contract=off ...

Then, once you are confident that the new compiler is producing a valid numerical solution, relax those constraints, update your validation scripts to allow for expected numerical differences, and move back toward higher optimization flags.

2.6. Command-line option differences

The previous sections describe how beta nvfortran treats classic options in general. This section lists the options and suboptions of classic nvfortran that beta nvfortran does not accept, the options that it accepts but does not yet implement, and the options that behave differently. The Reference Guide describes the options that beta nvfortran supports. For -O and -fast, see Optimization levels and floating-point behavior.

2.6.1. Options that beta nvfortran rejects

Beta nvfortran rejects these options with the error Unknown switch. It rejects the suboptions with the error Switch <option> with unknown keyword.

Table 4 Options and suboptions that beta nvfortran does not accept

Option

Notes

-drystdinc, --flagcheck, -g77libs, -Mmoddeps, -Mlist, -Mnolist, -Mcpp

-fcx-limited-range, -fno-cx-limited-range

Beta nvfortran enables the equivalent behavior with -Ofast.

-fmax-errors=<n>

Use -ferror-limit=<n>.

--gcc-toolchain=<path>

The beta driver lists the option in its help, but f18 rejects it with the error Unknown command line argument.

-i2

Use -i4 or -i8.

-M

Make dependence lists.

-Munlink_module

-KPIC, -Kpic

Use -fpic or -fPIC. Classic nvfortran also rejects these flags.

-Mno-nan, -Mno-inf

Use -Ofast, which enables the equivalent behavior.

-qp

Use -pg, which is not yet implemented.

-silent

Use -w.

-target={gpu|multicore}

-W0,<option>, -Wa,<option>

Beta nvfortran accepts -Wl,<option> for the linker.

-acc= legacy, [no]autopar, sync, wait, noroutineseq

-gpu= [no]managed, pinned, [no]stacklimit, [no]unified

Use -gpu=mem:managed, -gpu=mem:unified or -gpu=mem:separate:pinnedalloc.

-mp= align, noalign, autopar, noautopar

-Mfunc32, -Minstrument=functions, -Minstrument-exclude-file-list, -Minstrument-exclude-func-list, -Mnolarge_arrays, -M[no]pre, -M[no]ref_externals, -Msafe_lastval, -M[no]signextend, -Mnostride0, -Mvarargs

Code generation. -Minstrument without a value is accepted.

-Mnostartup, -M[no]hugetlb, -M[no]stddef, -Mnostdinc, -Mnostdlib

Environment controls. Beta nvfortran has no equivalent for any of them.

-M[no]defaultunit, -M[no]dlines, -Mdollar, -M[no]iomutex, -M[no]onetrip

Fortran language controls.

-Mconcur, -Mnodepchk, -M[no]fpmisalign, -Mnoi4, -Mnovintr

Optimization controls. Use -mp in place of -Mconcur.

-Mr8, -Mnor8, -Mr8intrinsics, -Mnor8intrinsics

Use -r8 or -r4.

-Mgccbug, -Mgccbugs

Two options that older documentation describes, -Mnames= and -Miface=, are not accepted by either compiler on x86-64.

2.6.2. Options that are accepted but not yet implemented

Beta nvfortran accepts these options, issues the warning not yet implemented and ignores them: -C, -pg, -std, -acc=host, -acc=multicore, -acc=routineseq, -acc=nowait, -Mbounds, -Mchkptr, -Mchkstk, -Manno, -Mdepchk, -Mdse, -Mlre, -Mpropcond, -Mextract, -Mstride0, -Mnounixlogical and -Mpcast. -mp=gpu issues the warning OpenMP target offload is not yet implemented. -Msecond_underscore and -Mnosecond_underscore report an error. Beta nvfortran has no option that checks array bounds at run time.

Beta nvfortran accepts these options with a deprecation warning, and ignores them: -Mupcase, -Mnoupcase, -Mcache_align (this alignment is now the default), -Mtarget_temps, and -mcpu on x86-64 (use -march). It ignores -Mprefetch and the -Mvect keywords [no]altcode, cachesize:n, [no]gather, levels:n, nocond, prefetch, [no]short, nosimd, [no]simdresidual, [no]sizelimit:n and [no]uniform, and it warns.

2.6.3. Options that behave differently

  • -I and INCLUDE. Beta nvfortran searches the directory that contains the source file first, and then the directories that -I specifies, for an INCLUDE statement and for #include. Classic nvfortran searches the -I directories first, then the directory that contains the source file, then the current directory.

  • -march, -tp, -mcpu and -mtune. -tp is an alias of -march. Beta nvfortran rejects px, host, zen, zen2, zen3, zen4 and zen5 for -march, but it accepts them for -tp (except zen5; use znver5). Both compilers reject x86-64-v2, bulldozer, piledriver, bdver3 and sandybridge for -tp; beta nvfortran also rejects bdver4. Classic nvfortran rejects skx and emeraldrapids, which beta nvfortran accepts. -march=help, -tp=help and -mtune=help list the supported processors. -mtune selects a micro-architecture in beta nvfortran; classic nvfortran accepts it and does nothing.

  • -mcmodel. Beta nvfortran accepts -mcmodel=large and -mcmodel=kernel on x86-64. Classic nvfortran rejects both.

  • -Ktrap. Beta nvfortran accepts -Ktrap=align, and classic nvfortran rejects it.

  • -gpu. Beta nvfortran also accepts -gpu=cuda:{newest|oldest} and -gpu=ccall:preblackwell, and it requires a compute capability of 7.5 or higher. With -acc, only the macro __NVCOMPILER_OPENACC_GPU is defined. The NVIDIA accelerator directives such as !$acc region are errors.

  • -Mbackslash. The default is -Mbackslash in beta nvfortran and -Mnobackslash in classic nvfortran.

  • -O and -Munroll. -O4 is the same as -O3. -Munroll does not raise the optimization level in beta nvfortran; in classic nvfortran it sets level 2 when you specify no -O or -g.

  • -r4. The classic documentation says that -r4 interprets DOUBLE PRECISION variables as REAL. Neither compiler does so.

  • -time. Beta nvfortran prints a report that is headed Compiler Execution Time Report. Classic nvfortran prints Timing stats.

  • -help. Beta nvfortran has the subgroup -help=flang, which classic nvfortran does not have.

  • -Minit-real. Beta nvfortran also accepts -Minit-real=nan. Classic nvfortran accepts only snan and zero.

Options that only beta nvfortran accepts: -ferror-limit, -Minline-intrn and -Mnoinline-intrn, -Mplugin and -Mnoplugin, -Midiom and -Mnoidiom (classic nvfortran does not require them), and -help=flang.

2.7. Front-end strictness, diagnostics, and output formatting changes

One of the most noticeable user-visible differences is that beta nvfortran is stricter about the Fortran standard than classic nvfortran. In practice this is usually a good thing – we repeatedly found real bugs in applications that classic and other compilers had silently accepted – but it can be jarring on a code base that has accumulated non-standard constructs over time.

2.7.1. Example: logical comparisons

Classic nvfortran quietly accepted code like this:

$ cat teq.f90
logical function f(a,b)
logical a, b
f = a .eq. b
end function

With beta nvfortran, the Fortran standard is enforced more strictly – logical operands must be compared using .EQV. or .NEQV. The same source now fails with a clear diagnostic:

$ nvfortran teq.f90 -c
error: Semantic errors in teq.f90
teq.f90:3:5: error: LOGICAL operands must be compared using .EQV. or .NEQV.
f = a .eq. b
    ^^^^^^^^

In these cases, the right fix is to update the source rather than trying to suppress the warning or error.

2.7.2. Example: irrelevant attributes

Beta nvfortran also warns about attributes that only make sense on dummy arguments when they are applied elsewhere. A simple example:

$ cat intpar.f90
integer function f(a,x)
integer, value :: x,i
do i = 1, x
  f = f + i
end do
end function
$ nvfortran -c intpar.f90
intpar.f90:2:21: warning: Only a dummy argument should have an INTENT, VALUE, or OPTIONAL attribute [-Wignore-irrelevant-attributes]
integer, value :: x,i
^

Code like this often compiled cleanly with classic nvfortran, but the beta compiler nudges you toward cleaner, more portable Fortran. You can disable this warning if you really need to, but we generally recommend fixing the code instead.

2.7.3. Example: C_LOC arguments without POINTER or TARGET

A common legacy pattern is using C_LOC from ISO_C_BINDING on an ordinary local variable that is neither a POINTER nor a TARGET. Classic nvfortran compiled this with only a warning, so it is present in many existing applications. Beta nvfortran rejects it by default, but there are two practical migration paths: update the source or use the relaxed compatibility option.

For example:

$ cat cloc.f90
program test_relaxed_cloc
  use iso_c_binding, only: c_loc, c_ptr
  implicit none
  integer :: x = 42
  type(c_ptr) :: p
  p = c_loc(x)
end program test_relaxed_cloc

Classic nvfortran warns and creates an object file:

$ nvfortran -c cloc.f90
NVFORTRAN-W-0468-Argument to ISO_C_BINDING intrinsic  must have TARGET or POINTER attribute set (cloc.f90: 6)
  0 inform,   1 warnings,   0 severes, 0 fatal for test_relaxed_cloc

With beta nvfortran, this fails by default:

$ nvfortran -c cloc.f90
error: Semantic errors in cloc.f90
cloc.f90:6:13: error: C_LOC() argument must be a data pointer or target
    p = c_loc(x)
            ^

The best long-term fix is to update the source so the argument has the attributes required by the standard, for example by declaring the object with TARGET when taking its C address is intentional:

integer, target :: x = 42

For migration of legacy code, beta nvfortran also provides -frelaxed-c-loc-checks. This option allows a data object or function pointer as the C_LOC() argument even when it is not a pointer or target. If you want to find each affected call site while using the compatibility mode, add -Wrelaxed-c-loc-checks:

nvfortran -frelaxed-c-loc-checks -Wrelaxed-c-loc-checks -c cloc.f90

The relaxed option is intended as a compatibility aid, not as a semantic fix. The compiler does not reason about aliases created through non-target, non-pointer arguments, and code that depends on such aliases may behave unexpectedly. Other C_LOC restrictions still apply even with -frelaxed-c-loc-checks enabled, including contiguity, zero-sized array, and invalid type or character length checks.

Another difference that the new beta compiler has, is the default printing formatting is different than with classic. This can cause hiccups in validation scripts that rely on specific default formatting.

2.7.4. Example: default formatted output

We also saw user tests fail simply because the default formatted output of REAL values changed. Consider:

$ cat tprint.f90
program tprint
real :: x(12)
integer :: i
do i = 1, 12
  x(i) = 1.0 / real(i)
end do
print *, x
end program tprint

Compiled and run with beta nvfortran:

$ nvfortran tprint.f90
$ a.out
 1. .5 .33333334 .25 .2 .16666667 .14285715 .125 .11111111 .1 9.090909E-02
 8.3333336E-02

Classic nvfortran prints:

$ nvfortran tprint.f90
$ a.out
    1.000000       0.5000000       0.3333333       0.2500000
   0.2000000       0.1666667       0.1428571       0.1250000
   0.1111111       0.1000000       9.0909094E-02   8.3333336E-02

The numerical values are the same, but the default formatting is different enough that a line-oriented regression test can misclassify this as a failure. In practice you can either add explicit FORMAT statements where formatting matters, or relax your testing harness to allow for these harmless formatting differences.

2.7.5. Example: type/kind/rank Enhanced Interface Checks [-Wexternal-interface-mismatch]

Another example of beta nvfortran strictness in diagnostics is with interface checking. Beta nvfortran provides extensive interface checking compared to classic nvfortran. By default, beta nvfortran may return warning-level diagnostics when the actual arguments type, kind, rank, or attributes do not match those of the dummy arguments. The source(s) of these warnings should be investigated and corrected. If left uncorrected these errors may affect generic procedure resolution, could cause runtime errors, or in some cases silently corrupt data.

The following example code compiles with classic nvfortran. Notice that subroutine sub1 has one dummy argument d_arg declared as type integer. It is an array with 10 elements. However, in sub2 the interface for sub1 declares the dummy argument as a scalar real. Furthermore, it calls sub1 with a real scalar actual argument. This is sure to cause a runtime error.

$ cat iface2.f90
subroutine sub1( d_arg )
integer :: d_arg(10)
d_arg = 42 !..segfault
end subroutine sub1

subroutine sub2()
  interface
   subroutine sub1(d_actual)
     real :: d_actual
   end subroutine sub1
  end interface
  real :: x
  call sub1(x)
end subroutine sub2

$ # classic nvfortran
$ nvfortran -c iface2.f90
$

This demonstrates a trait of classic nvfortran. Classic nvfortran does not check interfaces across program units even if they are in the same compilation unit (source file), as shown above. By contrast, beta nvfortran will check interfaces and diagnose these with warnings:

$ nvfortran -c iface2.f90
iface2.f90:8:15: warning: The global subprogram 'sub1' is not compatible with its local procedure declaration (incompatible dummy argument #1: incompatible dummy data object shapes) [-Wexternal-interface-mismatch]
     subroutine sub1(d_actual)
                ^^^^
iface2.f90:1:12: Declaration of 'sub1'
  subroutine sub1( d_arg )
             ^^^^
iface2.f90:8:15: Declaration of 'sub1'
     subroutine sub1(d_actual)
                ^^^^

Note that beta nvfortran diagnosed a mismatch in the first dummy argument (#1 is the argument position): the ranks of the arguments do not match, as reported by incompatible dummy data object shapes. The arguments also differ in type (integer versus real), but the message does not mention it, because beta nvfortran reports only the first incompatibility it finds for an argument. After fixing one mismatch, recompile to check for others.

Recommendation: beta nvfortran provides a warning-level diagnostic in such cases: [-Wexternal-interface-mismatch]. However, because this is a warning-level diagnostic, beta nvfortran will still create an object file by default. This object file could be linked into an application, and if run, this could lead to a segmentation fault. For this reason and as a general correctness step it is recommended to compile with option -Werror. Using option -Werror instructs nvfortran to treat all warnings as errors. This stops compilation and creation of object file(s). Note that with -Werror the diagnostic itself is still labeled warning:, but it appears under an error: Semantic errors header, the compiler exits with a nonzero status, and no object file is created:

$ nvfortran -c -Werror iface2.f90
error: Semantic errors in iface2.f90
iface2.f90:8:15: warning: The global subprogram 'sub1' is not compatible with its local procedure declaration (incompatible dummy argument #1: incompatible dummy data object shapes) [-Wexternal-interface-mismatch]
     subroutine sub1(d_actual)
                ^^^^
iface2.f90:1:12: Declaration of 'sub1'
  subroutine sub1( d_arg )
             ^^^^
iface2.f90:8:15: Declaration of 'sub1'
     subroutine sub1(d_actual)
                ^^^^

In addition to diagnosing argument mismatches as demonstrated above, beta nvfortran will also diagnose argument mismatches in type, kind, rank and mismatches along with mismatches in data attributes, such as INTENT, VALUE, DEVICE, PINNED, CONTIGUOUS, etc. that classic nvfortran did not diagnose, or diagnosed only with a warning. It is highly recommended to investigate all [-Wexternal-interface-mismatch] diagnostics provided by beta nvfortran and to correct any previously uncorrected errors.

2.7.6. Example: INTENT Enhanced Interface Checks error: argument is not definable

Beta nvfortran performs extensive checks to ensure that arguments match in INTENT and that the INTENTS are compatible. As an example, if a procedure passes one of its own INTENT(IN) dummy arguments as the actual argument of a subroutine call or function invocation, and the corresponding dummy argument of the callee is declared INTENT(OUT) or INTENT(INOUT), beta nvfortran will return an error. Classic nvfortran only warned about this case.

$ cat intent.f90
module m
contains
  subroutine callee(a)
    real, intent(out) :: a
    a = 1.0
  end subroutine callee
  subroutine caller(b)
    real, intent(in) :: b
    call callee(b)
  end subroutine caller
end module m

$ # classic nvfortran
$ nvfortran -c intent.f90
NVFORTRAN-W-0193-Argument number 1 to callee does not match INTENT (OUT) (intent.f90: 9)
  0 inform,   1 warnings,   0 severes, 0 fatal for caller

$ # beta nvfortran
$ nvfortran -c intent.f90
error: Semantic errors in intent.f90
intent.f90:9:17: error: Actual argument associated with INTENT(OUT) dummy argument 'a=' is not definable
      call callee(b)
                  ^
intent.f90:9:17: because: 'b' is an INTENT(IN) dummy argument
      call callee(b)
                  ^
intent.f90:8:25: Declaration of 'b'
      real, intent(in) :: b
                          ^

This error indicates that a dummy argument declared INTENT(IN) in the calling procedure could possibly be modified by the callee. The “not definable” error message is followed by additional information helpful in finding the error: the because: line names the actual argument and gives the reason, and the Declaration of <variable> line shows where it is declared. Compare this to how the dummy arguments are declared in the SUBROUTINE or FUNCTION being called and make sure that intents are compatible.

2.7.7. Other argument checking, attributes

Where possible, Beta nvfortran provides extensive checks of type/kind/rank and other attributes of actual arguments against declarations of dummy arguments. Look for errors in argument mismatches for Fortran attributes such as TARGET, POINTER, VALUE, or CONTIGUOUS. Also check for OpenACC or CUDA attribute mismatches on attributes such as DEVICE, PINNED, etc. Finally, if there are ISO_C_BINDING attributes on actual arguments and dummy arguments ensure that the arguments are compatible.

2.7.8. Format of messages

Classic nvfortran has a catalog of numbered messages. Beta nvfortran does not. The part of the compiler or of the runtime library that detects a condition issues the message. The Reference Guide describes the messages of beta nvfortran.

  • A classic message has a severity letter and a number, for example NVFORTRAN-S-0038-Symbol, x, has not been explicitly declared (sem.f90: 1). The severities are inform (I), warn (W), severe (S) and fatal (F). A beta message has no number, and the severities are error, warning and portability.

  • Classic nvfortran ends the diagnostics of a program unit with a summary line such as 0 inform, 0 warnings, 1 severes, 0 fatal for t. Beta nvfortran displays no summary line.

  • Classic nvfortran displays the file name and the line number only. Beta nvfortran displays the line and the column, and it shows the source line with a mark under the text that the message is about.

  • A classic run-time message starts with a code, for example FIO-F-209/OPEN/unit=11/'OLD' specified for file which does not exist., and it is followed by the file name and the line number on separate lines. A beta run-time message is one line that starts with fatal Fortran runtime error.

  • Classic messages do not show warning names. In beta nvfortran, -Wno-<name> suppresses a warning by the name that the message shows.

  • Classic nvfortran creates a listing file with the diagnostic messages when you specify -Mlist. Beta nvfortran does not support -Mlist.

  • The classic -Minform level inform has no messages in beta nvfortran. -Minform=severe does not display warnings.

2.8. Language and data type differences

2.8.1. CHARACTER kinds

Classic nvfortran supports only the default kind of CHARACTER. It does not accept KIND=2 or KIND=4, and it reports the error Illegal selector - KIND parameter has unknown value for a declaration or a literal that uses one. Code that uses the other kinds cannot be compiled by classic nvfortran. The Reference Guide describes the kinds that beta nvfortran supports.

2.8.2. LOGICAL values

Beta nvfortran represents .TRUE. as 1 and treats a logical value as true when its integer value is not zero. This matches gfortran. Classic nvfortran represents .TRUE. as -1. The next table compares the representations. For classic nvfortran, Intel ifort and PGI pgf90, any value other than the two representations in the table is undefined behavior.

Table 5 Representation of LOGICAL values in different compilers

Compiler

Value of .TRUE.

Value of .FALSE.

A value is true when

Beta nvfortran, gfortran

1_kind

0_kind

The integer value is not zero

Classic nvfortran, Intel ifort, PGI pgf90

-1_kind

0_kind

The low-order bit is set

IBM XLF

1_kind

0_kind

The low-order bit is set

Beta nvfortran accepts the classic option -Munixlogical and ignores it, because it always treats a non-zero logical value as true. It does not yet implement -Mnounixlogical.

2.9. Compiler Directives Differences

2.9.1. !pgi$ Directives Compatibility

The !pgi$ directive sentinel is accepted as an alias for !dir$ in most cases. However, scope-suffixed forms such as !pgi$g !pgi$r !pgi$l (Global, Routine, and Loop scopes) are not supported, and they are silently ignored: beta nvfortran gives no warning or error for them. For example, a loop preceded by !pgi$l novector is still vectorized, while the same loop preceded by !pgi$ novector or !dir$ novector is not. Search your sources for these forms and replace them with !dir$ directives. Because a !dir$ directive applies only to the loop that follows it, a global or routine-scope directive must be replaced by a !dir$ directive before each loop it was meant to affect.

2.9.2. Other directive differences

  • ignore_tkr. Classic nvfortran supports fewer forms of !dir$ ignore_tkr. For example, it rejects the P letter with the error Illegal IGNORE_TKR specifier.

  • Loop directives and OpenMP. Classic nvfortran accepts a loop directive on either side of an OpenMP directive. Beta nvfortran warns when the loop directive follows the OpenMP directive. Put the loop directive before the OpenMP directive.

  • assume_aligned and unroll. Classic nvfortran accepts !dir$ assume_aligned and the forms !dir$ unroll=n and !dir$ unroll(n) without a message. Beta nvfortran ignores all three and issues the warning Unrecognized compiler directive was ignored.

The Reference Guide describes the directives that beta nvfortran supports.

2.10. Preprocessing and predefined macros

Another practical difference is how the two compilers handle preprocessing and what macros they define by default. This matters both for direct command-line builds and for build systems like CMake or custom Makefiles.

2.10.1. Behavior differences

With classic nvfortran, source files containing # directives typically require either -Mpreprocess or an uppercase file extension; otherwise you get a syntax error and a clear prompt to enable preprocessing.

With beta nvfortran, preprocessing is effectively always enabled – the preprocessor runs by default – but the set of predefined macros is different, and files with # directives may compile without error even if the macro you expected was never defined. This can make certain preprocessor-heavy build systems behave differently until you update them.

A small example illustrates the difference:

$ cat mac.f90
#ifdef MAC
print *, "Yes"
#else
print *, "No"
#endif
end

Classic nvfortran:

$ nvfortran mac.f90
NVFORTRAN-S-0021-Label field of continuation line is not blank (mac.f90: 1)
NVFORTRAN-S-0021-Label field of continuation line is not blank (mac.f90: 3)
NVFORTRAN-S-0021-Label field of continuation line is not blank (mac.f90: 5)
  0 inform,   0 warnings,   3 severes, 0 fatal for MAIN

Beta nvfortran, with no preprocessing option:

$ nvfortran mac.f90
$ a.out
 No
$ nvfortran -DMAC mac.f90
$ a.out
 Yes

The key points for porting are:

  • With beta, the preprocessor is always on: # directives are processed even in a file with a lowercase .f90 extension, and -D macro definitions take effect without -cpp or -Mpreprocess.

  • Be explicit about which macros you define on the command line (for example, -DMAC) and when you expect them.

2.10.2. Other preprocessor differences

Classic nvfortran preprocesses only files that have an uppercase suffix, such as .F and .F90, or that you compile with -Mpreprocess. Beta nvfortran preprocesses every Fortran source file; the option -nocpp is accepted and has no effect. These differences remain:

  • Classic nvfortran does not accept Fortran relational operators in #if and #elif expressions. #if 2 .LT. 3 is an error.

  • Classic nvfortran does not expand __COUNTER__, __TIMESTAMP__ or __VA_OPT__.

  • Classic nvfortran does not recognize a macro name or a function-like macro invocation that is split across fixed form continuation lines, and it does not treat a # in column 6 as a continuation marker.

  • Classic nvfortran does not remove a Fortran comment inside the arguments of a macro invocation. The comment text becomes part of the argument, which usually breaks the statement.

Classic nvfortran also defines a macro for each processor feature of its default target, such as __AVX2__ and __SSE4_2__. Beta nvfortran does not define these macros by default. For the GPU memory mode, classic nvfortran defines __PGI_ACC_UMEM, and beta nvfortran defines __NV_ACC_UMEM. Beta nvfortran does not define __NVCOMPILER_OPENACC_HOST or __NVCOMPILER_OPENACC_MULTICORE. The Reference Guide lists the macros that beta nvfortran defines.

2.10.3. Detecting classic vs beta in source

When you really need to compile different code paths under classic and beta, use the predefined macros that actually exist in each compiler.

For a simple empty test file, the same command lists the predefined macros with both classic and beta nvfortran:

nvfortran -dM -E test.F90 -c

Classic nvfortran defines __PGI, __PGIF90__ and __NVCOMPILER_LLVM__; beta nvfortran defines none of them. Beta nvfortran defines __nvflang__, which classic does not.

A robust pattern for conditional compilation is:

#ifdef __nvflang__
! beta nvfortran (Flang/LLVM-based)
#elif defined(__PGI)
! classic nvfortran
#else
! some other compiler
#endif

Watch for two checks in existing code that will silently take a different branch under beta nvfortran:

  • #ifdef __NVCOMPILER – both classic and beta nvfortran define __NVCOMPILER, so a check intended to detect classic nvfortran now also matches beta. Use __nvflang__ or __PGI to tell them apart.

  • #ifdef __flang__ – beta nvfortran defines __flang__, so blocks written for LLVM Flang now also apply to beta nvfortran. Review them before relying on them.

We recommend keeping such conditionals localized (for example, in a small configuration header) so that the rest of the code stays portable and clean.

2.11. Modules and module hashes

Beta nvfortran introduces module hashes: each generated .mod file contains a small header that encodes a hash of the module’s contents and the exact hashes of the modules it depends on. This is new behavior compared to classic nvfortran.

At a high level, each module file now begins with a line like:

!mod$ v1 sum:<hash>

and then contains one or more dependency lines of the form:

!need$ <hash> n <module_name>

The module file is UTF-8 text and starts with a byte order mark (BOM) before the !mod$ line. If your scripts search module files for a line beginning with !mod$, make sure they allow for the BOM.

These hashes allow the compiler to check that all the modules being used in a build are consistent with one another. If a module is rebuilt and its hash changes, anything that depends on it must also be rebuilt; otherwise beta nvfortran will emit an error instead of silently using an inconsistent module file.

For example, suppose you have two modules:

! module_a.F90
module module_a
implicit none
integer, parameter :: value_a = 10
contains
function get_value_a() result(val)
integer :: val
val = value_a
end function get_value_a
end module module_a
! module_b.F90
module module_b
use module_a
implicit none
contains
function compute_sum(x) result(res)
integer, intent(in) :: x
integer :: res
res = x + get_value_a()
end function compute_sum
end module module_b

When compiled with beta nvfortran, module_a.mod and module_b.mod will each contain their own !mod$ hash, and module_b.mod will also contain a !need$ line referencing the exact hash of module_a.mod that it was built against. Recompiling module_a.F90 from unchanged source produces the same hash, so nothing else needs to be rebuilt. If you change module_a.F90 and recompile it without rebuilding module_b.F90, the next compilation that uses module_b will detect the mismatch and stop with an error instead of letting a stale module slip through:

error: Cannot use module file for module 'module_a': File is not the right module file for 'module_a': module_a.mod

This caught real problems for us in practice. In one large weather model we found four different module files with the same name coming from four different source locations. The hash checks made the problem obvious and forced the build system to be cleaned up.

If this behavior ever gets in your way or confuses you while you are still cleaning up an old build system, remember that the .mod files are just text files – you can open them, see which hash is expected, and track down where the wrong copy came from. For more advanced use cases (for example, removing module hash dependence for building generic libraries, including hermetic modules), see Module Hashes.

Classic nvfortran has no module hashes, and it rejects the option -fhermetic-module-files with the error Unknown switch. Compile all the files of a project, and the libraries that provide its modules, with the same compiler, and keep the module files of the two compilers in different directories. See also Object files, libraries, and Modulefile Compatibility.

2.12. Runtime environment and ABI differences

If you mix object files and libraries from classic nvfortran and beta nvfortran, or you port code between them, note these differences. As Object files, libraries, and Modulefile Compatibility explains, the two compilers are not ABI compatible. The Reference Guide describes the conventions that beta nvfortran uses.

  • COMPLEX function results (x86-64). Classic nvfortran returns the value of a COMPLEX or DOUBLE COMPLEX function in memory, through a hidden first argument. Beta nvfortran returns the value in registers (%xmm0, and %xmm1 for DOUBLE COMPLEX), and the first visible argument is in %rdi.

  • Logical values. Classic nvfortran uses -1 for .TRUE.. Beta nvfortran uses 1. See LOGICAL values.

  • Module symbol names. The symbol names of module procedures and module variables are different. For example, classic nvfortran names a module procedure mod1_msub_, and beta nvfortran names it _QMmod1Pmsub.

  • Environment variables. Classic nvfortran ignores DEFAULT_UTF8, does not check pointer deallocation, and does not truncate a stream file on output after POS=, so FORT_CHECK_POINTER_DEALLOCATION and FORT_TRUNCATE_STREAM have no effect there.

  • Byte order of unformatted files. Both compilers accept -Mbyteswapio. Beta nvfortran accepts -fconvert=<mode> but does not implement it yet, and it issues a warning. An explicit CONVERT= specifier in an OPEN statement takes precedence over FORT_CONVERT in beta nvfortran; in classic nvfortran the environment variable takes precedence.

2.13. Stack usage and memory placement

Programs compiled with beta nvfortran usually require more stack memory than when compiled with classic nvfortran. This is a deliberate design choice: large local arrays of procedures live on the stack, which often improves performance and locality, but it does mean that existing applications sometimes run into OS stack limits.

In rough terms:

  • Classic nvfortran:

    – Automatic arrays live on the heap unless -Mstack_arrays is in effect (explicitly or via bundles like -Ofast).

    – Non-automatic explicit-shape arrays often live in static storage unless -Mrecursive is used.

  • Beta nvfortran:

    – Automatic arrays live on the heap unless -fstack-arrays is in effect (explicitly, via -Mstack_arrays, or via -Ofast, which implies it). -fstack-arrays also moves some array temporaries onto the stack.

    – Non-automatic explicit-shape local arrays of procedures live on the stack under the default -fautomatic, unless -fno-automatic moves them to static storage.

At the default optimization level and at -O2, the two compilers treat automatic arrays the same way. The difference that most often matters is the non-automatic local arrays: a large array such as real :: big(200000) declared in a subroutine is in static storage with classic nvfortran but on the stack with beta nvfortran.

In practice, the symptom of running into a OS stack limit in this way is: the code compiles successfully with beta nvfortran, but the executable segfaults during execution, sometimes even before the main work begins. This is most likely when procedures declare large local arrays, or when the code is compiled with -Ofast or -fstack-arrays and uses large automatic arrays. In many of our porting cases, simply removing the OS stack limit fixed the immediate problem:

$ ulimit -s unlimited
$ ./your_app ...

If you’re in an environment with limited stack, or lifting the limit isn’t a viable option, then beyond lifting the stack limit, you can also:

  • Use -fno-stack-arrays with -Ofast, which enables stack arrays by default, and

  • use -fno-automatic cautiously to move some arrays back to static storage (taking care with any recursive code).

You do not need -fsave-main-program for large arrays in the main program: beta nvfortran already keeps main-program variables larger than 32 bytes in static storage. -fsave-main-program affects only the smaller ones.

2.13.1. Default alignment of arrays and -Mcache_align

The option -Mcache_align supported by classic nvfortran is deprecated in beta nvfortran and will be removed at a future date. This option was used to align certain data objects above a certain size threshold to cache-line boundaries.

BETA nvfortran improves alignment and makes the -Mcache_align option obsolete. In beta nvfortran, all static and allocatable arrays are default aligned on 64-byte boundaries without the need for a compiler option or compiler directives.

2.13.2. Unsupported align Allocation-Specifier

Codebases migrating from PGI or previous versions of nvfortran from the NVIDIA NVHPC SDK that rely on the vendor-specific align allocation-specifier (such as ALLOCATE(a(N), align=4096)) will encounter compilation errors. This extension is unsupported by LLVM Flang.

By default, nvfortran aligns static and allocatable arrays on 64-byte boundaries. If a different alignment is necessary, the following methods could be used:

  1. OpenMP 5.x Directives (not yet supported): The !$OMP ALLOCATE(a) ALIGN(4096) directive and the !$OMP ALLOCATORS construct are not yet supported by beta nvfortran. Do not use them to align arrays.

  2. C Interoperability: Allocate memory using posix_memalign or aligned_alloc via Fortran’s intrinsic ISO_C_BINDING module.

Note

Using C allocation functions requires passing the resulting C pointer to Fortran using the c_f_pointer subroutine.

For example, the following program allocates an array on a 4096-byte boundary with posix_memalign:

program memalign
  use iso_c_binding
  implicit none
  interface
    integer(c_int) function posix_memalign(p, alignment, size) bind(c)
      import :: c_int, c_ptr, c_size_t
      type(c_ptr) :: p
      integer(c_size_t), value :: alignment, size
    end function posix_memalign
    subroutine free(p) bind(c)
      import :: c_ptr
      type(c_ptr), value :: p
    end subroutine free
  end interface
  integer, parameter :: n = 1000
  type(c_ptr) :: cp
  real, pointer :: a(:)

  ! Allocate n reals on a 4096-byte boundary
  if (posix_memalign(cp, 4096_c_size_t, int(n * c_sizeof(0.0), c_size_t)) /= 0) &
    stop "posix_memalign failed"
  call c_f_pointer(cp, a, [n])

  a = 1.0
  print *, sum(a), mod(transfer(cp, 0_c_intptr_t), 4096_c_intptr_t)

  ! Release with free, not DEALLOCATE
  nullify(a)
  call free(cp)
end program memalign

Memory obtained this way must be released with free, not with DEALLOCATE.

2.14. Libraries, NVPL, and PIE/linking behavior

Two other differences that showed up in real ports were the default BLAS/LAPACK implementation on some platforms and the default use of -fPIE.

2.14.1. NVPL vs OpenBLAS

On AArch64 platforms, the beta nvfortran package uses the NVIDIA Performance Library (NVPL) as the default BLAS, LAPACK, and ScaLAPACK implementation. For example:

nvfortran test.F90 -o test -lblas -llapack

will pick up NVPL BLAS/LAPACK on Arm instead of OpenBLAS. This is not a difference between classic and beta: classic nvfortran also uses NVPL by default on Arm, at least since release 26.11. On x86_64, NVHPC still ships OpenBLAS as the default. Similarly, -Mscalapack maps to the NVPL version on Arm, and on x86_64 to the ScaLAPACK library bundled with NVHPC, which is built on OpenBLAS.

For most codes NVPL is an improvement, but we did see a few cases where applications had implicitly relied on OpenBLAS-specific behavior. If you hit BLAS/LAPACK issues on Arm, try rebuilding against OpenBLAS explicitly as a first experiment, and then check whether your application assumes non-standard behavior that differs between implementations. Because classic nvfortran also uses NVPL by default on Arm, you will likely see the same issue with classic nvfortran.

2.14.2. -fPIE defaults and mixed linking

C, C++, and Fortran compilers in the beta nvfortran package (nvc, nvc++, nvfortran) imply -fPIE by default so that objects can be linked into a position-independent executable. This differs from the classic NVHPC compilers, which do not imply -fPIE or -fPIC.

The most common symptom is a link-time failure when an object file or static library that was not compiled as position-independent code is linked into a beta executable. For example, on x86_64:

/usr/bin/ld: libsub.o: relocation R_X86_64_32 against `.rodata' can not be used when making a PIE object; recompile with -fPIC
/usr/bin/ld: final link failed: Nonrepresentable section on output

(Depending on the linker version, the message may suggest -fPIE instead of -fPIC.) There are two ways to resolve this:

  • Rebuild the object or library with -fPIC or -fPIE, or with the beta compilers, which imply -fPIE.

  • Link the executable with -no-pie, for example nvfortran -no-pie main.o -L. -lthirdparty. This works for non-PIE C or C++ objects and libraries.

If the object was compiled with classic nvfortran, -no-pie does not help: the link then fails with undefined references to classic Fortran runtime routines (for example pgf90io_print_init), because classic and beta Fortran objects are not compatible (see Object files, libraries, and Modulefile Compatibility). Rebuild such objects with beta nvfortran.

In our porting experience we ran into a few cases where we needed to pass “-no-pie” to get correct behavior, largely due to bugs in external 3rd party libraries. We also found that to compile “-mcmodel=large” on Arm, the compiler must default to “-fno-pie”, so please be aware of this.

2.15. Build systems and CMake

Because beta nvfortran is based on Flang/LLVM, some build systems (especially CMake-based ones) may not recognize it in exactly the same way as classic nvfortran. In practice we saw a few common patterns in CMakeLists.txt and other scripts:

  • hand-rolled checks that look for classic-specific compiler IDs or predefined macros (for example, __PGI or __NVCOMPILER_LLVM__) and assume anything else is unsupported;

  • logic that assumes there is only one nvfortran compiler and that its behavior always matches classic exactly.

The safest way forward is to:

  • treat “NVHPC Fortran” as a family with two members (classic and beta),

  • use the preprocessor macros only when you genuinely need different behavior, and

  • keep compiler-specific CMake logic isolated in a small module or toolchain file instead of scattered throughout the project.

If you already have a CMake toolchain file for classic nvfortran, consider cloning it for beta nvfortran and adjusting only the pieces that need to change (for example, additional -f* options, module-hash settings, or linker flags). In some cases you may also need to update CMake to a newer version to pick up improved NVHPC/Flang integration.

2.16. Performance expectations and tuning

Performance is ultimately why most users care about compilers. In our porting work we saw a mix of outcomes:

  • some kernels and applications were faster immediately under beta nvfortran,

  • some were roughly the same, and

  • a few were slower until we adjusted flags or code structure.

For fastest performance, but not necessarily most bitwise accurate, we recommend -Ofast, but we also recommend the user to read the included performance discussion on the new beta compiler. It does a deep dive into the difference in the compilers and why classic may be out performing beta currently, but also why beta has room for a lot of performance improvements.

2.17. OpenACC

OpenACC support in beta nvfortran is based on the new Flang/LLVM front end and is still actively being developed by NVIDIA with help from the community. The goal is to track the most recent OpenACC standards as closely as possible while trying to keep behavior familiar for users coming from classic nvfortran.

2.17.1. Disambiguation of host and device pointers

Prior to Unified Memory, programmers were required to specify variable references as either host data or device data. Classic nvfortran used context to make assumptions on user intent when variable references could be either host references or device references. While these OpenACC extensions did not strictly follow the OpenACC standards, it did provide ease of use and allowed users to migrate serial code to OpenACC accelerated code. In many cases where there are ambiguous variable references, classic nvfortran would assume references were to device data. In these cases, classic nvfortran did not give warning or error diagnostic messages.

Beta nvfortran uses the Flang front-end to parse and analyze use of OpenACC directives. Since Flang was a new and original front-end implementation, it was designed to be strict in following the OpenACC Standard for syntax and semantics. Development is underway to ease strictness in following the OpenACC Standard and implement many of the ease-of-use extensions popularized by classic nvfortran.

To assist the compiler disambiguate variable references in OpenACC regions or CUDA library calls, OpenACC provides the !$acc host_data directive. This is an interoperability construct used to expose the memory address of device (GPU) data directly to the host (CPU). It essentially creates a “reverse data region” where the host code can access and pass raw device pointers into external, device-aware routines (such as NVIDIA cuBLAS, cuFFT, or CUDA-aware MPI) without copying the data back to the CPU first.

!$acc host_data use_device(list)
  ! Structured block
!$acc end host_data

2.17.2. Disambiguation of arguments to generic functions

Efforts have been made to enable Beta nvfortran to mimic the ease-of-use characteristics of classic nvfortran. One such area is in the passing of ambiguous arguments to NVIDIA cuBLAS generic functions. This is one case where Beta nvfortran relaxes the need for !$acc host_data use_device(list) blocks for most cases. However, user-written generics may require use of these blocks to help the compiler disambiguate argument references. Without these blocks, argument matching to specific functions of the generic interface may fail in Beta nvfortran. For example, Beta nvfortran may diagnose a generic resolution error for user-written generics being called with ambiguous variable reference(s).

error: No specific subroutine of generic 'name' matches the actual arguments

To illustrate this problem, the code below contains a generic “CALLEE” with a specific subroutine named “CALLEE_X”. Notice that dummy argument array_pinned is declared DEVICE. However, the call to the generic

call callee(array_pinned, n)

from the routine driver is passing an actual argument that is declared PINNED. References to array_pinned in driver will not match the interface since there is no DEVICE attribute on array_pinned in this context.

! pinned.f90: Beta nvfortran rejects a call where a PINNED (page-locked
! host) array is passed to a dummy declared ATTRIBUTES(DEVICE) via an
! explicit generic interface. This was accepted by classic nvfortran
!
! Compile:
!   nvfortran -cuda -acc -c pinned.f90

module callee_impl
  use cudafor
  implicit none
  ! generic interface referencing the module procedure below.
  interface callee
    module procedure callee_x
  end interface

  ! declaration of PINNED array "array_pinned".
  complex(8), allocatable, target ,PINNED :: array_pinned(:,:)
contains
  ! Specific implementation referenced by the generic interface.
  subroutine callee_x(x, n)
    complex(8), device, intent(in) :: x(:,:)
    integer :: n
  end subroutine callee_x
end module callee_impl

subroutine driver(n)
  use cudafor
  use callee_impl
  implicit none
  integer :: n
  allocate(array_pinned(n, n))

  !$acc data copy(array_pinned)
  !
  ! Bug: array_pinned's declared attribute is PINNED, but the generic resolves to
  ! callee_x whose dummy `x` requires ATTRIBUTES(DEVICE). The !$acc data
  ! region above creates a device copy, but without
  ! `!$acc host_data use_device(array_pinned)` the reference still resolves to
  ! the PINNED host pointer.
  !
  call callee(array_pinned, n)
  !
  ! Fix:
  !   !$acc host_data use_device(array_pinned)
  !   call callee(array_pinned, n)
  !   !$acc end host_data
  !
  !$acc end data

  deallocate(array_pinned)
end subroutine driver

Classic nvfortran will compile this example without a warning or error message. Classic nvfortran interprets the actual argument array_pinned as a device reference in this context even though it could also be interpreted as a host reference. It guesses that because there is a specific that would match IF array_pinned had the DEVICE attribute it makes the decision to implicitly give it DEVICE attribute. If this example had both HOST and DEVICE specifics for CALLEE then it is not clear which specific would match the generic.

Beta nvfortran will diagnose call callee(array_pinned, n) as an error since the actual argument has attribute PINNED while the dummy argument has attribute DEVICE. Beta nvfortran does not try to guess the user intent.

nvfortran -cuda -acc -c pinned.f90
error: Semantic errors in pinned.f90
pinned.f90:41:3: error: No specific subroutine of generic 'callee' matches the actual arguments
    call callee(array_pinned, n)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pinned.f90:20:14: Specific procedure 'callee_x' does not match the actual arguments because
    subroutine callee_x(x, n)
               ^^^^^^^^
pinned.f90:41:15: dummy argument 'x=' has ATTRIBUTES(DEVICE) but its associated actual argument has ATTRIBUTES(PINNED)
    call callee(array_pinned, n)
                ^^^^^^^^^^^^

As mentioned earlier, Beta nvfortran provides extensive argument checks between actual arguments and dummy arguments. In this particular case, following CUDA Fortran semantics, PINNED does not imply DEVICE: a PINNED array is a host array allocated in page-locked host memory. The arguments to CALLEE do not match in attributes. Therefore, Beta nvfortran will not find a specific function for the call to the generic CALLEE and thus will fail generic resolution. Pinned memory has both host and device contexts and thus requires the user to disambiguate data references. One way to correct this issue is to use !$acc host_data use_device(array_pinned) to inform the compiler that within the host_data block references to array_pinned should be interpreted as device references and not host references.

!$acc data copy(array_pinned)
!   callee_x's dummy `x` is ATTRIBUTES(DEVICE), so pass the device copy created
!   by the !$acc data region via host_data use_device.
 !$acc host_data use_device(array_pinned)
  call callee(array_pinned, n)
 !$acc end host_data
!$acc end data

You may find other contexts in which classic nvfortran assumptions about variable references in OpenMP and CUDA Fortran regions as either host or device based on context being rejected as errors or warnings by Beta nvfortran.

2.18. OpenMP

OpenMP support in beta nvfortran is based on the new Flang/LLVM front end and is still actively being developed by the community. The goal is to track the most recent OpenMP standards as closely as possible while trying to keep behavior familiar for users coming from classic nvfortran.

You enable OpenMP in beta nvfortran the same way you do in classic:

  • -mp – the long-standing NVHPC/OpenMP switch, kept for compatibility.

  • -fopenmp – the more generic, Flang/LLVM-style OpenMP switch.

Either form will enable OpenMP in beta; you can keep using -mp if that is already baked into your build system, or you can standardize on -fopenmp if you prefer to align with other LLVM-based toolchains.

Internally, beta nvfortran uses the same libnvomp OpenMP runtime library as classic nvfortran on supported platforms. That means once an OpenMP region is set up and running, the runtime behavior (thread management, environment variables, etc.) is largely shared. However, the front-end and code generation are different:

  • the Flang-based front end parses and validates directives more strictly against the OpenMP standard,

  • the LLVM optimizer may reorder floating-point operations differently, and

  • loop scheduling and outlining can differ from classic.

Because of this, you should expect that:

  • Some OpenMP codes will show small numerical differences between classic and beta, especially in reductions and other order-sensitive patterns.

  • Some kernels may be faster or slower under beta even at the same nominal optimization level and OpenMP settings.

Treat beta as a different implementation that needs its own correctness and performance validation.

Because the new implementation is aiming for the latest OpenMP standards, you will inevitably run into cases that are not allowed in beta that are allowed in classic. For example, you may have an OpenMP region using a “reduction(-:var)” pattern that compiles and runs correctly with classic, but beta emits an error and halts compilation as seen here:

Beta:

$ nvfortran minus_reduction.F90 -o test -mp
error: Semantic errors in minus_reduction.F90
./minus_reduction.F90:5:20: error: The minus reduction operator is
deprecated since OpenMP 5.2 and is not supported in the REDUCTION
clause.
!$OMP PARALLEL DO REDUCTION(-:x)
                  ^^^^^^^^^^^^^^

We expect that these error messages should point the user to the offending code and the user should update their code to be standard compliant – this will be the most beneficial decision, as the code will be much more portable and usable by other compilers in this way.

Similarly, there will be OpenMP constructs that classic supports and beta has not yet implemented. For example, at the time of writing this, beta nvfortran supports simple metadirectives, but some metadirective forms are not yet implemented, whereas classic supports them. One such form is a metadirective whose variants are loop-associated constructs with data environments, such as parallel do. When compiling the following program, meta_omp.F90, classic will accept it, but beta will stop with a compile-time error, as seen below:

program meta_omp
integer :: i, n; real :: a(100), b(100), c(100)
n = 100
!$omp metadirective when(device={kind(cpu)}: parallel do) default(parallel do)
do i = 1, n
a(i) = b(i) + c(i)
end do
end program meta_omp

Beta:

$ nvfortran meta_omp.F90 -o test -fopenmp
error: loc("meta_omp.F90":4:46): ...: not yet implemented: data-environment construct in loop-associated METADIRECTIVE variant
LLVM ERROR: aborting

In general, if you use an OpenMP feature that beta nvfortran does not yet support, you should see:

  • a compile-time error, and

  • an explicit message that the OpenMP feature or clause is “not yet implemented” (or similar wording).

That behavior is intentional: we would much rather tell you that a given OpenMP feature is not ready rather than compile it and give you incorrect results or misleading performance.

There are exceptions, where beta nvfortran ignores an OpenMP directive and reports it only with a warning, then continues compiling. For example, an !$omp allocate directive for an allocatable array in the main program is ignored with:

warning: loc("ompmain.f90":3:7): TODO : OpenMP declarative ALLOCATE on SAVE variables or COMMON blocks is not yet supported, ignoring the ALLOCATE directive for 'a'

Do not treat a successful compilation as proof that every OpenMP directive took effect: review the warnings as well as the errors.

From a porting perspective:

  • Plan to re-validate OpenMP regions numerically under beta, even if they have been stable under classic, especially for reductions and complicated OpenMP structures.

  • Be prepared to tweak or modernize OpenMP directives that have relied on older legacy behavior or looser checking in classic nvfortran.

  • If you run into an OpenMP construct that fails without a “not yet implemented” error in beta – or if you see a surprising performance gap with OpenMP enabled – that is exactly the kind of feedback the NVHPC team would like to know about.

2.19. Working with us: reporting issues and feedback

Beta nvfortran is a new compiler. Although it has already been used on a wide range of codes, we fully expect that releasing into the wild will lead to users finding corner cases, missing options, or performance outliers that we have not yet seen.

The NVHPC team is very interested in your experience porting from classic to beta. If you run into anything that looks like a compiler bug, a surprising behavior change, or a serious performance issue:

  • Save a small reproducer

  • Note which compiler version, flags, and platform you are using,

  • Notify NVIDIA through your usual NVIDIA support channels, contact, or the NVHPC User Forum.

In many cases we may already have reported the underlying issue upstream to LLVM/Flang or be working on it internally. If not, we will work with you to characterize the problem, get it fixed, and, where appropriate, push a fix upstream so that the entire ecosystem benefits.

Your feedback directly shapes how beta nvfortran evolves and how quickly it becomes the default compiler in future NVHPC releases. Thank you for trying it out and for taking the time to tell us what works well and what does not.

Note that we highlighted earlier that this was not an all-inclusive guide – if anything was unclear or incomplete, please read the rest of the documentation that we shipped with the compiler. If you have questions beyond that, please reach out to us with questions. We would love to answer them for you.

3. Use Command-line Options

A command line option allows you to control specific behavior when a program is compiled and linked. This section describes the syntax for properly using command-line options and provides a brief overview of a few of the more common options.

3.1. Command-line Option Overview

Before looking at all the command-line options, first become familiar with the syntax for these options. There are a large number of options available to you, yet most users only use a few of them. So, start simple and progress into using the more advanced options.

By default, the NVIDIA HPC Fortran compiler generates code that is optimized for the type of processor on which compilation is performed, the compilation host. Before adding options to your command-line, review Help with Command-line Options and Frequently-used Options.

3.1.1. Command-line Options Syntax

On a command-line, options need to be preceded by a hyphen (-). If the compiler does not recognize an option, you get an unknown switch error. The error can be downgraded to a warning by adding the -noswitcherror option.

This document uses the following notation when describing options:

[item]

Square brackets indicate that the enclosed item is optional.

{item | item}

Braces indicate that you must select one and only one of the enclosed items. A vertical bar (|) separates the choices.

…

Horizontal ellipses indicate that zero or more instances of the preceding item are valid.

3.1.2. Command-line Suboptions

Some options accept several suboptions. You can specify these suboptions either by using the full option statement multiple times or by using a comma-separated list for the suboptions.

The following two command lines are equivalent:

nvfortran -Mvect=simd -Mvect=noaltcode
nvfortran -Mvect=simd,noaltcode

3.1.3. Command-line Conflicting Options

Some options have an opposite or negated counterpart. For example, both -Mvect and -Mnovect are available. -Mvect enables vectorization and -Mnovect disables it. If you used both of these commands on a command line, they would conflict.

Note

When you use conflicting options on a command line, the last encountered option takes precedence over any previous one.

The conflicting options rule is important for a number of reasons.

  • Some options, such as -fast, include other options. Therefore, it is possible for you to be unaware that you have conflicting options.

  • You can use this rule to create makefiles that apply specific flags to a set of files, as shown in the following example.

Example: Makefiles with Options

In this makefile fragment, FFLAGS uses vectorization. FNOVECTFLAGS uses the flags defined for FFLAGS but disables vectorization.

FFLAGS=-c -Mvect=simd
FNOVECTFLAGS=$(FFLAGS) -Mnovect

3.2. Help with Command-line Options

If you are just getting started with the NVIDIA HPC Fortran compiler, it is helpful to know which options are available, when to use them, and which options most users find effective.

Using -help

The -help option is useful because it provides information about all options supported by the compiler.

You can use -help in one of three ways:

  • Use -help with no parameters to obtain a list of all the available options with a brief one-line description of each.

  • Add a parameter to -help to restrict the output to information about a specific option. The syntax for this usage is:

    -help <command line option>
    

    Suppose you use the following command to restrict the output to information about the -fast option:

    $ nvfortran -help -fast
    

    The output you see is similar to:

    -fast Common optimizations; includes -O2 -Munroll=c:1 -Mnoframe -Mlre
    

    In the following example, we add the -help parameter to restrict the output to information about the help command. The usage information for -help shows how groups of options can be listed or examined according to function.

    $ nvfortran -help -help
            -help[=groups|asm|debug|language|linker|opt|other|overall|phase|prepro|
             suffix|switch|target|variable]
    
  • Add a parameter to -help to restrict the output to a specific set of options or to a building process. The syntax for this usage is this:

    -help=<subgroup>
    

3.3. Getting Started with Performance

This section provides a quick overview of a few of the command-line options that are useful in improving multicore CPU performance.

3.3.1. Using -fast

The NVIDIA HPC Fortran compiler implements a wide range of options that allow users a fine degree of control on each optimization phase. When it comes to optimization of code, the quickest way to start is to use the option -fast. These options create a generally optimal set of flags. They incorporate optimization options to enable use of vector streaming SIMD instructions for 64-bit targets. They enable vectorization with SIMD instructions, cache alignment, and flush to zero mode.

Note

The contents of the -fast option are host-dependent. Further, you should use these options on both compile and link command lines.

The following table shows the typical -fast options.

Table 6 Typical -fast Options

Use this option…

To do this…

-O2

Specifies a code optimization level of 2.

-Munroll=c:1

Unrolls loops, executing multiple instances of the original loop during each iteration.

-Mnoframe

Do not generate code to set up a stack frame. Note: With this option, a stack trace does not work.

-Mlre

Enable loop-carried redundancy elimination.

-Mpre

Enable partial redundancy elimination

On most modern CPUs the -fast also includes the options shown in this table:

Table 7 Additional -fast Options

Use this option…

To do this…

-Mvect=simd

Generates packed SIMD instructions.

-Mcache_align

Aligns long objects on cache-line boundaries.

-Mflushz

Sets flush-to-zero mode.

-M[no]vect

Controls automatic vector pipelining.

To see the specific behavior of -fast for your target, use the following command:

$ nvfortran -help -fast

3.4. Frequently-used Options

In addition to overall performance, there are a number of other options that many users find useful when getting started. The following table provides a brief summary of these options.

Table 8 Commonly Used Command-Line Options

Use this option…

To do this…

-acc

Enable parallelization using OpenACC directives. By default the compilers will parallelize and offload OpenACC regions to an NVIDIA GPU. Use -acc=multicore to parallelize OpenACC regions for execution on all the cores of a multicore CPU.

-fast

This option creates a generally optimal set of flags for targets that support SIMD capability. It incorporates optimization options to enable use of vector streaming SIMD instructions, cache alignment and flushz.

-g

Instructs the compiler to include symbolic debugging information in the object module; sets the optimization level to zero unless a -O option is present on the command line. Conversely, to prevent the generation of DWARF information, use the -Mnodwarf option.

-gopt

Instructs the compiler to include symbolic debugging information in the object file, and to generate optimized code identical to that generated when -g is not specified.

-gpu

Control the type of GPU for which code is generated, the version of CUDA to be targeted, and several other aspects of GPU code generation.

-help

Provides information about available options.

-mcmodel=medium

Enables medium=model code generation for 64-bit targets, which is useful when the data space of the program exceeds 4GB.

-mp

Enable parallelization using OpenMP directives. By default the compilers will parallelize OpenMP regions for execution on all the cores of a multicore CPU. Use -mp=gpu to parallelize OpenMP regions for offload to an NVIDIA GPU.

-Mconcur

Instructs the compiler to enable auto-concurrentization of loops. If specified, the compiler uses multiple CPU cores to execute loops that it determines to be parallelizable; thus, loop iterations are split to execute optimally in a multithreaded execution context.

-Minfo

Instructs the compiler to produce information on standard error.

-Minline

Enables function inlining.

-Mkeepasm

Keeps the generated assembly files.

-Munroll

Invokes the loop unroller to unroll loops, executing multiple instances of the loop during each iteration. This also sets the optimization level to 2 if the level is set to less than 2, or if no -O or -g options are supplied.

-M[no]vect

Enables [Disables] the code vectorizer.

-o

Names the output file.

-O <level>

Specifies code optimization level where <level> is 0, 1, 2, 3, or 4.

-stdpar

Enable parallelization and offloading of Standard Fortran parallel constructs to NVIDIA GPUs; default is -stdpar=gpu.

-tp <target>

Specify a CPU target other than the compilation host CPU.

-Wl, <option>

Compiler driver passes the specified options to the linker.

3.5. Floating-point Subnormal

Starting with the 22.7 release of the NVIDIA HPC SDK the default setting of how floating-point denormal (IEEE 754 terminology “subnormal”) values are processed at runtime across both x86_64 and aarch64 processors has been changed to be more consistent.

Denormal values can be both operands to, and results of, floating-point operations. The x86_64 ISA differentiate between the two categories, operands and results, and use the terminology “daz” denormals are zeros for operands, and “flushz” flush to zero for results. The Arm V8 ISA as defined can differentiate between the two categories, but currently the processors that NVIDIA HPC SDK support only have a single setting for both operands and results and is defined as “fz” in the floating-point status and control register.

The NVIDIA HPC SDK Fortran compiler has command line switches -M[no]daz and -M[no]flushz, which when specified for the Fortran main program affect how denormals are handled by the processor at runtime. The values of these two command line switches are passed to the runtime library to configure the floating-point status and control register at program startup.

NVIDIA HPC SDK supports x86_64 processors from both Intel and AMD, and ArmV8.1 and later processors. The following table summarizes the default settings of the -Mdaz and -Mflushz command line switches pre and post the 22.7 release.

Table 9 Default settings of -Mdaz and -Mflushz

Pre 22.7 defaults

22.7 defaults

Intel

-Mdaz

-Mnoflushz

-Mdaz

-Mflushz

AMD

-Mnodaz

-Mnoflushz

-Mdaz

-Mflushz

Arm processors

-Mnodaz

-Mdaz

With the NVIDIA HPC SDK 22.7 release, the default handling of denormals operands and results is to treat them as zero, as if the main program were compiled with -Mdaz -Mflushz. Consequently, these changes can potentially affect applications that are dependent on subnormal values being non-zero.

Along with the change to the default treatment of denormal values, users now have the ability to configure the floating-point status and control register through the NVCOMPILER_FPU_STATE environment variable — effectively overriding how the program was originally compiled. For further information, see the description of the NVCOMPILER_FPU_STATE environment variable.

4. Multicore CPU Optimization

Source code that is readable, maintainable, and produces correct results is not always organized for efficient execution. Normally, the first step in the program development process involves producing code that executes and produces the correct results. This first step usually involves compiling without much worry about optimization. After code is compiled and debugged, code optimization and parallelization become an issue.

Invoking the NVFORTRAN compiler command with certain options instructs the compiler to generate optimized code. Optimization is not always performed since it increases compilation time and may make debugging difficult. However, optimization produces more efficient code that usually runs significantly faster than code that is not optimized.

The compiler optimizes code according to the specified optimization level. You can use a number of options to specify the optimization levels, including -⁠O, and -⁠Mvect. In addition, you can use several of the -⁠M<nvflag> switches to control specific types of optimization.

This chapter describes the overall effect of the optimization options supported by the NVIDIA HPC Fortran compiler (NVFORTRAN), and basic usage of several options.

4.1. Overview of Optimization

In general, optimization involves using transformations and replacements that generate more efficient code. This is done by the compiler and involves replacements that are independent of the particular target processor’s architecture as well as replacements that take advantage of the architecture, instruction set and registers.

For discussion purposes, we categorize optimization:

4.1.1. Local Optimization

A basic block is a sequence of statements in which the flow of control enters at the beginning and leaves at the end without the possibility of branching, except at the end. Local optimization is performed on a block-by-block basis within a program’s basic blocks.

The NVFORTRAN compiler performs many types of local optimization including: algebraic identity removal, constant folding, common sub-expression elimination, redundant load and store elimination, scheduling, strength reduction, and peephole optimizations.

4.1.2. Global Optimization

This optimization is performed on a subprogram over all its basic blocks. The optimizer performs control-flow and data-flow analysis for an entire program unit. All loops, including those formed by ad hoc branches such as IFs or GOTOs, are detected and optimized.

Global optimization includes: constant propagation, copy propagation, dead store elimination, global register allocation, invariant code motion, and induction variable elimination.

4.1.3. Loop Optimization: Unrolling, Vectorization and Parallelization

The performance of certain classes of loops may be improved through vectorization or unrolling options. Vectorization transforms loops to improve memory access performance and make use of packed SSEvector instructions which perform the same operation on multiple data items concurrently. Unrolling replicates the body of loops to reduce loop branching overhead and provide better opportunities for local optimization, vectorization and scheduling of instructions. Performance for loops on systems with multiple processors may also improve using the parallelization features of the NVFORTRAN compiler.

4.1.4. Function Inlining

This optimization allows a call to a function or subroutine to be replaced by a copy of the body of that function or subroutine. This optimization will sometimes speed up execution by eliminating the function call and return overhead. Function inlining may also create opportunities for other types of optimization. Function inlining is not always beneficial. When used improperly it may increase code size and generate less efficient code.

4.2. Getting Started with Optimization

The first concern should be getting the program to execute and produce correct results. To get the program running, start by compiling and linking without optimization. Add -O0 to the compile line to select no optimization; or add -g to debug the program easily and isolate any coding errors exposed during porting.

To get started quickly with optimization, a good set of options to use with the NVFORTRAN compiler is -fast. For example:

$ nvfortran -fast prog.f

For the NVFORTRAN compiler, the -⁠fast option generally produces code that is well-optimized without the possibility of significant slowdowns due to pathological cases.

  • The``-⁠fast`` option is an aggregate option that includes a number of individual NVIDIA compiler options; which compiler options are included depends on the target for which compilation is performed.

These aggregate options incorporate a generally optimal set of flags for targets that support SIMD capability, including vectorization with SIMD instructions, cache alignment, and flushz.

The following table shows the typical -⁠fast options.

Table 10 Typical -fast Options

Use this option…

To do this…

-O2

Specifies a code optimization level of 2 and -Mvect=SIMD.

-Munroll=c:1

Unrolls loops, executing multiple instances of the original loop during each iteration.

-Mnoframe

Indicates to not generate code to set up a stack frame. Note With this option, a stack trace does not work.

-Mlre

Indicates loop-carried redundancy elimination.

-Mpre

Indicates partial redundancy elimination

On modern multicore CPUs the -fast also typically includes the options shown in the following table:

Table 11 Additional -fast Options

Use this option…

To do this…

-Mvect=simd

Generates packed SSE and AVX instructions.

-Mcache_align

Aligns long objects on cache-line boundaries.

-Mflushz

Sets flush-to-zero mode.

By experimenting with individual compiler options on a file-by-file basis, further significant performance gains can sometimes be realized. However, depending on the coding style, individual optimizations can sometimes cause slowdowns, and must be used carefully to ensure performance improvements.

There are other useful command line options related to optimization and parallelization, such as -help, -Minfo, -Mneginfo, -dryrun, and -v.

4.2.1. -help

As described in Help with Command-Line Options, you can see a specification of any command-line option by invoking the NVFORTRAN compiler with -help in combination with the option in question, without specifying any input files.

For example, you might want information on -O:

$ nvfortran -help -O

The resulting output is similar to this:

-O Set opt level. All -O1 optimizations plus traditional scheduling and
  global scalar optimizations performed

Or you can see the full functionality of -help itself, which can return information on either an individual option or groups of options:

$ nvfortran -help -help

The resulting output is similar to this:

-help[=groups|asm|debug|language|linker|opt|other|overall|
phase|prepro|suffix|switch|target|variable]
Show compiler switches

4.2.2. -Minfo

You can use the -Minfo option to display compile-time optimization listings. When this option is used, the NVFORTRAN compiler issues informational messages to standard error (stderr) as compilation proceeds. From these messages, you can determine which loops are optimized using unrolling, SIMD vectorization, parallelization, GPU offloading, interprocedural optimizations and various miscellaneous optimizations. You can also see where and whether functions and subroutines are inlined.

4.2.3. -Mneginfo

You can use the -Mneginfo option to display informational messages to standard error (stderr) that explain why certain optimizations are inhibited.

4.2.4. -dryrun

The -⁠dryrun option can be useful as a diagnostic tool if you need to see the steps used by the compiler driver to preprocess, compile, assemble and link in the presence of a given set of command line inputs. When you specify the -⁠dryrun option, these steps are printed to standard error (stderr) but are not actually performed. For example, you can use this option to inspect the default and user-specified libraries that are searched during the link phase, and the order in which they are searched by the linker.

4.2.5. -v

The -v option is similar to -dryrun, except each compilation step is performed and not simply printed.

4.3. Local and Global Optimization

This section describes local and global optimization.

4.3.1. -O

Using the NVFORTRAN compiler command with the -O<level> option (the capital O is for Optimize), you can specify any integer level from 0 to 4.

-O0

Level zero specifies no optimization. A basic block is generated for each language statement. At this level, the compiler generates a basic block for each statement.

Performance will almost always be slowest using this optimization level. This level is useful for the initial execution of a program. It is also useful for debugging, since there is a direct correlation between the program text and the code generated. To enable debugging, include -g on your compile line.

-O1

Level one specifies local optimization. Scheduling of basic blocks is performed. Register allocation is performed.

Local optimization is a good choice when the code is very irregular, such as code that contains many short statements containing IF statements and does not contain loops (DO or DO WHILE statements ). Although this case rarely occurs, for certain types of code, this optimization level may perform better than level-two (-O2).

-O

When no level is specified, level two global optimizations are performed, including traditional scalar optimizations, induction recognition, and loop invariant motion. No SIMD vectorization is enabled.

-O2

Level two specifies global optimization. This level performs all level-one local optimization as well as level two global optimization described in -O. In addition, more advanced optimizations such as SIMD code generation, cache alignment, and partial redundancy elimination are enabled.

-O3

Level three specifies aggressive global optimization. This level performs all level-one and level-two optimizations and enables more aggressive hoisting and scalar replacement optimizations that may or may not be profitable.

-O4

Level four performs all level-one, level-two, and level-three optimizations and enables hoisting of guarded invariant floating point expressions.

Types of Optimizations

The NVFORTRAN compiler performs many different types of local optimizations, including but not limited to:

  • Algebraic identity removal

  • Constant folding

  • Common subexpression elimination

  • Local register optimization

  • Peephole optimizations

  • Redundant load and store elimination

  • Strength reductions

Level-two optimization (-⁠O2 or -⁠O) specifies global optimization. The -⁠fast option generally specifies global optimization; however, the -⁠fast switch varies from release to release, depending on a reasonable selection of switches for any one particular release. The -⁠O or -⁠O2 level performs all level-one local optimizations as well as global optimizations. Control flow analysis is applied and global registers are allocated for all functions and subroutines. Loop regions are given special consideration. This optimization level is a good choice when the program contains loops, the loops are short, and the structure of the code is regular.

The NVFORTRAN compiler performs many different types of global optimizations, including but not limited to:

  • Branch to branch elimination

  • Constant propagation

  • Copy propagation

  • Dead store elimination

  • Global register allocation

  • Induction variable elimination

  • Invariant code motion

You can explicitly select the optimization level on the command line. For example, the following command line specifies level-two optimization which results in global optimization:

$ nvfortran -O2 prog.f

The default optimization level changes depending on which options you select on the command line. For example, when you select the -⁠g debugging option, the default optimization level is set to level-zero (-⁠O0). However, if you need to debug optimized code, you can use the -⁠gopt option to generate debug information without perturbing optimization. For a description of the default levels, refer to Default Optimization Levels.

The -⁠fast option includes -⁠O2 on all targets. If you want to override the default for -⁠fast with -⁠O3 while maintaining all other elements of -⁠fast, simply compile as follows:

$ nvfortran -fast -O3 prog.f

4.4. Loop Unrolling using -Munroll

This optimization unrolls loops, which reduces branch overhead, and can improve execution speed by creating better opportunities for instruction scheduling. A loop with a constant count may be completely unrolled or partially unrolled. A loop with a non-constant count may also be unrolled. A candidate loop must be an innermost loop containing one to four blocks of code.

The following example shows the use of the -Munroll option:

$ nvfortran -Munroll prog.f

The -Munroll option is included as part of -fast on all targets. The loop unroller expands the contents of a loop and reduces the number of times a loop is executed. Branching overhead is reduced when a loop is unrolled two or more times, since each iteration of the unrolled loop corresponds to two or more iterations of the original loop; the number of branch instructions executed is proportionately reduced. When a loop is unrolled completely, the loop’s branch overhead is eliminated altogether.

Loop unrolling may be beneficial for the instruction scheduler. When a loop is completely unrolled or unrolled two or more times, opportunities for improved scheduling may be presented. The code generator can take advantage of more possibilities for instruction grouping or filling instruction delays found within the loop.

Examples Showing Effect of Unrolling

The following side-by-side examples show the effect of code unrolling on a segment that computes a dot product.

Note

This example is only meant to represent how the compiler can transform the loop; it is not meant to imply that the programmer needs to manually change code. In fact, manually unrolling your code can sometimes inhibit the compiler’s analysis and optimization.

Table 12 Example of Effect of Code Unrolling

Dot Product Code

Unrolled Dot Product Code

REAL*4 A(100), B(100), Z
 INTEGER I
 DO I=1, 100
   Z = Z + A(i) * B(i)
 END DO
END
REAL*4 A(100), B(100), Z
 INTEGER I
 DO I=1, 100, 2
   Z = Z + A(i) * B(i)
   Z = Z + A(i+1) * B(i+1)
 END DO
END

Using the -Minfo option, the compiler informs you when a loop is being unrolled. For example, a message similar to the following, indicating the line number, and the number of times the code is unrolled, displays when a loop is unrolled:

dot:
  5, Loop unrolled 5 times

Using the c:<m> and n:<m> sub-options to -⁠Munroll, or using -⁠Mnounroll, you can control whether and how loops are unrolled on a file-by-file basis. For more information on -⁠Munroll, refer to Use Command-line Options.

4.5. Vectorization using -Mvect

The -⁠Mvect option is included as part of -⁠fast on all multicore CPU targets. If your program contains computationally-intensive loops, the -⁠Mvect option may be helpful. If in addition you specify -⁠Minfo, and your code contains loops that can be vectorized, the compiler reports relevant information on the optimizations applied.

When the NVFORTRAN compiler command is invoked with the -⁠Mvect option, the vectorizer scans code searching for loops that are candidates for high-⁠level transformations such as loop distribution, loop interchange, cache tiling, and idiom recognition (replacement of a recognizable code sequence, such as a reduction loop, with optimized code sequences or function calls). When the vectorizer finds vectorization opportunities, it internally rearranges or replaces sections of loops (the vectorizer changes the code generated; your source code’s loops are not altered). In addition to performing these loop transformations, the vectorizer produces extensive data dependence information for use by other phases of compilation and detects opportunities to use vector or packed SIMD instructions on processors where these are supported.

The -⁠Mvect option can speed up code which contains well-behaved countable loops which operate on large floating point arrays in Fortran. However, it is possible that some codes will show a decrease in performance when compiled with the -⁠Mvect option due to the generation of conditionally executed code segments, inability to determine data alignment, and other code generation factors. For this reason, it is recommended that you check carefully whether particular program units or loops show improved performance when compiled with this option enabled.

4.5.1. Vectorization Sub-options

The vectorizer performs high-level loop transformations on countable loops. A loop is countable if the number of iterations is set only before loop execution and cannot be modified during loop execution. Some of the vectorizer transformations can be controlled by arguments to the -Mvect command line option. The following sections describe the arguments that affect the operation of the vectorizer. In addition, some of these vectorizer operations can be controlled from within code using directives.

The vectorizer performs the following operations:

  • Loop interchange

  • Loop splitting

  • Loop fusion

  • Generation of SIMD instructions on CPUs where these are supported

  • Generation of prefetch instructions on processors where these are supported

  • Loop iteration peeling to maximize vector alignment

  • Alternate code generation

The following table lists and briefly describes some of the -Mvect suboptions.

Table 13 -Mvect Suboptions

Use this option …

To instruct the vectorizer to do this …

-Mvect=altcode

Generate appropriate code for vectorized loops.

-Mvect=[no]assoc

Perform[disable] associativity conversions that can change the results of a computation due to a round-off error. For example, a typical optimization is to change one arithmetic operation to another arithmetic operation that is mathematically correct,

but can be computationally different and generate faster code. This option is provided to enable or disable this transformation, since a round-off error for such associativity conversions may produce unacceptable results.

-Mvect=fuse

Enable loop fusion.

-Mvect=gather

Enable vectorization of indirect array references.

-Mvect=idiom

Enable idiom recognition.

-Mvect=levels:<n>

Set the maximum next level of loops to optimize.

-Mvect=nocond

Disable vectorization of loops with conditions.

-Mvect=partial

Enable partial loop vectorization via inner loop distribution.

-Mvect=prefetch

Automatically generate prefetch instructions when vectorizable loops are encountered, even in cases where SSESIMD instructions are not generated.

-Mvect=short

Enable short vector operations.

-Mvect=simd

Automatically generate packed SSE (Streaming SIMD Extensions)SIMD, and prefetch instructions when vectorizable loops are encountered. SIMD instructions, first introduced on Pentium III and AthlonXP processors, operate on single-precision floating-point data.

-Mvect=sizelimit:n

Limit the size of vectorized loops.

-Mvect=sse

Equivalent to -Mvect=simd.

-Mvect=uniform

Perform consistent optimizations in both vectorized and residual loops. Be aware that this may affect the performance of the residual loop.

Note

Inserting no in front of an option disables the option. For example, to disable the generation of SIMD instructions, compile with -Mvect=nosimd.

4.5.2. Vectorization Example Using SIMD Instructions

One of the most important vectorization options is -Mvect=simd. When you use this option, the compiler automatically generates SIMD vector instructions, where possible, when targeting processors on which these instructions are supported. This process can improve performance by several factors compared with the equivalent scalar code. The NVFORTRAN compiler supports this capability.

In the program in Vector operation using SIMD instructions, the vectorizer recognizes the vector operation in subroutine ‘loop’ when either compiler switch -Mvect=simd or -fast is used. This example shows the compilation, informational messages, and runtime results using SIMD instructions on an Intel Core i7 7800X Skylake system, along with issues that affect SIMD performance.

Loops vectorized using SIMD instructions operate much more efficiently when processing vectors that are aligned to a cache-line boundary. You can cause unconstrained data objects of size 16 bytes or greater to be cache-aligned by compiling with the -Mcache_align switch. An unconstrained data object is a data object that is not a common block member and not a member of an aggregate data structure.

Note

For stack-based local variables to be properly aligned, the main program or function must be compiled with -Mcache_align.

The -Mcache_align switch has no effect on the alignment of Fortran allocatable or automatic arrays. If you have arrays that are constrained, such as vectors that are members of Fortran common blocks, you must specifically pad your data structures to ensure proper cache alignment. You can use -Mcache_align for only the beginning address of each common block to be cache-aligned.

The following examples show the results of compiling the sample code in Vector operation using SIMD instructions both with and without the option -Mvect=simd.

Vector operation using SIMD instructions

program vector_op
 parameter (N = 9999)
 real*4 x(N), y(N), z(N), W(N)
 do i = 1, n
   y(i) = i
   z(i) = 2*i
   w(i) = 4*i
 enddo
 do j = 1, 200000
   call loop(x,y,z,w,1.0e0,N)
 enddo
 print *, x(1),x(771),x(3618),x(6498),x(9999)
end
subroutine loop(a,b,c,d,s,n)
 integer i, n
 real*4 a(n), b(n), c(n), d(n),s
 do i = 1, n
   a(i) = b(i) + c(i) - s * d(i)
 enddo
end

Assume the preceding program is compiled as follows, where -Mvect=nosimd disables SIMD vectorization:

$ nvfortran -fast -Mvect=nosimd -Minfo vadd.f -Mfree -o vadd
vector_op:
      4, Loop unrolled 16 times
         Generated 1 prefetches in scalar loop
      9, Loop not vectorized/parallelized: contains call
loop:
     18, Loop unrolled 8 times
         FMA (fused multiply-add) instruction(s) generated

The following output shows a sample result if the generated executable is run and timed on an Intel Core i7 7800X Skylake system:

$ /bin/time vadd
   -1.000000       -771.0000       -3618.000       -6498.000
   -9999.000
0.99user 0.01system 0:01.18elapsed 84%CPU (0avgtext+0avgdata 3120maxresident)k
7736inputs+0outputs (4major+834minor)pagefaults 0swaps
$ /bin/time vadd
   -1.000000       -771.0000       -3618.000       -6498.000
   -9999.000
2.31user 0.00system 0:02.57elapsed 89%CPU (0avgtext+0avgdata 6976maxresident)k
8192inputs+0outputs (4major+149minor)pagefaults 0swaps

Now, recompile with vectorization enabled, and you see results similar to these:

$ nvfortran -fast -Minfo vadd.f -Mfree -o vadd
vector_op:
      4, Loop not vectorized: may not be beneficial
         Unrolled inner loop 8 times
         Residual loop unrolled 7 times (completely unrolled)
         Generated 1 prefetches in scalar loop
      9, Loop not vectorized/parallelized: contains call
loop:
     18, Generated 2 alternate versions of the loop
         Generated vector simd code for the loop
         Generated 3 prefetch instructions for the loop
         Generated vector simd code for the loop
         Generated 3 prefetch instructions for the loop
         Generated vector simd code for the loop
         Generated 3 prefetch instructions for the loop
         FMA (fused multiply-add) instruction(s) generated

Notice the informational messages for the loop at line 18. The first line of the message indicates that two alternate versions of the loop were generated. The loop count and alignments of the arrays determine which of these versions is executed. The next several lines indicate the loop was vectorized and that prefetch instructions have been generated for three loads to minimize latency of data transfers from main memory.

Executing again, you should see results similar to the following:

$ /bin/time vadd-simd
   -1.000000       -771.0000       -3618.000       -6498.000
   -9999.000
0.27user 0.00system 0:00.29elapsed 93%CPU (0avgtext+0avgdata 3124maxresident)k
0inputs+0outputs (0major+838minor)pagefaults 0swaps
$ /bin/time vadd-simd
   -1.000000       -771.0000       -3618.000       -6498.000
   -9999.000
0.62user 0.00system 0:00.65elapsed 95%CPU (0avgtext+0avgdata 6976maxresident)k
0inputs+0outputs (0major+151minor)pagefaults 0swaps

The SIMD result is 3.7 times faster than the equivalent non-SIMD version of the program.

Speed-up realized by a given loop or program can vary widely based on a number of factors:

  • When the vectors of data are resident in the data cache, performance improvement using SIMD instructions is most effective.

  • If data is aligned properly, performance will be better in general than when using SIMD operations on unaligned data.

  • If the compiler can guarantee that data is aligned properly, even more efficient sequences of SIMD instructions can be generated.

  • The efficiency of loops that operate on single-precision data can be higher. SIMD instructions can operate on four single-precision elements concurrently, but only two double-precision elements.

Note

Compiling with -Mvect=simd can result in numerical differences from the executables generated with less optimization. Certain vectorizable operations, for example dot products, are sensitive to order of operations and the associative transformations necessary to enable vectorization (or parallelization).

5. Using Function Inlining

Function inlining replaces a call to a function or a subroutine with the body of the function or subroutine. This can speed up execution by eliminating parameter passing and function/subroutine call and return overhead. It also allows the compiler to optimize the function with the rest of the code. Note that using function inlining indiscriminately can result in much larger code size and no increase in execution speed.

The NVFORTRAN compiler lets you inline functions and subroutines with the -Minline option.

Note

In this release, nvfortran does not yet implement inline libraries or the -Minline suboptions. -Minline enables inlining, the same as -finline-functions, and the compiler chooses which procedures to inline. -Mextract is ignored with the warning nvfortran-Warning-not yet implemented: -Mextract. Calls are inlined only when the procedure is defined in the same source file, unless you compile and link with -flto.

This section describes how to use the following options related to function inlining:

-Minline
-Mnoinline
-Mrecursive

In this release, -Mrecursive changes neither the generated code nor which procedures are inlined, because nvfortran already compiles procedures so that they can be called recursively.

5.1. Invoking Procedure Inlining

To invoke the procedure inliner, use the -Minline option. Inlining can be disabled with -Mnoinline. Inlining is turned on implicitly when -O2, -O3, -O4 or -fast option is applied.

5.2. Error Detection during Inlining

You can specify the -Minfo=inline option to request inlining information from the compiler when you invoke the inliner. For example:

$ nvfortran -Minline -Minfo=inline myext.f

5.3. Examples

Assume the program dhry consists of a single source file dhry.f. The following command line builds an executable file for dhry in which functions or subroutines are inlined wherever they are called:

$ nvfortran dhry.f -Minline

6. Using GPUs

An NVIDIA GPU can be used as an accelerator to which a CPU can offload data and executable kernels to perform compute-intensive calculations. This section gives an overview of options for programming NVIDIA GPUs with the NVIDIA HPC Fortran compiler (NVFORTRAN) and covers topics that affect GPU programming when using one or more of the GPU programming models.

6.1. Overview

With the NVIDIA HPC Fortran compiler you can program NVIDIA GPUs using certain standard language constructs, OpenACC directives, or CUDA Fortran language extensions. GPU programming with standard language constructs or directives allows you to create high-level GPU-accelerated programs without the need to explicitly initialize the GPU, manage data or program transfers between the host and GPU, or initiate GPU startup and shutdown. Rather, all of these details are implicit in the programming model and are managed by the NVIDIA HPC SDK Fortran compiler. GPU programming with CUDA Fortran extensions gives you access to all NVIDIA GPU features and full control over data management and offloading of compute-intensive loops and kernels.

The NVFORTRAN compiler supports automatic offload to NVIDIA GPUs of certain Fortran array intrinsics and patterns of array syntax, including use of Volta and Ampere architecture Tensor Cores for appropriate intrinsics. See the Blog post Bringing Tensor Cores to Standard Fortran for details on using this feature.

The NVFORTRAN compiler supports CUDA programming in Fortran. See the NVIDIA CUDA Fortran Programming Guide for complete details on how to use CUDA Fortran.

The NVFORTRAN compiler supports directive-based programming of NVIDIA GPUs using OpenACC. OpenACC is an accelerator programming model that is portable across operating systems and various host CPUs and types of accelerators, including both NVIDIA GPUs and multicore CPUs. OpenACC directives allow a programmer to migrate applications incrementally to accelerator targets using standards-compliant Fortran that remains completely portable to other compilers and systems. It allows the programmer to augment information available to the compiler, including specification of data local to an accelerator region, guidance on mapping of loops onto an accelerator, and similar performance-related details.

The NVFORTRAN compiler supports a subset of the OpenMP Application Program Interface for multicore CPUs. The -mp option defaults to -mp=multicore. OpenMP offload to GPUs is not supported.

In user-directed accelerator programming the user specifies the regions of a host program to be targeted for offloading to an accelerator. The bulk of a user’s program, as well as regions containing constructs that are not supported on the targeted accelerator, are executed on the host.

6.2. Terminology

Clear and consistent terminology is important in describing any programming model. This section provides definitions of the terms required for you to effectively use this section and the associated programming model.

Accelerator

a parallel processor, such as a GPU or a CPU running in multicore mode, to which a CPU can offload data and executable kernels to perform compute-intensive calculations.

Compute intensity

for a given loop, region, or program unit, the ratio of the number of arithmetic operations performed on computed data divided by the number of memory transfers required to move that data between two levels of a memory hierarchy.

Compute region

a structured block defined by a compute construct. A compute construct is a structured block containing loops which are compiled for the accelerator. A compute region may require device memory to be allocated and data to be copied from host to device upon region entry, and data to be copied from device to host memory and device memory deallocated upon exit. The dynamic range of a compute construct, including any code in procedures called from within the construct, is the compute region. In this release, compute regions may not contain other compute regions or data regions.

Construct

a structured block identified by the programmer or implicitly defined by the language. Certain actions may occur when program execution reaches the start and end of a construct, such as device memory allocation or data movement between the host and device memory. Loops in a compute construct are targeted for execution on the accelerator. The dynamic range of a construct including any code in procedures called from within the construct, is called a region.

CUDA

stands for Compute Unified Device Architecture; CUDA Fortran language extensions and API calls can be used to explicitly control and program an NVIDIA GPU.

Data region

a region defined by a data construct, or an implicit data region for a function or subroutine containing directives. Data regions typically require device memory to be allocated and data to be copied from host to device memory upon entry, and data to be copied from device to host memory and device memory deallocated upon exit. Data regions may contain other data regions and compute regions.

Device

a general reference to any type of accelerator.

Device memory

memory attached to an accelerator which is physically separate from the host memory.

Directive

a specially formatted comment statement that is interpreted by a compiler to augment information about or specify the behavior of the program.

DMA

Direct Memory Access, a method to move data between physically separate memories; this is typically performed by a DMA engine, separate from the host CPU, that can access the host physical memory as well as an IO device or GPU physical memory.

GPU

a Graphics Processing Unit; one type of accelerator device.

Host

the main CPU that in this context has an attached accelerator device. The host CPU controls the program regions and data loaded into and executed on the device.

Loop trip count

the number of times a particular loop executes.

Private data

with respect to an iterative loop, data which is used only during a particular loop iteration. With respect to a more general region of code, data which is used within the region but is not initialized prior to the region and is re-initialized prior to any use after the region.

Region

the dynamic range of a construct, including any procedures invoked from within the construct.

Structured block

a block of executable statements with a single entry at the top and a single exit at the bottom.

Vector operation

a single operation or sequence of operations applied uniformly to each element of an array.

Visible device copy

a copy of a variable, array, or subarray allocated in device memory, that is visible to the program unit being compiled.

6.3. Execution Model

The execution model targeted by the NVIDIA HPC Fortran compiler is host-directed execution with an attached accelerator device, such as a GPU. The bulk of a user application executes on the host. Compute intensive regions are offloaded to the accelerator device under control of the host. The accelerator device executes kernels, which may be as simple as a tightly-nested loop, or as complex as a subroutine, depending on the accelerator hardware.

6.3.1. Host Functions

Even in accelerator-targeted regions, the host must orchestrate the execution; it

  • allocates memory on the accelerator device

  • initiates data transfer

  • sends the kernel code to the accelerator

  • passes kernel arguments

  • queues the kernel

  • waits for completion

  • transfers results back to the host

  • deallocates memory

Note

In most cases, the host can queue a sequence of kernels to be executed on the device, one after the other.

6.4. Memory Model

The most significant difference between a host-only program and a host+accelerator program is that the memory on the accelerator can be completely separate from host memory, which is the case on many GPUs. For example:

  • The host cannot read or write accelerator memory directly because it is not mapped into the virtual memory space of the host.

  • All data movement between host memory and accelerator memory must be performed by the host through runtime library calls that explicitly move data between the separate memories.

  • In general it is not valid for the compiler to assume the accelerator can read or write host memory directly. This is well-defined starting with the OpenACC 2.7 specification.

The systems with the latest GPUs provide a unified single address space between CPU and GPU for some or all memory regions, as detailed in the Managed and Unified Memory Modes subsection below. In these systems data can be accessed from host and accelerator subprograms without the need for explicit data movement.

The NVIDIA HPC Fortran compiler supports the following system memory modes:

Table 14 GPU Memory Modes

Memory Mode

Description

Compiler flags

Separate

All data accessed in host and accelerator programs are in separate (CPU and GPU) memories. Data in the application need to be physically moved between CPU and GPU memory either by adding explicit annotations or by relying on a compiler to detect and migrate the data.

-gpu=mem:separate

Managed

Dynamically allocated host data are placed in CUDA Managed Memory which is a unified single address space between host and accelerator programs and can therefore be accessed on device without explicit data movement. All other data (host, stack, or global data) remain in separate memory.

-gpu=mem:managed

Unified

All host data are placed in a unified single address space between the host and accelerator subprograms; no explicit data movements are required. This mode is intended for targets with full CUDA Unified Memory capability and by default uses CUDA Managed Memory for dynamic allocations.

-gpu=mem:unified

If the memory mode is not selected explicitly by passing one of the above -gpu=mem:* options, the compiler selects a default memory mode. The default memory mode for Stdpar is explained in Using Stdpar. When Stdpar is not enabled, the default memory mode is Separate Memory. Memory modes may have specific semantics in each programming model and the compiler can sometimes implicitly determine the data movement that’s required. More details can be found in the subsections of each programming model.

The compiler implicitly defines the following macros corresponding to the memory mode it compiles for:

  • When the code is compiled for Separate Memory Mode, the compiler defines __NVCOMPILER_GPU_SEPARATE_MEM macro.

  • When the code is compiled for Managed Memory Mode, the compiler defines __NVCOMPILER_GPU_MANAGED_MEM macro.

  • When the code is compiled for Unified Memory Mode, the compiler defines __NVCOMPILER_GPU_UNIFIED_MEM macro.

When a binary is compiled for one memory mode it may need to be run on a system with specific memory capabilities as follows:

  • Applications compiled for Separate Memory Mode can run on any CUDA platforms.

  • Applications compiled for Managed Memory Mode must be run on platforms with CUDA Managed Memory or full CUDA Unified Memory capabilities.

  • Applications compiled for Unified Memory Mode must be run on platforms with full CUDA Unified Memory.

Note

Memory allocated in the accelerator subprogram can’t be accessed or deallocated from the host.

6.4.1. Separate Host and Accelerator Memory Considerations

The programmer must be aware of the potentially separate memories for many reasons, including but not limited to:

  • Memory bandwidth between host memory and accelerator memory determines the compute intensity required to effectively accelerate a given region of code.

  • Limited size of accelerator memory may prohibit offloading of regions of code that operate on very large amounts of data.

6.4.1.1. Accelerator Memory

On the accelerator side, current GPUs implement a weak memory model. In particular, they do not support memory coherence between threads unless those threads are parallel only at the synchronous level and the memory operations are separated by an explicit barrier. Otherwise, if one thread updates a memory location and another reads the same location, or two threads store a value to the same location, the hardware does not guarantee the results. While the results of running such a program might be inconsistent, it is not accurate to say that the results are incorrect. By definition, such programs are defined as being in error. While a compiler can detect some potential errors of this nature, it is nonetheless possible to write an accelerator region that produces inconsistent numerical results.

Stack data in accelerator subprograms are allocated per thread. Stack data from one thread are not accessible by the other threads.

6.4.1.2. Staging Memory Buffer

Memory transfers between the accelerator and host may not always be asynchronous with respect to the host, even if the chosen programming model (for instance, OpenACC) declares that. This limitation may be due to the specific GPU and host memory architectures.

In order to help the host program proceed while a memory transfer to or from the accelerator is underway, the NVIDIA HPC Compilers Runtime maintains a designated staging memory area, also known as a pinned buffer. This memory area is registered with the CUDA API, which makes it suitable for asynchronous memory transfers between the GPU and the host. When an asynchronous memory transfer is started, the data being transferred is staged through the pinned buffer. Multiple asynchronous operations on the same data can be issued - in that case, the runtime system will operate on the data staged in the pinned buffer, not on the original host memory. When the host program issues an explicit or implicit synchronization request, the data is moved from the pinned buffer to its destination transparently to the application.

The runtime has the discretion to enable or disable the pinned buffer depending on the host and GPU memory architecture. Also, the size of the pinned buffer is determined by the runtime system as appropriate. The user can control some of these decisions using environment variables at the start of the application. Please refer to Environment Variables Controlling Device Memory Management to learn more.

6.4.1.3. Cache Management

Some current GPUs have a software-managed cache, some have hardware-managed caches, and most have hardware caches that can be used only in certain situations and are limited to read-only data. In low-level programming models such as CUDA Fortran, it is up to the programmer to manage these caches. The OpenACC programming model provides directives the programmer can use as hints to the compiler for cache management.

6.4.1.4. Environment Variables Controlling Device Memory Management

This section summarizes the environment variables that the NVIDIA HPC Fortran compiler runtime uses to control device memory management.

The following table contains the environment variables that are currently supported and provides a brief description of each.

Table 15 Memory Management Environment Variables

Environment Variable

Use

NVCOMPILER_ACC_BUFFERSIZE

For NVIDIA CUDA devices, this defines the size of the pinned buffer used to transfer data between host and device.

NVCOMPILER_ACC_CHECK_UNIFIED

For NVIDIA CUDA devices, in the Unified Memory mode, when set to a non-zero integer value, this environment variable enables the run-time data validation checks for data shared between host and device. For more information, please refer to OpenACC with CUDA Unified Memory.

NVCOMPILER_ACC_CUDA_HEAPSIZE

For NVIDIA CUDA devices, sets the heap size limit for malloc() when called on device.

NVCOMPILER_ACC_CUDA_MAX_L2_FETCH_GRANULARITY

For NVIDIA CUDA devices, sets the maximum L2 cache fetch granularity size in bytes. A correct value is an integer between 0 and 128.

NVCOMPILER_ACC_CUDA_MEMALLOCASYNC

For NVIDIA CUDA devices, when set to a non-zero integer value, enables CUDA asynchronous memory allocations from the default CUDA memory pool as described in the CUDA Toolkit Documentation. By default, an internal NVIDIA HPC Runtime memory pool is used instead.

NVCOMPILER_ACC_CUDA_MEMALLOCASYNC_POOLSIZE

For NVIDIA CUDA devices, sets the size of the default CUDA memory pool for asynchronous allocations if the NVCOMPILER_ACC_CUDA_MEMALLOCASYNC environment variable is also set to a non-zero integer value.

NVCOMPILER_ACC_CUDA_NOCOPY

Disables the use of the pinned buffer when transferring user data between host and NVIDIA CUDA devices. When this variable is set to a non-zero integer value, user data will be transferred directly bypassing the pinned buffer. Asynchronous execution of such data transfers can be limited when this setting is in effect.

NVCOMPILER_ACC_CUDA_PIN

For NVIDIA CUDA devices, enables host memory pinning at data directives. When host memory is pinned, data transfers to and from the device can be asynchronous, which can potentially improve program performance. A non-zero integer value enables this mechanism. A value of 2 or greater additionally disallows unpinning the host data after it is pinned. A value of 3 or greater also enables pinning the whole array referenced in a data directive (provided that the size of the array is known), rather than its subarray specified in the data directive. By default, host data referenced at data directives is not pinned unless directed by the compiler at compile-time; refer to Command-line Options Selecting Compiler Memory Modes for more information about the compile-time memory modes.

NVCOMPILER_ACC_CUDA_PINSIZE

For NVIDIA CUDA devices, sets the host memory pinning granularity. If host memory pinning is enabled with the NVCOMPILER_ACC_CUDA_PIN environment variable, the runtime will attempt to use this setting to pin larger regions of memory at once, thus potentially lowering the cost of pinning memory when the program needs to pin multiple data regions separately. The maximum allowed value is 1 MB. By default, single byte pinning granularity is used. Pinning larger regions at once only takes effect when NVCOMPILER_ACC_CUDA_PIN is set to 2 or greater; with a value of 1 this setting has no visible effect.

NVCOMPILER_ACC_CUDA_PRINTFIFOSIZE

For NVIDIA CUDA devices, sets the buffer size for formatted output calls on device.

NVCOMPILER_ACC_CUDA_STACKSIZE

For NVIDIA CUDA devices, sets the stack size limit for device threads.

NVCOMPILER_ACC_DEV_MEMORY

For NVIDIA CUDA devices, when set to a valid non-zero size value, enables the use of a device memory pool and sets its size. By default, the device memory pool is not used.

NVCOMPILER_ACC_MEM_MANAGE

For NVIDIA CUDA devices, when set to the integer value 0, disables the use of an internal device memory manager. By default, the device memory manager is enabled. It maintains a list of deallocated chunks of device memory in an attempt to efficiently reuse them for future allocations.

NVCOMPILER_ACC_MEMHINTS

For NVIDIA CUDA devices, controls the use of automatic memory hints at data constructs in the managed and unified memory modes. Below is a breakdown of the permitted values (case insensitive):

  • DEFAULT: Use the default settings. On NVIDIA Grace Hopper systems, the default is currently ENABLE_EXPLICIT; on all other systems, the default is DISABLE.

  • DISABLE: Memory hints are disabled for all data constructs.

  • ENABLE_EXPLICIT: Memory hints are enabled for explicit data constructs only.

  • ENABLE_ALL: Memory hints are enabled for explicit and implicit data constructs.

NVCOMPILER_ACC_MEMPREFETCH

For NVIDIA CUDA devices, controls the use of automatic memory prefetching at data constructs in the managed and unified memory modes. Below is a breakdown of the permitted values (case insensitive):

  • DEFAULT: Use the default settings. On NVIDIA Grace Hopper systems, the default is currently DISABLE; on all other systems, the default is ENABLE_UPDATE.

  • DISABLE: Memory prefetching is disabled for all data constructs.

  • ENABLE_UPDATE: Memory prefetching is enabled for update data constructs only.

  • ENABLE_EXPLICIT: Memory prefetching is enabled for explicit data constructs only.

  • ENABLE_ALL: Memory prefetching is enabled for explicit and implicit data constructs.

NVCOMPILER_ACC_UNIFIED_ALLOC_MODE

For NVIDIA CUDA devices, controls the type of dynamically allocated memory when the application is compiled in the Unified Memory mode using the -gpu=mem:unified switch (case insensitive):

  • DEFAULT: Use the default settings. Currently, the default is MANAGED.

  • SYSTEM: Allocate system memory.

  • MANAGED: Allocate CUDA managed memory.

  • PINNED: Allocate host pinned memory.

6.4.1.5. NUMA Balancing

In system configurations where GPU memory is visible to the operating system as a NUMA node, automatic NUMA balancing (/proc/sys/kernel/numa_balancing=1) can degrade application performance and increase run-to-run performance variation in certain situations.

For best performance, disable automatic NUMA balancing system-wide when possible. Otherwise, use an explicit memory mapping policy, such as numactl -m 0 ./app, to bind CPU memory allocations to the CPU NUMA node closest to the GPU used by the application.

6.4.2. Managed and Unified Memory Modes

The NVIDIA HPC Fortran compiler supports interoperability with CUDA Unified Memory. This feature is available with the x86-64 and Arm Server compilers. Unified memory provides a single address space for CPU and GPU; data movement between CPU and GPU memories is implicitly handled by the NVIDIA CUDA driver.

Whenever data is accessed on the CPU or the GPU, it could trigger a data transfer if the last time it was accessed was not on the same device. In some cases, page thrashing may occur and impact performance. An introduction to CUDA Unified Memory is available on Parallel Forall.

6.4.2.1. Managed Memory Mode

In Managed Memory Mode, all Fortran explicit allocation statements (allocate) in a program unit are replaced by equivalent CUDA managed data allocation calls that place the data in CUDA Managed Memory. The result is that OpenACC data clauses and directives are not needed to manage data movement. They are essentially ignored and can be omitted. For Stdpar this is the minimal required memory mode since there are no specific annotations for data used in the parallel region.

To enable Managed Memory Mode, add the option -gpu=mem:managed to the compiler and linker command lines.

When a program allocates managed memory, it allocates host pinned memory as well as device memory thus making allocate and deallocate operations somewhat more expensive and data transfers somewhat faster. A memory pool allocator is used to mitigate the overhead of the allocate and deallocate operations. More details can be found in Memory Pool Allocator.

Managed Memory Mode has the following limitations:

  • Use of managed memory applies only to dynamically-allocated data.

  • Given an allocatable aggregate with a member that points to local, global, or static data, compiling with -gpu=mem:managed and attempting to access memory through that pointer from the compute kernel will cause a failure at runtime.

  • The -gpu=mem:managed compiler option must be used to compile the files in which variables (accessed from GPU) are allocated, even if there is no code to accelerate on the GPU in the source file.

  • When linking multiple object files, the application must ensure that all data are deallocated using the scheme corresponding to their allocation. For example if the data are allocated in managed memory the deallocation must be performed using CUDA API calls for managed memory. More details and extra compiler support is detailed in Interception of Deallocations.

Memory Allocations/Deallocations Automatically Changed to Managed Memory

When the compiler utilizes CUDA Managed Memory capability either with -gpu=mem:managed or -gpu=mem:unified, the following explicit allocations/deallocations are automatically changed into cudaMallocManaged/cudaFree-type allocations/deallocations:

  • All allocations of automatic arrays.

  • All allocate/deallocate statements with allocatable arrays or pointer variables.

6.4.2.2. Unified Memory Mode

In Unified Memory Mode, the requirements for the program are further relaxed compared to Managed Memory Mode. Specifically, not only is dynamically allocated system memory accessible on the GPU, but global and local memory are also accessible.

To enable this feature, add the option -gpu=mem:unified to the compiler and linker command lines.

Programs compiled with -gpu=mem:unified must be run on systems that support full CUDA Unified Memory capability. At this time, full CUDA Unified Memory is supported on NVIDIA Grace Hopper Superchip systems, NVIDIA Grace Blackwell Superchip systems, and Linux x86-64 systems running with the Heterogeneous Memory Management (HMM) feature enabled in the Linux kernel. Details about these platforms are available in the following blog posts on the NVIDIA website: Simplifying GPU Programming for HPC with NVIDIA Grace Hopper Superchip and Simplifying GPU Application Development with Heterogeneous Memory Management.

In Unified Memory Mode, the compiler assumes that any system memory is accessible on the GPU. By default, dynamic allocations are nevertheless placed in CUDA Managed Memory, because this can improve program performance. If you would like to enforce or prohibit the use of managed memory for dynamic allocations pass -gpu=mem:unified:managedalloc or -gpu=mem:unified:nomanagedalloc, respectively, to compilation and linking. To allocate system memory instead of managed memory you can also set NVCOMPILER_ACC_UNIFIED_ALLOC_MODE=SYSTEM at run time.

If the program is compiled with the -gpu=mem:unified switch, you can also use the NVCOMPILER_ACC_UNIFIED_ALLOC_MODE environment variable to select the dynamic memory allocation mode at runtime. Please refer to Environment Variables Controlling Device Memory Management for a comprehensive list of its recognized values.

Unified Memory Mode has the following limitations:

  • Unified memory support for OpenACC and Stdpar Fortran is not mix-and-match; all object files containing OpenACC directives or Fortran DO CONCURRENT constructs must be compiled and linked with -gpu=mem:unified to ensure correct execution.

Transitioning to Unified Memory Mode

Applications transitioning to architectures that support Unified Memory Mode can be recompiled with -gpu=mem:unified without any code modifications.

The programmer should be aware that in Unified Memory Mode, the whole program state becomes essentially shared between the CPU and the GPU. By implication, modifications to program variables made on the GPU are visible on the CPU. That is, the GPU does not operate on a copy of the data even if the program contains respective directives, but instead the GPU operates directly on the data in system memory. To understand the importance of this idea, consider the following OpenACC Fortran program:

module m
  integer, parameter :: N = 1000
  integer :: x(N)
contains
  subroutine foo()
    integer :: i
    !$acc enter data create(x(1:N))
    !$acc parallel loop
    do i = 1, N
      x(i) = i
    end do
  end subroutine foo
end module m

When compiled in Separate Memory Mode, in the subroutine foo a copy of the array x is created in GPU memory and initialized as written in the loop construct. When -gpu=mem:unified is added, however, the compiler ignores the acc enter data construct, and the loop construct initializes the array x in system memory.

Another implication of which to be aware, asynchronous code execution on the GPU can introduce race conditions over access to program data. More details about code patterns to avoid when writing application sources for Unified Memory Mode can be found in the sections about specific programming models of this guide e.g. OpenACC or CUDA Fortran.

6.4.2.3. Memory Hints and Prefetching

In Managed and Unified Memory Modes, applications can benefit from automatically issued memory hints and prefetching at both explicit and implicit data constructs.

Consider the following example:

real, allocatable :: a(:)
allocate(a(N))
do i = 1, N
   a(i) = i
end do
!$acc enter data copyin(a) async
!$acc parallel loop async
do i = 1, N
   a(i) = a(i) * 2.0
end do
!$acc update self(a) async

If the array a is allocated in managed or unified memory, no explicit memory copies are performed. However, at the acc enter data directive, it is often beneficial to automatically set the preferred memory location of the data to the device. At the acc update directive, the data is updated on the host, which the OpenACC runtime can translate into asynchronous memory prefetching from the device.

Similarly, copying data to the host or updating data on the device can be automatically translated into setting the preferred memory location to the host or prefetching to the device, respectively.

This behavior of the OpenACC runtime is controlled by the NVCOMPILER_ACC_MEMHINTS and NVCOMPILER_ACC_MEMPREFETCH environment variables. Refer to the section Environment Variables Controlling Device Memory Management to learn more.

OpenACC Runtime Interface

integer(accx_mem_hints_kind), parameter :: accx_mem_hints_default = 0
integer(accx_mem_hints_kind), parameter :: accx_mem_hints_disable = 1
integer(accx_mem_hints_kind), parameter :: accx_mem_hints_enable_explicit = 2
integer(accx_mem_hints_kind), parameter :: accx_mem_hints_enable_all = 3

integer(accx_mem_prefetch_kind), parameter :: accx_mem_prefetch_default = 0
integer(accx_mem_prefetch_kind), parameter :: accx_mem_prefetch_disable = 1
integer(accx_mem_prefetch_kind), parameter :: accx_mem_prefetch_enable_update = 2
integer(accx_mem_prefetch_kind), parameter :: accx_mem_prefetch_enable_explicit = 3
integer(accx_mem_prefetch_kind), parameter :: accx_mem_prefetch_enable_all = 4

subroutine accx_set_mem_hints( mode ) bind(c,name='accx_set_mem_hints')
subroutine accx_set_mem_prefetch( mode ) bind(c,name='accx_set_mem_prefetch')

The accx_set_mem_hints and accx_set_mem_prefetch APIs operate on a per-thread basis, meaning they affect only the calling host thread. The parameter values correspond directly to the values of the NVCOMPILER_ACC_MEMHINTS and NVCOMPILER_ACC_MEMPREFETCH environment variables.

The following APIs operate on a specific region of memory as a convenient shortcut you can use instead of relying on the CUDA Runtime API:

OpenACC Runtime Interface

integer, parameter :: accx_mem_advise_kind = 4
integer(accx_mem_advise_kind), parameter :: accx_mem_advise_set_read_mostly = 0
integer(accx_mem_advise_kind), parameter :: accx_mem_advise_unset_read_mostly = 1
integer(accx_mem_advise_kind), parameter :: accx_mem_advise_set_preferred_location = 2
integer(accx_mem_advise_kind), parameter :: accx_mem_advise_unset_preferred_location = 3
integer(accx_mem_advise_kind), parameter :: accx_mem_advise_set_accessed_by = 4
integer(accx_mem_advise_kind), parameter :: accx_mem_advise_unset_accessed_by = 5

integer, parameter :: accx_mem_advise_location_kind = 4
integer(accx_mem_advise_location_kind), parameter :: accx_mem_advise_location_none = 0
integer(accx_mem_advise_location_kind), parameter :: accx_mem_advise_location_host = 1
integer(accx_mem_advise_location_kind), parameter :: accx_mem_advise_location_device = 2

integer, parameter :: accx_mem_prefetch_location_kind = 4
integer(accx_mem_prefetch_location_kind), parameter :: accx_mem_prefetch_location_host = 0
integer(accx_mem_prefetch_location_kind), parameter :: accx_mem_prefetch_location_device = 1

subroutine accx_mem_advise (advice, location, ptr, bytes) bind(c,name='accx_mem_advise')
subroutine accx_mem_prefetch (location, ptr, bytes, async) bind(c,name='accx_mem_prefetch')

The accx_mem_advise subroutine maps directly to the CUDA Runtime function cudaMemAdvise.

The accx_mem_prefetch subroutine maps to the CUDA Runtime function cudaMemPrefetchAsync. A notable difference is the async parameter, which is associated with an OpenACC async queue, rather than a specific CUDA stream.

For more information, refer to the Memory Management section in CUDA Toolkit Documentation.

6.4.3. Memory Pool Allocator

Dynamic memory allocations may be made using cudaMallocManaged(), a routine which has higher overhead than allocating non-managed memory using cudaMalloc(). The more calls to cudaMallocManaged(), the more significant the impact on performance.

To mitigate the overhead of cudaMallocManaged() or other CUDA allocation API calls, there is a pool allocator enabled by default in the presence of the -gpu=mem:managed, -gpu=mem:separate:pinnedalloc, or -gpu=mem:unified compiler options. It can be disabled, or its behavior modified, using these environment variables:

Table 16 Pool Allocator Environment Variables

Environment Variable

Use

NVCOMPILER_ACC_POOL_ALLOC

Disable the pool allocator. The pool allocator is enabled by default; to disable it, set NVCOMPILER_ACC_POOL_ALLOC to 0.

NVCOMPILER_ACC_POOL_SIZE

Set the pool size. The default size is 1GB but other sizes (i.e., 2GB, 100MB, 500KB, etc.) can be used. The actual pool size is set such that the size is the nearest, smaller number in the Fibonacci series compared to the provided or default size. If necessary, the pool allocator will add more pools but only up to the NVCOMPILER_ACC_POOL_THRESHOLD value.

NVCOMPILER_ACC_POOL_ALLOC_MAXSIZE

Set the maximum size for allocations. The default maximum size for allocations is 500MB but another size (i.e., 100KB, 10MB, 250MB, etc.) can be used as long as it is greater than or equal to 16B.

NVCOMPILER_ACC_POOL_ALLOC_MINSIZE

Set the minimum size for allocation blocks. The default size is 128B but other sizes can be used. The size must be greater than or equal to 16B.

NVCOMPILER_ACC_POOL_THRESHOLD

Set the percentage of total device memory that the pool allocator can occupy. Values from 0 to 100 are accepted. The default value is 50, corresponding to 50% of device memory.

Note

Note that where the size is specified if the unit suffix (B, KB, MB or GB) is omitted, the value is set by default in bytes.

6.4.4. Interception of Deallocations

While the NVIDIA HPC Fortran compiler facilitates the use of managed or pinned memory automatically, the application must ensure that memory is deallocated using the API which “matches” the API used to allocate said memory. For example, if cudaMallocManaged is used to allocate, then cudaFree must be used to deallocate; if cudaMallocHost is used for allocations, cudaFreeHost must be used for deallocations. Understanding this requirement is particularly important when third party or standard libraries are used; these libraries may have been compiled without any memory mode settings which sets up a situation where the deallocation routines in the libraries may not match the allocations made. When data is deallocated with an unmatching API call, the application may exhibit undefined behavior including crashing. To mitigate this issue, the compiler supports an interception mode in which standard deallocations (e.g. the deallocate statement) are inspected by the runtime and, if the memory is not detected as being system-allocated, the runtime replaces the standard deallocation function with the deallocation API corresponding to the allocation scheme in use. To activate this interception mode, use the -gpu=interceptdeallocations compiler flag. The interception is enabled by default for Stdpar in the presence of managed memory allocations. To deactivate the interception use the -gpu=nointerceptdeallocations compiler switch. This interception can incur extra runtime overhead.

Note

In the current release, nvfortran -stdpar does not enable the interception of deallocations implicitly. Data allocated in Stdpar code and deallocated with a mismatched API, such as C free(), can cause a segmentation fault. To enable the interception, add the -gpu=interceptdeallocations option, for example nvfortran -stdpar -gpu=interceptdeallocations example.f90.

6.4.5. Command-line Options Selecting Compiler Memory Modes

The following table lists the command-line options that select the compiler memory modes.

Table 17 Command-line Options Corresponding to Compiler Memory Modes

Flag

Brief Description

-gpu=mem:managed

Managed Memory Mode

-gpu=mem:managed -stdpar

Managed Memory Mode with Stdpar, which otherwise defaults to Unified Memory Mode.

-gpu=mem:unified

Unified Memory Mode

-gpu=mem:unified:managedalloc

Unified Memory Mode, all dynamically allocated data are implicitly in CUDA Managed Memory. This is also the default behavior of -gpu=mem:unified.

-gpu=mem:unified:nomanagedalloc

Unified Memory Mode, CUDA Managed Memory is not used implicitly.

-gpu=mem:separate

Separate Memory Mode

-gpu=mem:separate:pinnedalloc

Separate Memory Mode, dynamically allocated data are in CPU pinned memory implicitly.

-gpu=mem:separate:nopinnedalloc

Separate Memory Mode, dynamically allocated data are not implicitly in CPU pinned memory.

6.4.6. Coherent Driver-based Memory Management (CDMM)

NVIDIA hardware-coherent architectures (including Grace Hopper, Grace Blackwell, and Vera Rubin) allow the NVIDIA driver to operate in either NUMA or CDMM mode. While NUMA mode exposes both CPU and GPU memory directly to the operating system, CDMM mode (available in driver version 13.0 and later) prevents GPU memory from being exposed to the operating system as a NUMA node. In this configuration, the NVIDIA driver manages GPU memory separately from CPU system memory. Detailed information is available in the blog post Understanding Memory Management on Hardware-Coherent Platforms. Starting with CUDA driver 13.4 (branch R615), CDMM mode is default.

All applications will continue to function correctly in CDMM mode. Performance will remain unchanged for OpenACC and Stdpar applications compiled for Separate or Managed Memory Mode.

The behavior and performance of Unified Memory applications may be affected by CDMM mode. In NVIDIA driver versions up to and including 13.5, system-allocated memory will not migrate to GPU memory. The GPU is able to access system-allocated memory, but there will be no migration of memory pages. This may hurt application performance if the data is accessed frequently by the GPU. NVHPC-inserted memory advice and prefetch hints have no effect in CDMM mode.

We recommend that HPC systems are configured in NUMA mode rather than CDMM mode for best performance of Unified Memory applications. To configure NUMA mode, see the NVIDIA Data Center GPU Driver Release Notes: select the release notes for the driver version you are installing and follow its NUMA mode configuration instructions. To check which mode a system is in:

$ grep Coherent /proc/driver/nvidia/params

This will return CoherentGPUMemoryMode: “driver” for CDMM, or “numa” for NUMA mode. When in NUMA mode, please also check that migration of system-allocated memory is enabled:

$ cat /sys/module/nvidia_uvm/parameters/uvm_disable_sam_migration

This will return “N” if migration is enabled and “Y” if it is disabled; it should be “N”. If it returns “Y”, ask your system administrator to reload the nvidia_uvm kernel module with uvm_disable_sam_migration=0. If the file does not exist, the installed driver predates this parameter and no action is needed.

If CDMM mode is necessary, please see the following recommendations.

To facilitate data migration, compile applications using the -gpu=mem:unified flag so that dynamic memory allocations use CUDA managed memory (refer to Command-line Options Selecting Compiler Memory Modes). Avoid the -gpu=mem:unified:nomanagedalloc flag, as it will use system-allocated memory. Additionally, since static, global, and local data are not allocated dynamically, they will remain in CPU memory; transforming these into dynamic allocations (for example, allocatable arrays) can lead to better performance. Set NVCOMPILER_ACC_MEMHINTS=DISABLE to eliminate overhead from the memory hint API. Please note that these recommendations are subject to change as CDMM Unified Memory capabilities evolve in subsequent NVIDIA driver versions.

Table 18 CDMM vs. NUMA Comparison and NVHPC Guidance

Mode/Version

Memory Management/OS Exposure

Key Behavior/Support

NVHPC Compiler/Runtime Suggestion

NUMA Mode

Both CPU and GPU memory exposed directly to the OS

Preferred for optimal Unified Memory application performance

N/A (optimal configuration)

CDMM (Driver <= 13.5)

GPU memory is hidden from the OS; managed by NVIDIA driver

System-allocated memory will not migrate to GPU memory. NVHPC memory advice and prefetch hints have no effect

Compile: Use -gpu=mem:unified,
avoid -gpu=mem:unified:nomanagedalloc
Data: Convert static/global/local data to dynamic allocations
Runtime: Set NVCOMPILER_ACC_MEMHINTS=DISABLE

CDMM (Driver > 13.5)

GPU memory is hidden from the OS; managed by NVIDIA driver

Capabilities evolving

Follow the guidance for Driver <= 13.5 until new recommendations are provided

6.5. Fortran pointers in device code

A Fortran pointer variable is implemented with a pointer and a descriptor, where the descriptor (often called a “dope vector”) holds the array bounds and strides for each dimension, among other information, such as the size for each element and whether the pointer is associated. A Fortran scalar pointer has no bounds information, but does have a minimal descriptor. In Fortran, referring to the pointer variable always refers to the pointer target. There is no syntax to explicitly refer to the pointer and descriptor that implement the pointer variable.

Fortran allocatable arrays and variables are implemented much the same way as pointer arrays and variables. Much of the discussion below applies both to allocatables and pointers.

In OpenACC, when a pointer variable reference appears in a data clause, it’s the pointer target that gets allocated or moved to device memory. The pointer and descriptor are neither allocated nor moved.

When a pointer variable is declared in a module declaration section and appears in an !$acc declare create() directive, then the pointer and descriptor are statically allocated in device memory. When the pointer variable appears in a data clause, the pointer target is allocated or copied to the device, and the pointer and descriptor are ‘attached’ to the device copy of the data. If the pointer target is already present in device memory, no new memory is allocated or copied, but the pointer and descriptor are still ‘attached’, making the pointer valid in device memory. An important side effect of adding declare create in the module declaration section is that when the program executes an ‘allocate’ statement for the pointer (or allocatable), memory is allocated in both CPU and device memory. This means the newly allocated data is already present in device memory. To get values from CPU to device memory or back, you’ll have to use update directives.

When a pointer variable is used in an OpenACC compute construct, the compiler creates a private copy of the pointer and descriptor for each thread, unless the pointer variable was in a module as described above. The private pointer and descriptor will contain information about the device copy of the pointer target. In the compute construct, the pointer variables may be used pretty much as they can in host code outside a compute construct. However, there are some limitations. The program can do a pointer assignment to the pointer, changing the pointer, but that will only change the private pointer for that thread. The modified pointer in the compute construct will not change the corresponding pointer and descriptor in host memory.

6.6. Calling routines in a compute kernel

Using explicit interfaces is a common occurrence when writing Fortran applications. Here are some cases where doing so is required for GPU programming.

  • Explicit interfaces are required when using OpenACC routine bind.

  • Fortran do concurrent requires routines to be pure which creates the need for an explicit interface.

6.7. Supported Processors and GPUs

This NVIDIA HPC Fortran compiler release supports x86-64 and Arm Server CPUs. Cross-compilation across the different families of CPUs is not supported, but you can use the -tp=<target> flag as documented in the man pages to specify a target processor within a family.

To direct the compiler to generate code for NVIDIA GPUs, use the -acc flag to enable OpenACC directives, the -stdpar flag for standard language parallelism, and the -cuda flag for CUDA Fortran. Use the -gpu flag to select specific options for GPU code generation. You can then use the generated code on any supported system with CUDA installed that has a CUDA-enabled GeForce, Quadro, or Tesla card.

For more information on these flags as they relate to accelerator technology, refer to Compiling an OpenACC Program.

For a complete list of supported CUDA GPUs, refer to the NVIDIA website at: https://developer.nvidia.com/cuda/gpus

6.8. CUDA Versions

The NVIDIA HPC Fortran compiler uses components from NVIDIA’s CUDA Toolkit to build programs for execution on an NVIDIA GPU. The NVIDIA HPC SDK puts the CUDA Toolkit components into an HPC SDK installation sub-directory; the HPC SDK currently bundles two versions of recently-released Toolkits.

You can compile a program for an NVIDIA GPU on any system supported by the HPC compilers. You will be able to run that program only on a system with an NVIDIA GPU and an installed NVIDIA CUDA driver. NVIDIA HPC SDK products do not contain CUDA device drivers. You must download and install the appropriate CUDA Driver from NVIDIA.

The NVIDIA HPC SDK utility nvaccelinfo prints the driver version as its first line of output. You can use it to find out which version of the CUDA Driver is installed on your system.

The NVIDIA HPC SDK 26.11ng-beta includes components from the following versions of the CUDA Toolkit:

  • CUDA 12.9U1

  • CUDA 13.0

If you are compiling a program for GPU execution on a system without an installed CUDA driver, the compiler uses the newest CUDA Toolkit bundled with the HPC SDK, CUDA 13.0.

If you are compiling a program for GPU execution on a system with an installed CUDA driver, the compiler detects the version of the CUDA driver and selects the appropriate CUDA Toolkit version to use from those bundled with the HPC SDK.

The compiler looks for a CUDA Toolkit version in the /opt/nvidia/hpc_sdk/target/26.11ng-beta/cuda directory that matches the version of the CUDA Driver installed on the system. If an exact match is not found, the compiler searches for the closest match. For CUDA Driver versions 12.0 through 12.9, the compiler will use the CUDA 12.9 Toolkit. For CUDA Driver versions 13.0 and later, the compiler will use the CUDA 13.0 Toolkit.

You can change the compiler’s default selection of CUDA Toolkit version using a compiler option. Add the cudaX.Y sub-option to -gpu where X.Y denotes the CUDA version. Using a compiler option changes the CUDA Toolkit version for one invocation of the compiler. For example, to compile an OpenACC Fortran file with the CUDA 12.9 Toolkit you would use:

nvfortran -acc -gpu=cuda12.9

6.9. Compute Capability

The compiler can generate code for NVIDIA GPU compute capabilities 5.0 through 12.1. The compiler constructs a default list of compute capabilities that matches the compute capabilities supported by the GPUs found on the system used in compilation. If there are no GPUs detected, the compiler generates code for every supported compute capability.

You can override the default by specifying one or more compute capabilities with the -gpu option. Provide a comma-separated list of compute capabilities, for example:

nvfortran -acc -gpu=cc80,cc90 prog.f90

The generation of device code can be time consuming, so you may notice an increase in compile time as the number of compute capabilities increases.

6.10. PTX JIT Compilation

As of HPC SDK 22.9, support for PTX JIT compilation is enabled in the NVFORTRAN compiler for relocatable device code mode. This means that applications built with -gpu=rdc (that is, with relocatable device code enabled, which is the default mode) are forward-compatible with newer GPUs thanks to the embedded PTX code. The embedded PTX code is dynamically compiled when the application runs on a GPU architecture newer than the architecture specified at compile time.

The support for PTX JIT compilation is enabled automatically, which means that you do not need to change the compiler invocation command lines for your existing projects.

Use scenarios

  • As an example, you can compile your application targeting the Ampere GPU without having to worry about the Hopper GPU architecture. Once the application runs on a Hopper GPU, it will seamlessly use the embedded PTX code.

  • In CUDA Fortran, or with the CUDA Interoperability mode enabled, you can mix in object files compiled with the CUDA NVCC compiler containing PTX code. This PTX code from NVCC will be handled by the JIT compiler alongside the PTX code contained in object files produced by the HPC SDK compilers. When using the CUDA NVCC compiler, the relocatable device code generation must be enabled explicitly using the NVCC --relocatable-device-code true switch, as explained in the CUDA Compiler Driver guide. More information is available in the CUDA Fortran Programming Guide.

By default, the compiler will choose the compute capability that matches the GPU on the system where the code is being compiled. For code that is going to run on the system where it is compiled, we recommend letting the compiler set the compute capability.

When the default won’t work, we recommend compiling applications for a range of compute capabilities that the application is expected to run against, for example, using the -gpu=ccall compiler option. When running the application on a system that supports one of those compute capabilities, the CUDA driver minor version is allowed to be less than the version of the CUDA toolkit used at compile time, as covered in section CUDA Versions.

Performance considerations

PTX JIT compilation, when it occurs, can have a start-up overhead for the application. The JIT compiler keeps a cached copy of the produced device code, which reduces the overhead on subsequent runs. Please refer to the CUDA Programming Guide for detailed information about how the JIT compiler works.

Known limitations

In general, in order for PTX JIT compilation to work, the CUDA driver installed on the deployment system must be at least of the version that matches the CUDA toolkit used to compile the application. This requirement is stricter than those explained in section CUDA Versions.

For example, as explained in that section, the compiler will use the CUDA 12.9 toolkit that is shipped as part of the HPC SDK toolkit when the CUDA driver installed in the system is at least 12.0. However, while the CUDA 12.0 driver is commonly sufficient to run the application, it will not be able to compile the PTX code produced by the CUDA 12.9 toolkit. This means that any deployment system where the PTX JIT compilation is expected to be used must have at least the CUDA 12.9 driver installed. Please refer to the CUDA Compatibility guide for further information about the CUDA Driver compatibility with CUDA Toolkits.

When the application is expected to run on a newer GPU architecture than specified at compile time, we recommend having a CUDA driver installed on the deployment system matching the CUDA toolkit used to build the application. One way to achieve that is to use the NVHPC_CUDA_HOME environment variable at compile time to provide a specific CUDA toolkit.

Below are a few examples of how the PTX version incompatibility can be diagnosed and fixed. As a general rule, if the CUDA driver is unable to run the application due to incompatible PTX, the application will terminate with an error message indicating the cause. OpenACC applications will in most cases suggest compiler flags to target the current CUDA installation.

OpenACC

Consider this program that we will compile for a Turing GPU and attempt to run on an Ampere GPU, on a system that has CUDA 12.1 installed:

program app
  integer, parameter :: N = 1000
  integer :: array(N)
  integer :: i
  !$acc parallel loop copy(array(1:N))
  do i = 1, N
     array(i) = 3
  end do
  print *, "Success!"
end program app

When we build the program, HPC SDK will choose the CUDA 12.9 toolkit that is included as the default. When we attempt to run it, it fails because code generated with 12.9 does not work with the 12.1 driver:

$ nvfortran -acc -gpu=cc75 app.f90
$ ./a.out
fatal OpenACC runtime(app.f90:5): function load failed: CUDA error: named symbol not found (500)
Rebuild this file with -gpu=cc80 to use NVIDIA Tesla GPU 0
NVIDIA CUDA PTX JIT Compiler was unable to compile device code.
This file was compiled with NVIDIA CUDA Toolkit 12.9, the current CUDA Driver is 12.1.
Rebuild the application with the NVHPC_CUDA_HOME environment variable set to the matching CUDA Tookit.
Please consult the NVIDIA HPC Compilers User's Guide for details.

From the error message it follows that the system is unable to execute the Turing GPU instructions on the current system. The embedded Turing PTX could not be compiled, which implies a CUDA driver incompatibility. A way to fix this is to use the installed CUDA 12.1 toolkit at compile time:

$ export NVHPC_CUDA_HOME=/usr/local/cuda-12.1
$ nvfortran -acc -gpu=cc75 app.f90
$ ./a.out
 Success!

6.11. Supported Intrinsics

An intrinsic is a function available in a given language whose implementation is handled specifically by the compiler. Typically, an intrinsic substitutes a sequence of automatically-generated instructions for the original function call. Since the compiler has an intimate knowledge of the intrinsic function, it can better integrate it and optimize it for the situation.

Intrinsics make the use of processor-specific enhancements easier because they provide a language interface to assembly instructions. In doing so, the compiler manages things that the user would normally have to be concerned with, such as register names, register allocations, and memory locations of data.

This section contains an overview of the Fortran intrinsics that the accelerator supports.

6.11.1. Supported Fortran Intrinsics Summary Table

Table 19 is an alphabetical summary of the supported Fortran intrinsics that the accelerator supports. These functions are specific to Fortran 90/95 unless otherwise specified.

In most cases support is provided for all the data types for which the intrinsic is valid. When support is available for only certain data types, the middle column of the table specifies which ones, using the following codes:

I for integer

S for single precision real D for double precision real

C for single precision complex Z for double precision complex

Table 19 Supported Fortran Intrinsics

This intrinsic

Return value

ABS

absolute value of the argument.

ACOS

arccosine of the specified argument.

AINT

truncation of the argument to a whole number.

ANINT

nearest whole number of the real argument.

ASIN

arcsine of the argument.

ATAN

arctangent of the argument.

ATAN2

angle in radians of the complex value first-argument + i*second-argument.

COS

S,D,C,Z

cosine of the argument.

COSH

hyperbolic cosine of the argument.

DBLE

conversion of the argument to double precision real.

DPROD

double precision product of two single precision arguments.

EXP

S,D,C,Z

natural exponential value of the argument.

IAND

result of logical AND of the two integer arguments.

IEOR

result of the boolean exclusive OR of the two integer arguments.

INT

conversion of the argument to integer type.

IOR

result of the boolean inclusive OR of the two integer arguments.

LOG

S,D,C,Z

base-e (natural logarithm) of the argument.

LOG10

base-10 logarithm of the argument.

MAX

maximum value of the arguments.

MIN

minimum value of the arguments.

MOD

remainder of the first argument divided by the second argument.

NINT

nearest integer of the real argument.

NOT

logical complement of the integer argument.

REAL

conversion of the argument to real.

SIGN

absolute value of first argument times the sign of second argument.

SIN

S,D,C,Z

sine of the argument.

SINH

hyperbolic sine of the argument.

SQRT

S,D,C,Z

square root of the argument.

TAN

tangent of the argument.

TANH

hyperbolic tangent of the argument.

7. Using OpenACC

This chapter gives an overview of directive-based OpenACC programming in which compiler directives are used to specify regions of code in Fortran programs to be offloaded from a host CPU to an NVIDIA GPU. For complete details on using OpenACC with NVIDIA GPUs, see the OpenACC Getting Started Guide.

7.1. OpenACC Programming Model

With the emergence of GPU architectures in high performance computing, programmers want the ability to program using a familiar, high level programming model that provides both high performance and portability to a wide range of computing architectures. OpenACC emerged in 2011 as a programming model that uses high-level compiler directives to expose parallelism in the code and parallelizing compilers to build the code for a variety of parallel accelerators.

This chapter will not attempt to describe OpenACC itself. For that, please refer to the OpenACC specification on the OpenACC www.openacc.org website. Here, we will discuss differences between the OpenACC specification and its implementation by the NVIDIA HPC Fortran compiler (NVFORTRAN).

Other resources to help you with your parallel programming including video tutorials, course materials, code samples, a best practices guide and more are available on the OpenACC website.

7.1.1. Levels of Parallelism

OpenACC supports three levels of parallelism:

  • an outer doall (fully parallel) loop level

  • a workgroup or threadblock (worker parallel) loop level

  • an inner synchronous (SIMD or vector) loop level

Each level can be multidimensional with 2 or 3 dimensions, but the domain must be strictly rectangular. The synchronous level may not be fully implemented with SIMD or vector operations, so explicit synchronization is supported and required across this level. No synchronization is supported between parallel threads across the doall level.

The OpenACC execution model on the device side exposes these levels of parallelism and the programmer is required to understand the difference between, for example, a fully parallel loop and a loop that is vectorizable but requires synchronization across iterations. All fully parallel loops can be scheduled for any of doall, workgroup or synchronous parallel execution, but by definition SIMD vector loops that require synchronization can only be scheduled for synchronous parallel execution.

7.1.2. Enable OpenACC Directives

The NVIDIA HPC Fortran compiler enables OpenACC directives with the -acc and -gpu command line options. For more information on these options refer to Compiling an OpenACC Program.

_OPENACC macro

The _OPENACC macro name is defined to have a value yyyymm where yyyy is the year and mm is the month designation of the version of the OpenACC directives supported by the implementation. For example, the version for November, 2017 is 201711. All OpenACC compilers define this macro when OpenACC directives are enabled.

7.1.3. OpenACC Support

The NVIDIA HPC Fortran compiler implements most features of OpenACC 3.3 as defined in The OpenACC Application Programming Interface, Version 3.3, November 2022, http://www.openacc.org, with the exception that the following OpenACC features are not supported:

  • nested parallelism (accepted, but nested loops and constructs are flattened, with no nested kernel launch)

  • enforcement of the cache clause restriction that all references to listed variables must lie within the region being cached

7.2. Compiling an OpenACC Program

Several compiler options are applicable specifically when working with OpenACC. These options include -acc, -gpu, and -Minfo.

7.2.1. -[no]acc

Enable [disable] OpenACC directives. The following suboptions may be used following an equals sign (“=”), with multiple sub-options separated by commas:

gpu

OpenACC directives are compiled for GPU execution only.

Default

By default OpenACC directives are compiled for GPU execution (i.e. equivalent to explicitly setting -acc=gpu).

Predefined Macros

The following macros corresponding to the target compiled for are added implicitly:

  • __NVCOMPILER_OPENACC_GPU when the OpenACC directives are compiled for GPU.

7.2.2. -gpu

Used in combination with the -acc, -cuda, -mp, and -stdpar flags to specify options for GPU code generation. The following sub-options may be used following an equals sign (“=”), with multiple sub-options separated by commas:

ccXY

Generate code for a device with compute capability X.Y. Multiple compute capabilities can be specified, and one version will be generated for each. By default, the compiler will detect the compute capability for each installed GPU. Use -help -gpu to see the valid compute capabilities for your installation.

ccall

Generate code for all compute capabilities supported by this platform and by the selected or default CUDA Toolkit.

ccall-major

Compile for all major supported compute capabilities.

ccnative

Detects the visible GPUs on the system and generates codes for them. If no device is available, the compute capability matching NVCC’s default will be used.

cudaX.Y

Use CUDA X.Y Toolkit compatibility, where installed

[no]debug

Enable [disable] debug information generation in device code

[no]fma

Generate [do not generate] fused multiply-add instructions on the GPU; default at -O1. This can be used in conjunction with the global -M[no]fma option to explicitly enable/disable FMAs on the CPU or GPU.

[no]interceptdeallocations

Intercept [do not intercept] calls to standard library memory deallocations (e.g. free) and call the corresponding CUDA memory deallocation version if address is in pinned or managed memory, regular version otherwise.

keep

Keep the kernel files (.cubin, .ptx, source)

maxregcount:n

Specify the maximum number of registers to use on the GPU; leaving this blank indicates no limit

mem:{separate|managed|unified}

Select GPU memory mode for the generated binary. This controls CUDA memory capability to be utilized such as separate GPU memory only (separate), GPU Managed Memory for the dynamically allocated data (managed), or system memory aka full CUDA Unified Memory (unified). Use of Managed or Unified Memory facilitates simpler programming by eliminating the need to detect all data to be copied into and outside of the code region executing on the GPU.

ptxinfo

Print PTX info

[no]rdc

Generate [do not generate] relocatable device code.

sm_XY

Generate code for a device with compute capability X.Y. Multiple compute capabilities can be specified, and one version will be generated for each. By default, the compiler will detect the compute capability for each installed GPU. Use -help -gpu to see the valid compute capabilities for your installation.

Usage

In the following example, the compiler generates code for NVIDIA GPUs with compute capabilities 8.0 and 9.0.

$ nvfortran -acc -gpu=cc80,cc90 myprog.f

The compiler automatically invokes the necessary software tools to create the kernel code and embeds the kernels in the object file.

To link in the appropriate GPU libraries, you must link an OpenACC program with the -acc flag, and similarly for -cuda, -mp, or -stdpar.

DWARF Debugging Formats

Use the -g option to enable generation of full DWARF information on both the host and device; in the absence of other optimization flags, -g sets the optimization level to zero. If a -O option raises the optimization level to one or higher, only GPU line information is generated in device code even when -g is specified. The debug sub-option to -gpu generates GPU line information only, not full DWARF information. To prevent the generation of debug information for device code, use the nodebug sub-option to -gpu. Both debug and nodebug can be used independently of -g.

7.3. OpenACC with CUDA Unified Memory

When developing OpenACC source for a target supporting CUDA Unified Memory, you can take advantage of a simplified approach to programming because there is no need for data clauses and directives, either in full or in part, depending on the exact memory capability the target supports and the compiler options used.

The discussion in this section assumes you have become familiar with the Separate, Managed, and Unified Memory Modes covered in the Memory Model and Managed and Unified Memory Modes sections.

In Managed Memory Mode, only dynamically-allocated data are implicitly managed by the CUDA runtime; OpenACC data clauses and directives are therefore not needed for movement of this “managed” data. Data clauses and directives are still required to handle static data (module, common block and save variables) and procedure local data.

In Unified Memory Mode, all data is managed by the CUDA runtime. Explicit data clauses and directives are no longer required to indicate which data should reside in GPU memory. All variables are accessible from the OpenACC compute regions executing on the GPU. The NVHPC compiler implementation closely adheres to the shared memory mode detailed in the OpenACC specification, meaning that copy, copyin, copyout, and create clauses will not result in any device allocation or data transfer. The device_resident clause is still honored as in discrete memory mode and results in an allocation of data only accessible from device code. Device memory can also be allocated or deallocated in OpenACC programs in Unified Memory Mode by using the acc_malloc or acc_free API calls.

Understanding Data Movement

In the absence of visible data clauses or directives, when the compiler encounters a compute construct it attempts to determine what data is required for correct execution of the region on the GPU. When the compiler is unable to determine the size and shape of data needing to be accessible on the device, it behaves as follows:

  • In Separate Memory Mode, the program stops at run time with the message array dimensions for 'ptr' must be explicitly provided using OpenACC array syntax, requesting an explicit data clause be added to specify size/shape of the data to be copied.

  • In Managed Memory Mode (-gpu=mem:managed), the compiler assumes the data is allocated in managed memory and thus is accessible from the device; if this assumption is wrong, if the data was defined globally or is located on the CPU stack, the program may fail at runtime.

  • In Unified Memory Mode (-gpu=mem:unified), all data is accessible from the device making information about size and shape unnecessary.

Take the following example, where ptr is an assumed-size array:

subroutine set(ptr, i, j, dim)
  integer :: ptr(*)
  integer :: i, j, dim
  integer :: idx
  idx = (i - 1) * dim + j
  ptr(idx) = someval(i, j)
end subroutine

subroutine fill2d(ptr, dim)
  integer :: ptr(*)
  integer :: dim
  integer :: i, j
!$acc parallel loop
  do i = 1, dim
    do j = 1, dim
      call set(ptr, i, j, dim)
    end do
  end do
end subroutine

In Separate Memory Mode, the only way to guarantee correctness for this example is to change the line with the acc directive as follows:

!$acc parallel loop create(ptr(1:dim*dim)) copyout(ptr(1:dim*dim))

This change explicitly instructs the OpenACC implementation about the precise data segment used within the parallel loop.

In Unified Memory Mode, that is, by compiling with -acc -gpu=mem:unified and executing on a platform with unified memory capability, the create and copyout clauses are not required.

The next example illustrates how a global variable can be accessed in an OpenACC routine without requiring any explicit annotation.

module m
integer :: globmin = 1234
contains
subroutine findmin(a)
!$acc routine seq
  integer, intent(in)  :: a(:)
  integer :: i
  do i = 1, size(a)
    if (a(i) .lt. globmin) then
      globmin = a(i)
    endif
  end do
end subroutine
end module m

Compile the example above for Unified Memory Mode:

nvfortran -acc -gpu=mem:unified example.f90

The source does not need any OpenACC directives to access module variable globmin, to either read or update its value, in the routine invoked from CPU and GPU. Moreover, any access to globmin will be made to the same exact instance of the variable from CPU and GPU; its value is synchronized automatically. In Separate or Managed Memory Modes, such behavior can only be achieved with a combination of OpenACC declare and update directives in the source code.

In most cases, migrating existing OpenACC applications written for Separate Memory Mode should be a seamless process requiring no source changes. Some data access patterns, however, may lead to different results produced during application execution in Unified Memory Mode.

Applications which rely on having separate data copies in GPU memory to conduct temporary computations on the GPU – without maintaining data synchronization with the CPU – pose a challenge for migration to Unified Memory.

For the following example, the value of variable c after the last loop will differ depending on whether the example is compiled with or without -gpu=mem:unified.

b(:) = ...
c = 0

!$acc kernels copyin(b) copyout(a)
!$acc loop
do i = 1, N
  b(i) = b(i) * i
end do
!$acc loop
do i = 1, N
  a(i) =  b(i) + i
end do
!$acc end kernels

do i = 1, N
  c = c + a(i) + b(i)
end do

Without Unified Memory, array b is copied into the GPU memory at the beginning of the OpenACC kernels region. It is then updated in the GPU memory and used to compute elements of array a. As instructed by the data clause copyin(b), b is not copied back to the CPU memory at the end of the kernels region and therefore its initial value is used in the computation of c. With -acc -gpu=mem:unified, the updated value of b in the first loop is automatically visible in the last loop leading to a different value of c at its end.

Implications of Asynchronous Execution

Additional complexities can arise when dealing with asynchronous execution, particularly when CPU-GPU shared data is accessed within async compute regions instead of using an independent data copy on GPU. The programmer should be especially careful about accessing local variables in asynchronous GPU code. Unless the GPU code execution is explicitly synchronized before the end of the scope in which local variables are defined, the GPU can access stale data thus resulting in undefined behavior. Consider the following OpenACC Fortran example, where a local array is used to hold temporary data on the GPU:

subroutine bar()
  integer :: x(N), i
  !$acc enter data create(x(1:N)) async
  !$acc parallel loop async
  do i = 1, N
    x(i) = i
  end do
  ...
  !$acc exit data delete(x(1:N)) async
end subroutine

When compiled for Separate Memory Mode, the bar subroutine creates a copy of the array x in GPU memory and initializes it as written in the loop construct. That copy is eventually deleted. In Unified Memory Mode, however, the compiler ignores the acc enter data and acc exit data directives, so the loop construct executed on the GPU accesses the array x in local CPU memory. Moreover, since all constructs in this example are made asynchronous, the access to x on the GPU leads to undefined behavior of the program because the variable x goes out of scope once the bar subroutine finishes.

Here is a similar example, where the local array x is dynamically allocated:

subroutine bar()
  integer, allocatable :: x(:)
  integer :: i
  allocate(x(N))
  !$acc enter data create(x(1:N)) async
  !$acc parallel loop async
  do i = 1, N
    x(i) = i
  end do
  ...
  !$acc exit data delete(x(1:N)) async
  deallocate(x)
end subroutine

To help detect programming mistakes like this, the NVIDIA OpenACC Runtime provides the NVCOMPILER_ACC_CHECK_UNIFIED environment variable. When set to a non-zero integer value, it enables the runtime to emit information to the standard error output about variables still used on the device after they have been deallocated on the host.

For the example with the x array dynamically allocated with allocate, you can compile the application normally and run it as follows:

$ nvfortran -acc -gpu=mem:unified app.f90
$ NVCOMPILER_ACC_CHECK_UNIFIED=1 ./a.out
Deallocated pointer 0x4a1d00000a80 still referenced on device! File app.f90, function bar_, line 7, variable '_QFbarEx'.

When the x array is automatically allocated in stack memory, the OpenACC runtime reports a message for each construct in the example that refers to the array, even when -Mstack_frame_trace is not used:

$ nvfortran -acc -gpu=mem:unified app.f90
$ NVCOMPILER_ACC_CHECK_UNIFIED=1 ./a.out
Stack pointer 0xffffd71a13e0 still referenced on device! File app.f90, function bar_, line 5, variable 'x(1:1000)'.
Stack pointer 0xffffd71a13e0 still referenced on device! File app.f90, function bar_, line 6, variable 'x'.
Stack pointer 0xffffd71a13e0 still referenced on device! File app.f90, function bar_, line 10, variable 'x(1:1000)'.

You can compile the application with the -Mstack_frame_trace switch added, which will result in generating additional facilities that will assist the runtime when automatic memory is deallocated. The runtime then reports the problem once, for the first construct that refers to the array:

$ nvfortran -acc -gpu=mem:unified -Mstack_frame_trace app.f90
$ NVCOMPILER_ACC_CHECK_UNIFIED=1 ./a.out
Stack pointer 0xffffd71a13c0 still referenced on device! File app.f90, function bar_, line 5, variable 'x(1:1000)'.

Note that the NVCOMPILER_ACC_CHECK_UNIFIED environment variable as well as the compiler switch -Mstack_frame_trace, are designed for diagnostic purposes. Either of them can add run-time overhead, impacting application performance. We recommend avoiding their use when the application is deployed in a production environment.

Performance Considerations

In Unified Memory Mode, the OpenACC runtime may leverage data action information such as create/delete or copyin/copyout to communicate preferable data placement to the CUDA runtime by means of memory hint APIs as elaborated in the following blog post on the NVIDIA website: Simplifying GPU Application Development with Heterogeneous Memory Management. Such actions originate either from explicit data clauses in the source code or via implicit data movement generated by the compiler. This approach can minimize the amount of automatic data migration and may let a developer fine-tune application performance. For the fill2d example above, while adding the data clauses create(ptr(1:dim*dim)) and copyout(ptr(1:dim*dim)) becomes optional with -gpu=mem:unified, their uses in the OpenACC parallel loop directive may improve performance.

7.4. OpenACC Error Handling

The OpenACC specification provides a mechanism to allow you to intercept errors triggered during execution on a GPU and execute a specific routine in response before the program exits. For example, if an MPI process fails while allocating memory on the GPU, the application may want to call MPI_Abort to shut down all the other processes before the program exits. This section explains how to take advantage of this feature.

To intercept errors the application must give a callback routine to the OpenACC runtime. To provide the callback, the application calls acc_set_error_routine with a C function pointer to the callback routine, obtained with c_funloc.

The interface is the following, where the callback routine is a bind(c) subroutine that receives err_msg, a null-terminated C string containing a description of the error:

interface
  subroutine acc_set_error_routine(callback_routine) &
      bind(c, name="acc_set_error_routine")
    import :: c_funptr
    type(c_funptr), value :: callback_routine
  end subroutine acc_set_error_routine
end interface

! callback_routine has the interface:
!   subroutine callback_routine(err_msg) bind(c)
!     character(kind=c_char), dimension(*) :: err_msg

When the OpenACC runtime detects a runtime error, it will invoke the callback_routine.

Note

This feature is not the same as error recovery. If the callback routine returns to the application, the behavior is decidedly undefined.

Let’s look at this feature in more depth using an example.

Take the MPI program below and run it with two processes. Process 0 tries to allocate a large array on the GPU, then sends a message to the second process to acknowledge the success of the operation. Process 1 waits for the acknowledgment and terminates upon receiving it.

program error_handling_mpi
  use mpi
  implicit none

  integer(8), parameter :: N = 2147483648_8
  integer :: rank, nprocs, ierr, ack
  integer(8) :: i
  real, allocatable :: a(:)

  call MPI_Init(ierr)

  call MPI_Comm_rank(MPI_COMM_WORLD, rank, ierr)
  call MPI_Comm_size(MPI_COMM_WORLD, nprocs, ierr)

  if (rank == 0) then
    allocate(a(N))

!$acc enter data create(a(1:N))
!$acc parallel loop independent
    do i = 1, N
      a(i) = i * 0.5
    end do
!$acc exit data copyout(a(1:N))
    print *, "I am process ", rank, ", I have initialized a vector of size ", N, &
             " bytes on the GPU. Sending acknowledgment to process 1."
    ack = 1
    call MPI_Send(ack, 1, MPI_INTEGER, 1, 0, MPI_COMM_WORLD, ierr)
  else if (rank == 1) then
    call MPI_Recv(ack, 1, MPI_INTEGER, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE, ierr)
    print *, "I am process ", rank, ", I have received the acknowledgment from process 0 ", &
             "that data in the GPU has been initialized."
    flush(6)
  end if

  ! do some more work

  call MPI_Finalize(ierr)

end program error_handling_mpi

We compile the program with:

$ mpif90 -acc -o error_handling_mpi error_handling_mpi.f90

If we run this program with two MPI processes, the output will look like the following:

$ mpirun -n 2 ./error_handling_mpi
Out of memory allocating 68719476736 bytes of device memory
Failing in Thread:1
total/free CUDA memory: 42406903808/41959358464
Present table dump for device[1]: NVIDIA Tesla GPU 0, compute capability 8.0, threadid=1
Hint: specify 0x800 bit in NV_ACC_DEBUG for verbose info.
...empty...
Accelerator Fatal Error: call to cuMemAlloc returned error 2 (CUDA_ERROR_OUT_OF_MEMORY): Out of memory
 File: error_handling_mpi.f90
 Function: _QQmain
 Line: 18

--------------------------------------------------------------------------
prterun detected that one or more processes exited with non-zero status,
thus causing the job to be terminated. The first process to do so was:

   Process name: [prterun-node-12345@1,0]
   Exit code:    1
--------------------------------------------------------------------------

Process 0 failed while allocating memory on the GPU and terminated unexpectedly with an error. In this case mpirun was able to identify that one of the processes failed, so it shut down the remaining process and terminated the application. A simple two-process program like this is straightforward to debug. In a real world application though, with hundreds or thousands of processes, having a process exit prematurely may cause the application to hang indefinitely. Therefore it would be ideal to catch the failure of a process, control the termination of the other processes, and provide a useful error message.

We can use the OpenACC error handling feature to improve the previous program and correctly terminate the application in case of failure of an MPI process.

In the following sample code, we have added an error handling callback routine that will shut down the other processes if a process encounters an error while executing on the GPU. Process 0 tries to allocate a large array into the GPU and, if the operation is successful, process 0 will send an acknowledgment to process 1. Process 0 calls the OpenACC routine acc_set_error_routine to set the subroutine handle_gpu_errors as an error handling callback routine. This routine prints a message and calls MPI_Abort to shut down all the MPI processes. If process 0 successfully allocates the array on the GPU, process 1 will receive the acknowledgment. Otherwise, if process 0 fails, it will terminate itself and trigger the call to handle_gpu_errors. Process 1 is then terminated by the code executed in the callback routine.

module gpu_error_handling
  use iso_c_binding
  use mpi
  implicit none

  interface
    subroutine acc_set_error_routine(callback_routine) &
        bind(c, name="acc_set_error_routine")
      import :: c_funptr
      type(c_funptr), value :: callback_routine
    end subroutine acc_set_error_routine
  end interface

contains

  subroutine handle_gpu_errors(err_msg) bind(c)
    character(kind=c_char), dimension(*) :: err_msg
    integer :: k, ierr
    write(*, '(a)', advance='no') "GPU Error: "
    k = 1
    do while (err_msg(k) /= c_null_char)
      write(*, '(a)', advance='no') err_msg(k)
      k = k + 1
    end do
    write(*, '(a)') "Exiting..."
    write(*, '(a)') ""
    call MPI_Abort(MPI_COMM_WORLD, 1, ierr)
    stop 1
  end subroutine handle_gpu_errors

end module gpu_error_handling


program error_handling_mpi
  use gpu_error_handling
  implicit none

  integer(8), parameter :: N = 2147483648_8
  integer :: rank, nprocs, ierr, ack
  integer(8) :: i
  real, allocatable :: a(:)

  call MPI_Init(ierr)

  call MPI_Comm_rank(MPI_COMM_WORLD, rank, ierr)
  call MPI_Comm_size(MPI_COMM_WORLD, nprocs, ierr)

  if (rank == 0) then
    allocate(a(N))


    call acc_set_error_routine(c_funloc(handle_gpu_errors))


!$acc enter data create(a(1:N))
!$acc parallel loop independent
    do i = 1, N
      a(i) = i * 0.5
    end do
!$acc exit data copyout(a(1:N))
    print *, "I am process ", rank, ", I have initialized a vector of size ", N, &
             " bytes on the GPU. Sending acknowledgment to process 1."
    flush(6)
    ack = 1
    call MPI_Send(ack, 1, MPI_INTEGER, 1, 0, MPI_COMM_WORLD, ierr)
  else if (rank == 1) then
    call MPI_Recv(ack, 1, MPI_INTEGER, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE, ierr)
    print *, "I am process ", rank, ", I have received the acknowledgment from process 0 ", &
             "that data in the GPU has been initialized."
    flush(6)
  end if

  ! more work

  call MPI_Finalize(ierr)

end program error_handling_mpi

Again, we compile the program with:

$ mpif90 -acc -o error_handling_mpi error_handling_mpi.f90

We run the program with two MPI processes and obtain the output below:

$ mpirun -n 2 ./error_handling_mpi
Out of memory allocating 68719476736 bytes of device memory
Failing in Thread:1
total/free CUDA memory: 42406903808/41959358464
Present table dump for device[1]: NVIDIA Tesla GPU 0, compute capability 8.0, threadid=1
Hint: specify 0x800 bit in NV_ACC_DEBUG for verbose info.
...empty...
GPU Error: Accelerator Fatal Error: call to cuMemAlloc returned error 2 (CUDA_ERROR_OUT_OF_MEMORY): Out of memory
 File: error_handling_mpi.f90
 Function: _QQmain
 Line: 55
Exiting...

--------------------------------------------------------------------------
MPI_ABORT was invoked on rank 0 in communicator MPI_COMM_WORLD
  Proc: [[17329,1],0]
  Errorcode: 1

NOTE: invoking MPI_ABORT causes Open MPI to kill all MPI processes.
You may or may not see output from other processes, depending on
exactly when Open MPI kills them.
--------------------------------------------------------------------------
--------------------------------------------------------------------------
prterun has exited due to process rank 0 with PID 0 on node node calling
"abort". This may have caused other processes in the application to be
terminated by signals sent by prterun (as reported here).
--------------------------------------------------------------------------

This time the error on the GPU was intercepted by the application which managed it with the error handling callback routine. In this case the routine printed some information about the problem and called MPI_Abort to terminate the remaining processes and avoid any unexpected behavior from the application.

7.5. OpenACC and CUDA Graphs

NVIDIA provides an optimized model for work submission onto GPUs called CUDA Graphs. A graph is a series of operations, such as kernel launches and other stream-oriented tasks, connected by their dependencies. A graph can be defined once, “captured”, then launched repeatedly. This has potential benefits in reducing launch latencies and other overheads associated with kernel setup.

A complete write-up explaining CUDA Graphs and the CUDA API for graph definition, instantiation, and execution can be found in Chapter 3 of the CUDA C Programming Guide. In OpenACC, we currently expose just the minimal set of operations to allow capture and replay of a graph containing OpenACC compute regions and data directives. The code executed between a “begin capture” call, accx_async_begin_capture(), and the “end capture” call, accx_async_end_capture(), is called the capture region.

The CUDA graph API captures (or records) all the device work between accx_async_begin_capture and accx_async_end_capture. The host code in the capture region will be executed once normally, with the exception that no device work is actually executed on the device. Instead, a graph object is created that can be used to replay the captured work multiple times.

Note

Graph capture is similar to a closure concept in many programming languages, like lambda-functions in C++. In lambda-function terms, CUDA graphs capture all the variables by value. That means that all the FIRSTPRIVATE scalars, array shapes, and those derived types, arrays and scalar addresses for data resident on the GPU, are baked into the graph object and cannot be altered. The device data behind the pointers, of course, can be updated by the graph execution normally, and updated by the host between replays.

It is important to understand both what can and cannot be captured within a CUDA Graph capture region:

  • Asynchronous data directives, including data create, can be captured. The OpenACC runtime will use the stream-ordered cudaMallocAsync() call in the capture region for variables which need allocation in data clauses, an API call allowed in CUDA Graphs.

  • Asynchronous compute regions, preferably ACC parallel regions, can be captured. For ACC kernels regions, verify that no work is performed on the host. Host compute sections cannot be captured.

  • Asynchronous ACC update host (self) and update device directives can be captured. The host and device addresses which are captured must be valid during the graph replay/execution.

  • Since only the device work is captured and replayed, any data dependencies between the host and device inside the capture region are erroneous. For example, downloading data from the device, processing it on host and uploading it back to the device within the capture region is invalid.

  • Host code, even host code containing conditionals, can occur within a capture region. Note though that the path taken through the host code will be the path captured by the graph, i.e. the conditionals must likely be consistent during the replay for correct results. Host code which updates host variables, such as i=i+1 will not be captured in the graph, which might affect proper indexing into device-side arrays or other kernel arguments.

  • Similarly, device work initiated in host code loops can be captured in the CUDA Graph. The graph will not contain a notion of looping, just the sequence of device operations submitted to the device during the loop.

  • Subroutine and function calls within a capture region, which contain further compute regions or other work which runs on the device, are captured. Care must be taken that the device data addresses passed to the kernels are valid throughout graph execution, and don’t come and go based on stack addresses or something similar.

  • Codes which double-buffer, or ping-pong between source and destination arrays that are input on odd iterations and output on even iterations (for example, the snippet shown below), can be accommodated by capturing two graphs: one per even iteration, one per odd iteration.

    integer, pointer :: src(:), dest(:), tmp(:)
    do while (err > tolerance)
      do i = 1, N
        dest(i) = foo(src(i))
      end do
      err = bar(dest)
      tmp => dest
      dest => src
      src => tmp
    end do
    
  • Many CUDA library calls, like cublas, etc. can occur in a captured region. Setup for the library calls, such as creating handles, and computing and allocating workspace requirements, should be done before the capture region.

  • Graph capturing is thread-safe with respect to each async queue. Host threads can independently capture graphs using different async queues.

  • Loop trip counts can vary between runs of the same captured graph, as long as the trip count is updated on the device.

The OpenACC API follows the basic portion of the CUDA Graph API fairly closely. The major difference is OpenACC includes the cudaGraphInstantiate() call as part of the end capture function.

The graph type is defined in the OpenACC module:

type, bind(c) :: acc_graph_t
  type(c_ptr) :: graph
  type(c_ptr) :: graph_exec
end type acc_graph_t

These subroutines are available in the OpenACC runtime. Here, pGraph is type(acc_graph_t) and async is just the asynchronous queue value:

subroutine accx_async_begin_capture( async )
subroutine accx_async_end_capture( async, pGraph )
subroutine accx_graph_launch( pGraph, async )
subroutine accx_graph_delete( pGraph )
type(c_ptr) function accx_get_graph( pGraph )
type(c_ptr) function accx_get_graph_exec( pGraph )

We will use a simple Fortran example code which demonstrates some of the modifications needed to use CUDA Graphs from OpenACC. The original serial code for a conjugate gradient iterative solver:

subroutine RunCG(N, A, b, x, tol, max_iter)
  implicit none
  integer, intent(in) :: N, max_iter
  real(WP), intent(in) :: A(N, N), b(N), tol
  real(WP), intent(inout) :: x(N)

  real(WP) :: alpha, rr0, rr
  real(WP), allocatable :: Ax(:), r(:), p(:)
  integer :: it, i

  allocate(Ax(N), r(N), p(N))

  call symmatvec(N, N, A, x, Ax)
  do i = 1, N
    r(i) = b(i) - Ax(i)
    p(i) = r(i)
  enddo
  rr0 = dot(N, r, r)

  do it = 1, max_iter
    call symmatvec(N, N, A, p, Ax)
    alpha = rr0 / dot(N, p, Ax)

    do i = 1, N
      x(i) = x(i) + alpha * p(i)
      r(i) = r(i) - alpha * Ax(i)
    enddo

    rr = dot(N, r, r)

    print*, "Iteration ", it, " residual: ", sqrt(rr)
    if (sqrt(rr) <= tol) then
      deallocate(Ax, r, p)
      return
    endif
    do i = 1, N
      p(i) = r(i) + (rr / rr0) * p(i)
    enddo
    rr0 = rr
  enddo

  deallocate(Ax, r, p)

end subroutine RunCG

For this exercise we wish to put the do it = 1,max_iter work for each iteration into a CUDA graph. Step one is to port the code to OpenACC, keeping in mind that we want to use asynchronous queues. We annotate the dot function with OpenACC directives like this:

function dot(N, x, y) result(r)
  integer, intent(in) :: N
  real(WP), intent(in) :: x(N), y(N)
  integer :: i
  real(WP) :: r

  r = 0.d0
  !$acc parallel loop present(x, y) reduction(+:r) async(1)
  do i = 1, N
    r = r + x(i) * y(i)
  enddo
  !$acc wait(1)
end function dot

We write the symmetric matrix multiply like this:

subroutine symmatvec(M, N, AT, x, Ax)
  implicit none
  integer, intent(in) :: M, N
  real(WP), intent(in) :: AT(N, M), x(N)
  real(WP), intent(out) :: Ax(M)

  integer :: i, j
  real(WP) :: s

  ! Note: Since A is symmetric, we can use the "transpose"
  ! for better memory access here
  !$acc parallel loop gang present(AT, x, Ax) async(1)
  do i = 1, M
    s = 0.d0
    !$acc loop vector reduction(+:s)
    do j = 1, N
      s = s + AT(j,i) * x(j)
    end do
    Ax(i) = s
  end do
end subroutine

And now our main loop of the conjugate gradient solver looks like this:

do it = 1, max_iter
  call symmatvec(N, N, A, p, Ax)
  alpha = rr0 / dot(N, p, Ax)

  !$acc parallel loop gang vector async(1)
  do i = 1, N
    x(i) = x(i) + alpha * p(i)
    r(i) = r(i) - alpha * Ax(i)
  enddo

  rr = dot(N, r, r)

  print*, "Iteration ", it, " residual: ", sqrt(rr)
  if (sqrt(rr) <= tol) exit

  !$acc parallel loop gang vector async(1)
  do i = 1, N
    p(i) = r(i) + (rr / rr0) * p(i)
  enddo
  rr0 = rr
enddo

Step 2 is to prepare the code for running under CUDA Graphs. There is a lot of host code executing in the main loop. While the dot() function runs on the GPU, the rest of the statement alpha = rr0 / dot(...) runs on the host. Similarly, the 2nd dot() call returns its value to the host. The print statement occurs on the host, as does the residual check. Finally, this iteration’s value for rr is moved to rr0 in the last statement of the loop, on the host.

The dot product is tricky. We wish to compute the dot product on the GPU, and leave the result on the GPU, so the reduction variable must be present on the GPU. Here, we change the function call to a subroutine, and remove the initialization which is outside of the parallel region:

subroutine dot(N, x, y, r)
  implicit none
  integer, intent(in) :: N
  real(WP), intent(in) :: x(N), y(N)
  integer :: i
  real(WP) :: r

  !$acc parallel loop present(x, y, r) reduction(+:r) async(1)
  do i = 1, N
    r = r + x(i) * y(i)
  enddo
end subroutine dot

We add one serial kernel to do some of the swapping between rr0 and rr, as well as zeroing out the scalar that will hold the dot product reduction, and move the print and check outside of the GPU capture region, replaced by a update host operation. The finished loop, complete with graph control, looks like this:

do it = 1, max_iter
  if (it .eq. 1) then  ! First time capture
    call accx_async_begin_capture(1)

    call symmatvec(N, N, A, p, Ax)
    call dot(N, p, Ax, rden)

    !$acc serial async(1)
    rr0 = rr
    alpha = rr0 / rden
    rden = 0.0d0
    rr = 0.0d0
    !$acc end serial

    !$acc parallel loop gang vector async(1)
    do i = 1, N
      x(i) = x(i) + alpha * p(i)
      r(i) = r(i) - alpha * Ax(i)
    enddo

    call dot(N, r, r, rr)

    !$acc update host(rr) async(1)

    !$acc parallel loop gang vector async(1)
    do i = 1, N
      p(i) = r(i) + (rr / rr0) * p(i)
    enddo
    call accx_async_end_capture(1, graph)
  endif
  ! Always launch, then wait
  call accx_graph_launch(graph, 1)
  !$acc wait(1)

  rra(it) = rr
  if (sqrt(rr) <= tol) exit
enddo

Step 3 is to compile, run, and profile the result. No special compiler options are needed besides -acc=gpu. When running, you may be advised to set the NVCOMPILER_ACC_USE_GRAPH environment variable. This is currently necessary to properly set the OpenACC runtime for graph capture. Failure to abide by the guidelines above may result in wrong answers, which can be hard to debug. See the following sections on how to use environment variables to help. A common issue is that the pointers passed to the device kernels during graph playback will be the same every time. Make sure that is the case between iterations in the code without graph capture.

The Nsight Systems tool has very good support for profiling CUDA graphs. The timeline view will provide information on whether you have reduced the launch overhead gaps between the GPU kernels. Figure 1 shows a timeline of the iterations of the original OpenACC loop:

_images/nsys-cg-report1-timeline.png

Figure 1 Nsight Systems Report1 Timeline

Figure 2 shows a timeline of the iterations when using CUDA Graphs. When the size N is less than a few thousand, launch latency becomes a major contributor to the overall time and here we can see about a 2x speedup:

_images/nsys-cg-report2-timeline.png

Figure 2 Nsight Systems Report2 Timeline

You can see a more-detailed trace of the CUDA Graph components by adding the --cuda-graph-trace=node option to the nsys profile command.

The above loop demonstrates several of the guidelines outlined at the top of this section, namely, capturing compute regions, whether at the top level or in subprogram units, capturing data movement, and restructuring code regions to minimize or eliminate the host code within a capture region. And the minimal API to begin capture, end capture, then launch the captured graph.

7.6. Environment Variables

This section summarizes the environment variables that NVIDIA OpenACC supports. These environment variables are user-settable environment variables that control behavior of accelerator-enabled programs at execution. These environment variables must comply with these rules:

  • The names of the environment variables must be upper case.

  • The values of environment variables are case insensitive and may have leading and trailing white space.

  • The behavior is implementation-defined if the values of the environment variables change after the program has started, even if the program itself modifies the values.

The following table contains the environment variables that are currently supported and provides a brief description of each.

Table 20 Supported Environment Variables

Use this environment variable…

To do this…

NVCOMPILER_ACC_CUDA_PROFSTOP

Set to 1 (or any positive value) to tell the runtime environment to insert an ‘atexit(cuProfilerStop)’ call upon exit. This behavior may be desired in the case where a profile is incomplete or where a message is issued to call cudaProfilerStop().

NVCOMPILER_ACC_DEVICE_NUM

Sets the default device number to use. NVCOMPILER_ACC_DEVICE_NUM. Specifies the default device number to use when executing accelerator regions. The value of this environment variable must be a nonnegative integer between zero and the number of devices attached to the host.

ACC_DEVICE_NUM

Legacy name. Superseded by NVCOMPILER_ACC_DEVICE_NUM.

NVCOMPILER_ACC_DEVICE_TYPE

Sets the default device type to use for OpenACC regions. NVCOMPILER_ACC_DEVICE_TYPE. Specifies which accelerator device to use when executing accelerator regions when the program has been compiled to use more than one different type of device. The value of this environment variable is implementation-defined, and in the NVIDIA OpenACC implementation is the string NVIDIA

ACC_DEVICE_TYPE

Legacy name. Superseded by NVCOMPILER_ACC_DEVICE_TYPE.

NVCOMPILER_ACC_NOTIFY

With no argument, a debug message will be written to stderr for each kernel launch and/or data transfer. When set to an integer value, the value is used as a bit mask to print information about: 1: kernel launches

2: data transfers

4: region entry/exit

8: wait operations or synchronizations with the device

16: device memory allocates and deallocates

NVCOMPILER_ACC_PROFLIB

Enables 3rd party tools interface using the new profiler dynamic library interface.

NVCOMPILER_ACC_SYNCHRONOUS

Disables asynchronous launches and data movement.

NVCOMPILER_ACC_TIME

Enables a lightweight profiler to measure data movement and accelerator kernel execution time and print a summary at the end of program execution.

7.7. Profiling Accelerator Kernels

Support for Profiler/Trace Tool Interface

The NVIDIA HPC Fortran compiler supports the OpenACC Profiler/Trace Tools Interface. This is the interface used by the NVIDIA profilers to collect performance measurements of OpenACC programs.

Using NVCOMPILER_ACC_TIME

Setting the environment variable NVCOMPILER_ACC_TIME to a nonzero value enables collection and printing of simple timing information about the accelerator regions and generated kernels.

Note

Turn off all CUDA Profilers (NVIDIA’s Visual Profiler, NVPROF, CUDA_PROFILE, etc) when enabling NVCOMPILER_ACC_TIME, they use the same library to gather performance data and cannot be used concurrently.

Accelerator Kernel Timing Data

Accelerator Kernel Timing data
bb04.f90
  s1_  NVIDIA  devicenum=0
    time(us): 46
    15: data region reached 2 times
        15: data copyin transfers: 2
             device time(us): total=20 max=14 min=6 avg=10
        15: data copyout transfers: 1
             device time(us): total=26 max=26 min=26 avg=26
bb04.f90
  s1_  NVIDIA  devicenum=0
    time(us): 0
    15: compute region reached 1 time
        15: kernel launched 1 time
            grid: [8]  block: [128]
            elapsed time(us): total=155 max=155 min=155 avg=155
    15: data region reached 2 times

In this example, a number of things are occurring:

  • For each accelerator region, the file name bb04.f90 and subroutine or function name s1_ is printed, followed by the device type and device number, with the line number of the accelerator region, which in the example is 15.

  • The library counts how many times each region is reached (2 for the data region and 1 for the compute region in the example) and the microseconds spent in the region (in this example 46 for the data region).

  • The time is then divided into kernel execution time and data transfer time between the host and GPU. The data transfers are further split into copyin and copyout transfers, each with a count and the total, maximum, minimum, and average device time.

  • For each kernel, the line number is given, (15 in the example), along with a count of kernel launches, the grid and block size, and the total, maximum, minimum, and average time spent in the kernel, all of which are 155 in this example.

7.8. OpenACC Runtime Libraries

This section provides an overview of the user-callable functions and library routines that are available for use by programmers to query the accelerator features and to control behavior of accelerator-enabled programs at runtime.

Note

None of the OpenACC runtime library routines may be called from a PURE or ELEMENTAL procedure.

7.8.1. Runtime Library Definitions

Fortran Runtime Library Files

Interface declarations are provided in a Fortran include file named accel_lib.h and in a Fortran module named accel_lib. These files define:

  • Interfaces for all routines in this section.

  • Integer parameters to define integer kinds for arguments to those routines.

  • Integer parameters to describe types of accelerators.

7.8.2. Runtime Library Routines

Table 21 lists and briefly describes the runtime library routines supported by the NVIDIA HPC Fortran compiler in addition to the standard OpenACC runtime API routines.

Table 21 Accelerator Runtime Library Routines

This Runtime Library Routine…

Does this…

acc_allocs

Returns the number of arrays allocated in data or compute regions.

acc_bytesalloc

Returns the total bytes allocated by data or compute regions.

acc_bytesin

Returns the total bytes copied in to the accelerator by data or compute regions.

acc_bytesout

Returns the total bytes copied out from the accelerator by data or compute regions.

acc_copyins

Returns the number of arrays copied in to the accelerator by data or compute regions.

acc_copyouts

Returns the number of arrays copied out from the accelerator by data or compute regions.

acc_disable_time

Tells the runtime to stop profiling accelerator regions and kernels.

acc_enable_time

Tells the runtime to start profiling accelerator regions and kernels, if it is not already doing so.

acc_exec_time

Returns the number of microseconds spent on the accelerator executing kernels.

acc_frees

Returns the number of arrays freed or deallocated in data or compute regions.

acc_get_device

Returns the type of accelerator device used to run the next accelerator region, if one is selected.

acc_get_device_num

Returns the number of the device being used to execute an accelerator region.

acc_get_free_memory

Returns the total available free memory on the attached accelerator device.

acc_get_memory

Returns the total memory on the attached accelerator device.

acc_get_num_devices

Returns the number of accelerator devices of the given type attached to the host.

acc_kernels

Returns the number of accelerator kernels launched since the start of the program.

acc_present_dump

Summarizes all data present on the current device.

acc_present_dump_all

Summarizes all data present on all devices.

acc_regions

Returns the number of accelerator regions entered since the start of the program.

acc_total_time

Returns the number of microseconds spent in accelerator compute regions and in moving data for accelerator data regions.

8. Using OpenMP

OpenMP is a specification for a set of compiler directives, an applications programming interface (API), and a set of environment variables that can be used to specify parallel execution in Fortran programs. For general information about using OpenMP and to obtain a copy of the OpenMP specification, refer to the OpenMP organization’s website.

OpenMP GPU target offload (-mp=gpu) is not supported in this NG beta. Use -mp or -mp=multicore for multicore CPU execution.

The NVFORTRAN compiler supports a subset of the OpenMP Application Program Interface for CPUs. In defining this subset, we have focused on OpenMP 5.0 features that will enable CPU targeting for OpenMP applications with a goal of encouraging programming practices that are portable and scalable. For features that are to be avoided, wherever possible, the directives and API calls related to those features are parsed and ignored to maximize portability. Where ignoring such features is not possible, or could result in ambiguous or incorrect execution, the compiler emits appropriate error messages at compile- or run-time.

Use the -mp compiler switch to enable processing of OpenMP directives. The multicore sub-option compiles OpenMP directives for multicore CPU execution and is the default.

With -mp or -mp=multicore, the default OpenMP version selection is 5.0 (-fopenmp-version=50). Use -fopenmp-version=<value> to request another version. Version selection does not enable unimplemented features.

Predefined Macros

The following macro is added implicitly for multicore CPU compilation:

  • __NVCOMPILER_OPENMP_MULTICORE when OpenMP target directives are compiled for multicore CPU.

In this NG beta, _OPENMP expands to 201511 with multicore OpenMP, independently of -fopenmp-version. It does not identify the selected version.

8.1. Environment Variables

The OpenMP specification includes many environment variables related to program execution.

Thread affinity

One important environment variable is OMP_PROC_BIND. It controls the OpenMP CPU thread affinity policy. When thread affinity is disabled, the operating system is free to move threads between the available CPU cores. When thread affinity is enabled, each thread is bound to a subset of the available CPU cores. The environment variable OMP_PLACES can be used to specify how a subset of the available CPU cores is determined for each thread. When OMP_PROC_BIND is unset, a valid OMP_PLACES setting enables thread affinity and overrides the default thread affinity policy. An explicit OMP_PROC_BIND=false disables affinity even when OMP_PLACES is set.

Binding threads to certain CPU cores is often beneficial for application performance, because that can improve the CPU cache hit rate and limit memory transactions between different NUMA nodes. Therefore, it is important to consider enabling thread affinity for your application.

The default value of OMP_PROC_BIND is false. Thus, thread affinity is disabled by default. This is a conservative setting that allows certain classes of applications (such as OpenMP + MPI) to create multiple processes without taking special care of the thread affinity policy to avoid binding threads in different processes to the same CPU cores.

The following table explains the simplest possible values of OMP_PROC_BIND. For the comprehensive explanation of OMP_PROC_BIND and OMP_PLACES, please refer to the OpenMP specification.

Value

Behavior

OMP_PROC_BIND=false

An explicit OMP_PROC_BIND=false disables thread affinity even if OMP_PLACES is set. When thread affinity is disabled, the operating system is free to assign threads to any available CPU core at any time. This is the default value.

OMP_PROC_BIND=true

Thread affinity is enabled. Unless OMP_PLACES is set, the implementation attempts to assign threads optimally to CPU cores to maximize the cache hit rate and minimize the number of memory transactions between NUMA nodes.

Delaying Thread Affinity

Some applications need to initialize non-OpenMP threads or third-party multithreaded libraries before entering OpenMP logic. In such cases, if thread affinity is enabled, the application may want to prevent the restricted main thread affinity from being inherited by non-OpenMP threads (which is the standard behavior in the Linux OS).

To support this use case, the NVIDIA HPC OpenMP Runtime provides the NVCOMPILER_OMP_LAZY_PROC_BIND environment variable. This variable controls whether OpenMP CPU thread affinity binding should be delayed until an OpenMP parallel region is created, or whether it should be set as early as possible. The table below explains the behavior for each setting:

Value

Behavior

NVCOMPILER_OMP_LAZY_PROC_BIND=false

The main thread affinity is set during the initialization of the NVIDIA HPC OpenMP Runtime. This occurs at an unspecified point in the application’s lifecycle, before any OpenMP directive or most OpenMP API functions are executed. This is the default setting.

NVCOMPILER_OMP_LAZY_PROC_BIND=true

The OpenMP CPU thread affinity binding is delayed until the first parallel region is created.

Note: When thread affinity is disabled, the NVCOMPILER_OMP_LAZY_PROC_BIND environment variable has no effect.

Number of threads

By default, the NVIDIA HPC OpenMP Runtime limits the number of threads that can be created for a parallel region to 4 times the number of logical CPU processors.

If an application attempts to exceed this limit, a warning message is emitted to the standard error output. You can suppress this warning by setting the NVCOMPILER_OMP_DISABLE_WARNINGS environment variable to the true value.

To override the default limit on the maximum number of threads, use the NVCOMPILER_CPU_HARD_THREAD_LIMIT environment variable:

Value

Behavior

NVCOMPILER_CPU_HARD_THREAD_LIMIT=<positive_integer>

Maximum number of threads in parallel regions

Handling Stack Overflows

OpenMP threads created by the NVIDIA HPC OpenMP Runtime have a default stack size determined by the implementation and the operating system. This can be adjusted by setting the OMP_STACKSIZE environment variable. When the stack size is too small, the application may crash due to a stack overflow.

To help diagnose this situation, the NVIDIA HPC OpenMP Runtime attempts to recognize stack overflows and can provide a meaningful error message along with a backtrace when a stack overflow occurs. You can control this behavior by setting the NVCOMPILER_OMP_STACK_GUARD environment variable. The table below explains the behavior for each setting:

Value

Behavior

NVCOMPILER_OMP_STACK_GUARD=true

The runtime will handle stack overflows by showing a meaningful error message along with a backtrace. This is the default setting.

NVCOMPILER_OMP_STACK_GUARD=false

The runtime will not handle stack overflows. Applications may crash with a memory access violation error such as segmentation fault.

Handling stack overflows is only supported for OpenMP threads created by the NVIDIA HPC OpenMP Runtime.

The implementation of the stack overflow handling relies on the use of system calls such as sigaction and sigaltstack to set up a signal handler for stack overflows. This may cause issues with third-party libraries that rely on the default signal handler behavior. To work around this, you can set the NVCOMPILER_OMP_STACK_GUARD environment variable to false to disable stack overflow handling.

Runtime warnings

The NVIDIA HPC OpenMP Runtime may issue warnings when it encounters behavior that is non-standard or not explicitly defined by the OpenMP specification. These warnings are printed to the application’s standard error output. Warnings do not interrupt execution; the application continues running normally.

To suppress all runtime warning messages, set the NVCOMPILER_OMP_DISABLE_WARNINGS environment variable to the true value.

Value

Behavior

NVCOMPILER_OMP_DISABLE_WARNINGS=false

The runtime can generate warning messages to the standard error output. This is the default setting.

NVCOMPILER_OMP_DISABLE_WARNINGS=true

No warning messages will be generated.

8.2. Host Execution

OpenMP target regions execute on the host with -mp or -mp=multicore. Execution should always be correct but the performance of the target region may not always be optimal when run on the host.

firstprivates with nowait not supported for host execution

There is currently a limitation on the use of the nowait clause on target regions intended for execution on the host (-mp or -mp=multicore). If the target region references variables having the firstprivate data-sharing attribute, their concurrent updates are not guaranteed to be safe. To work around this limitation, when running on the host, we recommend avoiding the nowait clause on such target regions or equivalently using the taskwait construct immediately following the region.

8.3. Loop

The NVFORTRAN compiler supports the loop construct with an extension to the default binding thread set mechanism specified by OpenMP in order to allow the compiler the freedom to analyze loops and dependencies to generate highly parallel code for CPU targets. In other words, the compiler maps loop to either teams or to threads, as the compiler chooses, unless the user explicitly specifies otherwise.

The following table summarizes the OpenMP mapping to multicore CPUs:

Construct

CPU

!$omp target

host execution

!$omp teams

single team

!$omp parallel

CPU threads

!$omp simd

hint for vector instructions

HPC programs need to leverage all available parallelism to achieve performance. The programmer can attempt to become an expert in the intricacies of each target architecture and use that knowledge to structure programs accordingly. This prescriptive model can be successful but tends to increase source code complexity and often requires restructuring for each new target architecture. Here’s an example where a programmer explicitly requests the steps the compiler should take to map parallelism to CPU threads:

   !$omp parallel do reduction(max:error)
do j = 2, n-1
  do i = 2, m-1
    Anew(i,j) = 0.25 * ( A(i+1,j) + A(i-1,j) &
                       + A(i,j-1) + A(i,j+1) )
    error = max( error, abs(Anew(i,j)-A(i,j)) )
  end do
end do

An alternative is for the programmer to focus on exposing parallelism in a program and allowing a compiler to do the mapping onto the target architectures. The NVFORTRAN implementation of loop supports this descriptive model. In this example, the programmer specifies the loop regions to be parallelized by the compiler and the compiler parallelizes loop across teams and threads:

!$omp target teams loop reduction(max:error)
do j = 2, n-1
  !$omp loop reduction(max:error)
  do i = 2, m-1
    Anew(i,j) = 0.25 * ( A(i+1,j) + A(i-1,j) &
                       + A(i,j-1) + A(i,j+1) )
    error = max( error, abs(Anew(i,j)-A(i,j)) )
  end do
end do

The programmer’s tuning tool with loop is the bind clause. The following table extends the previous mapping example:

Construct

CPU

!$omp loop bind(teams)

threads

!$omp loop bind(parallel)

threads

!$omp loop bind(thread)

single thread (useful for vector instructions)

Orphaned loop constructs within a single file are supported; parallel, thread and teams bindings can be specified with the bind clause. If no binding is specified, thread binding is used. The compiler supports loop regions containing procedure calls, including callees containing critical regions.

Here are a few additional examples using loop.

Use of loop:

!$omp target teams loop
do n1loc_blk = 1, n1loc_blksize
  do igp = 1, ngpown
    do ig_blk = 1, ig_blksize
      do ig = ig_blk, ncouls, ig_blksize
        do n1_loc = n1loc_blk, ntband_dist, n1loc_blksize
          !expensive computation codes
        enddo
      enddo
    enddo
  enddo
enddo

Use of loop, collapse, and bind:

!$omp target teams loop collapse(3)
do n1loc_blk = 1, n1loc_blksize
  do igp = 1, ngpown
    do ig_blk = 1, ig_blksize
      !$omp loop bind(parallel) collapse(2)
      do ig = ig_blk, ncouls, ig_blksize
        do n1_loc = n1loc_blk, ntband_dist, n1loc_blksize
          !expensive computation codes
        enddo
      enddo
    enddo
  enddo
enddo

Use of loop, collapse, and bind(thread):

!$omp target teams loop collapse(3)
do n1loc_blk = 1, n1loc_blksize
  do igp = 1, ngpown
    do ig_blk = 1, ig_blksize
      !$omp loop bind(thread) collapse(2)
      do ig = ig_blk, ncouls, ig_blksize
        do n1_loc = n1loc_blk, ntband_dist, n1loc_blksize
          ! expensive computation codes
        enddo
      enddo
    enddo
  enddo
enddo

8.4. OpenMP Subset

This section contains the subset of OpenMP 5.0 features that the NVFORTRAN compiler supports. Most constructs from OpenMP 3.1 and OpenMP 4.5 that apply to multicore CPUs are supported for CPU targets, and some features from OpenMP 5.0 are supported as well.

The section numbers below correspond to the section numbers in the OpenMP Application Programming Interface Version 5.0 November 2018 document.

2. Directives

2.3 Variant Directives

2.3.4 Metadirectives

The target_device context selector is not supported. The device context selector is supported with the kind(host) and kind(cpu) trait selectors. The isa selector is treated as not matching or is ignored.

The implementation context selector is supported with the vendor(llvm) trait selector; vendor(nvidia) is treated as not matching.

The user context selector is supported with the condition(expression) trait selector including dynamic user traits.

Loop-associated metadirective variants are supported only for do, simd and do simd constructs without data-sharing clauses. Loop-associated metadirectives lexically nested in an OpenMP data environment are not supported. Nested OpenMP constructs in the associated loop are not supported.

The begin/end metadirective syntax is supported.

2.3.5 Declare Variant Directive

The device context selector is supported with kind(host) and kind(cpu). The isa selector is treated as not matching or is ignored.

The implementation context selector is supported with the vendor(llvm) trait selector; vendor(nvidia) is treated as not matching.

2.4 Requires Directive

The requires directive has limited support. The requirement clauses unified_address and unified_shared_memory are accepted but have no effect.

2.5 Internal Control Variables

ICV support is as follows.

  • dyn-var, nthread-var, thread-limit-var, max-active-levels-var, active-levels-var, levels-var, run-sched-var, dyn-sched-var, and stacksize-var are supported

  • place-partition-var, bind-var, wait-policy-var, display-affinity-var, and default-device-var are supported only on the CPU

  • affinity-format-var is supported only on the CPU; its value is immutable

  • max-task-priority-var, def-allocator-var are not supported

  • cancel-var is not supported; it always returns false

2.6 Parallel Construct

Support for parallel construct clauses is as follows.

  • The num_threads, default, private, firstprivate, and shared clauses are supported

  • The reduction clause is supported as described in 2.19.5

  • The if and copyin clauses are supported for CPU targets

  • The proc_bind clause is supported for CPU targets

  • The allocate clause is not supported.

2.7 Teams Construct

The teams construct is supported for CPU targets. The number of teams is one. Support for teams construct clauses is as follows.

  • The num_teams, thread_limit, default, private, and firstprivate clauses are supported

  • The reduction clause is supported as described in 2.19.5

  • The shared clause is supported for CPU targets

  • The allocate clause is not supported.

2.8 Worksharing Constructs

2.8.1 Sections Construct

The sections construct is supported for CPU targets. Support for sections construct clauses is as follows.

  • The private and firstprivate clauses are supported

  • The reduction clause is supported as described in 2.19.5

  • The lastprivate clause is supported; the optional conditional modifier is supported for scalar intrinsic numeric or logical variables. POINTER and ALLOCATABLE list items are not supported with this modifier.

  • The allocate clause is not supported.

2.8.2 Single Construct

Support for single construct clauses is as follows.

  • The private, firstprivate, and nowait clauses are supported

  • The copyprivate clause is supported for CPU targets

  • The allocate clause is not supported.

2.8.3 Workshare Construct

The workshare construct is supported for CPU targets.

2.9 Loop-Related Constructs

2.9.2 Worksharing-Loop Construct (do)

Support for worksharing do construct clauses is as follows.

  • The private, firstprivate, and collapse clauses are supported

  • The reduction clause is supported as described in 2.19.5

  • The schedule clause is supported. The monotonic modifier is supported; nonmonotonic is supported with dynamic and guided schedules. The simd modifier is supported with static, dynamic and auto schedules, but not with guided or runtime schedules.

  • The lastprivate clause is supported; the optional conditional modifier is supported for scalar intrinsic numeric or logical variables. POINTER and ALLOCATABLE list items are not supported with this modifier.

  • The ordered clause is supported only for CPU targets; ordered(n) clause is not supported

  • The linear clause is supported.

  • The order(concurrent) clause is ignored

  • The allocate clause is not supported.

2.9.3 SIMD Directives

The simd construct can be used to provide tuning hints for CPU targets. Support for simd construct clauses is as follows.

  • The reduction clause is supported as described in 2.19.5

  • The lastprivate clause is supported; the optional lastprivate modifier is not supported

  • The if, simdlen, and linear clauses are supported.

  • The safelen, aligned, and nontemporal clauses are supported; the order(concurrent) clause is ignored

The composite dosimd construct is supported for CPU targets. Supported simd clauses are supported on the composite construct for the CPU.

The declaresimd directive is not supported and is ignored.

2.9.4 Distribute Directives

The distribute construct is supported within a teams construct. Support for distribute construct clauses is as follows:

  • The private, firstprivate, collapse, and dist_schedule(static [ ,chunksize]) clauses are supported

  • The lastprivate clause is not supported

  • The allocate clause is not supported.

The distributesimd construct is supported for CPU targets.

The distributeparalleldo construct is supported for CPU targets.

The distribute parallel do simd construct is supported for CPU targets.

2.9.5 Loop Construct

Support for loop construct clauses is as follows.

  • The private, bind, and collapse clauses are supported

  • The reduction clause is supported as described in 2.19.5

  • The order(concurrent) clause is assumed

  • The lastprivate clause is not supported

2.10 Tasking Constructs

2.10.1 Task Construct

The task construct is supported for CPU targets. Support for task construct clauses is as follows:

  • The if, final, default , private, firstprivate, and shared clauses are supported

  • The depend([dependmodifier,] dependtype : list) clause is supported as described in 2.17.11

2.10.4 Taskyield Construct

The taskyield construct is supported for CPU targets.

2.11 Memory Management Directives

The memory management allocators and memory management directives are not supported. Memory management API routines have limited support; see 3.7 below.

2.12 Device Directives

2.12.5 Target Construct

The target construct is supported for host execution. Support for target construct clauses is as follows:

  • The if, private, firstprivate, and nowait clauses are supported

  • The device clause is supported for host execution without the device-modifier ancestor keyword

  • The map clause is supported as described in 2.19.7

  • The defaultmap clause is supported using OpenMP 5.0 semantics

  • The depend([dependmodifier,] dependtype : list) clause is supported as described in 2.17.11

  • The allocate and uses_allocators clauses are not supported

2.13 Combined Constructs

Combined constructs are supported to the extent that the component constructs are themselves supported.

2.14 Clauses on Combined and Composite Constructs

Clauses on combined constructs are supported to the extent that the clauses are supported on the component constructs.

The nowait clause is not supported on the combined target teams distribute parallel do construct. For host execution of target regions with firstprivate and nowait, use taskwait as described in Host Execution.

2.16 Master Construct

The master construct is supported for CPU targets.

2.17 Synchronization Constructs and Clauses

2.17.1 Critical Construct

The critical construct is supported for CPU targets.

2.17.2 Barrier Construct

The barrier construct is supported.

2.17.3 Implicit Barriers

Implicit barriers are implemented.

2.17.4 Implementation-Specific Barriers

There may be implementation-specific barriers.

2.17.5 Taskwait Construct

The taskwait construct is supported for CPU targets.

  • The depend([dependmodifier,] dependtype : list) clause is supported as described in 2.17.11

2.17.6 Taskgroup Construct

The taskgroup construct is supported for CPU targets.

2.17.7 Atomic Construct

Support for atomic construct clauses is as follows.

  • The read, write, update, and capture clauses are supported.

  • The memory order clauses seq_cst, acq_rel, release, acquire, and relaxed are supported.

  • The hint clause is ignored

2.17.8 Flush Construct

The flush construct is supported only for CPU targets.

2.17.9 Ordered Construct and Ordered Directive

The ordered block construct is supported only for CPU targets.

2.17.11 Depend Clause

The depend clause is supported on CPU targets. The dependence types in, out, inout, and mutexinoutset and the dependence modifier iterator(iters) are supported. The dependence type depobj, depend(source), and depend(sink:vector) are not supported.

2.19 Data Environment

2.19.2 Threadprivate Directive

The threadprivate directive is supported for CPU targets.

2.19.5 Reduction Clauses and Directives

The reduction clause is supported. The optional modifier is not supported.

2.19.6 Data Copying Clauses

The data copying copyin and copyprivate clauses are supported for CPU targets.

2.19.7 Data Mapping Attribute Rules, Clauses, and Directives

  • The map([[mapmod[,]...] maptype:] datalist) clause is supported for host execution. Of the map-type-modifiers, always and mapper(mapid) are supported, and close is ignored for host execution.

  • The defaultmap clause is supported for host execution using OpenMP 5.0 semantics.

2.20 Nesting of Regions

For constructs supported in this subset, restrictions on nesting of regions is observed. Additionally, nested parallel regions on CPU are not supported.

Runtime Library Routines

3.2 Execution Environment Routines

The following execution environment runtime API routines are supported.

  • omp_set_num_threads, omp_get_num_threads, omp_get_max_threads, omp_get_thread_num, omp_get_thread_limit, omp_get_supported_active_levels, omp_set_max_active_levels, omp_get_max_active_levels, omp_get_level, omp_get_ancestor_thread_num, omp_get_team_size, omp_get_num_teams, omp_get_team_num, omp_is_initial_device

The following execution environment runtime API routines are supported only on the CPU.

  • omp_get_num_procs, omp_set_dynamic, omp_get_dynamic, omp_set_schedule, omp_get_schedule, omp_in_final, omp_get_proc_bind, omp_get_num_places, omp_set_default_device, omp_get_default_device, omp_get_num_devices, omp_get_device_num, omp_get_initial_device, omp_get_place_num_procs, omp_get_place_proc_ids, omp_get_place_num, omp_get_partition_num_places, omp_get_partition_place_nums

The following execution environment runtime API routines have limited support.

  • omp_get_cancellation, omp_get_nested; supported only on the CPU; the value returned is always false

  • omp_set_nested; supported only on the CPU, the value is ignored

The following execution environment runtime API routines are not supported.

  • omp_get_affinity_format, omp_set_affinity_format, omp_display_affinity, omp_capture_affinity, omp_get_max_task_priority, omp_pause_resource, omp_pause_resource_all

3.3 Lock Routines

The following lock runtime API routines are supported on the CPU.

  • omp_init_lock, omp_init_nest_lock, omp_destroy_lock, omp_destroy_nest_lock, omp_set_lock, omp_set_nest_lock, omp_unset_lock, omp_unset_nest_lock, omp_test_lock, omp_test_nest_lock

The following lock initialization routines are supported on the CPU.

  • omp_init_lock_with_hint, omp_init_nest_lock_with_hint

3.4 Timing Routines

The following timing runtime API routines are supported.

  • omp_get_wtime, omp_get_wtick

3.6 Device Memory Routines

The following device memory routines are supported for the initial host device (omp_get_initial_device()).

  • omp_target_is_present

  • omp_target_memcpy and omp_target_memcpy_rect are supported for copies within the initial host device.

The following device memory routines are supported on the CPU for allocation and deallocation on the initial host device.

  • omp_target_alloc, omp_target_free

The following device memory routines are not supported on the initial host device.

  • omp_target_associate_ptr, omp_target_disassociate_ptr

3.7 Memory Management Routines

The following memory management routines are supported.

  • omp_alloc, omp_free

The following memory management routines are not supported.

  • omp_init_allocator, omp_destroy_allocator, omp_set_default_allocator, omp_get_default_allocator

6 Environment Variables

The following environment variables have limited support.

  • OMP_SCHEDULE, OMP_NUM_THREADS, OMP_NUM_TEAMS, OMP_DYNAMIC, OMP_PROC_BIND, OMP_PLACES, OMP_STACKSIZE, OMP_WAIT_POLICY, OMP_MAX_ACTIVE_LEVELS, OMP_NESTED, OMP_THREAD_LIMIT, OMP_TEAMS_THREAD_LIMIT, OMP_DISPLAY_ENV, OMP_DISPLAY_AFFINITY, and OMP_DEFAULT_DEVICE are supported on CPU.

  • OMP_CANCELLATION and OMP_MAX_TASK_PRIORITY are ignored.

  • OMP_AFFINITY_FORMAT is supported with OMP_DISPLAY_AFFINITY.

  • OMP_TOOL and OMP_TOOL_LIBRARIES are supported only when the program is compiled with -mp=ompt. OMP_TOOL=disabled disables tool loading.

  • OMP_DEBUG and OMP_ALLOCATOR are not supported

8.5. Using metadirective

This section contains limitations affecting metadirective along with a few guidelines for its use.

The following example illustrates the supported begin/end metadirective form with a parallel construct:

program p
  integer :: total
  total = 0
!$omp begin metadirective when(device={kind(cpu)}: parallel reduction(+:total))
  total = total + 1
!$omp end metadirective
  print *, total
end program p

Loop-associated variants that contain data-sharing clauses or introduce an OpenMP data environment are not supported. Loop-associated metadirectives lexically nested in an OpenMP data environment are not supported. Nested OpenMP constructs in the associated loop are not supported.

8.6. Interoperability with Other OpenMP Compilers

OpenMP CPU-parallel object files compiled with NVFORTRAN are interoperable with OpenMP CPU-parallel object files compiled by other compilers using the KMPC OpenMP runtime interface. Compilers supporting KMPC OpenMP include Intel and CLANG. The NVIDIA HPC compilers support a GNU OpenMP interface layer as well which provides OpenMP CPU-parallel interoperability with the GNU compilers.

9. Using Stdpar

This chapter describes the NVIDIA HPC Fortran compiler (NVFORTRAN) support for standard language parallelism, also known as Stdpar: the ISO Fortran do concurrent loop construct with nvfortran. For information about ISO C++ standard library parallel algorithms with nvc++, refer to the HPC C and C++ Compilers User’s Guide.

Use the -stdpar compiler option to enable parallel execution with standard parallelism. The sub-options to -stdpar are the following:

  • gpu: compile for parallel execution on GPU; this sub-option is the default. This feature requires an NVIDIA GPU with compute capability 7.5 (Turing architecture) or newer.

  • multicore: compile for multicore CPU execution.

By default, NVFORTRAN auto-detects and generates GPU code for the type of GPU that is installed on the system on which the compiler is running. To generate code for a specific GPU architecture, which may be necessary when the application is compiled and run on different systems, add the -gpu=ccXX command-line option. More details can be found in Compute Capability.

Predefined Macros

The following macros corresponding to the parallel execution target compiled for are added implicitly:

  • __NVCOMPILER_STDPAR_GPU for parallel execution on GPU.

  • __NVCOMPILER_STDPAR_MULTICORE for parallel execution on multicore CPU.

9.1. GPU Memory Modes

When compiling for GPU execution, Stdpar utilizes Managed and Unified Memory Modes for managing data accessed from the sequential code running on CPU and from the parallel do concurrent loops on GPU.

The compiler detects the memory capability of the system on which the compiler is running and uses that information to enable the correct memory mode as follows:

  • When compiled on a platform with full CUDA Unified Memory capability, -stdpar implies -gpu=mem:unified.

  • When compiled on a platform with CUDA Managed Memory capability only, -stdpar implies -gpu=mem:managed.

To compile code for a specific Memory Mode regardless of the memory capability of the system on which you are compiling, add the desired -gpu=mem:unified or -gpu=mem:managed option.

Stdpar with Separate Memory Mode can only be supported when the data are fully managed through features of other programming models, such as OpenACC.

All restrictions on variables used on the GPU in standard language parallel code in Managed Memory Mode have been removed when using Unified Memory Mode.

If the compiler utilizes CUDA Managed Memory automatically, the interception of deallocations is enabled implicitly at runtime. This is to prevent deallocating the data with a mismatched API, which may lead to undefined behavior. The interception incurs some runtime overhead and may be unnecessary if allocations and deallocations for all data in the application are performed using the matching APIs. The interception can be disabled using dedicated command-line options detailed in Interception of Deallocations. More details about the memory modes supported by the NVIDIA HPC Fortran compiler and dedicated command-line options can be found in Memory Model.

Note

In the current release, nvfortran -stdpar does not enable the interception of deallocations implicitly. Data allocated in Stdpar code and deallocated with a mismatched API, such as C free(), can cause a segmentation fault. To enable the interception, add the -gpu=interceptdeallocations option, for example nvfortran -stdpar -gpu=interceptdeallocations example.f90.

9.2. Stdpar Fortran

Fortran 2008 introduced the do concurrent (DC) loop construct signaling that loop iterations have no interdependencies. Such loop iterations are executed in parallel on the GPU when -stdpar (or -stdpar=gpu) is passed to nvfortran or on CPU threads when -stdpar=multicore is passed to nvfortran. More details can be found in the following blog post on the NVIDIA website: Accelerating Fortran DO CONCURRENT with GPUs and the NVIDIA HPC SDK.

9.2.1. Calling Routines in DO CONCURRENT on the GPU

When compiling for the GPU, calling routines in the body of a do concurrent loop can be constrained. PURE routines can generally be called inside the do concurrent loop body. The compiler detects that such routines are to be compiled for the GPU target. External routines, however, can’t be called from within the DC loop unless they are explicitly annotated with the OpenACC routine directive (refer to Interoperability with OpenACC) or CUDA device attribute (refer to Interoperability with CUDA Fortran).

The following example will compile successfully.

module m
contains
pure subroutine foo()
return
end subroutine
end module m

program dc
use m
implicit none
integer :: i

do concurrent (i=1:10)
  call foo()
enddo
end program

The following example, however, doesn’t compile unless foo is either

  • annotated with !$acc routine,

  • or attributed with attributes(device) and compiled as Stdpar and CUDA Fortran.

program dc
implicit none
interface
  pure subroutine foo()
  end subroutine foo
end interface
integer :: i

do concurrent (i=1:10)
  call foo()
enddo
end program

9.2.2. GPU Data Management

If -gpu=mem:managed is enabled by default or is explicitly passed on the command line, some data accesses in do concurrent loops are invalid. For example, accessing global variables in the routines called from the do concurrent loop does not perform expected value updates in the CPU code.

Additionally, there are rare instances where the compiler cannot accurately determine variable sizes for implicit data movements between CPU and GPU. As demonstrated in the following example, a is an assumed-size array, and its access region inside the DC construct cannot be determined at compile time because the element index positions are taken from another array b initialized outside of the routine. Such code does not update a as expected and may result in a memory violation and undefined behavior.

subroutine r(a, b)
  integer :: a(*)
  integer :: b(:)
  do concurrent (i = 1 : size(b))
    a(b(i)) = i
  enddo
end subroutine

There are no limitations on the variable accessed in do concurrent loops described above when the code is compiled with -gpu=mem:unified, whether this option is enabled by default or explicitly via an option on the command line.

9.2.3. Interoperability with OpenACC

OpenACC features can be used when compiling Stdpar code for GPUs. To activate OpenACC directive recognition with Stdpar code, add the -acc command-line flag to nvfortran.

nvfortran -stdpar -acc example.f90

OpenACC functionality and interoperability with DO CONCURRENT loops are detailed in the OpenACC specification and the NVIDIA HPC Fortran compiler specific differences are detailed in Using OpenACC of this guide.

Using OpenACC features can enhance the functionality of DC-loops, for example:

  • Explicit data management to improve the performance of implicit CPU-GPU data movement, or to use Separate Memory Mode when compiling with -gpu=mem:separate.

  • Tuning DC-loop execution on the GPU, e.g., the GPU kernel launch configuration.

  • Executing DC-loops asynchronously.

  • Calling external routines from within DC-loops.

  • Atomic operations in DC-loops.

Examples

Some examples of using OpenACC directives with DC-loops are provided below.

The following example demonstrates how the data accessed inside the DC-loop are fully managed in the OpenACC data construct.

!$acc data copyin(b) copyout(a)
do concurrent (j=1:N)
  do i=1,K
    a(j,i) = b(j,i)
  end do
end do
!$acc end data

While in the above example the data construct is used for GPU data management, the same effect can be achieved with the use of data clauses on the compute construct enclosing DC-loop.

The following example shows how the scheduling of DC loop on the GPU is controlled through the clauses on the compute construct.

!$acc parallel loop num_gangs(50000) vector_length(32)
do concurrent (i=1:K,j=1:N)
  a(j,i) = real(j)
end do

The OpenACC async clause on compute constructs can be used to perform computations in DC-loops asynchronously.

!$acc parallel loop async
do concurrent (j=1:N)
  a(j) = j
end do

b = foo()

!$acc wait

c = sum(a) + b

In the previous example, array a is filled in with values asynchronously in DC-loop.

9.2.4. Interoperability with CUDA Fortran

CUDA Fortran features can also be used when compiling Stdpar code for GPUs. To recognize CUDA Fortran features in your source code, compile with the -cuda command line flag using nvfortran.

nvfortran -stdpar -cuda example.f90

Using CUDA Fortran extensions can enhance the functionality of a do concurrent (DC) loop and Stdpar program, for several cases:

  • Explicit data locality, accessing CUDA Fortran attributed arrays or other data with the device, managed, unified, or constant attributes from within DC-loops.

  • Tuning DC-loop execution on the GPU, e.g., controlling the GPU kernel launch configuration.

  • Executing DC-loops asynchronously using a specific CUDA stream.

  • Calling external, user-defined CUDA device routines from within DC-loops.

  • Using CUDA atomic operations in DC-loops, or other CUDA-specific device-side runtime library calls.

  • Inserting CUDA Runtime API calls for memory tuning hints outside of DC-loops.

Examples

Some examples of using CUDA Fortran features with DC-loops are provided below. The following example demonstrates how a DC-loop can access CUDA Fortran device data, run on a specific CUDA stream, call the CUDA Runtime API for creating a stream, and hide non-standard features behind the CUF sentinel for code portability.

!@cuf use cudafor
!@cuf integer(kind=cuda_stream_kind) :: istrm
      real, allocatable :: a(:,:), b(:,:)
!@cuf attributes(device) :: a  ! A is device array only, not unified/managed
      . . .
!@cuf istat = cudaStreamCreate(istrm)
      . . .
      a(:,:) = 0.0
      . . .
!$cuf kernel do(1) <<< *, *, stream=istrm>>>
      do concurrent (j=1:N)
        do i=1,K
          a(j,i) = a(j,i) + 2.0 * b(j,i)
        end do
      end do

This program demonstrates how to call low-level CUDA device functions from within a DC-loop. The function can be written in either CUDA Fortran or CUDA C++, depending on the interface. The CUDA C function must be compiled for relocatable device code. This can be used for accessing features in CUDA and NVIDIA GPUs not readily available in directive-based models or standard languages.

module mcuda
  contains
    attributes(host,device) pure integer function std_dbg(itype)
    integer, value :: itype
    if (itype.eq.1) then
      std_dbg = threadIdx%x
    else if (itype.eq.2) then
      std_dbg = blockIdx%x
    else
      std_dbg = (blockIdx%x-1)*blockDim%x + threadIdx%x
    end if
    end function
end module

program test
use mcuda
integer, parameter :: N = 2000
integer, allocatable :: a(:), b(:), c(:)
allocate(a(N),b(N),c(N))

do concurrent (j=1:N)
  a(j) = std_dbg(1)
  b(j) = std_dbg(2)
  c(j) = std_dbg(3)
end do

print *,a(1),a(N/2),a(N)
print *,b(1),b(N/2),b(N)
print *,c(1),c(N/2),c(N)
end

Many functions from the CUDA Fortran cudadevice module are available within do concurrent loops, not just atomics. This code snippet shows two uses:

real :: tmp(4), x, y
...
block; use cudadevice
do concurrent (i=1:K,j=1:N)
  x = real(j) + a(i,j)
  y = atomicAdd(b(1,j), x)
end do

do concurrent (j=1:N)
  x = real(j)
  tmp(1:4) = __ldca(a(1:4,j))
  tmp(1:4) = tmp(1:4) + x
  call __stwt(b(1:4,j), tmp)
end do
end block

10. PCAST

Parallel Compiler Assisted Software Testing (PCAST) is a set of API calls and compiler directives useful in testing program correctness. Numerical results produced by a program can diverge when parts of the program are mapped onto a GPU, when new or additional compiler options are used, or when changes are made to the program itself. PCAST can help you determine where these divergences begin, and pinpoint the changes that cause them. It is useful in other situations as well, including when using new libraries, determining whether parallel execution is safe, or porting programs from one ISA or type of processor to another.

10.1. Overview

PCAST Comparisons can be performed in two ways. The first saves the initial run’s data into a file through the pcast_compare call or directive. Add the calls or directives to your application where you want intermediate results to be compared. Then, execute the program to save the “golden” results where the values are known to be correct. During subsequent runs of the program, the same pcast_compare calls or directives will compare the computed intermediate results to the saved “golden” results and report the differences.

The second approach works in conjunction with the NVIDIA OpenACC implementation to compare GPU computation against the same program running on a CPU. In this case, all compute constructs are performed redundantly, both on the CPU and GPU. GPU results are compared against the CPU results, and differences reported. This is essentially like the first case where the CPU-calculated values are treated as the “golden” results. GPU to CPU comparisons can be done implicitly at the end of data regions with the autocompare flag or explicitly after kernels with the acc_compare call or directive.

With the autocompare flag, OpenACC regions will run redundantly on the CPU and GPU. On an OpenACC region exit where data is to be downloaded from device to host, PCAST will compare the values calculated on the CPU with those calculated in the GPU. Comparisons done with autocompare or acc_compare are handled in memory and do not write results to an intermediate file.

The following table outlines the supported data types that can be used with PCAST. Integer and half precision (real(2)) data types are not supported with ABS, REL, ULP, or IEEE options; only a bit-for-bit comparison is supported.

For floating-point types, PCAST can calculate absolute, relative, and unit-last-place differences. Absolute differences measures only the absolute value of the difference (subtraction) between two values, i.e. abs(A-B). Relative differences are calculated as a ratio between the difference of values, A-B, and the previous value A; abs((A-B)/A). Unit-least precision (Unit-last place) is a measure of the smallest distance between two values A and B. With the ULP option set, PCAST will report if the calculated ULP between two numbers is greater than some threshold.

Table 22 Supported Types for Tolerance Measurements

Fortran Type

ABS

REL

ULP

IEEE

real, real(4)

Yes

Yes

Yes

Yes

double precision, real(8)

Yes

Yes

Yes

Yes

complex, complex(4)

Yes

Yes

Yes

Yes

complex(8)

Yes

Yes

Yes

Yes

real(2)

No

No

No

No

integer(2)

N/A

N/A

N/A

N/A

integer, integer(4)

N/A

N/A

N/A

N/A

integer(8)

N/A

N/A

N/A

N/A

10.2. PCAST with a “Golden” File

The run-time call pcast_compare highlights differences between successive program runs. It has two modes of operation, depending on the presence of a data file named pcast_compare.dat by default. If the file does not exist, pcast_compare assumes this is the first “golden” run. It will create the file and fill it with the computed data at each call to pcast_compare. If the file exists, pcast_compare assumes it is a test run. It will read the file and compare the computed data with the saved data from the file. The default behavior is to consider the first 50 differences to be a reportable error, no matter how small.

By default, the pcast_compare.dat file is in the same directory as the executable. The behavior of pcast_compare, and other comparison parameters, can be changed at runtime with the PCAST_COMPARE environment variable discussed in the Environment Variables section.

The signature of pcast_compare is:

subroutine pcast_compare(a, datatype, len, varname, filename, funcname, lineno)
    type(*), dimension(..) :: a
    character(*) :: datatype, varname, filename, funcname
    integer(8),value :: len
    integer(4),value :: lineno

The call takes seven arguments:

  1. The data to be saved or compared.

  2. A string containing the data type.

  3. The number of elements to compare.

  4. A string treated as the variable name.

  5. A string treated as the source file name.

  6. A string treated as the function name.

  7. An integer treated as a line number.

For example, the pcast_compare runtime call can be invoked like the following:

call pcast_compare(a, 'real', n, 'a', 'pcast_compare1.f90', 'program', 9)

The caller should give meaningful names to the last four arguments. They can be anything, since they only serve to annotate the report. It is imperative that the identifiers are not modified between comparisons; comparisons must be called in the same order for each program run. If, for example, you are calling pcast_compare inside a loop, it is reasonable to set the last argument to be the loop index.

There also exists a directive form of the pcast_compare, which is functionally the same as the runtime call. It can be used at any point in the program to compare the current value of data to that recorded in the golden file, same as the runtime call. There are two benefits to using the directive over the API call:

  1. The directive syntax is much simpler than the API syntax. Most of what the compare call needs to output data to the user can be gleaned by the compiler at compile-time (The type, variable name, file name, function name, and line number).

    !$nvf compare(a(1:n))
    

    as opposed to:

    call pcast_compare(a, 'real', n, 'a', 'pcast_compare1.f90', 'program', 9)
    
  2. The directive is only enabled when the -Mpcast flag is set, so the source need not be changed when testing is complete. Consider the following usage example:

    !$nvf compare(a(1:N))
    

The directive interface is given below. Note that var-list is a variable name, a subarray specification, an array element, or a composite variable member.

!$nvf compare (var-list)

Let’s look at an example of the pcast_compare runtime call:

program main
    use openacc
    implicit none
    integer(8), parameter :: n = 1000
    integer :: i, t
    real, allocatable :: a1(:), a2(:)

    allocate(a1(n), a2(n))

    do i = 1, n
      a1(i) = 1.0
      a2(i) = 2.0
    end do

    do t = 1, 5
    do i = 1, n
      a2(i) = a2(i) + a1(i)
    end do
    call pcast_compare(a2, 'real', n, 'a2', 'example.f90', 'main', 19)
    end do
end program

Compile the example using these compiler options:

$ nvfortran -fast -o a.out example.f90

Compiling with redundant or autocompare options are not required to use pcast_compare. Once again, running the compiled executable using the options below, results in the following output:

$ PCAST_COMPARE=summary,rel=1 ./a.out
datafile pcast_compare.dat created with 5 blocks, 5000 elements, 20000 bytes
$ PCAST_COMPARE=summary,rel=1 ./a.out
datafile pcast_compare.dat compared with 5 blocks, 5000 elements, 20000 bytes
no errors found
 relative tolerance = 0.100000, rel=1

Running the program for the first time, the data file “pcast_compare.dat” is created. Subsequent runs compare calculated data against this file. Use the PCAST_COMPARE environment variable to set the name of the file, or force the program to create a new file on the disk with PCAST_COMPARE=create.

The same example above can be written with the compare directive. Notice how much more concise the directive is than the pcast_compare call.

program main
    use openacc
    implicit none
    integer(8), parameter :: n = 1000
    integer :: i, t
    real, allocatable :: a1(:), a2(:)

    allocate(a1(n), a2(n))

    do i = 1, n
      a1(i) = 1.0
      a2(i) = 2.0
    end do

    do t = 1, 5
    do i = 1, n
      a2(i) = a2(i) + a1(i)
    end do
    !$nvf compare(a2(1:n))
    end do
end program

With the directive, you will want to add “-Mpcast” to the compilation line to enable the directive. Other than that, the output from this program is identical to the runtime example above.

10.3. PCAST with OpenACC

PCAST can also be used with the NVIDIA OpenACC implementation to compare GPU computation against the same program running on a CPU. In this case, all compute constructs are performed redundantly on both the CPU and GPU. The CPU results are considered to be the “golden master” copy which GPU results are compared against.

There are two ways to perform comparisons with GPU-calculated results. The first is with the explicit call or directive acc_compare. To use acc_compare, you must compile with -acc -gpu=redundant to force the CPU and GPU to compute results redundantly. Then, insert calls to acc_compare or put an acc compare directive at points where you want to compare the GPU-computed values against those computed by the CPU.

The second approach is to turn on autocompare mode by compiling with -acc -gpu=autocompare. In autocompare mode, PCAST will automatically perform a comparison at each point where data is moved from the device to the host. It does not require the programmer to add any additional directives or runtime calls; it’s a convenient way to do all comparisons at the end of a data region. If there are multiple compute kernels within a data region, and you’re only interested in one specific kernel, you should use the previously-mentioned acc_compare to target a specific kernel. Note that autocompare mode implies -gpu=redundant.

During redundant execution, the compiler will generate both CPU and GPU code for each compute construct. At runtime, both the CPU and GPU versions will execute redundantly, with the CPU code reading and modifying values in system memory and the GPU reading and modifying values in device memory. Insert calls to acc_compare() calls (or the equivalent acc compare directive) at points where you want to compare the GPU-computed values against CPU-computed values. PCAST treats the values generated by the CPU code as the “golden” values. It will compare those results against GPU values. Unlike pcast_compare, acc_compare does not write to an intermediary file; the comparisons are done in-memory.

acc_compare only has two arguments: the data to be compared, a, and optionally the number of elements to compare, len. The type can be inferred in the OpenACC runtime, so it doesn’t need to be specified. The interface is given below:

subroutine acc_compare(a)
subroutine acc_compare(a, len)
    type(*), dimension(*) :: a
    integer(8), value :: len

You can call acc_compare on any variable or array that is present in device memory. You can also call acc_compare_all (no arguments) to compare all values that are present in device memory against the correponding values in host memory.

subroutine acc_compare_all()

Directive forms of the acc_compare calls exist. They work the same as the API calls and can be used in lieu of them. Similar to PCAST compare directives, acc compare directives are ignored when redundant or autocompare modes are not enabled on the compilation line.

The acc compare directive takes one or more arguments, or the ‘all’ clause (which corresponds to acc_compare_all(). The interface is given below. Argument “var-list” can be a variable name, a sub-array specification, and array element, or a composite variable member.

!$acc compare [ (var-list) | all ]

For example:

!$acc compare(a, b)
!$acc compare(a(1:N))
!$acc compare all

Consider the following OpenACC program that uses the acc_compare() API call and an acc compare directive. This Fortran example uses real*4 and real*8 arrays.

program main
    use openacc
    implicit none
    parameter N = 1000
    integer :: i
    real :: a(N)
    real*4 :: b(N)
    real(4) :: c(N)
    double precision :: d(N)
    real*8 :: e(N)
    real(8) :: f(N)

    d = 1.0d0
    e = 0.1d0

    !$acc data copyout(a, b, c, f) copyin(d, e)

    !$acc parallel loop
    do i = 1,N
    a(i) = 1.0
    b(i) = 2.0
    c(i) = 0.0
    enddo
    !$acc end parallel

    !$acc compare(a(1:N), b(1:N), c(1:N))

    !$acc parallel loop
    do i = 1,N
    f(i) = d(i) * e(i)
    enddo
    !$acc end parallel

    !$acc compare(f)

    !$acc parallel loop
    do i = 1,N
    a(i) = 1.0
    b(i) = 1.0
    c(i) = 1.0
    enddo
    !$acc end parallel

    call acc_compare(a, N)
    call acc_compare(b, N)
    call acc_compare(c, N)

    !$acc parallel loop
    do i = 1,N
    f(i) = 1.0D0
    enddo
    !$acc end parallel

    call acc_compare_all()

    !$acc parallel loop
    do i = 1,N
    a(i) = 3.14;
    b(i) = 3.14;
    c(i) = 3.14;
    f(i) = 3.14d0;
    enddo
    !$acc end parallel

    ! In redundant mode, no comparison is performed here. In
    ! autocompare mode, a comparison is made for a, b, c, and f (but
    ! not e and d), since they are copied out of the data region.

    !$acc end data

    call verify(N, a, b, c, f)
end program

subroutine verify(N, a, b, c, f)
    integer, intent(in) :: N
    real, intent(in) :: a(N)
    real*4, intent(in) :: b(N)
    real(4), intent(in) :: c(N)
    real(8), intent(in) :: f(N)
    integer :: i, errcnt

    errcnt = 0
    do i=1,N
    if(abs(a(i) - 3.14e0) .gt. 1.0e-06) then
   errcnt = errcnt + 1
    endif
    end do
    do i=1,N
    if(abs(b(i) - 3.14e0) .gt. 1.0e-06) then
   errcnt = errcnt + 1
    endif
    end do
    do i=1,N
    if(abs(c(i) - 3.14e0) .gt. 1.0e-06) then
   errcnt = errcnt + 1
    endif
    end do
    do i=1,N
    if(abs(f(i) - 3.14d0) .gt. 1.0d-06) then
   errcnt = errcnt + 1
    endif
    end do

    if(errcnt /= 0) then
    write (*, *) "FAILED"
    else
    write (*, *) "PASSED"
    endif
end subroutine verify

The program can be compiled with the following command:

$ nvfortran -fast -acc -gpu=redundant -Minfo=accel example.F90
main:
     16, Generating copyout(a(:),b(:))
    Generating copyin(e(:))
    Generating copyout(f(:),c(:))
    Generating copyin(d(:))
     18, Generating Tesla code
    19, !$acc loop gang, vector(128) ! blockidx%x threadidx%x
     26, Generating acc compare(c(:),b(:),a(:))
     28, Generating Tesla code
    29, !$acc loop gang, vector(128) ! blockidx%x threadidx%x
     34, Generating acc compare(f(:))
     36, Generating Tesla code
    37, !$acc loop gang, vector(128) ! blockidx%x threadidx%x
     48, Generating Tesla code
    49, !$acc loop gang, vector(128) ! blockidx%x threadidx%x
     56, Generating Tesla code
    57, !$acc loop gang, vector(128) ! blockidx%x threadidx%x

Here, you can see where the acc compare directives are generated on lines 26 and 34. The program can be run with the following command:

$ ./a.out
 PASSED

As you can see, no PCAST output is generated when the comparisons match. We can get more information with the summary option:

$ PCAST_COMPARE=summary ./a.out
    PASSED
compared 13 blocks, 13000 elements, 68000 bytes
no errors found
    absolute tolerance = 0.00000000000000000e+00, abs=0

There are 13 blocks compared. Let’s count the blocks in the compare calls.

!$acc compare(a(1:N), b(1:N), c(1:N))

Compares three blocks, one each for a, b, and c.

!$acc compare(f)

Compares one block for f.

call acc_compare(a, N)
call acc_compare(b, N)
call acc_compare(c, N)

Each call compares one block for their respective array.

call acc_compare_all()

Compares one block for each array present on the device (a, b, c, d, e, and f) for a total of 6 blocks.

If the same example is compiled with autocompare, we’ll see four additional comparisons, since the four arrays that are copied out (with the copyout clause) are compared at the end of the data region.

$ nvfortran -fast -acc -gpu=autocompare example.F90
$ PCAST_COMPARE=summary ./a.out
PASSED
compared 17 blocks, 17000 elements, 88000 bytes
no errors found
   absolute tolerance = 0.00000000000000000e+00, abs=0

10.4. Limitations

There are currently a few limitations with using PCAST that are worth keeping in mind.

  • Comparisons are not thread-safe. If you are using PCAST with multiple threads, ensure that only one thread is doing the comparisons. This is especially true if you are using PCAST with MPI. If you use pcast_compare with MPI, you must make sure that only one thread is writing to the comparison file. Or, use a script to set PCAST_COMPARE to encode the file name with the MPI rank.

  • Comparisons must be done with like types; you cannot compare one type with another. It is not possible to, for example, check for differing results after changing from double precision to single. Comparisons are limited to those present in table Table 22. Currently there is no support for derived types.

  • The -gpu=mem:managed or -gpu=mem:unified options are incompatible with autocompare and acc_compare. Both the CPU and GPU need to calculate result separately and to do so they must have their own working memory spaces.

  • If you do any data movement on the device, you must account for it on the host. For example, if you are using CUDA-aware MPI or GPU-accelerated libraries that modify device data, then you must also make the host aware of the changes. In these cases it is helpful to use the host_data clause, which allows you to use device addresses within host code.

10.5. Environment Variables

Behavior of PCAST/Autocompare is controlled through the PCAST_COMPARE variable. Options can be specified in a comma-separated list: PCAST_COMPARE=<opt1>,<opt2>,...

If no options are specified, the default is to perform comparisons with abs=0. Comparison options are not mutually exclusive. PCAST can compare absolute differences with some n=3 and relative differences with a different threshold, e.g. n=5; PCAST_COMPARE=abs=3,rel=5,….

You can specify either an absolute or relative location to be used with the datafile option. The parent directory should be owned by the same user executing the comparisons and the datafile should have the appropriate read/write permissions set.

Table 23 PCAST_COMPARE Options

Option

Description

abs=n

Compare absolute difference; tolerate differences up to 10^(-n), only applicable to floating point types. Default value is 0

create

Specifies that this is the run that will produce the reference file (pcast_compare only)

compare

Specifies that the current run will be compared with a reference file (pcast_compare only)

datafile="name"

Name of the file that data will be saved to, or compared against. If empty will use the default, pcast_compare.dat (pcast_compare only)

disable

Calls to pcast_compare, acc_compare, acc_compare_all, and directives (pcast compare, acc compare, and acc compare) all immediately return from the runtime with no effect. Note that this doesn’t disable redundant execution; that will require a recompile.

ieee

Compare IEEE NaN checks (only implemented for floats and doubles)

outputfile="name"

Save comparison output to a specific file. Default behavior is to output to stderr

patch

Patch errors (outside tolerance) with correct values

patchall

Patch all differences (inside and outside tolerance) with correct values

rel=n

Compare relative difference; tolerated differences up to 10^(-n), only applicable to floating point types. Default value is 0.

report=n

Report up to n (default of 50) passes/fails

reportall

Report all passes and fails (overrides limit set in report=n)

reportpass

Report passes; respects limit set with report=n

silent

Suppress output - overrides all other output options, including summary and verbose

stop

Stop at first differences

summary

Print summary of comparisons at end of run

ulp=n

Compare Unit of Least Precision difference (only for floats and doubles)

verbose

Outputs more details of comparison (including patches)

verboseautocompare

Outputs verbose reporting of what and where the host is comparing (autocompare only)

11. Using MPI

MPI (Message Passing Interface) is an industry-standard application programming interface designed for rapid data exchange between processors in a distributed-memory environment. MPI is computer software used in scalable computer systems that allows the processes of a parallel application to communicate with one another.

The NVIDIA HPC SDK includes a pre-compiled version of HPC-X MPI. You can also supply an alternate version of MPI with the -I, -L, and -l options.

This section describes how to use HPC-X MPI with the NVIDIA HPC Fortran compiler.

11.1. Using HPC-X MPI on Linux

The NVIDIA HPC Compilers for Linux ship with a pre-compiled version of HPC-X MPI that includes everything required to compile, execute and debug MPI programs using HPC-X MPI.

To build a Fortran application using HPC-X MPI, use the HPC-X MPI compiler wrapper mpifort. This wrapper automatically sets up the compiler command with the correct include file search paths, library directories, and link libraries.

The following MPI example program uses HPC-X MPI.

$ cd my_example_dir
$ MODULEPATH=/opt/nvidia/hpc_sdk/modulefiles/Linux_aarch64 module load ng/26.11ng-beta
$ cp -r /opt/nvidia/hpc_sdk/Linux_aarch64/26.11ng-beta/examples/MPI/samples/mpihello .
$ cd mpihello
$ mpifort mpihello.f -o mpihello
$ mpiexec -np 4 mpihello
Hello world! I'm node 0
Hello world! I'm node 2
Hello world! I'm node 1
Hello world! I'm node 3

To build an application using HPC-X MPI for debugging, add -g to the compiler wrapper command line arguments.

11.2. Testing and Benchmarking

The /opt/nvidia/hpc_sdk/Linux_x86_64/26.11ng-beta/examples/MPI directory contains various benchmarks and tests. Copy this directory into a local working directory by issuing the following command:

% cp -r /opt/nvidia/hpc_sdk/Linux_x86_64/26.11ng-beta/examples/MPI .

There are several example programs available in this directory.

12. Creating and Using Libraries

A library is a collection of functions or subprograms that are grouped for reference and ease of linking. This section discusses issues related to NVIDIA-supplied compiler libraries. Specifically, it addresses the creation of dynamically linked libraries, known as shared objects or shared libraries, and math libraries.

NVIDIA provides libraries that export C interfaces by using Fortran modules.

12.1. Using System Libraries

Release 26.11ng-beta of the nvfortran compiler runtime libraries makes use of Linux system libraries to implement, for example, OpenMP and Fortran I/O.

On 64-bit Linux systems, the nvfortran compiler runtime libraries require these system libraries:

  • libc: memory allocation, file and terminal I/O, and process, environment and time routines

  • libm: math functions and floating-point exception handling

  • libpthread: threads and synchronization, used by the OpenMP runtime and Fortran I/O

  • libdl: dynamic loading, used by the OpenMP runtime

  • libgcc_s: stack unwinding

  • libatomic: atomic operations

  • libstdc++: C++ standard library, required when linking the static runtime libraries

12.2. Creating and Using Shared Object Files on Linux

The nvfortran compiler supports creation of shared object files. Unlike statically-linked object and library files, shared object files link and resolve references with an executable at runtime via a dynamic linker supplied with your operating system. The compiler must generate position independent code to support creation of shared objects by the linker. However, this is not the default. You must create object files with position independent code and shared object files that will include them.

12.2.1. Procedure to create and use a shared object file

The following steps describe how to create and use a shared object file.

  1. Create an object file with position independent code. To do this, compile your code with nvfortran using the -fpic option, or the equivalent option -fPIC, which is supported for compatibility with other systems. For example, use the following command to create an object file with position independent code using nvfortran:

    % nvfortran -c -fpic tobeshared.f
    
  2. Produce a shared object file. To do this, use nvfortran to invoke the linker supplied with your system. It is customary to name such files using a .so filename extension. On Linux, you do this by passing the -shared option to the linker:

    % nvfortran -shared -o tobeshared.so tobeshared.o
    

    Note

    Compilation and generation of the shared object can be performed in one step using both the -fpic option and the -shared option, for example nvfortran -fpic -shared -o tobeshared.so tobeshared.f.

  3. Use a shared object file. To do this, use nvfortran to compile and link the program which will reference functions or subroutines in the shared object file, and list the shared object on the link line, as shown here:

    % nvfortran -o myprog myprog.f tobeshared.so
    
  4. Make the executable available.

    You now have an executable myprog which does not include any code from functions or subroutines in tobeshared.so, but which can be executed and dynamically linked to that code. By default, when the program is linked to produce myprog, no assumptions are made on the location of tobeshared.so. Therefore, for myprog to execute correctly, you must initialize the environment variable LD_LIBRARY_PATH to include the directory containing tobeshared.so. If LD_LIBRARY_PATH is already initialized, it is important not to overwrite its contents. If you have placed tobeshared.so in directory /home/myusername/bin, you can initialize LD_LIBRARY_PATH to include that directory and preserve its existing contents, as shown in the following:

    % setenv LD_LIBRARY_PATH "$LD_LIBRARY_PATH":/home/myusername/bin
    

    If you know that tobeshared.so always resides in a specific directory, you can create the executable myprog in a form that assumes this directory by using the -R link-time option. For example, you can link as follows:

    % nvfortran -o myprog myprog.f tobeshared.so -R/home/myusername/bin
    

    Note

    As with the -L option, there is no space between -R and the directory name. If the -R option is used, it is not necessary to initialize LD_LIBRARY_PATH.

    In the previous example, the dynamic linker always looks in /home/myusername/bin to resolve references to tobeshared.so. By default, if the LD_LIBRARY_PATH environment variable is not set, the linker only searches /usr/lib and /lib for shared objects.

12.2.2. ldd Command

The ldd command is a useful tool when working with shared object files and executables that reference them. When applied to an executable, as shown in the following example, ldd lists all shared object files referenced in the executable along with the pathname of the directory from which they will be extracted.

% ldd myprog

If the pathname is not hard-coded using the -R option, and if LD_LIBRARY_PATH is not initialized, the pathname is listed as “not found”. For more information on ldd, its options and usage, see the online man page for ldd.

12.3. Using Math Libraries

The NVIDIA HPC SDK includes several math libraries including the NVIDIA Performance Libraries (NVPL) for Arm architecture. The -Mmathlib and -Mscalapack options select the libraries when linking, and the libraries they select depend on the target architecture. You can also link specific math libraries with the -l option.

12.3.1. Math Libraries on x86

On x86-64, the NVIDIA HPC SDK includes a BLAS and LAPACK library based on the customized OpenBLAS project source and built with the NVIDIA HPC Compilers. The ScaLAPACK libraries are installed alongside the HPC-X MPI library that accompanies an NVIDIA HPC SDK installation.

-Mmathlib

Use -Mmathlib when linking your main program to link the OpenBLAS BLAS and LAPACK libraries:

% nvfortran myprog.f -Mmathlib

The option takes an optional sub-option:

Option

Libraries linked

-Mmathlib

BLAS and LAPACK

-Mmathlib=blas

BLAS only

-Mmathlib=lapack

BLAS and LAPACK

-Mmathlib=openblas

BLAS and LAPACK (same as -Mmathlib)

The compiler also selects the library variant from other options on the command line:

  • By default it links the 32-bit integer (LP64), sequential (single-threaded) libraries. With -i8 it links the 64-bit integer (ILP64) libraries.

  • With -mp it links the threaded variants of the libraries instead of the sequential ones.

-Mscalapack

You can link with the ScaLAPACK libraries by specifying -Mscalapack on the MPI wrapper command line. For example:

% mpifort myprog.f -Mscalapack

ScaLAPACK depends on MPI, so use an MPI wrapper such as mpifort. Linking with -Mscalapack on the nvfortran command line without the wrapper fails because the linker cannot find the ScaLAPACK library. As with -Mmathlib, -i8 selects the 64-bit integer ScaLAPACK libraries, and -mp selects the threaded BLAS and LAPACK libraries.

A pre-built version of the BLAS and LAPACK libraries is automatically added when the -Mscalapack option is specified. If you wish to use a different BLAS library and still use the -Mscalapack option, then you can list the set of libraries explicitly on your link line.

12.3.2. Math Libraries on Arm

The NVIDIA Performance Libraries (NVPL) are a suite of high-performance mathematical libraries optimized for the NVIDIA Grace Arm architecture. These CPU-only libraries have no dependencies on CUDA or CTK, and are drop-in replacements for standard C and Fortran mathematical APIs allowing HPC applications to achieve maximum performance on the Grace platform. They are available for Arm CPUs only. The NVPL includes the following math libraries: BLAS, FFT, LAPACK, RAND, ScaLAPACK, Sparse, and Tensor. Refer to the NVPL documentation for more information about these math libraries.

On Arm, nvfortran links the NVPL libraries by default when you specify -Mmathlib or -Mscalapack. To link the OpenBLAS libraries instead, use -Mmathlib=openblas.

-Mmathlib

Use -Mmathlib when linking your main program to link the NVPL libraries:

% nvfortran myprog.f -Mmathlib

Without a sub-option, -Mmathlib links all of the NVPL libraries except ScaLAPACK. You can link only the libraries your application needs using sub-options. For example, if you only want the BLAS and LAPACK libraries, link as follows:

% nvfortran myprog.f -Mmathlib=lapack

The following table lists the sub-options and the NVPL libraries they link:

Option

NVPL libraries linked

-Mmathlib

BLAS, LAPACK, FFT (FFTW interface), RAND, Sparse, and Tensor

-Mmathlib=blas

BLAS only

-Mmathlib=lapack

BLAS and LAPACK

-Mmathlib=fftw

FFT (FFTW interface)

-Mmathlib=rand

RAND

-Mmathlib=sparse

Sparse

-Mmathlib=tensor

Tensor

-Mmathlib=openblas

OpenBLAS BLAS and LAPACK instead of NVPL

The compiler selects the library variant from other options on the command line: by default it links the 32-bit integer (LP64), sequential libraries; -i8 selects the 64-bit integer (ILP64) libraries; and -mp selects the threaded libraries (for RAND, the multithreaded libnvpl_rand_mt).

You can also use the -Mnvpl option, which takes the sub-options blas, fftw (also accepted as fft), lapack, rand, sparse, and tensor. For example, to link only the BLAS and FFT libraries from the NVPL:

% nvfortran myprog.f -Mnvpl=blas,fft

Refer to the HPC Fortran Compiler Reference Guide for a complete list of supported options for the -Mnvpl flag.

-Mscalapack

Similar to other ScaLAPACK libraries, the NVPL version is designed to be used with MPI. A straightforward way to access the NVPL ScaLAPACK library is to use an MPI wrapper (for example, mpifort) and specify -Mscalapack:

% mpifort myprog.f -Mscalapack

This links the NVPL ScaLAPACK and BLACS libraries together with the NVPL BLAS and LAPACK libraries that they depend on. -i8 selects the 64-bit integer (ILP64) variants and -mp selects the threaded BLAS and LAPACK libraries. Specifying -Mnvpl in addition to -Mscalapack also links the other NVPL libraries (FFT, RAND, Sparse, and Tensor). To use OpenBLAS-based ScaLAPACK instead, specify -Mscalapack -Mmathlib=openblas.

If you choose not to use an MPI wrapper, you can satisfy ScaLAPACK’s dependency on libmpi.so by explicitly providing this library at link time.

12.4. Linking with the nvmalloc Library

The NVIDIA HPC SDK installation includes a custom host (system) memory allocation library based on the jemalloc memory allocator. This library, nvmalloc, replaces the system malloc(), free(), and other related functions used by the nvfortran runtime for dynamic heap allocations. Using nvmalloc can improve the performance of your application as the underlying jemalloc avoids memory fragmentation and provides scalable concurrency. You can link with this library by specifying -nvmalloc on the compiler command line used for linking. For example:

% nvfortran main.f90 -nvmalloc

The -nvmalloc option is turned on by default on Arm systems when building executables. The option -nonvmalloc can be used to turn off nvmalloc.

12.4.1. Using nvmalloc with Shared Libraries

The -nvmalloc option cannot be used when building shared libraries, due to limitations inherent with function interception. If you specify it, nvfortran ignores it and prints a warning. Instead, use -nvmalloc when building the main executables to handle memory allocations and frees from all the linked shared libraries.

12.4.2. Performance Considerations

The environment variable MALLOC_CONF can be used to control the behavior of nvmalloc. The parameter dirty_decay_ms controls how nvmalloc returns unused memory pages back to the OS via a time-smoothed decay curve. While tuning is possible, users should first aim to avoid frequent allocation and deallocation patterns through buffer reuse or pooling whenever possible. For applications with unavoidable, bursty allocate/deallocate patterns, setting MALLOC_CONF="dirty_decay_ms:-1" may improve performance by reusing warm memory pages. However, this will result in an increase in the Resident Set Size (RSS) of the application. This configuration is not advisable when operating near the system’s total memory capacity or in shared-use environments.

13. Environment Variables

Environment variables allow you to set and pass information that can alter the default behavior of the NVIDIA HPC Fortran compiler (NVFORTRAN) and the executables which it generates. This section includes explanations of the environment variables specific to NVFORTRAN.

  • Standard OpenMP environment variables are used to control the behavior of OpenMP programs; these environment variables are described in the OpenMP Specification available online.

  • Several NVIDIA-specific environment variables can be used to control the behavior of OpenACC programs. OpenACC-related environment variables are described in the OpenACC section: Environment Variables and the OpenACC Getting Started Guide.

13.1. Setting Environment Variables

Before we look at the environment variables that you might use with the HPC Fortran compiler and tools, let’s take a look at how to set environment variables. To illustrate how to set these variables in various environments, let’s look at how a user might initialize a Linux shell environment to enable use of the NVIDIA HPC Fortran compiler.

13.1.1. Setting Environment Variables on Linux

Let’s assume that you want access to the NVIDIA products when you log in, and that you installed the NVIDIA HPC SDK in /opt/nvidia/hpc_sdk. For access at startup, you can add the following lines to your shell startup files on a Linux_x86_64 system.

For csh, use these commands:

$ setenv NVHPCSDK /opt/nvidia/hpc_sdk
$ setenv MANPATH "$MANPATH":$NVHPCSDK/Linux_x86_64/26.11ng-beta/compilers/man
$ set path = ($NVHPCSDK/Linux_x86_64/26.11ng-beta/compilers/bin $path)

For bash, sh, zsh, or ksh, use these commands:

$ NVHPCSDK=/opt/nvidia/hpc_sdk; export NVHPCSDK
$ MANPATH=$MANPATH:$NVHPCSDK/Linux_x86_64/26.11ng-beta/compilers/man; export MANPATH
$ PATH=$NVHPCSDK/Linux_x86_64/26.11ng-beta/compilers/bin:$PATH; export PATH

On a Linux/Arm Server system replace Linux_x86_64 with Linux_aarch64.

13.4. Using Environment Modules on Linux

On Linux, if you use the Environment Modules package, that is, the module load command, the NVIDIA HPC SDK includes a script to set up the appropriate module files. The install script will generate environment module files for you as part of the set up process.

Assuming your installation base directory is /opt/nvidia/hpc_sdk, the environment modules will be installed under /opt/nvidia/hpc_sdk/modulefiles. There will be these sets of module files:

  1. nvhpc

    Adds environment variable settings for the NVIDIA HPC Compilers, CUDA libraries, and additional libraries such as MPI, NCCL, and NVSHMEM.

  2. nvhpc-nompi

    Adds environment variable settings for the NVIDIA HPC Compilers, CUDA libraries, and additional libraries such as NCCL and NVSHMEM. This will not include MPI, if you wish to use an alternate MPI implementation.

  3. nvhpc-byo-compiler

    Adds environment variable settings for the CUDA libraries and additional libraries such as NCCL and NVSHMEM. This will not include the NVIDIA HPC Compilers nor MPI, if you wish to use alternate compilers and MPI.

  4. nvhpc-hpcx

    Adds the same environment variable settings as nvhpc, with the HPC-X MPI compiler wrappers in comm_libs/hpcx/bin.

  5. nvhpc-hpcx-cudaXX, nvhpc-hpcx-cudaXX-openmpi4, and nvhpc-hpcx-cudaXX-openmpi5

    One set for each CUDA major version XX included in the HPC SDK, for example nvhpc-hpcx-cuda12 and nvhpc-hpcx-cuda13. These modules use the CUDA toolkit, math libraries, NCCL, and NVSHMEM for that CUDA version instead of the default, and load the full HPC-X environment, which also sets OPAL_PREFIX and the MPI include and library paths. The -openmpi4 variant uses Open MPI 4; the other two use Open MPI 5.

You can load the nvhpc environment module for the 26.11ng-beta release as follows:

$ module load nvhpc/26.11ng-beta

To see what versions of nvhpc are available on this system, use this command:

$ module avail nvhpc

The nvhpc, nvhpc-nompi, and nvhpc-byo-compiler modules set or modify the environment variables relevant to NVFORTRAN as indicated in the following table. The nvhpc and nvhpc-nompi modules also set CC, CXX, and CPP, and the nvhpc, nvhpc-nompi, and nvhpc-byo-compiler modules set C_INCLUDE_PATH and CPLUS_INCLUDE_PATH, for the NVIDIA HPC C and C++ compilers; refer to the HPC C and C++ Compilers User’s Guide for details.

This Environment Variable…

Is set or modified by the module load command

CPATH

Prepends the math libraries, NCCL and NVSHMEM include directories, the QD (quad-double) include directory (nvhpc and nvhpc-nompi only), and the CUDA include directory (nvhpc-byo-compiler only)

FC

Full path to nvfortran (nvhpc and nvhpc-nompi only)

F90

Full path to nvfortran (nvhpc and nvhpc-nompi only)

F77

Full path to nvfortran (nvhpc and nvhpc-nompi only)

LD_LIBRARY_PATH

Prepends the CUDA library directory, the NVIDIA HPC Compilers and QD library directories (nvhpc and nvhpc-nompi only), and the math libraries, NCCL and NVSHMEM library directories

NVHPC

The installation base directory, e.g. /opt/nvidia/hpc_sdk

NVHPC_ROOT

The release directory, e.g. /opt/nvidia/hpc_sdk/Linux_x86_64/26.11ng-beta

PATH

Prepends the CUDA bin directory, the MPI bin directory (nvhpc only), and the NVIDIA HPC Compilers and QD bin directories (nvhpc and nvhpc-nompi only)

Note

NVIDIA does not provide support for the Environment Modules package. For more information about the package, go to: https://envmodules.io/.

13.5. Stack Traceback and JIT Debugging

When a programming error results in a runtime error message or an application exception, a program will usually exit, perhaps with an error message. The NVFORTRAN runtime library includes a mechanism to override this default action and instead print a stack traceback, start a debugger, or, on Linux, create a core file for post-mortem debugging.

The stack traceback and just-in-time debugging functionality is controlled by an environment variable, NVCOMPILER_TERM, described in NVCOMPILER_TERM. The runtime libraries use the value of NVCOMPILER_TERM to determine what action to take when a program abnormally terminates.

14. Distributing Files - Deployment

Once you have successfully built, debugged and tuned your application, you may want to distribute it to users who need to run it on a variety of systems. This section addresses how to effectively distribute applications built using the NVIDIA HPC Fortran compiler. The application must be installed in such a way that it executes accurately on a system other than the one on which it was built, and which may be configured differently.

14.1. Deploying Applications on Linux

To successfully deploy your application on Linux, some of the issues to consider include:

  • Runtime Libraries

  • 64-bit Linux Systems

  • Redistribution of Files

14.1.1. Runtime Library Considerations

On Linux systems, the system runtime libraries can be linked to an application either statically or dynamically. For example, for the C runtime library, libc, you can use either the static version libc.a or the shared object version libc.so. If the application is intended to run on Linux systems other than the one on which it was built, it is generally safer to use the shared object version of the library. This approach ensures that the application uses a version of the library that is compatible with the system on which the application is running. Further, it works best when the application is linked on a system that has an equivalent or earlier version of the system software than the system on which the application will be run.

Note

Building on a newer system and running the application on an older system may not produce the desired output.

To use the shared object version of a library, the application must also link to shared object versions of the NVIDIA HPC Fortran compiler runtime libraries. To execute an application built in such a way on a system on which the NVIDIA HPC compilers are not installed, those shared objects must be available. To build using the shared object versions of the runtime libraries, use the -Bdynamic option, as shown here:

$ nvfortran -Bdynamic myprog.f90

14.1.2. 64-bit Linux Considerations

On 64-bit Linux systems, 64-bit applications that use the -mcmodel=medium option sometimes cannot be successfully linked statically. Therefore, users with executables built with the -mcmodel=medium option may need to use shared libraries, linking dynamically. Also, runtime libraries built using the -fpic option use 32-bit offsets, so they sometimes need to reside near other runtime libs in a shared area of Linux program memory.

Note

If your application is linked dynamically using shared objects, then the shared object versions of the NVIDIA HPC Fortran compiler runtime are required.

14.1.3. Linux Redistributable Files

The method for installing the shared object versions of the runtime libraries required for applications built with the NVIDIA HPC Fortran compiler is manual distribution.

When the NVIDIA HPC Compilers are installed, there is a directory named REDIST; this directory contains the redistributed shared object libraries. These may be redistributed by licensed NVIDIA HPC Compilers users under the terms of the End-User License Agreement.

14.1.4. Restrictions on Linux Portability

You cannot expect to be able to run an executable on any given Linux machine. Portability depends on the system you build on as well as how much your program uses system routines that may have changed from Linux release to Linux release. For example, an area of significant change between some versions of Linux is in libpthread.so. The NVIDIA HPC Fortran compiler uses this dynamically linked library for the options -acc (OpenACC) and -mp (OpenMP). Statically linking this library may not be possible, or may result in failure at execution.

Typically, portability is supported for forward execution, meaning running a program on the same or a later version of Linux, but not for backward compatibility, that is, running on a prior release. For example, a user who compiles and links a program under RHEL 10.2 should not expect the program to run without incident on a RHEL 9.2 system, an earlier Linux version. It may run, but it is less likely. Developers might consider building applications on earlier Linux versions for wider usage. Dynamic linking of Linux and gcc system routines on the platform executing the program can also reduce problems.

14.1.5. Licensing for Redistributable (REDIST) Files

The files in the REDIST directory may be redistributed under the terms of the End-User License Agreement for the product in which they were included.

15. Inter-language Calling

This section describes inter-language calling conventions between Fortran programs compiled with the NVIDIA HPC Fortran compiler (NVFORTRAN) and C and C++ code compiled with the NVIDIA HPC C and C++ compilers (nvc and nvc++). Fortran 2003 ISO_C_Binding provides a mechanism to support the interoperability with C. This includes the iso_c_binding intrinsic module, binding labels, and the BIND attribute. Additional interoperability with C is available with Fortran 2018 and the ISO_Fortran_binding.h C header file. nvfortran supports both the iso_c_binding module and the ISO_Fortran_binding.h header file. In the absence of these mechanisms, the following sections describe how to call a C or C++ function from a Fortran program and how to call a Fortran function or subroutine from a C or C++ program.

This section provides examples that use the following options related to inter-language calling.

  • -c

  • -Mnomain

  • -c++libs

  • -fortranlibs

15.1. Overview of Calling Conventions

This section includes information on the following topics:

  • Functions and subroutines in Fortran, C, and C++

  • Naming and case conversion conventions

  • Compatible data types

  • Argument passing and special return values

  • Arrays and indexes

  • Interoperability with iso_c_binding and ISO_Fortran_binding.h

Inter-language Calling Considerations and the sections that follow it, through the examples, describe how to perform inter-language calling using the Linux convention. Interoperability with iso_c_binding and ISO_Fortran_binding.h, at the end of this chapter, describes the standard Fortran mechanisms that replace many of those conventions.

15.2. Inter-language Calling Considerations

In general, when argument data types and function return values agree, you can call a C or C++ function from Fortran as well as call a Fortran function from C or C++. When data types for arguments do not agree, you may need to develop custom mechanisms to handle them. For example, the Fortran COMPLEX type has a matching type in C99 but does not have a matching type in C89; however, it is still possible to provide inter-language calls but there are no general calling conventions for such cases.

  • If a C++ function contains objects with constructors and destructors, calling such a function from either C or Fortran is not possible unless the initialization in the main program is performed from a C++ program in which constructors and destructors are properly initialized.

  • If you want to call a C++ function from Fortran or C, you have to use the extern "C" keyword to declare the C++ function. This keeps the C++ compiler from mangling the name of the function. Similarly, you can call a C or Fortran function from C++ without problems as long as you use the extern "C" keyword to declare the function in the C++ program. This declaration prevents name mangling for the C function name.

  • You can use the __cplusplus macro to allow a program or header file to work for both C and C++. For example, the following defines in the header file stdio.h allow this file to work for both C and C++.

    #ifndef _STDIO_H
    #define _STDIO_H
    #ifdef __cplusplus
    extern "C" {
    #endif /* __cplusplus */
    .
    . /* Functions and data types defined... */
    .
    #ifdef __cplusplus
    }
    #endif /* __cplusplus */
    #endif
    
  • C++ member functions cannot be declared extern, since their names will always be mangled. Therefore, C++ member functions cannot be called from Fortran or C.

15.3. Functions and Subroutines

Fortran, C, and C++ define functions and subroutines differently.

For a Fortran program calling a C or C++ function, observe the following return value convention:

  • When a C or C++ function returns a value, call it from Fortran as a function.

  • When a C or C++ function does not return a value, call it as a subroutine.

For a C/C++ program calling a Fortran function, the call should return a similar type. Table 28 and Table 29 list compatible types. If the call is to a Fortran subroutine or a Fortran CHARACTER function, call it from C/C++ as a function that returns void. A CHARACTER function receives its result buffer and length as additional leading arguments. A Fortran COMPLEX function returns its value directly, so declare it in C as returning the matching _Complex type, for example float _Complex cf_(float *c, int *i);. The exception to this convention is when a Fortran subroutine has alternate returns; call such a subroutine from C/C++ as a function returning int whose value is the value of the integer expression specified in the alternate RETURN statement.

15.4. Upper and Lower Case Conventions, Underscores

By default on Linux systems, all Fortran symbol names are converted to lower case. C and C++ are case sensitive, so upper-case function names stay upper-case. When you use inter-language calling, name your C/C++ functions with lower-case names, or use the BIND(C, NAME="...") attribute in the Fortran source to specify the exact symbol name. The -Mupcase option is deprecated and does not change the generated symbol names.

When programs are compiled using nvfortran on Linux systems, an underscore is appended to Fortran global names (names of functions, subroutines and common blocks). This mechanism distinguishes the Fortran name space from the C/C++ name space. Procedures defined inside a Fortran module are not named this way; their symbols are mangled with the module name (for example, _QMmPms for subroutine ms in module m). To call a module procedure from C or C++, declare it with BIND(C). Use these naming conventions:

  • If you call a C/C++ function from Fortran, you should rename the C/C++ function by appending an underscore or use bind(c) in the Fortran program.

  • If you call a Fortran function from C/C++, you should append an underscore to the Fortran function name in the calling program.

15.5. Compatible Data Types

Table 28 shows compatible data types between Fortran and C/C++. Table 29 shows how the Fortran COMPLEX type may be represented in C/C++.

Tip

If you can make your function/subroutine parameters as well as your return values match types, you should be able to use inter-language calling.

Table 28 Fortran and C/C++ Data Type Compatibility

Fortran Type (lower case)

C/C++ Type

Size (bytes)

character x

char x

1

character*n x

char x[n]

n

real x

float x

4

real*4 x

float x

4

real*8 x

double x

8

double precision

double x

8

integer x

int x

4

integer*1 x

signed char x

1

integer*2 x

short x

2

integer*4 x

int x

4

integer*8 x

long long x

8

logical x

int x

4

logical*1 x

char x

1

logical*2 x

short x

2

logical*4

int x

4

logical*8

long x

8

A default logical is not a C bool; see Interoperability with iso_c_binding and ISO_Fortran_binding.h for guidance on passing logical values and for logical(c_bool).

Table 29 Fortran and C/C++ Representation of the COMPLEX Type

Fortran Type (lower case)

C/C++ Type

Size (bytes)

complex x

struct {float r,i;} x;

8

float complex x;

8

complex*8 x

struct {float r,i;} x;

8

float complex x;

8

double complex x

struct {double dr,di;} x;

16

double complex x;

16

complex*16 x

struct {double dr,di;} x;

16

double complex x;

16

Note

For C/C++, the complex type implies C99 or later.

15.5.1. Fortran Named Common Blocks

A named Fortran common block can be represented in C/C++ by a structure whose members correspond to the members of the common block. The name of the structure in C/C++ must have the added underscore. For example, here is a Fortran common block:

INTEGER I
COMPLEX C
DOUBLE COMPLEX CD
DOUBLE PRECISION D
COMMON /COM/ i, c, cd, d

This Fortran Common Block is represented in C with the following equivalent:

extern struct {
  int i;
  struct {float real, imag;} c;
  struct {double real, imag;} cd;
  double d;
} com_;

This same Fortran Common Block is represented in C++ with the following equivalent:

extern "C" struct {
 int i;
 struct {float real, imag;} c;
 struct {double real, imag;} cd;
 double d;
} com_;

Tip

For global or external data sharing, extern "C" is not required.

15.6. Argument Passing and Return Values

In Fortran, arguments are passed by reference, that is, the address of the argument is passed, rather than the argument itself. In C/C++, arguments are passed by value, except for strings and arrays, which are passed by reference. Due to the flexibility provided in C/C++, you can work around these differences. Solving the parameter passing differences generally involves intelligent use of the & and * operators in argument declarations when Fortran calls C/C++ and in argument passing when C/C++ calls Fortran.

For strings declared in Fortran as type CHARACTER, an argument representing the length of the string is also passed to a calling function.

On Linux systems, the compiler places the length argument(s) at the end of the parameter list, following the other formal arguments.

The length argument is passed by value, not by reference. The examples in Examples declare it as size_t.

15.6.1. Passing by Value (%VAL)

When passing parameters from a Fortran subprogram to a C/C++ function, it is possible to pass by value using the %VAL function. If you enclose a Fortran parameter with %VAL(), the parameter is passed by value. For example, the following call passes the integer i and the logical bvar by value.

integer*1   i
logical*1   bvar
call cvalue (%VAL(i), %VAL(bvar))

15.6.2. Character Return Values

Functions and Subroutines describes the general rules for return values for C/C++ and Fortran inter-language calling. There is a special return value to consider. When a Fortran function returns a character, two arguments need to be added at the beginning of the C/C++ calling function’s argument list:

  • The address of the return character or characters

  • The length of the return character

The following example illustrates the extra parameters, tmp and 10, supplied by the caller:

Character Return Parameters

! Fortran function returns a character
CHARACTER*(*) FUNCTION CHF(C1,I)
   CHARACTER*(*) C1
   INTEGER I
END
#include <stddef.h>

/* C declaration of Fortran function */
extern void chf_(char *, size_t, char *, int *, size_t);
char tmp[10];
char c1[9];
int i;
chf_(tmp, 10, c1, &i, 9);

If the Fortran function is declared to return a character value of constant length, for example CHARACTER*4 FUNCTION CHF(), the second extra parameter representing the length must still be supplied, but is not used.

Note

The value of the character function is not automatically NULL-terminated.

15.6.3. Complex Return Values

A Fortran function that returns a complex value returns it directly, as the matching C complex type. No extra argument is added to the argument list. The following example shows a COMPLEX function and the C declaration used to call it.

COMPLEX Return Values

COMPLEX FUNCTION CF(C, I)
REAL C
INTEGER I
CF = CMPLX(1.0, 2.0)
END
#include <complex.h>
extern float _Complex cf_(float *c, int *i);
float c = 5.0f;
int i = 3;
float _Complex r = cf_(&c, &i);   /* r is (1,2) */

15.7. Array Indices

Fortran arrays and C/C++ arrays use different default initial array index values. By default, arrays in Fortran start at 1 and arrays in C/C++ start at 0. If you adjust your array comparisons so that a Fortran second element is compared to a C/C++ first element, and adjust similarly for other elements, you should not have problems working with this difference. If this is not satisfactory, you can declare your Fortran arrays to start at zero.

Another difference between Fortran and C/C++ arrays is the storage method used. Fortran uses column-major order and C/C++ uses row-major order. For one-dimensional arrays, this poses no problems. A multidimensional Fortran array has the same memory layout as a C array declared with the dimensions in reverse order: a Fortran a(2,3) is a C int a[3][2], and the Fortran element a(i,j) is the C element a[j-1][i-1]. For example, a Fortran 2x3 array filled with 10*i + j is stored in memory as 11 21 12 22 13 23. If you prefer to keep the C declaration in natural order, pass the dimensions explicitly and index with a computed offset.

15.8. Examples

This section contains examples that illustrate inter-language calling. The first examples show a Fortran main program calling C and C++ functions; these are followed by examples of C and C++ main programs calling Fortran subroutines, and examples of calls between C and C++.

15.8.1. Example – Fortran Calling C

Note

There are other solutions to calling C from Fortran than the one presented in this section. For example, you can use the iso_c_binding intrinsic module which NVIDIA does support. For more information on this module and for examples of how to use it, see Example – Fortran Calling C Using iso_c_binding.

C function f2c_func_ shows a C function that is called by the Fortran main program shown in Fortran Main Program f2c_main.f. Notice that each argument is defined as a pointer, since Fortran passes by reference. Also notice that the C function name uses all lower-case and a trailing “_”.

Fortran Main Program f2c_main.f

 logical*1 bool1
 character letter1
 integer*4 numint1, numint2
 real numfloat1
 double precision numdoub1
 integer*2 numshor1
 external f2c_func

 call f2c_func(bool1, letter1, numint1, numint2, numfloat1,
+              numdoub1, numshor1)

 write( *, "(L2, A2, I5, I5, F6.1, F6.1, I5)")
+ bool1, letter1, numint1, numint2, numfloat1, numdoub1, numshor1

 end

C function f2c_func_

#include <stddef.h>
#define TRUE 0xff
#define FALSE 0

/* Fortran passes every argument by reference, so each one is a pointer.
   The hidden length of the CHARACTER argument is passed by value, after
   all of the visible arguments. */
void f2c_func_(char *bool1, char *letter1, int *numint1, int *numint2,
               float *numfloat1, double *numdoub1, short *numshor1,
               size_t len_letter1)
{
    *bool1 = TRUE;  *letter1 = 'v';
    *numint1 = 11;  *numint2 = -44;
    *numfloat1 = 39.6;
    *numdoub1 = 39.2;
    *numshor1 = 981;
}

Compile and execute the program f2c_main.f with the call to f2c_func_ using the following command lines:

$ nvc -c f2c_func.c
$ nvfortran f2c_func.o f2c_main.f
$ ./a.out

Executing the a.out file should produce the following output:

T v   11  -44  39.6  39.2  981

15.8.2. Example – Fortran Calling C++

The Fortran main program shown in Fortran Main Program f2cp_main.f calling a C++ function calls the C++ function shown in C++ function f2cp_func.C .

Notice:

  • Each argument is defined as a pointer in the C++ function, since Fortran passes by reference.

  • The C++ function name uses all lower-case and a trailing “_”:

Fortran Main Program f2cp_main.f calling a C++ function

 logical*1 bool1
 character letter1
 integer*4 numint1, numint2
 real numfloat1
 double precision numdoub1
 integer*2 numshor1
 external f2cp_func

 call f2cp_func(bool1, letter1, numint1, numint2, numfloat1,
+               numdoub1, numshor1)

 write( *, "(L2, A2, I5, I5, F6.1, F6.1, I5)")
+ bool1, letter1, numint1, numint2, numfloat1, numdoub1, numshor1

 end

C++ function f2cp_func.C

#include <cstddef>
#define TRUE 0xff
#define FALSE 0

extern "C"
{
extern void f2cp_func_ (
    char *bool1, char *letter1,
    int *numint1, int *numint2,
    float *numfloat1,
    double *numdoub1,
    short *numshort1,
    std::size_t len_letter1)
{
    *bool1 = TRUE;     *letter1 = 'v';
    *numint1 = 11;     *numint2 = -44;
    *numfloat1 = 39.6; *numdoub1 = 39.2;   *numshort1 = 981;
}
}

Assuming the Fortran program is in a file f2cp_main.f, and the C++ function is in a file f2cp_func.C, create an executable, using the following command lines:

$ nvc++ -c f2cp_func.C
$ nvfortran f2cp_func.o f2cp_main.f -c++libs
$ ./a.out

When you link with nvfortran and one or more of the object files were compiled with nvc++, add the -c++libs option, as shown, so that the C++ runtime libraries are linked into the executable. Some simple cases, including this one, link without the option, but adding it is the safe choice.

Executing the a.out file should produce the following output:

T v   11  -44  39.6  39.2  981

15.8.3. Example – C Calling Fortran

Note

There are other solutions to calling Fortran from C than the one presented in this section. For example, the ISO_Fortran_binding.h C header file, which NVIDIA does support, lets a C function receive a Fortran assumed-shape array through a descriptor. For more information on this header file and for an example of how to use it, see Example – C Function Using ISO_Fortran_binding.h.

The example C Main Program c2f_main.c shows a C main program that calls the Fortran subroutine shown in Fortran Subroutine c2f_sub.f.

  • Each call uses the & operator to pass by reference.

  • The call to the Fortran subroutine uses all lower-case and a trailing “_”.

C Main Program c2f_main.c

#include <stdio.h>
#include <stddef.h>

extern void c2f_sub_(char *, char *, int *, int *, float *, double *,
                     short *, size_t);

int main (void) {
    char bool1, letter1;
    int numint1, numint2;
    float numfloat1;
    double numdoub1;
    short numshor1;

    /* The last argument is the hidden length of the CHARACTER argument. */
    c2f_sub_(&bool1, &letter1, &numint1, &numint2, &numfloat1,
             &numdoub1, &numshor1, 1);
    printf(" %s %c %d %d %3.1f %.0f %d\n",
           bool1 ? "TRUE" : "FALSE", letter1, numint1, numint2,
           numfloat1, numdoub1, numshor1);
    return 0;
}

Fortran Subroutine c2f_sub.f

 subroutine c2f_sub ( bool1, letter1, numint1, numint2,
+                     numfloat1, numdoub1, numshor1)
 logical*1 bool1
 character letter1
 integer numint1, numint2
 double precision numdoub1
 real numfloat1
 integer*2 numshor1

 bool1 = .true.
 letter1 = "v"
 numint1 = 11
 numint2 = -44
 numdoub1 = 902
 numfloat1 = 39.6
 numshor1 = 299
 return
 end

To compile this Fortran subroutine and C program, use the following commands:

$ nvc -c c2f_main.c
$ nvfortran -Mnomain c2f_main.o c2f_sub.f
$ ./a.out

Executing the resulting a.out file should produce the following output:

TRUE v 11 -44 39.6 902 299

15.8.4. Example – C++ Calling Fortran

Fortran Subroutine cp2f_func.f shows a Fortran subroutine called by the C++ main program shown in C++ main program cp2f_main.C. Notice that each call uses the & operator to pass by reference. Also notice that the call to the Fortran subroutine uses all lower-case and a trailing “_”:

C++ main program cp2f_main.C

#include <iostream>
#include <cstddef>

extern "C" {
    extern void cp2f_func_(char *, char *, int *, int *,
                           float *, double *, short *, std::size_t);
}

int main ()
{
    char bool1, letter1;
    int numint1, numint2;
    float numfloat1;
    double numdoub1;
    short numshor1;

    cp2f_func_(&bool1, &letter1, &numint1, &numint2, &numfloat1,
               &numdoub1, &numshor1, 1);
    std::cout << " bool1 = " << (bool1 ? "TRUE" : "FALSE") << std::endl;
    std::cout << " letter1 = " << letter1 << std::endl;
    std::cout << " numint1 = " << numint1 << std::endl;
    std::cout << " numint2 = " << numint2 << std::endl;
    std::cout << " numfloat1 = " << numfloat1 << std::endl;
    std::cout << " numdoub1 = " << numdoub1 << std::endl;
    std::cout << " numshor1 = " << numshor1 << std::endl;
    return 0;
}

Fortran Subroutine cp2f_func.f

 subroutine cp2f_func ( bool1, letter1, numint1,
+                       numint2, numfloat1, numdoub1, numshor1)
 logical*1 bool1
 character letter1
 integer numint1, numint2
 double precision numdoub1
 real numfloat1
 integer*2 numshor1

 print *, "in Fortran subroutine cp2f_func"
 bool1 = .true.
 letter1 = "v"
 numint1 = 11
 numint2 = -44
 numdoub1 = 902
 numfloat1 = 39.6
 numshor1 = 299
 return
 end

To compile this Fortran subroutine and C++ program, use the following command lines:

$ nvfortran -c cp2f_func.f
$ nvc++ cp2f_func.o cp2f_main.C -fortranlibs
$ ./a.out

Executing this C++ main should produce the following output:

bool1 = TRUE
letter1 = v
numint1 = 11
numint2 = -44
numfloat1 = 39.6
numdoub1 = 902
numshor1 = 299
in Fortran subroutine cp2f_func

Note

You must explicitly link in the NVFORTRAN runtime support libraries when linking nvfortran-compiled program units into C++ or C main programs. When linking with nvc or nvc++, use the -fortranlibs option, as shown in the preceding example. Without it the link fails with undefined references to Fortran runtime symbols such as _FortranAioBeginExternalListOutput, because the Fortran print statement calls into the runtime. The nvfortran driver does not need the option; it is accepted there but does nothing. The Fortran line appears last when stdout is a file or a pipe, because the Fortran runtime flushes its buffer at program exit while std::endl flushes immediately.

15.8.5. Example – C++ Calling C

C++ Main Program cp2c_main.C Calling a C Function shows a C++ main program that calls the C function shown in Simple C Function c2cp_func.c.

C++ Main Program cp2c_main.C Calling a C Function

#include <iostream>

extern "C" void cp2c_func(int n, int m, int *p);

int main()
{
    int a, b, c;
    a = 8;
    b = 2;
    c = 0;
    std::cout << "main: a = " << a << " b = " << b
              << " ptr c = " << static_cast<void *>(&c) << std::endl;
    cp2c_func(a, b, &c);
    std::cout << "main: res = " << c << std::endl;
    return 0;
}

Simple C Function c2cp_func.c

#include <stdio.h>

void cp2c_func(int num1, int num2, int *res)
{
    printf("func: a = %d b = %d ptr c = %p\n", num1, num2, (void *)res);
    *res = num1 / num2;
    printf("func: res = %d\n", *res);
    fflush(stdout);
}

To compile this C function and C++ main program, use the following commands:

$ nvc -c cp2c_func.c
$ nvc++ cp2c_main.C cp2c_func.o
$ ./a.out

Executing the resulting a.out file should produce the following output. The address printed for c differs from run to run.

main: a = 8 b = 2 ptr c = 0xffffcacaef7c
func: a = 8 b = 2 ptr c = 0xffffcacaef7c
func: res = 4
main: res = 4

15.8.6. Example – C Calling C++

The example in C Main Program c2cp_main.c Calling a C++ Function shows a C main program that calls the C++ function shown in Simple C++ Function c2cp_func.C with Extern C.

C Main Program c2cp_main.c Calling a C++ Function

#include <stdio.h>

extern void c2cp_func(int a, int b, int *c);

int main(void)
{
    int a, b, c;
    a = 8; b = 2;
    printf("main: a = %d b = %d ptr c = %p\n", a, b, (void *)&c);
    c2cp_func(a, b, &c);
    printf("main: res = %d\n", c);
    return 0;
}

Simple C++ Function c2cp_func.C with Extern C

#include <iostream>

extern "C" void c2cp_func(int num1, int num2, int *res)
{
    std::cout << "func: a = " << num1 << " b = " << num2
              << " ptr c = " << static_cast<void *>(res) << std::endl;
    *res = num1 / num2;
    std::cout << "func: res = " << *res << std::endl;
}

To compile this C function and C++ main program, use the following commands:

$ nvc -c c2cp_main.c
$ nvc++ c2cp_main.o c2cp_func.C
$ ./a.out

Executing the resulting a.out file should produce the following output. The address printed for c differs from run to run.

main: a = 8 b = 2 ptr c = 0xffffcacaef7c
func: a = 8 b = 2 ptr c = 0xffffcacaef7c
func: res = 4
main: res = 4

Note

You cannot use the extern “C” form of declaration for an object’s member functions.

15.9. Interoperability with iso_c_binding and ISO_Fortran_binding.h

The conventions described earlier in this chapter depend on compiler-specific details such as appended underscores and hidden character length arguments. The Fortran 2003 iso_c_binding intrinsic module and the Fortran 2018 ISO_Fortran_binding.h C header file replace those details with standard mechanisms. Use them in new code when you can change the Fortran interface.

  • Declare the interface with the BIND(C) attribute. With BIND(C, NAME="...") the symbol name is exactly the name you give; no underscore is appended and no case conversion is applied.

  • Give each dummy argument a kind from iso_c_binding, such as c_int, c_double or c_bool, so that it has a matching C type.

  • Without the VALUE attribute an argument is still passed by reference, so the C parameter is a pointer. With VALUE it is passed by value.

  • A CHARACTER argument in a BIND(C) interface must be of kind C_CHAR. A length-one scalar corresponds to a C char, and no hidden length argument is passed.

15.9.1. Logical Values and C bool

A default logical is not interoperable with the C bool type. Do not depend on how a default logical is represented on the C side, and do not depend on how a C value other than 0 or 1 is interpreted on the Fortran side. To pass logical values between Fortran and C:

  • Declare the Fortran argument as logical(c_bool) and the C parameter as _Bool (or bool from stdbool.h).

  • If the C side produces or consumes integer flags, pass them as integer(c_int) and convert in Fortran, for example flag = (n /= 0).

The logical*1 arguments used with the TRUE value 0xff in the examples earlier in this chapter are a convention of those examples, not a guarantee.

15.9.2. Example – Fortran Calling C Using iso_c_binding

The Fortran main program shown in Fortran Main Program bind_c_main.f90 calls the C function shown in C function bind_c_func. Notice:

  • The interface block uses BIND(C, NAME="bind_c_func"), so the C function is named bind_c_func with no trailing underscore.

  • Each argument has a kind from iso_c_binding, and each is a pointer in C because none has the VALUE attribute.

  • The logical(c_bool) argument corresponds to _Bool in C.

Fortran Main Program bind_c_main.f90

program bind_c_main
  use iso_c_binding
  implicit none

  interface
    subroutine bind_c_func(n, x, flag, result) bind(c, name="bind_c_func")
      import :: c_int, c_double, c_bool
      integer(c_int),  intent(in)    :: n
      real(c_double),  intent(in)    :: x
      logical(c_bool), intent(inout) :: flag
      real(c_double),  intent(out)   :: result
    end subroutine bind_c_func
  end interface

  integer(c_int)  :: n = 3
  real(c_double)  :: x = 2.5d0, result
  logical(c_bool) :: flag = .true.

  call bind_c_func(n, x, flag, result)
  print '(F6.1, L2)', result, flag
end program bind_c_main

C function bind_c_func

#include <stdbool.h>

/* Every argument is passed by reference because the Fortran dummy
   arguments do not have the VALUE attribute. */
void bind_c_func(int *n, double *x, bool *flag, double *result)
{
    *result = *flag ? *n * *x : -(*n * *x);
    *flag = !*flag;
}

Compile and execute the program using the following command lines:

$ nvc -c bind_c_func.c
$ nvfortran bind_c_main.f90 bind_c_func.o
$ ./a.out

Executing the a.out file should produce the following output:

7.5 F

15.9.3. Example – C Function Using ISO_Fortran_binding.h

When a BIND(C) procedure has an assumed-shape dummy argument, the C function receives a pointer to a descriptor of type CFI_cdesc_t instead of a pointer to the data. The descriptor carries the rank, the extent of each dimension and the address of the data, so the C code does not need the shape passed separately and can handle array sections that are not contiguous.

In the program shown in Fortran Main Program cdesc_main.f90, the Fortran main program passes the array section a(:, 1:3:2), which skips the middle column. The C function shown in C function sum_array uses CFI_address to locate each element, so the stride of the section is handled for it.

Fortran Main Program cdesc_main.f90

program cdesc_main
  use iso_c_binding
  implicit none

  interface
    subroutine sum_array(a, total) bind(c, name="sum_array")
      import :: c_double
      real(c_double), intent(in)  :: a(:,:)
      real(c_double), intent(out) :: total
    end subroutine sum_array
  end interface

  real(c_double) :: a(2,3), total
  integer :: i, j

  do j = 1, 3
    do i = 1, 2
      a(i,j) = 10*i + j
    end do
  end do

  call sum_array(a(:, 1:3:2), total)
  print '(F6.1)', total
end program cdesc_main

C function sum_array

#include <ISO_Fortran_binding.h>

void sum_array(CFI_cdesc_t *a, double *total)
{
    CFI_index_t i, j;
    CFI_index_t ext0 = a->dim[0].extent;
    CFI_index_t ext1 = a->dim[1].extent;
    CFI_index_t idx[2];

    *total = 0.0;
    for (j = 0; j < ext1; j++) {
        for (i = 0; i < ext0; i++) {
            idx[0] = i;
            idx[1] = j;
            *total += *(double *)CFI_address(a, idx);
        }
    }
}

The C subscripts passed to CFI_address start at the lower bound of each dimension, which is 0 for an assumed-shape argument. Compile and execute the program using the following command lines:

$ nvc -c sum_array.c
$ nvfortran cdesc_main.f90 sum_array.o
$ ./a.out

The section contains a(1,1), a(2,1), a(1,3) and a(2,3), which are 11, 21, 13 and 23. Executing the a.out file should produce the following output:

68.0

16. Programming Considerations for 64-Bit Environments

NVIDIA provides a 64-bit Fortran compiler for 64-bit Linux operating systems running on x86-64 (Linux_x86_64) and Arm Server (Linux_aarch64) architectures. You can use this compiler to create programs that use 64-bit memory addresses. The GNU toolchain on 64-bit Linux systems implements an option to control 32-bit vs 64-bit code generation, as described in Large Static Data in Linux. This section describes the specifics of how to use the nvfortran compiler to make use of 64-bit memory addressing.

Note

The nvfortran compiler itself is a 64-bit application which can only run on 64-bit CPUs running 64-bit Operating Systems.

This section describes how to use the following options related to 64-bit programming.

  • -mcmodel=medium

  • -i8

  • -fpic

16.1. Data Types in the 64-Bit Environment

The size of some data types can differ across 64-bit environments. This section describes the major differences.

16.1.1. Fortran Data Types

In Fortran, the default size of the INTEGER type is 4 bytes. The -i8 compiler option may be used to make the default size of all INTEGER data in the program 8 bytes.

16.2. Large Static Data in Linux

64-bit Linux operating systems support two different memory models. The default model used by the nvfortran compiler on Linux_x86_64 and Linux_aarch64 targets is the small memory model, which can be specified using -mcmodel=small. This is the 32-bit model, which limits the size of code plus statically allocated data, including system and user libraries, to 2GB. The medium memory model, specified by -mcmodel=medium, allows combined code and static data areas (.text and .bss sections) larger than 2GB. The -mcmodel=medium option must be used on both the compile command and the link command in order to take effect.

There are implications to using -mcmodel=medium. The generated code requires increased addressing overhead to support the large data range. This can affect performance, though the compiler seeks to minimize the added overhead through careful instruction selection and optimization.

Linux_aarch64 does not support -mcmodel=medium. If the medium model is specified on the command line, the compiler driver will automatically select the large model.

16.3. Large Dynamically Allocated Data

Dynamically allocated data objects in programs compiled by the nvfortran compiler can be larger than 2GB. No special compiler options are required to enable this functionality. The size of the allocation is only limited by the system. However, to correctly access dynamically allocated arrays with more than 2G elements you may need to use 64-bit INTEGER indices.

16.4. Compiler Options for 64-bit Programming

The usual switches that apply to 64-bit programmers seeking to increase the data range of their applications are in the following table.

Table 30 64-bit Compiler Options

Option

Purpose

Considerations

-⁠mcmodel=medium

Allow for data declarations larger than 2GB.

Linux_aarch64 does not support -mcmodel=medium. If the medium model is specified on the command line, the compiler driver will automatically select the large model.

-⁠i8

All INTEGER functions, data, and constants not explicitly declared INTEGER*4 are assumed to be INTEGER*8.

Users should take care to explicitly declare INTEGER functions as INTEGER*4.

-⁠fpic

Position independent code. Necessary for shared libraries.

Dynamic linking restricted to a 32-bit offset. External symbol references should refer to other shared lib routines, rather than the program calling them.

The following table summarizes the limits of these programming models under the specified conditions. The compiler options you use vary by processor.

Table 31 Effects of Options on Memory and Array Sizes

Condition

Addr. Math

Max Size Gbytes

A

I

AS

DS

TS

64-bit addr limited by option -mcmodel=small

64

32

2

2

2

-fpic incompatible with -mcmodel=medium

64

32

2

2

2

Enable full support for 64-bit data addressing

64

64

>2

>2

>2

A

Address Type – size in bits of data used for address calculations, 64-bits.

I

Index Arithmetic - bit size of data used to index into arrays and other aggregate data structures. If 32-bit, total range of any single data object is limited to 2GB.

AS

Maximum Array Size - the maximum size in gigabytes of any single data object.

DS

Maximum Data Size - max size in gigabytes combined of all data objects in .bss

TS

Maximum Total Size - max size in gigabytes, in aggregate, of all executable code and data objects in a running program.

16.5. Practical Limitations of Large Array Programming

The 64-bit addressing capability of 64-bit Linux environments can cause unexpected issues when data sizes are enlarged significantly. The following table describes the most common occurrences of practical limitations of large array programming.

Table 32 64-Bit Limitations

array initialization

Initializing a large array with a data statement may result in very large assembly and object files, where a line of assembler source is required for each element in the initialized array. Compilation and linking can be very time consuming as well. To avoid this issue, consider initializing large arrays in a loop at runtime rather than in a data statement.

stack space

Stack space can be a problem for data that is stack-based. On Linux, stack size is increased in your shell environment. If setting stacksize to unlimited is not large enough, try setting the size explicitly:

limit stacksize new_size ! in csh
ulimit -s new_size ! in bash

page swapping

If your executable is much larger than the physical size of memory, page swapping can cause it to run dramatically slower; it may even fail. This is not a compiler problem. Try smaller data sets to determine whether or not a problem is due to page thrashing.

configured space

Be sure your Linux system is configured with swap space sufficiently large to support the data sets used in your application(s). If your memory+swap space is not sufficiently large, your application will likely encounter a segmentation fault at runtime.

support for large address offsets in object file format

Arrays that are not dynamically allocated are limited by how the compiler can express the ‘distance’ between them when generating code. A field in the object file stores this ‘distance’ value, which is limited to 32-bits on Linux with -mcmodel=small. It is 64-bits on Linux with -mcmodel=medium.

Note

Without the 64-bit offset support in the object file format, large arrays cannot be declared statically, or locally on the stack.

16.6. Medium Memory Model and Large Array in Fortran

The following example works with the nvfortran compiler. It uses 64-bit addresses and index arithmetic when the -mcmodel=medium option is used.

Consider the following example:

Medium Memory Model and Large Array in Fortran

% cat mat.f
program mat
 integer i, j, k, size, l, m, n
 parameter (size=16000) ! >2GB
 parameter (m=size,n=size)
 real*8 a(m,n),b(m,n),c(m,n),d
 do i = 1, m
   do j = 1, n
     a(i,j)=10000.0D0*dble(i)+dble(j)
     b(i,j)=20000.0D0*dble(i)+dble(j)
   enddo
 enddo
 !$omp parallel private(d)
 !$omp do
 do i = 1, m
   do j = 1, n
     c(i,j) = a(i,j) + b(i,j)
   enddo
 enddo
 !$omp do
 do i=1,m
   do j = 1, n
     d = 30000.0D0*dble(i)+dble(j)+dble(j)
     if (d .ne. c(i,j)) then
       print *,"err i=",i,"j=",j
       print *,"c(i,j)=",c(i,j)
       print *,"d=",d
       stop
     endif
   enddo
 enddo
 !$omp end parallel
 print *, "M =",M,", N =",N
 print *, "c(M,N) = ", c(m,n)
end

When compiled with the nvfortran compiler using -mcmodel=medium:

% nvfortran -Mfree -mp -o mat mat.f -i8 -mcmodel=medium
% setenv OMP_NUM_THREADS 2
% mat
M = 16000 , N = 16000
c(M,N) = 480032000.

16.7. Large Array and Small Memory Model in Fortran

The following example uses large, dynamically-allocated arrays. The code is divided into a main and subroutine so you could put the subroutine into a shared library. Dynamic allocation of large arrays saves space in the size of executable and saves time initializing data.

Large Array and Small Memory Model in Fortran

% cat mat_allo.f90
program mat_allo
  integer i, j
  integer size, m, n
  parameter (size=16000)
  parameter (m=size,n=size)
  double precision, allocatable::a(:,:),b(:,:),c(:,:)
  allocate(a(m,n), b(m,n), c(m,n))
  do i = 100, m, 1
    do j = 100, n, 1
      a(i,j) = 10000.0D0 * dble(i) + dble(j)
      b(i,j) = 20000.0D0 * dble(i) + dble(j)
    enddo
  enddo
  call mat_add(a,b,c,m,n)
  print *, "M =",m,",N =",n
  print *, "c(M,N) = ", c(m,n)
end
subroutine mat_add(a,b,c,m,n)
  integer m, n, i, j
  double precision a(m,n),b(m,n),c(m,n)
  do i = 1, m
    do j = 1, n
      c(i,j) = a(i,j) + b(i,j)
    enddo
  enddo
  return
end
% nvfortran -o mat_allo mat_allo.f90  -fast

Notices

Notice and Disclaimers

All information provided in this document is provided as-is, for your informational purposes only and is subject to change at any time without notice. Reproduction of information in this document is permissible only if approved in advance by NVIDIA in writing. To obtain the latest information, please contact your NVIDIA representative. Product or service performance varies by use, configuration and other factors. Your costs and results may vary. No product or component is absolutely secure. TO THE FULLEST EXTENT PERMITTED BY APPLICABLE LAW, NVIDIA DISCLAIMS ALL WARRANTIES AND REPRESENTATIONS OF ANY KIND, WHETHER EXPRESS, IMPLIED OR STATUTORY, RELATING TO OR ARISING UNDER THIS DOCUMENT, INCLUDING, WITHOUT LIMITATION, THE WARRANTIES OF TITLE, NONINFRINGEMENT, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, USAGE OF TRADE AND COURSE OF DEALING. NVIDIA products are not intended or authorized for use as critical components in a system or application where the use of or failure of such system or application developed with products, technology, software or services provided by NVIDIA could result in injury, death or catastrophic damage.

Except for your permitted use of the information contained in this document, no license or right is granted by implication, estoppel or otherwise. If this document directly includes or links to third-party websites, products, services or information, please consult other sources to evaluate if and how to use that information since NVIDIA does not support, endorse or assume any responsibility for any third party offerings or its accuracy or usefulness.

TO THE FULLEST EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT WILL NVIDIA BE LIABLE FOR ANY (I) INDIRECT, PUNITIVE, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, OR (II) DAMAGES FOR THE (A) COST OF PROCURING SUBSTITUTE GOODS OR (B) LOSS OF PROFITS, REVENUES, USE, DATA OR GOODWILL ARISING OUT OF OR RELATED TO THIS DOCUMENT, WHETHER BASED ON BREACH OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY, OR OTHERWISE, AND EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES AND EVEN IF A PARTY’S REMEDIES FAIL THEIR ESSENTIAL PURPOSE. ADDITIONALLY, TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, NVIDIA’S TOTAL CUMULATIVE AGGREGATE LIABILITY FOR ANY AND ALL LIABILITIES, OBLIGATIONS OR CLAIMS ARISING OUT OF OR RELATED TO THIS DOCUMENT WILL NOT EXCEED FIVE U.S. DOLLARS (US$5).

Statements in this document that refer to future plans or expectations are forward-looking statements. These statements are based on currently available information, beliefs, assumptions and involve many risks and uncertainties that could cause actual results to differ materially from those expressed or implied in these statements. For more information on the factors that could cause actual results to differ materially, see our most recent earnings release and SEC filings at NVIDIA Corporation SEC Filings.

© NVIDIA Corporation. All rights reserved. NVIDIA, the NVIDIA logo, and other NVIDIA marks are trademarks of NVIDIA Corporation or its affiliates. Other names and brands may be claimed as the property of others.

Trademarks

NVIDIA, the NVIDIA logo, CUDA, CUDA-X, GPUDirect, HPC SDK, NGC, NVIDIA Volta, NVIDIA DGX, NVIDIA Nsight, NVLink, NVSwitch, and Tesla are trademarks and/or registered trademarks of NVIDIA Corporation in the U.S. and other countries. Other company and product names may be trademarks of the respective companies with which they are associated.