Check for support for Intel AVX acceleration.
331341
def _supports_avx():
    """"""
    if os.path.exists("/proc/cpuinfo"):
        with open("/proc/cpuinfo") as in_handle:
            for line in in_handle:
                if line.startswith("flags") and line.find("avx") > 0:
                    return True
323314
def _check_device(self, requested_device, map_device):
        
        type_1 = torch.device(requested_device)
        type_2 = torch.device(map_device)
        if type_1 != type_2:
            warnings.warn(
                'Setting self.device = {} since the requested device ({}) '
                'is not available.'.format(map_device, requested_device),
                DeviceWarning)
            return map_device
        # return requested_device instead of map_device even though we
        # checked for *type* equality as we might have 'cuda:0' vs. 'cuda:1'.
        return requested_device
679366
def validate(self):
        """"""
        errors = []
        app = errors.append

        if not self.hint_cores >= self.mpi_procs * self.omp_threads >= self.min_cores:
            app("self.hint_cores >= mpi_procs * omp_threads >= self.min_cores not satisfied")

        if self.omp_threads > self.hw.cores_per_node:
            app("omp_threads > hw.cores_per_node")

        if self.mem_per_proc > self.hw.mem_per_node:
            app("mem_mb >= self.hw.mem_per_node")

        if not self.max_mem_per_proc >= self.mem_per_proc >= self.min_mem_per_proc:
            app("self.max_mem_per_proc >= mem_mb >= self.min_mem_per_proc not satisfied")

        if self.priority <= 0:
            app("priority must be > 0")

        if not (1 <= self.min_cores <= self.hw.num_cores >= self.hint_cores):
            app("1 <= min_cores <= hardware num_cores >= hint_cores not satisfied")

        if errors:
            raise self.Error(str(self) + "\n".join(errors))
682670
def ok(self):
        
        try:
            v = int(self._value)
            if v < self.imin or v > self.imax:
                return False
            else:
                return True
        except:
            return False
1078787
def is_openmp_supported():
    
    log_threshold = log.set_threshold(log.FATAL)
    ret = check_openmp_support()
    log.set_threshold(log_threshold)
    return ret
1308795
def benchmark(self, func, gpu_args, instance, times, verbose):
        """"""
        logging.debug('benchmark ' + instance.name)
        logging.debug('thread block dimensions x,y,z=%d,%d,%d', *instance.threads)
        logging.debug('grid dimensions x,y,z=%d,%d,%d', *instance.grid)

        time = None
        try:
            time = self.dev.benchmark(func, gpu_args, instance.threads, instance.grid, times)
        except Exception as e:
            #some launches may fail because too many registers are required
            #to run the kernel given the current thread block size
            #the desired behavior is to simply skip over this configuration
            #and proceed to try the next one
            skippable_exceptions = ["too many resources requested for launch", "OUT_OF_RESOURCES", "INVALID_WORK_GROUP_SIZE"]
            if any([skip_str in str(e) for skip_str in skippable_exceptions]):
                logging.debug('benchmark fails due to runtime failure too many resources required')
                if verbose:
                    print("skipping config", instance.name, "reason: too many resources requested for launch")
            else:
                logging.debug('benchmark encountered runtime failure: ' + str(e))
                print("Error while benchmarking:", instance.name)
                raise e
        return time
720399
private function _fetchPciIdsPciConf()
    {
        try {
            $pciconf = $this->exec->exec('pciconf', '-l');
        } catch (Exception $e) {
            Errors::add('Linfo Core', 'Error using `pciconf -l` to get hardware info');

            return;
        }

        if (preg_match_all('/^.+chip=0x([a-z0-9]{4})([a-z0-9]{4})/m', $pciconf, $devs, PREG_SET_ORDER) == 0) {
            return;
        }

        foreach ($devs as $dev) {
            $this->_pci_entries[$dev[2]][$dev[1]] = 1;
        }
    }
415812
def with_cpu(ops, model):
    """"""
    model.to_cpu()

    def with_cpu_forward(inputs, drop=0.0):
        cpu_outputs, backprop = model.begin_update(_to_cpu(inputs), drop=drop)
        gpu_outputs = _to_device(ops, cpu_outputs)

        def with_cpu_backprop(d_outputs, sgd=None):
            cpu_d_outputs = _to_cpu(d_outputs)
            return backprop(cpu_d_outputs, sgd=sgd)

        return gpu_outputs, with_cpu_backprop

    return wrap(with_cpu_forward, model)
