FIXME: remove CudaContext return opType. We just don't need it
163716
@Override
    protected CudaContext invoke(BroadcastOp op) {
        processAsGridOp(op, op.getDimension());

        return null;
    }
223529
public static int cudnnOpTensor(
        cudnnHandle handle, 
        cudnnOpTensorDescriptor opTensorDesc, 
        Pointer alpha1, 
        cudnnTensorDescriptor aDesc, 
        Pointer A, 
        Pointer alpha2, 
        cudnnTensorDescriptor bDesc, 
        Pointer B, 
        Pointer beta, 
        cudnnTensorDescriptor cDesc, 
        Pointer C)
    {
        return checkResult(cudnnOpTensorNative(handle, opTensorDesc, alpha1, aDesc, A, alpha2, bDesc, B, beta, cDesc, C));
    }
140137
def get_cuda_visible_devices():
    
    gpu_ids_str = os.environ.get("CUDA_VISIBLE_DEVICES", None)

    if gpu_ids_str is None:
        return None

    if gpu_ids_str == "":
        return []

    return [int(i) for i in gpu_ids_str.split(",")]
124553
def cublasCsyr(handle, uplo, n, alpha, x, incx, A, lda):
    

    status = _libcublas.cublasCsyr_v2(handle,
                                        _CUBLAS_FILL_MODE[uplo], n, 
                                        ctypes.byref(cuda.cuFloatComplex(alpha.real,
                                                                        alpha.imag)),
                                        int(x), incx, int(A), lda)
    cublasCheckStatus(status)
373985
def customize_compiler_for_nvcc(self):
    '''
    '''
    self.src_extensions.append('.cu')
    default_compiler_so = self.compiler_so
    super = self._compile

    def _compile(obj, src, ext, cc_args, extra_postargs, pp_opts):
        if os.path.splitext(src)[1] == '.cu':
            self.set_executable('compiler_so', CUDA['nvcc'])
            postargs = extra_postargs['nvcc']
        else:
            postargs = extra_postargs['cc']

        super(obj, src, ext, cc_args, postargs, pp_opts)
        self.compiler_so = default_compiler_so
    self._compile = _compile
211289
def cudnnCreate():
    

    handle = ctypes.c_void_p()
    status = _libcudnn.cudnnCreate(ctypes.byref(handle))
    cudnnCheckStatus(status)
    return handle.value
1135048
def move_to_device(obj, cuda_device: int):
    
    if cuda_device < 0 or not has_tensor(obj):
        return obj
    elif isinstance(obj, torch.Tensor):
        return obj.cuda(cuda_device)
    elif isinstance(obj, dict):
        return {key: move_to_device(value, cuda_device) for key, value in obj.items()}
    elif isinstance(obj, list):
        return [move_to_device(item, cuda_device) for item in obj]
    elif isinstance(obj, tuple):
        return tuple([move_to_device(item, cuda_device) for item in obj])
    else:
        return obj
818476
def cast opts={}
      dt = opts[:dtype]
      raise ArgumentError, "Unsupported dtype #{opts[:dtype]}" unless %i[array nmatrix gsl].include?(dt)

      @data = cast_vector_to dt unless @dtype == dt
    end
1119189
def disable_glut(self):
        
        import OpenGL.GLUT as glut  # @UnresolvedImport
        from glut_support import glutMainLoopEvent  # @UnresolvedImport

        glut.glutHideWindow()  # This is an event to be processed below
        glutMainLoopEvent()
        self.clear_inputhook()
362401
public static int cusparseCdotci(
        cusparseHandle handle, 
        int nnz, 
        Pointer xVal, 
        Pointer xInd, 
        Pointer y, 
        Pointer resultDevHostPtr, 
        int idxBase)
    {
        return checkResult(cusparseCdotciNative(handle, nnz, xVal, xInd, y, resultDevHostPtr, idxBase));
    }
31930
@Override
    public void memcpyBlocking(DataBuffer dstBuffer, Pointer srcPointer, long length, long dstOffset) {
        // internally it's just memcpyAsync + sync
        CudaContext context = getCudaContext();
        memcpyAsync(dstBuffer, srcPointer, length, dstOffset);
        context.syncOldStream();
    }
890555
def cudnnCreateTensorDescriptor():
    

    tensor = ctypes.c_void_p()
    status = _libcudnn.cudnnCreateTensorDescriptor(ctypes.byref(tensor))
    cudnnCheckStatus(status)
    return tensor.value
