Skill Tracer
Skills › Scientific Agent Skills › optimize-for-gpu › kvikio.md

kvikio.md

658 lines · skills/optimize-for-gpu/references/kvikio.md at 5f2bc03

Open on GitHub
1# KvikIO Reference — High-Performance GPU File IO
2
3> Review: 2026-10-01. Code below is illustrative unless explicitly described as CPU-tested.
4> GPU execution, performance, GDS, and multi-GPU behavior require validation on target hardware.
5
6KvikIO is a Python and C++ library for high-performance file IO. It provides bindings to NVIDIA cuFile, enabling GPUDirect Storage (GDS) — eligible local reads and writes between supported storage and GPU memory. When GDS isn't available, KvikIO falls back gracefully to POSIX IO while still handling both host and device data seamlessly.
7
8KvikIO is part of the RAPIDS ecosystem and interoperates with CuPy, cuDF, Numba, and other GPU libraries.
9

KvikIO Reference — High-Performance GPU File IO

Review: 2026-10-01. Code below is illustrative unless explicitly described as CPU-tested. GPU execution, performance, GDS, and multi-GPU behavior require validation on target hardware.

KvikIO is a Python and C++ library for high-performance file IO. It provides bindings to NVIDIA cuFile, enabling GPUDirect Storage (GDS) — eligible local reads and writes between supported storage and GPU memory. When GDS isn't available, KvikIO falls back gracefully to POSIX IO while still handling both host and device data seamlessly.

KvikIO is part of the RAPIDS ecosystem and interoperates with CuPy, cuDF, Numba, and other GPU libraries.