314359
def get_num_gpu():
    

    def warn_return(ret, message):
        try:
            import tensorflow as tf
        except ImportError:
            return ret

        built_with_cuda = tf.test.is_built_with_cuda()
        if not built_with_cuda and ret > 0:
            logger.warn(message + "But TensorFlow was not built with CUDA support and could not use GPUs!")
        return ret

    env = os.environ.get('CUDA_VISIBLE_DEVICES', None)
    if env:
        return warn_return(len(env.split(',')), "Found non-empty CUDA_VISIBLE_DEVICES. ")
    output, code = subproc_call("nvidia-smi -L", timeout=5)
    if code == 0:
        output = output.decode('utf-8')
        return warn_return(len(output.strip().split('\n')), "Found nvidia-smi. ")
    try:
        # Use NVML to query device properties
        with NVMLContext() as ctx:
            return warn_return(ctx.num_devices(), "NVML found nvidia devices. ")
    except Exception:
        # Fallback
        logger.info("Loading local devices by TensorFlow ...")

        try:
            import tensorflow as tf
            # available since TF 1.14
            gpu_devices = tf.config.experimental.list_physical_devices('GPU')
        except AttributeError:
            from tensorflow.python.client import device_lib
            local_device_protos = device_lib.list_local_devices()
            # Note this will initialize all GPUs and therefore has side effect
            # https://github.com/tensorflow/tensorflow/issues/8136
            gpu_devices = [x.name for x in local_device_protos if x.device_type == 'GPU']
        return len(gpu_devices)
833583
def is_supported():
    '''
    
    '''
    # Check for supported platforms
    # NOTE: ZFS on Windows is in development
    # NOTE: ZFS on NetBSD is in development
    on_supported_platform = False
    if salt.utils.platform.is_sunos():
        on_supported_platform = True
    elif salt.utils.platform.is_freebsd() and _check_retcode('kldstat -q -m zfs'):
        on_supported_platform = True
    elif salt.utils.platform.is_linux() and os.path.exists('/sys/module/zfs'):
        on_supported_platform = True
    elif salt.utils.platform.is_linux() and salt.utils.path.which('zfs-fuse'):
        on_supported_platform = True
    elif salt.utils.platform.is_darwin() and \
         os.path.exists('/Library/Extensions/zfs.kext') and \
         os.path.exists('/dev/zfs'):
        on_supported_platform = True

    # Additional check for the zpool command
    return (salt.utils.path.which('zpool') and on_supported_platform) is True
540571
def possible_version_evaluation(self):
    """"""
    only_broken = self.get_options().only_broken
    ranges = self._ranges
    yield 'Allowable JVM platform ranges (* = anything):'
    for target in sorted(filter(self._is_relevant, self.jvm_targets)):
      min_version = ranges.min_allowed_version.get(target)
      max_version = ranges.max_allowed_version.get(target)
      current_valid = True
      if min_version and self.jvm_version(target) < min_version:
        current_valid = False
      if max_version and self.jvm_version(target) > max_version:
        current_valid = False
      current_text = str(self.jvm_version(target))
      if not current_valid:
        current_text = self._format_error(current_text)
      elif only_broken:
        continue

      if min_version and max_version:
        range_text = '{} to {}'.format(min_version, max_version)
        if min_version > max_version:
          range_text = self._format_error(range_text)
      elif min_version:
        range_text = '{}+'.format(min_version)
      elif max_version:
        range_text = '<={}'.format(max_version)
      else:
        range_text = '*'
      yield '{address}: {range}  (is {current})'.format(address=target.address.spec,
                                                        range=range_text,
                                                        current=current_text,)
      if self.get_options().detailed or not current_valid:
        if min_version:
          min_because = [t for t in ranges.target_dependencies[target]
                         if self.jvm_version(t) == min_version]
          yield '  min={} because of dependencies:'.format(min_version)
          for dep in sorted(min_because):
            yield '    {}'.format(dep.address.spec)
        if max_version:
          max_because = [t for t in ranges.target_dependees[target]
                         if self.jvm_version(t) == max_version]
          yield '  max={} because of dependees:'.format(max_version)
          for dep in sorted(max_because):
            yield '    {}'.format(dep.address.spec)
        yield ''
