kvikio: kvikio still segfaults on program termination

Hi everyone,

I’m getting a segfault when my python script terminates. This only happens when kvikio is used.

Reproducer

mamba env create -f img2tensor_kvikio.yaml && mamba clean -afy

// img2tensor_kvikio.yaml
name: img2tensor
channels:
  - pytorch
  - nvidia
  - rapidsai
  - conda-forge
dependencies:
  - notebook
  - tifffile
  - python=3.11
  - pytorch
  - pytorch-cuda=12.4
  - kvikio

bug.py

import kvikio

file_name = 'file0.txt'

fd = kvikio.CuFile(file_name, "w")
fd.close()

I’m running in a kubernetes environment. We use the open kernel driver 535.183.01

I assumed this #462 has fixed the issue but it seems there is more to it.

You can find the concretized environment here: exported_img2tensor_kvikio.txt

It uses kvikio 24.10 which should include the previously mentioned PR.

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Comments: 31 (21 by maintainers)

Most upvoted comments

Below is a minimally reproducible C++ example for the segfault. It emulates KvikIO’s dynamic loading, which seems to be correlated to the issue observed.

Concretely, KvikIO dynamically loads the cuFile shared library at runtime, and therefore the information on the cuFile library is not passed to the linker at link time. Apparently, the segfault somehow occurs with this setup (run_bad.sh).

If the information on the cuFile library is passed to the linker, the segfault would then be gone (run_good.sh). This, however, defies our purpose of using dynamic loading.

biu.cpp

Single source file to reproduce the segfault.

#include <cufile.h>
#include <dlfcn.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include <sstream>

#define CHECK_CUFILE(err_code) check_cufile(err_code, __FILE__, __LINE__)
void check_cufile(CUfileError_t err_code, const char* file, int line)
{
  auto cufile_err_code = err_code.err;  // CUfileOpError
  if (cufile_err_code != CU_FILE_SUCCESS) {
    std::stringstream ss;
    ss << "cuFile error at" << file << ":" << line << std::endl;
    throw std::runtime_error(ss.str());
  }
}

#define EXPECT(condition) expect(condition, __FILE__, __LINE__)
inline void expect(bool condition, const char* file, int line)
{
  if (condition) { return; }
  std::stringstream ss;
  ss << "EXPECT failed at " << file << ":" << line << std::endl;
  throw std::runtime_error(ss.str());
}

class TestManager {
 public:
  TestManager()
  {
    load_library();

    int flags{O_WRONLY | O_CREAT | O_TRUNC | O_DIRECT};
    mode_t mode{S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH};
    _fd = open(_file_path.c_str(), flags, mode);
    EXPECT(_fd != -1);

    CUfileDescr_t desc{};
    desc.type      = CU_FILE_HANDLE_TYPE_OPAQUE_FD;
    desc.handle.fd = _fd;
    CHECK_CUFILE(_func_handle_register(&_handle, &desc));
  }

  ~TestManager()
  {
    _func_handle_deregister(_handle);
    EXPECT(close(_fd) == 0);
    std::cout << "test done" << std::endl;
  }

 private:
  void load_library()
  {
    dlerror();
    auto* cufile_lib_handle =
      dlopen(_cufile_lib_path.c_str(), RTLD_LAZY | RTLD_LOCAL | RTLD_NODELETE);
    get_symbol(_func_handle_register, cufile_lib_handle, "cuFileHandleRegister");
    get_symbol(_func_handle_deregister, cufile_lib_handle, "cuFileHandleDeregister");
  }

  template <typename F>
  void get_symbol(F& func, void* cufile_lib_handle, std::string const& name)
  {
    dlerror();
    func      = reinterpret_cast<std::decay_t<F>>(dlsym(cufile_lib_handle, name.c_str()));
    auto* err = dlerror();
    if (err != nullptr) { throw std::runtime_error(err); }
  }

  int _fd{};
  CUfileHandle_t _handle{};
  std::string _cufile_lib_path{"/usr/local/cuda/targets/sbsa-linux/lib/libcufile.so.0"};
  std::string _file_path{"/mnt/nvme/biu.bin"};