Raw lines 1 to 9
10## Table of Contents
121. [Installation](#installation)
132. [When to Use KvikIO](#when-to-use-kvikio)
143. [CuFile — Local File IO](#cufile--local-file-io)
154. [RemoteFile — S3, HTTP, WebHDFS](#remotefile--s3-http-webhdfs)
165. [Zarr Integration](#zarr-integration)
176. [Memory-Mapped Files](#memory-mapped-files)
187. [Runtime Settings](#runtime-settings)
198. [Performance Optimization](#performance-optimization)
209. [Interoperability](#interoperability)
2110. [Common Patterns](#common-patterns)
2211. [Common Pitfalls](#common-pitfalls)
24---

Table of Contents

  1. Installation
  2. When to Use KvikIO
  3. CuFile — Local File IO
  4. RemoteFile — S3, HTTP, WebHDFS
  5. Zarr Integration
  6. Memory-Mapped Files
  7. Runtime Settings
  8. Performance Optimization
  9. Interoperability
  10. Common Patterns
  11. Common Pitfalls

Raw lines 10 to 25
26## Installation
28```bash
29# CUDA 12.x
30uv add "kvikio-cu12==26.8.*"
32# CUDA 13.x
33uv add "kvikio-cu13==26.8.*"
35# For Zarr support (optional)
36uv add "zarr==3.*"
37```
39Verify installation:
41```python
42import kvikio
43# Check if GDS is available
44import kvikio.cufile_driver
45print(kvikio.cufile_driver.get("is_gds_available")) # True if GDS is set up
46```
48---

Installation

# CUDA 12.x
uv add "kvikio-cu12==26.8.*"

# CUDA 13.x
uv add "kvikio-cu13==26.8.*"

# For Zarr support (optional)
uv add "zarr==3.*"

Verify installation:

import kvikio
# Check if GDS is available
import kvikio.cufile_driver
print(kvikio.cufile_driver.get("is_gds_available"))  # True if GDS is set up

Raw lines 26 to 49
50## When to Use KvikIO
52Use KvikIO when:
53- **Loading large binary data directly to GPU** — avoids the CPU-memory copy that standard `open()` or NumPy's `fromfile()` would require
54- **Writing GPU arrays to disk** — saves directly from device memory without copying to host first
55- **Reading from remote storage (S3, HTTP, WebHDFS) into GPU memory** — convenient device destinations; libcurl uses host bounce buffers
56- **Working with Zarr arrays on GPU** — the GDSStore backend reads chunks directly into CuPy arrays
57- **IO is the bottleneck** — compare the actual storage, filesystem, access pattern and GDS eligibility
58- **Overlapping IO and compute** — non-blocking reads/writes let you pipeline data loading with GPU computation
60KvikIO is a poor fit when:
61- Small transfers whose setup costs dominate measured latency
62- You're reading structured formats (CSV, Parquet, JSON) — use cuDF instead, which has its own optimized readers
63- You only need host memory — standard Python IO is simpler
65---

When to Use KvikIO

Use KvikIO when:

  • Loading large binary data directly to GPU — avoids the CPU-memory copy that standard open() or NumPy's fromfile() would require
  • Writing GPU arrays to disk — saves directly from device memory without copying to host first
  • Reading from remote storage (S3, HTTP, WebHDFS) into GPU memory — convenient device destinations; libcurl uses host bounce buffers
  • Working with Zarr arrays on GPU — the GDSStore backend reads chunks directly into CuPy arrays
  • IO is the bottleneck — compare the actual storage, filesystem, access pattern and GDS eligibility
  • Overlapping IO and compute — non-blocking reads/writes let you pipeline data loading with GPU computation

KvikIO is a poor fit when:

  • Small transfers whose setup costs dominate measured latency
  • You're reading structured formats (CSV, Parquet, JSON) — use cuDF instead, which has its own optimized readers
  • You only need host memory — standard Python IO is simpler

Raw lines 50 to 66
67## CuFile — Local File IO
69`kvikio.CuFile` is the primary interface for local file IO. It replaces Python's `open()` for GPU workloads.

CuFile — Local File IO

kvikio.CuFile is the primary interface for local file IO. It replaces Python's open() for GPU workloads.

Raw lines 67 to 70
71### Basic Usage
73```python
74import cupy as cp
75import kvikio
77# Write a GPU array to disk
78a = cp.arange(1_000_000, dtype=cp.float32)
79with kvikio.CuFile("data.bin", "w") as f:
80 f.write(a)
82# Read it back
83b = cp.empty(1_000_000, dtype=cp.float32)
84with kvikio.CuFile("data.bin", "r") as f:
85 f.read(b)
87assert cp.all(a == b)
88```

Basic Usage

import cupy as cp
import kvikio

# Write a GPU array to disk
a = cp.arange(1_000_000, dtype=cp.float32)
with kvikio.CuFile("data.bin", "w") as f:
    f.write(a)

# Read it back
b = cp.empty(1_000_000, dtype=cp.float32)
with kvikio.CuFile("data.bin", "r") as f:
    f.read(b)

assert cp.all(a == b)
Raw lines 71 to 89
90### API Methods
92| Method | Blocking | Description |
93|--------|----------|-------------|
94| `read(buf, size, file_offset)` | Yes | Read into device or host buffer |
95| `write(buf, size, file_offset)` | Yes | Write from device or host buffer |
96| `pread(buf, size, file_offset)` | No | Non-blocking parallel read, returns `IOFuture` |
97| `pwrite(buf, size, file_offset)` | No | Non-blocking parallel write, returns `IOFuture` |
98| `raw_read(buf, size, file_offset)` | Yes | Low-level single-thread read (device only) |
99| `raw_write(buf, size, file_offset)` | Yes | Low-level single-thread write (device only) |
100| `raw_read_async(buf, stream, size, file_offset)` | No | CUDA-stream async read (device only) |
101| `raw_write_async(buf, stream, size, file_offset)` | No | CUDA-stream async write (device only) |
103File modes: `"r"` (read), `"w"` (write/truncate), `"a"` (append), `"+"` (read+write).

API Methods

MethodBlockingDescription
read(buf, size, file_offset)YesRead into device or host buffer
write(buf, size, file_offset)YesWrite from device or host buffer
pread(buf, size, file_offset)NoNon-blocking parallel read, returns IOFuture
pwrite(buf, size, file_offset)NoNon-blocking parallel write, returns IOFuture
raw_read(buf, size, file_offset)YesLow-level single-thread read (device only)
raw_write(buf, size, file_offset)YesLow-level single-thread write (device only)
raw_read_async(buf, stream, size, file_offset)NoCUDA-stream async read (device only)
raw_write_async(buf, stream, size, file_offset)NoCUDA-stream async write (device only)

File modes: "r" (read), "w" (write/truncate), "a" (append), "+" (read+write).

Raw lines 90 to 104
105### Non-Blocking IO with Futures
107`pread` and `pwrite` split the operation into tasks executed in a thread pool and return an `IOFuture`:
109```python
110import cupy as cp
111import kvikio
113data = cp.empty(10_000_000, dtype=cp.float32)
115with kvikio.CuFile("data.bin", "r") as f:
116 # Launch two non-blocking reads for different sections
117 future1 = f.pread(data[:5_000_000])
118 future2 = f.pread(data[5_000_000:], file_offset=5_000_000 * 4)
120 # Do other work while IO happens...
122 # Wait for completion
123 bytes_read1 = future1.get()
124 bytes_read2 = future2.get()
125```

Non-Blocking IO with Futures

pread and pwrite split the operation into tasks executed in a thread pool and return an IOFuture:

import cupy as cp
import kvikio

data = cp.empty(10_000_000, dtype=cp.float32)

with kvikio.CuFile("data.bin", "r") as f:
    # Launch two non-blocking reads for different sections
    future1 = f.pread(data[:5_000_000])
    future2 = f.pread(data[5_000_000:], file_offset=5_000_000 * 4)

    # Do other work while IO happens...

    # Wait for completion
    bytes_read1 = future1.get()
    bytes_read2 = future2.get()
Raw lines 105 to 126
127### Partial Reads and Writes
129```python
130import cupy as cp
131import kvikio
133# Read only a portion of a file
134buf = cp.empty(1000, dtype=cp.float32)
135with kvikio.CuFile("data.bin", "r") as f:
136 # Read 1000 floats starting at byte offset 4000
137 f.read(buf, size=4000, file_offset=4000)
138```

Partial Reads and Writes

import cupy as cp
import kvikio

# Read only a portion of a file
buf = cp.empty(1000, dtype=cp.float32)
with kvikio.CuFile("data.bin", "r") as f:
    # Read 1000 floats starting at byte offset 4000
    f.read(buf, size=4000, file_offset=4000)
Raw lines 127 to 139
140### Host Memory Support
142KvikIO handles host memory transparently — no special API needed:
144```python
145import numpy as np
146import kvikio
148# Write from host memory
149a = np.arange(1_000_000, dtype=np.float32)
150with kvikio.CuFile("data.bin", "w") as f:
151 f.write(a)
153# Read into host memory
154b = np.empty_like(a)
155with kvikio.CuFile("data.bin", "r") as f:
156 f.read(b)
157```

Host Memory Support

KvikIO handles host memory transparently — no special API needed:

import numpy as np
import kvikio

# Write from host memory
a = np.arange(1_000_000, dtype=np.float32)
with kvikio.CuFile("data.bin", "w") as f:
    f.write(a)

# Read into host memory
b = np.empty_like(a)
with kvikio.CuFile("data.bin", "r") as f:
    f.read(b)
Raw lines 140 to 158
159### GDS Alignment
161GDS works best with page-aligned IO. The relevant GDS I/O alignment is 4 KiB (4096 bytes); this is not a universal GPU memory-page size:
162- **File offset**: should be a multiple of 4096
163- **Transfer size**: should be a multiple of 4096
165KvikIO handles unaligned IO correctly but splits it into aligned and unaligned parts, so aligned IO will be faster.
167---

GDS Alignment

GDS works best with page-aligned IO. The relevant GDS I/O alignment is 4 KiB (4096 bytes); this is not a universal GPU memory-page size:

  • File offset: should be a multiple of 4096
  • Transfer size: should be a multiple of 4096

KvikIO handles unaligned IO correctly but splits it into aligned and unaligned parts, so aligned IO will be faster.


Raw lines 159 to 168
169## RemoteFile — S3, HTTP, WebHDFS
171`kvikio.RemoteFile` reads remote files directly into GPU or host memory.

RemoteFile — S3, HTTP, WebHDFS

kvikio.RemoteFile reads remote files directly into GPU or host memory.

Raw lines 169 to 172
173### HTTP/HTTPS
175```python
176import cupy as cp
177import kvikio
179buf = cp.empty(1_000_000, dtype=cp.float32)
180with kvikio.RemoteFile.open_http("https://example.com/data.bin") as f:
181 print(f.nbytes()) # File size
182 f.read(buf)
183```

HTTP/HTTPS

import cupy as cp
import kvikio

buf = cp.empty(1_000_000, dtype=cp.float32)
with kvikio.RemoteFile.open_http("https://example.com/data.bin") as f:
    print(f.nbytes())  # File size
    f.read(buf)
Raw lines 173 to 184
185### AWS S3
187```python
188import cupy as cp
189import kvikio
191# Using bucket + object name (requires AWS env vars or explicit credentials)
192with kvikio.RemoteFile.open_s3("my-bucket", "data/file.bin") as f:
193 buf = cp.empty(f.nbytes(), dtype=cp.uint8)
194 f.read(buf)
196# Using S3 URL
197with kvikio.RemoteFile.open_s3_url("s3://my-bucket/data/file.bin") as f:
198 buf = cp.empty(f.nbytes(), dtype=cp.uint8)
199 f.read(buf)
201# Public S3 (no credentials needed)
202with kvikio.RemoteFile.open_s3_public("s3://public-bucket/data.bin") as f:
203 buf = cp.empty(f.nbytes(), dtype=cp.uint8)
204 f.read(buf)
206# Presigned URL
207with kvikio.RemoteFile.open_s3_presigned_url(presigned_url) as f:
208 buf = cp.empty(f.nbytes(), dtype=cp.uint8)
209 f.read(buf)
210```
212AWS credentials come from `AWS_DEFAULT_REGION`, `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and optionally `AWS_SESSION_TOKEN`, or documented keyword arguments. Resolve temporary credentials explicitly; do not assume the complete boto3 profile/role provider chain. S3/public/presigned endpoints and HTTP range behavior must match the actual service.

AWS S3

import cupy as cp
import kvikio

# Using bucket + object name (requires AWS env vars or explicit credentials)
with kvikio.RemoteFile.open_s3("my-bucket", "data/file.bin") as f:
    buf = cp.empty(f.nbytes(), dtype=cp.uint8)
    f.read(buf)

# Using S3 URL
with kvikio.RemoteFile.open_s3_url("s3://my-bucket/data/file.bin") as f:
    buf = cp.empty(f.nbytes(), dtype=cp.uint8)
    f.read(buf)

# Public S3 (no credentials needed)
with kvikio.RemoteFile.open_s3_public("s3://public-bucket/data.bin") as f:
    buf = cp.empty(f.nbytes(), dtype=cp.uint8)
    f.read(buf)

# Presigned URL
with kvikio.RemoteFile.open_s3_presigned_url(presigned_url) as f:
    buf = cp.empty(f.nbytes(), dtype=cp.uint8)
    f.read(buf)

AWS credentials come from AWS_DEFAULT_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and optionally AWS_SESSION_TOKEN, or documented keyword arguments. Resolve temporary credentials explicitly; do not assume the complete boto3 profile/role provider chain. S3/public/presigned endpoints and HTTP range behavior must match the actual service.

Raw lines 185 to 213
214### Auto-Detect Endpoint Type
216```python
217import kvikio
219# KvikIO figures out the protocol from the URL
220with kvikio.RemoteFile.open("s3://bucket/object") as f:
221 ...
223with kvikio.RemoteFile.open("https://example.com/file.bin") as f:
224 ...
225```

Auto-Detect Endpoint Type

import kvikio

# KvikIO figures out the protocol from the URL
with kvikio.RemoteFile.open("s3://bucket/object") as f:
    ...

with kvikio.RemoteFile.open("https://example.com/file.bin") as f:
    ...
Raw lines 214 to 226
227### WebHDFS
229```python
230import kvikio
232with kvikio.RemoteFile.open_webhdfs("http://namenode:9870/webhdfs/v1/path/to/file") as f:
233 buf = cp.empty(f.nbytes(), dtype=cp.uint8)
234 f.read(buf)
235```
237Use the deployment's actual scheme, host, explicit port, and `/webhdfs/v1/` path.
238This example does not configure Kerberos or establish access to a protected cluster.

WebHDFS

import kvikio

with kvikio.RemoteFile.open_webhdfs("http://namenode:9870/webhdfs/v1/path/to/file") as f:
    buf = cp.empty(f.nbytes(), dtype=cp.uint8)
    f.read(buf)

Use the deployment's actual scheme, host, explicit port, and /webhdfs/v1/ path. This example does not configure Kerberos or establish access to a protected cluster.

Raw lines 227 to 239
240### Host Memory with RemoteFile
242RemoteFile reads into host memory just as easily:
244```python
245import numpy as np
246import kvikio
248with kvikio.RemoteFile.open_http("https://example.com/data.bin") as f:
249 buf = np.empty(f.nbytes(), dtype=np.uint8)
250 f.read(buf)
251```
253---

Host Memory with RemoteFile

RemoteFile reads into host memory just as easily:

import numpy as np
import kvikio

with kvikio.RemoteFile.open_http("https://example.com/data.bin") as f:
    buf = np.empty(f.nbytes(), dtype=np.uint8)
    f.read(buf)

Raw lines 240 to 254
255## Zarr Integration
257KvikIO provides a GPU store backend for Zarr (version 3.x). This enables reading and writing chunked N-dimensional arrays directly in GPU memory via GDS.
259```python
260import zarr
261from kvikio.zarr import GDSStore
263# Enable GPU support in Zarr
264zarr.config.enable_gpu()
266# Create a GDS-backed store
267store = GDSStore(root="data.zarr")
269# Create and write a Zarr array (data stays on GPU)
270z = zarr.create_array(
271 store=store,
272 shape=(1000, 1000),
273 chunks=(100, 100),
274 dtype="float32",
275 overwrite=False,
278# Reading returns CuPy arrays
279chunk = z[:100, :100] # Returns cupy.ndarray
280```
282Zarr + KvikIO is useful for:
283- Climate/weather data (large multi-dimensional arrays)
284- Bioinformatics (genomic arrays)
285- Any workload using chunked arrays that need GPU processing
287Requires a compatible Zarr 3 release in addition to KvikIO 26.08. Check codec GPU support; a GPU store alone does not make every codec device-resident.
289---

Zarr Integration

KvikIO provides a GPU store backend for Zarr (version 3.x). This enables reading and writing chunked N-dimensional arrays directly in GPU memory via GDS.

import zarr
from kvikio.zarr import GDSStore

# Enable GPU support in Zarr
zarr.config.enable_gpu()

# Create a GDS-backed store
store = GDSStore(root="data.zarr")

# Create and write a Zarr array (data stays on GPU)
z = zarr.create_array(
    store=store,
    shape=(1000, 1000),
    chunks=(100, 100),
    dtype="float32",
    overwrite=False,
)

# Reading returns CuPy arrays
chunk = z[:100, :100]  # Returns cupy.ndarray

Zarr + KvikIO is useful for:

  • Climate/weather data (large multi-dimensional arrays)
  • Bioinformatics (genomic arrays)
  • Any workload using chunked arrays that need GPU processing

Requires a compatible Zarr 3 release in addition to KvikIO 26.08. Check codec GPU support; a GPU store alone does not make every codec device-resident.


Raw lines 255 to 290
291## Memory-Mapped Files
293`kvikio.mmap.Mmap` provides memory-mapped file access with support for both host and device destinations:
295```python
296from kvikio.mmap import Mmap
297import cupy as cp
299# Map a file for reading
300with Mmap("data.bin", flags="r") as m:
301 print(m.file_size())
303 # Sequential read into device memory
304 buf = cp.empty(1000, dtype=cp.float32)
305 m.read(buf, size=4000, offset=0)
307 # Parallel read (returns IOFuture)
308 future = m.pread(buf, size=4000, offset=0)
309 future.get()
310```
312---

Memory-Mapped Files

kvikio.mmap.Mmap provides memory-mapped file access with support for both host and device destinations:

from kvikio.mmap import Mmap
import cupy as cp

# Map a file for reading
with Mmap("data.bin", flags="r") as m:
    print(m.file_size())

    # Sequential read into device memory
    buf = cp.empty(1000, dtype=cp.float32)
    m.read(buf, size=4000, offset=0)

    # Parallel read (returns IOFuture)
    future = m.pread(buf, size=4000, offset=0)
    future.get()

Raw lines 291 to 313
314## Runtime Settings
316KvikIO behavior is controlled via environment variables or the `kvikio.defaults` API.

Runtime Settings

KvikIO behavior is controlled via environment variables or the kvikio.defaults API.

Raw lines 314 to 317
318### Key Settings
320| Setting | Env Variable | Default | Description |
321|---------|-------------|---------|-------------|
322| Compatibility mode | `KVIKIO_COMPAT_MODE` | `AUTO` | `ON`: POSIX only, `OFF`: GDS only, `AUTO`: try GDS, fall back |
323| Thread pool size | `KVIKIO_NTHREADS` | 1 | Number of IO threads for `pread`/`pwrite` |
324| Task size | `KVIKIO_TASK_SIZE` | 4 MiB | Max size per parallel IO task |
325| GDS threshold | `KVIKIO_GDS_THRESHOLD` | 16 KiB | Min size to use GDS (smaller uses POSIX) |
326| Bounce buffer size | `KVIKIO_BOUNCE_BUFFER_SIZE` | 16 MiB | Size of intermediate host buffers per thread |
327| Direct IO read | `KVIKIO_AUTO_DIRECT_IO_READ` | off | Opportunistic O_DIRECT for reads |
328| Direct IO write | `KVIKIO_AUTO_DIRECT_IO_WRITE` | on | Opportunistic O_DIRECT for writes |

Key Settings

SettingEnv VariableDefaultDescription
Compatibility modeKVIKIO_COMPAT_MODEAUTOON: POSIX only, OFF: GDS only, AUTO: try GDS, fall back
Thread pool sizeKVIKIO_NTHREADS1Number of IO threads for pread/pwrite
Task sizeKVIKIO_TASK_SIZE4 MiBMax size per parallel IO task
GDS thresholdKVIKIO_GDS_THRESHOLD16 KiBMin size to use GDS (smaller uses POSIX)
Bounce buffer sizeKVIKIO_BOUNCE_BUFFER_SIZE16 MiBSize of intermediate host buffers per thread
Direct IO readKVIKIO_AUTO_DIRECT_IO_READoffOpportunistic O_DIRECT for reads
Direct IO writeKVIKIO_AUTO_DIRECT_IO_WRITEonOpportunistic O_DIRECT for writes
Raw lines 318 to 329
330### Programmatic Configuration
332```python
333import kvikio.defaults
335# Query settings
336print(kvikio.defaults.get("compat_mode"))
337print(kvikio.defaults.get("num_threads"))
339# Modify settings at runtime
340kvikio.defaults.set({"num_threads": 16, "task_size": 8 * 1024 * 1024})
342# Enable direct IO for reads
343kvikio.defaults.set({"auto_direct_io_read": True})
344```

Programmatic Configuration

import kvikio.defaults

# Query settings
print(kvikio.defaults.get("compat_mode"))
print(kvikio.defaults.get("num_threads"))

# Modify settings at runtime
kvikio.defaults.set({"num_threads": 16, "task_size": 8 * 1024 * 1024})

# Enable direct IO for reads
kvikio.defaults.set({"auto_direct_io_read": True})
Raw lines 330 to 345
346### Compatibility Mode
348When GDS isn't available (missing `libcufile.so`, running in WSL, Docker without `/run/udev`), `AUTO` mode falls back to POSIX IO automatically. This fallback still requires a supported KvikIO/CUDA platform; it does not add macOS support or guarantee a speedup.
350```python
351import kvikio.cufile_driver
353# Check GDS capability; individual operations can still take compatibility/bounce-buffer paths
354print(kvikio.cufile_driver.get("is_gds_available"))
355```

Compatibility Mode

When GDS isn't available (missing libcufile.so, running in WSL, Docker without /run/udev), AUTO mode falls back to POSIX IO automatically. This fallback still requires a supported KvikIO/CUDA platform; it does not add macOS support or guarantee a speedup.

import kvikio.cufile_driver

# Check GDS capability; individual operations can still take compatibility/bounce-buffer paths
print(kvikio.cufile_driver.get("is_gds_available"))
Raw lines 346 to 356
357### cuFile Driver Configuration
359```python
360import kvikio.cufile_driver
362# Query driver properties
363print(kvikio.cufile_driver.get("is_gds_available"))
364print(kvikio.cufile_driver.get("major_version"))
366# Configure settable properties
367kvikio.cufile_driver.set("max_device_cache_size", 1024)
369# Use as context manager (auto-reverts on exit)
370with kvikio.cufile_driver.set({"poll_mode": True}):
371 # poll mode active here
372 ...
373# poll mode reverted
374```
376---

cuFile Driver Configuration

import kvikio.cufile_driver

# Query driver properties
print(kvikio.cufile_driver.get("is_gds_available"))
print(kvikio.cufile_driver.get("major_version"))

# Configure settable properties
kvikio.cufile_driver.set("max_device_cache_size", 1024)

# Use as context manager (auto-reverts on exit)
with kvikio.cufile_driver.set({"poll_mode": True}):
    # poll mode active here
    ...
# poll mode reverted

Raw lines 357 to 377
378## Performance Optimization

Performance Optimization

Raw lines 378 to 379
380### 1. Increase Thread Pool Size
382The default of 1 thread is conservative. For large files, increase it:
384```python
385import kvikio.defaults
386kvikio.defaults.set({"num_threads": 16})
387```

1. Increase Thread Pool Size

The default of 1 thread is conservative. For large files, increase it:

import kvikio.defaults
kvikio.defaults.set({"num_threads": 16})
Raw lines 380 to 388
389### 2. Use Non-Blocking IO for Pipelining
391Overlap IO with compute by using `pread`/`pwrite`:
393```python
394from pathlib import Path
395import cupy as cp
396import kvikio
398def process_float32_chunks(path, chunk_items, consume):
399 """Consume every chunk, including the tail, without reusing a live GPU buffer."""
400 if chunk_items <= 0:
401 raise ValueError("chunk_items must be positive")
402 nbytes = Path(path).stat().st_size
403 if nbytes % 4:
404 raise ValueError("Input must contain complete float32 values")
405 total = nbytes // 4
406 if total == 0:
407 return
408 buf_a = cp.empty(chunk_items, dtype=cp.float32)
409 buf_b = cp.empty_like(buf_a)
410 stream = cp.cuda.get_current_stream()
411 with kvikio.CuFile(path, "r") as f:
412 count = min(chunk_items, total)
413 future = f.pread(buf_a[:count], file_offset=0)
414 offset = 0
415 while count:
416 if future.get() != count * 4:
417 raise EOFError("Short read")
418 next_count = min(chunk_items, total - offset - count)
419 next_future = None
420 if next_count:
421 next_future = f.pread(buf_b[:next_count],
422 file_offset=(offset + count) * 4)
423 try:
424 try:
425 consume(buf_a[:count]) # Enqueue only on the current CuPy stream.
426 finally:
427 stream.synchronize() # Finish using this buffer before recycling it.
428 except BaseException:
429 if next_future is not None:
430 next_future.get() # Drain pending I/O before either buffer is freed.
431 raise
432 offset += count
433 count, future = next_count, next_future
434 buf_a, buf_b = buf_b, buf_a
436# consume must finish using its input on this stream and must not retain that view.
437# process_float32_chunks("large_data.bin", 1_000_000, consume)
438```
440The chunk/tail and buffer-lifetime logic is CPU-tested with fake asynchronous I/O and streams;
441actual overlap and throughput are not GPU-verified. A callback using other streams must join
442those streams before returning.

2. Use Non-Blocking IO for Pipelining

Overlap IO with compute by using pread/pwrite:

from pathlib import Path
import cupy as cp
import kvikio

def process_float32_chunks(path, chunk_items, consume):
    """Consume every chunk, including the tail, without reusing a live GPU buffer."""
    if chunk_items <= 0:
        raise ValueError("chunk_items must be positive")
    nbytes = Path(path).stat().st_size
    if nbytes % 4:
        raise ValueError("Input must contain complete float32 values")
    total = nbytes // 4
    if total == 0:
        return
    buf_a = cp.empty(chunk_items, dtype=cp.float32)
    buf_b = cp.empty_like(buf_a)
    stream = cp.cuda.get_current_stream()
    with kvikio.CuFile(path, "r") as f:
        count = min(chunk_items, total)
        future = f.pread(buf_a[:count], file_offset=0)
        offset = 0
        while count:
            if future.get() != count * 4:
                raise EOFError("Short read")
            next_count = min(chunk_items, total - offset - count)
            next_future = None
            if next_count:
                next_future = f.pread(buf_b[:next_count],
                                      file_offset=(offset + count) * 4)
            try:
                try:
                    consume(buf_a[:count])  # Enqueue only on the current CuPy stream.
                finally:
                    stream.synchronize()  # Finish using this buffer before recycling it.
            except BaseException:
                if next_future is not None:
                    next_future.get()  # Drain pending I/O before either buffer is freed.
                raise
            offset += count
            count, future = next_count, next_future
            buf_a, buf_b = buf_b, buf_a

# consume must finish using its input on this stream and must not retain that view.
# process_float32_chunks("large_data.bin", 1_000_000, consume)

The chunk/tail and buffer-lifetime logic is CPU-tested with fake asynchronous I/O and streams; actual overlap and throughput are not GPU-verified. A callback using other streams must join those streams before returning.

Raw lines 389 to 443
444### 3. Align IO to Page Boundaries
446GDS performs best with 4 KiB-aligned offsets and sizes:
448```python
449# Good: aligned offset and size
450f.read(buf, size=4096 * 1000, file_offset=4096 * 10)
452# Slower: unaligned (KvikIO handles it, but splits into aligned + unaligned parts)
453f.read(buf, size=5000, file_offset=100)
454```

3. Align IO to Page Boundaries

GDS performs best with 4 KiB-aligned offsets and sizes:

# Good: aligned offset and size
f.read(buf, size=4096 * 1000, file_offset=4096 * 10)

# Slower: unaligned (KvikIO handles it, but splits into aligned + unaligned parts)
f.read(buf, size=5000, file_offset=100)
Raw lines 444 to 455
456### 4. Enable Direct IO
458For sequential writes and cold reads, Direct IO (bypassing OS page cache) can help:
460```python
461import kvikio.defaults
462kvikio.defaults.set({
463 "auto_direct_io_read": True,
464 "auto_direct_io_write": True,
465})
466```

4. Enable Direct IO

For sequential writes and cold reads, Direct IO (bypassing OS page cache) can help:

import kvikio.defaults
kvikio.defaults.set({
    "auto_direct_io_read": True,
    "auto_direct_io_write": True,
})
Raw lines 456 to 467
468### 5. Tune Task and Bounce Buffer Sizes
470For very large files, increase task and bounce buffer sizes:
472```python
473import kvikio.defaults
474kvikio.defaults.set({
475 "task_size": 16 * 1024 * 1024, # 16 MiB per task
476 "bounce_buffer_size": 64 * 1024 * 1024, # 64 MiB bounce buffer
477})
478```

5. Tune Task and Bounce Buffer Sizes

For very large files, increase task and bounce buffer sizes:

import kvikio.defaults
kvikio.defaults.set({
    "task_size": 16 * 1024 * 1024,       # 16 MiB per task
    "bounce_buffer_size": 64 * 1024 * 1024,  # 64 MiB bounce buffer
})
Raw lines 468 to 479
480### 6. Page Cache Utilities
482For benchmarking, clear the page cache to measure cold-read performance:
484```python
485import kvikio
487# Check page cache residency
488pages_cached, total_pages = kvikio.get_page_cache_info("data.bin")
489print(f"{pages_cached}/{total_pages} pages in cache")
491# Drop the page cache for a single file (no elevated privileges needed; added in 26.04)
492kvikio.drop_file_page_cache("data.bin")
494# Avoid system-wide cache eviction on a shared host. Use a dedicated benchmark environment.
495```
497`kvikio.clear_page_cache()` is deprecated since 26.04 — use `drop_system_page_cache()` (or the per-file `drop_file_page_cache()`) instead.
499---

6. Page Cache Utilities

For benchmarking, clear the page cache to measure cold-read performance:

import kvikio

# Check page cache residency
pages_cached, total_pages = kvikio.get_page_cache_info("data.bin")
print(f"{pages_cached}/{total_pages} pages in cache")

# Drop the page cache for a single file (no elevated privileges needed; added in 26.04)
kvikio.drop_file_page_cache("data.bin")

# Avoid system-wide cache eviction on a shared host. Use a dedicated benchmark environment.

kvikio.clear_page_cache() is deprecated since 26.04 — use drop_system_page_cache() (or the per-file drop_file_page_cache()) instead.


Raw lines 480 to 500
501## Interoperability

Interoperability

Raw lines 501 to 502
503### With CuPy
505KvikIO reads directly into CuPy arrays — this is the most common usage:
507```python
508import cupy as cp
509import kvikio
511data = cp.empty(1_000_000, dtype=cp.float64)
512with kvikio.CuFile("data.bin", "r") as f:
513 f.read(data)
514# data is now a CuPy array, ready for GPU computation
515```

With CuPy

KvikIO reads directly into CuPy arrays — this is the most common usage:

import cupy as cp
import kvikio

data = cp.empty(1_000_000, dtype=cp.float64)
with kvikio.CuFile("data.bin", "r") as f:
    f.read(data)
# data is now a CuPy array, ready for GPU computation
Raw lines 503 to 516
517### With Numba CUDA
519KvikIO works with any buffer supporting the CUDA Array Interface:
521```python
522from numba import cuda
523import kvikio
525d_arr = cuda.device_array(1_000_000, dtype="float32")
526with kvikio.CuFile("data.bin", "r") as f:
527 f.read(d_arr)
528```

With Numba CUDA

KvikIO works with any buffer supporting the CUDA Array Interface:

from numba import cuda
import kvikio

d_arr = cuda.device_array(1_000_000, dtype="float32")
with kvikio.CuFile("data.bin", "r") as f:
    f.read(d_arr)
Raw lines 517 to 529
530### With cuDF
532For raw binary data that isn't in a tabular format, use KvikIO to load, then convert:
534```python
535import cupy as cp
536import cudf
537import kvikio
539# Load raw float array, wrap as cuDF Series
540buf = cp.empty(1_000_000, dtype=cp.float32)
541with kvikio.CuFile("signal.bin", "r") as f:
542 f.read(buf)
543signal = cudf.Series(buf)
544```
546For tabular formats (CSV, Parquet, JSON, ORC), use cuDF's own readers — they're optimized for those formats.

With cuDF

For raw binary data that isn't in a tabular format, use KvikIO to load, then convert:

import cupy as cp
import cudf
import kvikio

# Load raw float array, wrap as cuDF Series
buf = cp.empty(1_000_000, dtype=cp.float32)
with kvikio.CuFile("signal.bin", "r") as f:
    f.read(buf)
signal = cudf.Series(buf)

For tabular formats (CSV, Parquet, JSON, ORC), use cuDF's own readers — they're optimized for those formats.

Raw lines 530 to 547
548### With NumPy (Host Memory)
550KvikIO seamlessly handles host memory:
552```python
553import numpy as np
554import kvikio
556arr = np.empty(1_000_000, dtype=np.float32)
557with kvikio.CuFile("data.bin", "r") as f:
558 f.read(arr)
559```
561---

With NumPy (Host Memory)

KvikIO seamlessly handles host memory:

import numpy as np
import kvikio

arr = np.empty(1_000_000, dtype=np.float32)
with kvikio.CuFile("data.bin", "r") as f:
    f.read(arr)

Raw lines 548 to 562
563## Common Patterns

Common Patterns

Raw lines 563 to 564
565### Save and Load GPU Model Checkpoints
567This is a raw contiguous-array container, not a self-describing or atomic checkpoint
568format. Save an ordered manifest with each array's name, shape, dtype/byte order,
569and byte offset; load using that exact order, and validate total file length and
570checksums. Synchronize producers before writing. For recovery-safe checkpoints,
571publish only after the payload and manifest are both complete.
573```python
574import cupy as cp
575import kvikio
577def save_checkpoint(arrays: dict[str, cp.ndarray], path: str):
578 """Save multiple GPU arrays to a single file."""
579 with kvikio.CuFile(path, "w") as f:
580 offset = 0
581 for arr in arrays.values():
582 if not arr.flags.c_contiguous:
583 raise ValueError("Checkpoint arrays must be C-contiguous")
584 if f.write(arr, file_offset=offset) != arr.nbytes:
585 raise IOError("Incomplete checkpoint write")
586 offset += arr.nbytes
588def load_checkpoint(shapes_dtypes: dict, path: str) -> dict[str, cp.ndarray]:
589 """Load GPU arrays from a checkpoint file."""
590 arrays = {}
591 with kvikio.CuFile(path, "r") as f:
592 offset = 0
593 for name, (shape, dtype) in shapes_dtypes.items():
594 arr = cp.empty(shape, dtype=dtype)
595 if f.read(arr, file_offset=offset) != arr.nbytes:
596 raise IOError("Incomplete checkpoint read")
597 offset += arr.nbytes
598 arrays[name] = arr
599 return arrays
600```

Save and Load GPU Model Checkpoints

This is a raw contiguous-array container, not a self-describing or atomic checkpoint format. Save an ordered manifest with each array's name, shape, dtype/byte order, and byte offset; load using that exact order, and validate total file length and checksums. Synchronize producers before writing. For recovery-safe checkpoints, publish only after the payload and manifest are both complete.

import cupy as cp
import kvikio

def save_checkpoint(arrays: dict[str, cp.ndarray], path: str):
    """Save multiple GPU arrays to a single file."""
    with kvikio.CuFile(path, "w") as f:
        offset = 0
        for arr in arrays.values():
            if not arr.flags.c_contiguous:
                raise ValueError("Checkpoint arrays must be C-contiguous")
            if f.write(arr, file_offset=offset) != arr.nbytes:
                raise IOError("Incomplete checkpoint write")
            offset += arr.nbytes

def load_checkpoint(shapes_dtypes: dict, path: str) -> dict[str, cp.ndarray]:
    """Load GPU arrays from a checkpoint file."""
    arrays = {}
    with kvikio.CuFile(path, "r") as f:
        offset = 0
        for name, (shape, dtype) in shapes_dtypes.items():
            arr = cp.empty(shape, dtype=dtype)
            if f.read(arr, file_offset=offset) != arr.nbytes:
                raise IOError("Incomplete checkpoint read")
            offset += arr.nbytes
            arrays[name] = arr
    return arrays
Raw lines 565 to 601
602### Stream Data from S3 into GPU for Processing
604```python
605import cupy as cp
606import kvikio
608with kvikio.RemoteFile.open_s3("my-bucket", "large-dataset.bin") as f:
609 total_bytes = f.nbytes()
610 if total_bytes % 4:
611 raise ValueError("Object is not an integral number of float32 values")
612 chunk_size = 100 * 1024 * 1024 # 100 MB chunks
613 buf = cp.empty(chunk_size // 4, dtype=cp.float32)
615 for offset in range(0, total_bytes, chunk_size):
616 size = min(chunk_size, total_bytes - offset)
617 bytes_read = f.read(buf[:size // 4], size=size, file_offset=offset)
618 if bytes_read != size:
619 raise EOFError("Short remote read")
620 # Process chunk on GPU
621 result = cp.mean(buf[:size // 4])
622 cp.cuda.get_current_stream().synchronize() # Finish before the next read reuses buf.
623```

Stream Data from S3 into GPU for Processing

import cupy as cp
import kvikio

with kvikio.RemoteFile.open_s3("my-bucket", "large-dataset.bin") as f:
    total_bytes = f.nbytes()
    if total_bytes % 4:
        raise ValueError("Object is not an integral number of float32 values")
    chunk_size = 100 * 1024 * 1024  # 100 MB chunks
    buf = cp.empty(chunk_size // 4, dtype=cp.float32)

    for offset in range(0, total_bytes, chunk_size):
        size = min(chunk_size, total_bytes - offset)
        bytes_read = f.read(buf[:size // 4], size=size, file_offset=offset)
        if bytes_read != size:
            raise EOFError("Short remote read")
        # Process chunk on GPU
        result = cp.mean(buf[:size // 4])
        cp.cuda.get_current_stream().synchronize()  # Finish before the next read reuses buf.
Raw lines 602 to 624
625### Replace Python open() for GPU Workloads
627```python
628# Before: CPU-bound file IO
629import numpy as np
630data = np.fromfile("data.bin", dtype=np.float32)
631import cupy as cp
632gpu_data = cp.asarray(data) # Extra copy: disk → CPU → GPU
634# After: Direct to GPU
635import cupy as cp
636import kvikio
637gpu_data = cp.empty(1_000_000, dtype=cp.float32)
638with kvikio.CuFile("data.bin", "r") as f:
639 f.read(gpu_data) # disk → GPU directly (with GDS)
640```
642---

Replace Python open() for GPU Workloads

# Before: CPU-bound file IO
import numpy as np
data = np.fromfile("data.bin", dtype=np.float32)
import cupy as cp
gpu_data = cp.asarray(data)  # Extra copy: disk → CPU → GPU

# After: Direct to GPU
import cupy as cp
import kvikio
gpu_data = cp.empty(1_000_000, dtype=cp.float32)
with kvikio.CuFile("data.bin", "r") as f:
    f.read(gpu_data)  # disk → GPU directly (with GDS)

Raw lines 625 to 643
644## Common Pitfalls
6461. **Forgetting to set thread pool size** — The default is 1 thread. For large files, `kvikio.defaults.set({"num_threads": 16})` can dramatically improve throughput.
6482. **Using KvikIO for structured formats** — Don't use KvikIO to read CSV/Parquet/JSON. Use `cudf.read_csv()`, `cudf.read_parquet()`, etc. KvikIO is for raw binary data.
6503. **Not checking GDS availability** — Code works fine without GDS (falls back to POSIX), but won't get the full bandwidth benefit. Check with `kvikio.cufile_driver.get("is_gds_available")`.
6524. **Misaligned IO in performance-critical paths** — Use 4 KiB-aligned offsets and sizes for best GDS performance.
6545. **Not using context managers** — Always use `with kvikio.CuFile(...)` to ensure files are properly closed and deregistered.
6566. **Expecting RemoteFile writes** — `RemoteFile` is read-only. To write to remote storage, write locally first, then upload via the appropriate SDK (boto3 for S3, etc.).
6587. **Docker without GDS setup** — In Docker, mount `/run/udev` read-only (`--volume /run/udev:/run/udev:ro`) for GDS to work. Otherwise, KvikIO silently falls back to POSIX.

Common Pitfalls

  1. Forgetting to set thread pool size — The default is 1 thread. For large files, kvikio.defaults.set({"num_threads": 16}) can dramatically improve throughput.
  1. Using KvikIO for structured formats — Don't use KvikIO to read CSV/Parquet/JSON. Use cudf.read_csv(), cudf.read_parquet(), etc. KvikIO is for raw binary data.
  1. Not checking GDS availability — Code works fine without GDS (falls back to POSIX), but won't get the full bandwidth benefit. Check with kvikio.cufile_driver.get("is_gds_available").
  1. Misaligned IO in performance-critical paths — Use 4 KiB-aligned offsets and sizes for best GDS performance.
  1. Not using context managers — Always use with kvikio.CuFile(...) to ensure files are properly closed and deregistered.
  1. Expecting RemoteFile writes — RemoteFile is read-only. To write to remote storage, write locally first, then upload via the appropriate SDK (boto3 for S3, etc.).
  1. Docker without GDS setup — In Docker, mount /run/udev read-only (--volume /run/udev:/run/udev:ro) for GDS to work. Otherwise, KvikIO silently falls back to POSIX.
Raw lines 644 to 658