930186
def gpu_mem_trace(func):
    ""
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        with GPUMemTrace(ctx=func.__qualname__, on_exit_report=True):
            return func(*args, **kwargs)
    return wrapper
48410
def _ctypes_clean(parameter):
    
    if ("out" in parameter.direction and parameter.dimension is not None
        and ":" in parameter.dimension and ("pointer" in parameter.modifiers or
                                            "allocatable" in parameter.modifiers)):
        params = parameter.ctypes_parameter()
        result = []
        spacer = "    "
        #We get segfaults if we try to assign c-pointers to unallocated pointers or arrays.
        if "optional" in parameter.modifiers:
            if "pointer" in parameter.modifiers:
                result.append("{}if (associated({})) then".format(spacer, parameter.name))
                spacer += "  "
            elif "allocatable" in parameter.modifiers:
                result.append("{}if (allocated({})) then".format(spacer, parameter.name))
                spacer += "  "

        #We have to copy the values or at least update the pointer to access the
        #variables with 'target' and 'save' attributes.
        result.append("{0}{1}_t = {1}".format(spacer, parameter.name))
            
        if parameter.direction == "(inout)":
            result.append("{1}{0}_o = C_LOC({0}_t)".format(parameter.name, spacer))
            #Update the index variables for the dimensions of the output variable.
            for i, p in enumerate(params[1:-1]):
                result.append("{}{} = size({}, {})".format(spacer, p, parameter.name, i+1))
        else:
            #This is the case for intent(out)
            result.append("{1}{0}_c = C_LOC({0}_t)".format(parameter.name, spacer))
            for i, p in enumerate(params[1::]):
                result.append("{}{} = size({}, {})".format(spacer, p, parameter.name, i+1))

        if ("optional" in parameter.modifiers and
            ("pointer" in parameter.modifiers or "allocatable" in parameter.modifiers)):
            result.append("    end if")

        return ('\n'.join(result), True)
    elif parameter.dtype == "logical" and "out" in parameter.direction:
        return ("    {0}_c = {0}".format(parameter.name), False)
398325
def remove_unnecessary_stuff(self):
        

        glibc_functions_blacklist = {
            '_start',
            '_init',
            '_fini',
            '__gmon_start__',
            '__do_global_dtors_aux',
            'frame_dummy',
            'atexit',
            'deregister_tm_clones',
            'register_tm_clones',
            '__x86.get_pc_thunk.bx',
            '__libc_csu_init',
            '__libc_csu_fini',
        }

        glibc_data_blacklist = {
            '__TMC_END__',
            '_GLOBAL_OFFSET_TABLE_',
            '__JCR_END__',
            '__dso_handle',
            '__init_array_start',
            '__init_array_end',

            #
            'stdout',
            'stderr',
            'stdin',
            'program_invocation_short_',
            'program_invocation_short_name',
            'program_invocation_name',
            '__progname_full',
            '_IO_stdin_used',
            'obstack_alloc_failed_hand',
            'optind',
            'optarg',
            '__progname',
            '_environ',
            'environ',
            '__environ',
        }

        glibc_references_blacklist = {
            'frame_dummy',
            '__do_global_dtors_aux',
        }

        self.procedures = [p for p in self.procedures if p.name not in glibc_functions_blacklist and not p.is_plt]

        self.data = [d for d in self.data if not any(lbl.name in glibc_data_blacklist for _, lbl in d.labels)]

        for d in self.data:
            if d.sort == 'pointer-array':
                for i in range(len(d.content)):
                    ptr = d.content[i]
                    if isinstance(ptr, Label) and ptr.name in glibc_references_blacklist:
                        d.content[i] = 0
1112307
def cudaGetDevice():
    

    dev = ctypes.c_int()
    status = _libcudart.cudaGetDevice(ctypes.byref(dev))
    cudaCheckStatus(status)
    return dev.value
775140
def _lazily_initialize(self):
    """"""
    # TODO(nickfelt): remove on-demand imports once dep situation is fixed.
    import tensorflow.compat.v1 as tf
    with self._initialization_lock:
      if self._session:
        return
      graph = tf.Graph()
      with graph.as_default():
        self.initialize_graph()
      # Don't reserve GPU because libpng can't run on GPU.
      config = tf.ConfigProto(device_count={'GPU': 0})
      self._session = tf.Session(graph=graph, config=config)