  std::decay_t<decltype(cuFileHandleRegister)> _func_handle_register;
  std::decay_t<decltype(cuFileHandleDeregister)> _func_handle_deregister;
};

int main()
{
  TestManager tm;
  return 0;
}
my_cufile.json

A copy of /etc/cufile.json, except that cufile_stats is assigned a positive value.

{
    // NOTE : Application can override custom configuration via export CUFILE_ENV_PATH_JSON=<filepath>
    // e.g : export CUFILE_ENV_PATH_JSON="/home/<xxx>/cufile.json"

            "logging": {
                            // log directory, if not enabled will create log file under current working directory
                            //"dir": "/home/<xxxx>",

                            // NOTICE|ERROR|WARN|INFO|DEBUG|TRACE (in decreasing order of severity)
                            "level": "ERROR"
            },

            "profile": {
                            // nvtx profiling on/off
                            "nvtx": false,
                            // cufile stats level(0-3)
                            "cufile_stats": 3
            },

            "execution" : {
                    // max number of workitems in the queue;
                    "max_io_queue_depth": 128,
                    // max number of host threads per gpu to spawn for parallel IO
                    "max_io_threads" : 4,
                    // enable support for parallel IO
                    "parallel_io" : true,
                    // minimum IO threshold before splitting the IO
                    "min_io_threshold_size_kb" : 8192,
		    // maximum parallelism for a single request
		    "max_request_parallelism" : 4
            },

            "properties": {
                            // max IO chunk size (parameter should be multiples of 64K) used by cuFileRead/Write internally per IO request
                            "max_direct_io_size_kb" : 16384,
                            // device memory size (parameter should be 4K aligned) for reserving bounce buffers for the entire GPU
                            "max_device_cache_size_kb" : 131072,
                            // per-io bounce-buffer size (parameter should be multiples of 64K) ranging from 1024kb to 16384kb
                            // Note: ensure (max_device_cache_size_kb / per_buffer_cache_size_kb) >= io_batchsize
                            "per_buffer_cache_size_kb": 1024,
                            // limit on maximum device memory size (parameter should be 4K aligned) that can be pinned for a given process
                            "max_device_pinned_mem_size_kb" : 33554432,
                            // true or false (true will enable asynchronous io submission to nvidia-fs driver)
                            // Note : currently the overall IO will still be synchronous
                            "use_poll_mode" : false,
                            // maximum IO request size (parameter should be 4K aligned) within or equal to which library will use polling for IO completion
                            "poll_mode_max_size_kb": 4,
                            // allow p2pdma, this will enable use of cuFile without nvme patches
                            "use_pci_p2pdma": false,
                            // allow compat mode, this will enable use of cuFile posix read/writes
                            "allow_compat_mode": true,
                            // enable GDS write support for RDMA based storage
                            "gds_rdma_write_support": true,
                            // GDS batch size
                            "io_batchsize": 128,
                            // enable io priority w.r.t compute streams
                            // valid options are "default", "low", "med", "high"
                            "io_priority": "default",
                            // client-side rdma addr list for user-space file-systems(e.g ["10.0.1.0", "10.0.2.0"])
                            "rdma_dev_addr_list": [ ],
                            // load balancing policy for RDMA memory registration(MR), (RoundRobin, RoundRobinMaxMin)
                            // In RoundRobin, MRs will be distributed uniformly across NICS closest to a GPU
                            // In RoundRobinMaxMin, MRs will be distributed across NICS closest to a GPU
                            // with minimal sharing of NICS acros GPUS
                            "rdma_load_balancing_policy": "RoundRobin",
			    //32-bit dc key value in hex
			    //"rdma_dc_key": "0xffeeddcc",
			    //To enable/disable different rdma OPs use the below bit map
			    //Bit 0 - If set enables Local RDMA WRITE
			    //Bit 1 - If set enables Remote RDMA WRITE
			    //Bit 2 - If set enables Remote RDMA READ
			    //Bit 3 - If set enables REMOTE RDMA Atomics
			    //Bit 4 - If set enables Relaxed ordering.
			    //"rdma_access_mask": "0x1f",

                            // In platforms where IO transfer to a GPU will cause cross RootPort PCie transfers, enabling this feature
                            // might help improve overall BW provided there exists a GPU(s) with Root Port common to that of the storage NIC(s).
                            // If this feature is enabled, please provide the ip addresses used by the mount either in file-system specific
                            // section for mount_table or in the rdma_dev_addr_list property in properties section
                            "rdma_dynamic_routing": false,
                            // The order describes the sequence in which a policy is selected for dynamic routing for cross Root Port transfers
                            // If the first policy is not applicable, it will fallback to the next and so on.
                            // policy GPU_MEM_NVLINKS: use GPU memory with NVLink to transfer data between GPUs
                            // policy GPU_MEM: use GPU memory with PCIe to transfer data between GPUs
                            // policy SYS_MEM: use system memory with PCIe to transfer data to GPU
                            // policy P2P: use P2P PCIe to transfer across between NIC and GPU
                            "rdma_dynamic_routing_order": [ "GPU_MEM_NVLINKS", "GPU_MEM", "SYS_MEM", "P2P" ]
            },

            "fs": {
                    "generic": {

                            // for unaligned writes, setting it to true will, cuFileWrite use posix write internally instead of regular GDS write
                            "posix_unaligned_writes" : false
                    },

		    "beegfs" : {
                            // IO threshold for read/write (param should be 4K aligned)) equal to or below which cuFile will use posix read/write
                            "posix_gds_min_kb" : 0

                            // To restrict the IO to selected IP list, when dynamic routing is enabled
                            // if using a single BeeGFS mount, provide the ip addresses here
                            //"rdma_dev_addr_list" : []

                            // if using multiple lustre mounts, provide ip addresses used by respective mount here
                            //"mount_table" : {
                            //                    "/beegfs/client1" : {
                            //                                    "rdma_dev_addr_list" : ["172.172.1.40", "172.172.1.42"]
                            //                    },

                            //                    "/beegfs/client2" : {
                            //                                    "rdma_dev_addr_list" : ["172.172.2.40", "172.172.2.42"]
                            //                    }
                            //}

		    },
                    "lustre": {

                            // IO threshold for read/write (param should be 4K aligned)) equal to or below which cuFile will use posix read/write
                            "posix_gds_min_kb" : 0

                            // To restrict the IO to selected IP list, when dynamic routing is enabled
                            // if using a single lustre mount, provide the ip addresses here (use : sudo lnetctl net show)
                            //"rdma_dev_addr_list" : []

                            // if using multiple lustre mounts, provide ip addresses used by respective mount here
                            //"mount_table" : {
                            //                    "/lustre/ai200_01/client" : {
                            //                                    "rdma_dev_addr_list" : ["172.172.1.40", "172.172.1.42"]
                            //                    },

                            //                    "/lustre/ai200_02/client" : {
                            //                                    "rdma_dev_addr_list" : ["172.172.2.40", "172.172.2.42"]
                            //                    }
                            //}
                    },

                    "nfs": {

                           // To restrict the IO to selected IP list, when dynamic routing is enabled
                           //"rdma_dev_addr_list" : []

                           //"mount_table" : {
                           //                     "/mnt/nfsrdma_01/" : {
                           //                                     "rdma_dev_addr_list" : []
                           //                     },

                           //                     "/mnt/nfsrdma_02/" : {
                           //                                     "rdma_dev_addr_list" : []
                           //                     }
                           //}
                    },

		    "gpfs": {
                           //allow GDS writes with GPFS
                           "gds_write_support": false,

                           //allow Async support
                           "gds_async_support": true

                           //"rdma_dev_addr_list" : []

                           //"mount_table" : {
                           //                     "/mnt/gpfs_01" : {
                           //                                     "rdma_dev_addr_list" : []
                           //                     },

                           //                     "/mnt/gpfs_02/" : {
                           //                                     "rdma_dev_addr_list" : []
                           //                     }
                           //}
                    },

                    "weka": {

                            // enable/disable RDMA write
                            "rdma_write_support" : false
                    }
            },

            "denylist": {
                            // specify list of vendor driver modules to deny for nvidia-fs (e.g. ["nvme" , "nvme_rdma"])
                            "drivers":  [ ],

                            // specify list of block devices to prevent IO using cuFile (e.g. [ "/dev/nvme0n1" ])
                            "devices": [ ],

                            // specify list of mount points to prevent IO using cuFile (e.g. ["/mnt/test"])
                            "mounts": [ ],

                            // specify list of file-systems to prevent IO using cuFile (e.g ["lustre", "wekafs"])
                            "filesystems": [ ]
            },

            "miscellaneous": {
                            // enable only for enforcing strict checks at API level for debugging
                            "api_check_aggressive": false
	    }
}