361815
function isPreBuilt(indexObj, preBuiltPath) {
  if (!(indexObj.isDevelopingAddon && indexObj.isDevelopingAddon()) && fs.existsSync(preBuiltPath)) {
    return true;
  }
  return false;
}
902571
def inspect_cuda_version_and_devices(compiler, settings):
    
    try:
        output = build_and_run(compiler, '''
            #include <cuda.h>
            #include <stdio.h>

            __device__ void test(int * in, int * out)
            {
                int tid = blockIdx.x*blockDim.x + threadIdx.x;
                out[tid] = in[tid];
            }

            int main(int argc, char* argv[]) {

              printf("{\\n");
              printf("  \\"cuda_version\\": %d,\\n", CUDA_VERSION);

              printf("  \\"devices\\": [\\n");

              int nr_of_devices = 0;
              cudaGetDeviceCount(&nr_of_devices);

              for(int d=0; d < nr_of_devices; ++d)
              {
                cudaDeviceProp p;
                cudaGetDeviceProperties(&p, d);

                printf("    {\\n");

                bool last = (d == nr_of_devices-1);

                printf("      \\"name\\": \\"%s\\",\\n", p.name);
                printf("      \\"major\\": %d,\\n", p.major);
                printf("      \\"minor\\": %d,\\n", p.minor);
                printf("      \\"memory\\": %lu\\n", p.totalGlobalMem);

                printf("    }%s\\n", last ? "" : ",");
              }

              printf("  ]\\n");
              printf("}\\n");

              return 0;
            }
        ''',
        filename='test.cu',
        include_dirs=settings['include_dirs'],
        library_dirs=settings['library_dirs'],
        libraries=settings['libraries'])

    except Exception as e:
        msg = ("Running the CUDA device check "
            "stub failed\n{}".format(str(e)))
        raise InspectCudaException(msg), None, sys.exc_info()[2]

    return output
124477
function updateCpu (cpu, next) {
  if (cpu !== null) {
    getRealUptime(function (err, uptime) {
      if (err) return next(err)
      cpu.uptime = uptime
      next(null, cpu)
    })
    return
  }

  parallel([
    getClockAndPageSize,
    getRealUptime
  ], function (err, data) {
    if (err) return next(err)

    cpu = {
      clockTick: data[0].clockTick,
      pageSize: data[0].pageSize,
      uptime: data[1]
    }

    next(null, cpu)
  })
}
1292065
def cli(env, identifier, cpu, private, memory, network, flavor):
    """"""

    vsi = SoftLayer.VSManager(env.client)

    if not any([cpu, memory, network, flavor]):
        raise exceptions.ArgumentError("Must provide [--cpu], [--memory], [--network], or [--flavor] to upgrade")

    if private and not cpu:
        raise exceptions.ArgumentError("Must specify [--cpu] when using [--private]")

    vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
    if not (env.skip_confirmations or formatting.confirm("This action will incur charges on your account. Continue?")):
        raise exceptions.CLIAbort('Aborted')

    if memory:
        memory = int(memory / 1024)

    if not vsi.upgrade(vs_id, cpus=cpu, memory=memory, nic_speed=network, public=not private, preset=flavor):
        raise exceptions.CLIAbort('VS Upgrade Failed')
