a quick journey on CUDA Fortran
English

a quick journey on CUDA Fortran

—

by

1. The Big Picture: What is CUDA Fortran?

CUDA Fortran is an extension of the Fortran language that allows you to write code that runs directly on NVIDIA GPUs. Instead of just using the GPU for fixed tasks (like 3D rendering), it lets you write custom functions (Kernels) that can perform massive parallel computations.

The core philosophy is the Host-Device Model:

The Host: Your CPU and its memory (RAM). It manages the overall flow of the program.

The Device: The GPU and its high-speed memory (VRAM). It does the “heavy lifting” (the math).

2. Key Architectural ConceptsTo program in CUDA Fortran,

you must understand these four pillars:

A. Memory Spaces (Where does the data live?)In standard Fortran, all variables are on the Host. In CUDA Fortran, you must tell the compiler where a variable should reside using attributes:

attribute(host): The variable lives in CPU memory (default).

attribute(device): The variable lives in GPU memory.

attribute(managed): Unified Memory. This is a “magic” feature where the system automatically moves data between CPU and GPU as needed. It is highly recommended for beginners.

B. The Kernel (The GPU function)

A Kernel is a special subroutine that is executed NN

times in parallel by many different GPU threads.

It is defined using attributes(global).

Unlike a normal subroutine, you don’t call it to get one answer; you “launch” it to process a whole array of data at once.

C. The Thread Hierarchy (How is work divided?)The GPU doesn’t just run one big loop; it breaks the work into a hierarchy:

Thread: The smallest unit of execution (processes one element).

Block: A group of threads that can cooperate and share fast “Shared Memory.”

Grid: A collection of blocks that together make up the entire job.

D. Indexing (How does a thread know what to do?)

Inside a kernel, you don’t use a do loop. Instead, each thread calculates its own unique ID using built-in variables:

%tid: Thread ID within the block.

%bid: Block ID within the grid.

Formula: \text{Global ID} = (\text{Block ID} \times \text{Block Size}) + \text{Thread ID}

3. The Programming Workflow (The “Recipe”)

If you are writing a CUDA Fortran program, you will almost always follow these steps:

Initialize: Define your data on the Host.

Allocate: Create space for that data on the Device (allocate variables with the device attribute).

Transfer In: Copy the data from Host \rightarrow Device (using cudaMemcpy or by simply assigning values to managed memory).

Configure & Launch:

Decide how many blocks and threads you need.

Launch the kernel using the <<<grid, block>>> syntax.

Transfer Out: Copy the results from Device \rightarrow Host so the CPU can print or save them.

Cleanup: Deallocate device memory to avoid leaks.

0