Run this script to compile biu.cpp and observe the segfault. Note that CUFILE_ENV_PATH_JSON is set to my_cufile.json.

run_bad.sh
#!/usr/bin/env bash

rm -rf biu_check_bad_tmp
mkdir biu_check_bad_tmp

g++ -isystem /usr/local/cuda/targets/sbsa-linux/include -g -o biu_check_bad_tmp/biu.cpp.o -c biu.cpp

g++ -g biu_check_bad_tmp/biu.cpp.o -o biu_check_bad \
-Wl,-rpath,/usr/local/cuda-12.8/targets/sbsa-linux/lib \
-ldl

export CUFILE_ALLOW_COMPAT_MODE=false
export CUFILE_FORCE_COMPAT_MODE=false
export CUFILE_ENV_PATH_JSON=my_cufile.json

test_bin=./biu_check_bad

$test_bin

Sample output:

test done
./run_bad.sh: line 18: 1166604 Segmentation fault      (core dumped) $test_bin

Run this script to compile biu.cpp. The segfault ceases to exist once the cuFile library is linked to the program.

run_good.sh
#!/usr/bin/env bash

rm -rf biu_check_good_tmp
mkdir biu_check_good_tmp

g++ -isystem /usr/local/cuda/targets/sbsa-linux/include -g -o biu_check_good_tmp/biu.cpp.o -c biu.cpp

