MCPcopy Create free account
hub / github.com/NVIDIA/cuda-samples / run

Function run

python/2_CoreConcepts/simpleZeroCopy/simpleZeroCopy.py:97–222  ·  view source on GitHub ↗

Zero-copy vector add: map host memory, launch kernel with device pointers, validate on CPU. This function shows how to: 1. Allocate pinned (page-locked) host memory 2. Map host memory into GPU address space (zero-copy) 3. Access host memory directly from GPU kernel 4. V

(num_elements=1048576)

Source from the content-addressed store, hash-verified

95
96
97def run(num_elements=1048576):
98 """
99 Zero-copy vector add: map host memory, launch kernel with device
100 pointers, validate on CPU.
101
102 This function shows how to:
103 1. Allocate pinned (page-locked) host memory
104 2. Map host memory into GPU address space (zero-copy)
105 3. Access host memory directly from GPU kernel
106 4. Validate results
107
108 Parameters
109 ----------
110 num_elements : int
111 Number of elements in vectors (default: 1048576)
112 """
113 print("\n" + "=" * 70)
114 print("simpleZeroCopy - CUDA Python Sample")
115 print("=" * 70)
116
117 # Initialize device
118 device = Device()
119 device.set_current()
120 major, minor = device.compute_capability
121
122 print("\nDevice Information:")
123 print(f" Name: {device.name}")
124 print(f" Compute Capability: {major}.{minor}")
125
126 # Create stream
127 stream = device.create_stream()
128 mapped_host_ptrs = []
129
130 try:
131 print(
132 "\n> Memory: mapped pinned host "
133 "(cudaHostAlloc + cudaHostGetDevicePointer)"
134 )
135
136 print("\nCompiling CUDA kernel...")
137 program_options = ProgramOptions(std="c++17", arch=f"sm_{device.arch}")
138 prog = Program(VECTOR_ADD_KERNEL, code_type="c++", options=program_options)
139 mod = prog.compile("cubin")
140 kernel = mod.get_kernel("vectorAddGPU")
141 print(" Kernel compiled successfully")
142
143 bytes_total = num_elements * np.dtype(np.float32).itemsize
144 print("\nAllocating memory:")
145 print(f" Vector size: {num_elements:,} elements")
146 print(f" Memory per vector: {bytes_total / (1024**2):.2f} MB")
147 print(f" Total memory: {3 * bytes_total / (1024**2):.2f} MB")
148
149 print("\n> Allocating mapped pinned host memory...")
150 h_a, d_a = _mapped_host_alloc(num_elements, stream)
151 mapped_host_ptrs.append(h_a)
152 h_b, d_b = _mapped_host_alloc(num_elements, stream)
153 mapped_host_ptrs.append(h_b)
154 h_c, d_c = _mapped_host_alloc(num_elements, stream)

Callers 1

mainFunction · 0.70

Calls 3

_mapped_host_allocFunction · 0.85
_float_viewFunction · 0.85
maxMethod · 0.45

Tested by

no test coverage detected