1301511
def _actual_get_cpu_info_from_cpuid(queue):
	'''
	
	'''

	# Pipe all output to nothing
	sys.stdout = open(os.devnull, 'w')
	sys.stderr = open(os.devnull, 'w')

	# Get the CPU arch and bits
	arch, bits = _parse_arch(DataSource.arch_string_raw)

	# Return none if this is not an X86 CPU
	if not arch in ['X86_32', 'X86_64']:
		queue.put(_obj_to_b64({}))
		return

	# Return none if SE Linux is in enforcing mode
	cpuid = CPUID()
	if cpuid.is_selinux_enforcing:
		queue.put(_obj_to_b64({}))
		return

	# Get the cpu info from the CPUID register
	max_extension_support = cpuid.get_max_extension_support()
	cache_info = cpuid.get_cache(max_extension_support)
	info = cpuid.get_info()

	processor_brand = cpuid.get_processor_brand(max_extension_support)

	# Get the Hz and scale
	hz_actual = cpuid.get_raw_hz()
	hz_actual = _to_decimal_string(hz_actual)

	# Get the Hz and scale
	hz_advertised, scale = _parse_cpu_brand_string(processor_brand)
	info = {
	'vendor_id_raw' : cpuid.get_vendor_id(),
	'hardware_raw' : '',
	'brand_raw' : processor_brand,

	'hz_advertised_friendly' : _hz_short_to_friendly(hz_advertised, scale),
	'hz_actual_friendly' : _hz_short_to_friendly(hz_actual, 0),
	'hz_advertised' : _hz_short_to_full(hz_advertised, scale),
	'hz_actual' : _hz_short_to_full(hz_actual, 0),

	'l2_cache_size' : _to_friendly_bytes(cache_info['size_kb']),
	'l2_cache_line_size' : cache_info['line_size_b'],
	'l2_cache_associativity' : hex(cache_info['associativity']),

	'stepping' : info['stepping'],
	'model' : info['model'],
	'family' : info['family'],
	'processor_type' : info['processor_type'],
	'extended_model' : info['extended_model'],
	'extended_family' : info['extended_family'],
	'flags' : cpuid.get_flags(max_extension_support)
	}

	info = {k: v for k, v in info.items() if v}
	queue.put(_obj_to_b64(info))
992994
def _get_cpu_info_from_sysinfo_v2():
	'''
	
	'''
	try:
		# Just return {} if there is no sysinfo
		if not DataSource.has_sysinfo():
			return {}

		# If sysinfo fails return {}
		returncode, output = DataSource.sysinfo_cpu()
		if output == None or returncode != 0:
			return {}

		# Various fields
		vendor_id = '' #_get_field(False, output, None, None, 'CPU #0: ')
		processor_brand = output.split('CPU #0: "')[1].split('"\n')[0].strip()
		cache_size = '' #_get_field(False, output, None, None, 'machdep.cpu.cache.size')
		signature = output.split('Signature:')[1].split('\n')[0].strip()
		#
		stepping = int(signature.split('stepping ')[1].split(',')[0].strip())
		model = int(signature.split('model ')[1].split(',')[0].strip())
		family = int(signature.split('family ')[1].split(',')[0].strip())

		# Flags
		def get_subsection_flags(output):
			retval = []
			for line in output.split('\n')[1:]:
				if not line.startswith('                ') and not line.startswith('		'): break
				for entry in line.strip().lower().split(' '):
					retval.append(entry)
			return retval

		flags = get_subsection_flags(output.split('Features: ')[1]) + \
				get_subsection_flags(output.split('Extended Features (0x00000001): ')[1]) + \
				get_subsection_flags(output.split('Extended Features (0x80000001): ')[1])
		flags.sort()

		# Convert from GHz/MHz string to Hz
		lines = [n for n in output.split('\n') if n]
		raw_hz = lines[0].split('running at ')[1].strip().lower()
		hz_advertised = raw_hz.rstrip('mhz').rstrip('ghz').strip()
		hz_advertised = _to_decimal_string(hz_advertised)
		hz_actual = hz_advertised

		scale = 0
		if raw_hz.endswith('mhz'):
			scale = 6
		elif raw_hz.endswith('ghz'):
			scale = 9

		info = {
		'vendor_id_raw' : vendor_id,
		'brand_raw' : processor_brand,

		'hz_advertised_friendly' : _hz_short_to_friendly(hz_advertised, scale),
		'hz_actual_friendly' : _hz_short_to_friendly(hz_actual, scale),
		'hz_advertised' : _hz_short_to_full(hz_advertised, scale),
		'hz_actual' : _hz_short_to_full(hz_actual, scale),

		'l2_cache_size' : _to_friendly_bytes(cache_size),

		'stepping' : stepping,
		'model' : model,
		'family' : family,
		'flags' : flags
		}

		info = {k: v for k, v in info.items() if v}
		return info
	except:
		#raise # NOTE: To have this throw on error, uncomment this line
		return {}