g++ -g biu_check_good_tmp/biu.cpp.o -o biu_check_good \
-Wl,-rpath,/usr/local/cuda-12.8/targets/sbsa-linux/lib \
-ldl \
-L /usr/local/cuda/targets/sbsa-linux/lib/ -lcufile

export CUFILE_ALLOW_COMPAT_MODE=false
export CUFILE_FORCE_COMPAT_MODE=false
export CUFILE_ENV_PATH_JSON=my_cufile.json

test_bin=./biu_check_good

$test_bin

Sample output:

test done

@kingcrimsontianyu Thank you for this! I have a question: what’s the rationale behind KVIKIO’s use of dynamic loading?

We want to support setups that doesn’t have cuFile/gds installed. cuFile supports ARM64 as of CUDA toolkit v12.3+ so we might be able to use regular dynamic or static linking in the future but for now, we need to support systems without cuFile.

This has been fixed in CUDA-13.0 which would be available pretty soon.

I continued playing around with the environment to ensure the issue was not related to my setup. Just a few minutes ago I found out that the segmentation fault on termination does not occur when I set "cufile_stats": 0 in the cufile.json. Any value in cufile_stats above 0 causes the segfault. But as mentioned during execution everything works fine. The READ-WRITE SIZE histogram is written to cufile.log and all. Only on termination, the segfault happens. I could observe this both inside and outside of a docker container.

Do you still think that this is related to cufileDriverClose()?

Lawrence mentioned doing a debug build. So wanted to share that resource

If the segfault happens somewhere in KvikIO, it may help. If it happens in cuFile, we likely don’t learn much

Could you please slim the environment further like so and retry?

# filename: kvikio2410_cuda122.yaml
name: kvikio2410_cuda122
channels:
  - rapidsai
  - conda-forge
dependencies:
  - cuda-version=12.2
  - python=3.11
  - kvikio=24.10

Asking as there are mismatching CUDA versions in the reproducing environment. Plus some extra bits that appear unused in the example. So would like to simplify further to avoid other potential issues