乐闻世界logo
搜索文章和话题

Tensorflow 2 如何将执行从 GPU 切换到 CPU 再切换回来?

1 个月前提问
1 个月前修改
浏览次数10

1个答案

1

在Tensorflow 2中,可以通过设置设备上下文来控制模型的运行位置,即是在GPU上还是CPU上。这可以通过使用tf.device上下文管理器实现。

示例步骤:

  1. 初始化Tensorflow和检测设备: 首先,确认系统中可用的GPU和CPU。

    python
    import tensorflow as tf gpus = tf.config.list_physical_devices('GPU') if gpus: try: for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) except RuntimeError as e: print(e) cpus = tf.config.list_physical_devices('CPU')
  2. 定义Tensorflow操作: 创建一些Tensorflow操作,例如模型训练或者数据处理等。

    python
    def compute_on_device(device_name, size=10000): with tf.device(device_name): random_matrix = tf.random.normal((size, size), mean=0, stddev=1) dot_product = tf.linalg.matmul(random_matrix, tf.transpose(random_matrix)) sum_result = tf.reduce_sum(dot_product) return sum_result
  3. 在CPU上执行: 使用/CPU:0作为设备标识符来指定运行在CPU上。

    python
    result_cpu = compute_on_device('/CPU:0') print("Computed on CPU:", result_cpu)
  4. 在GPU上执行: 如果系统中有GPU,使用/GPU:0作为设备标识符来指定运行在第一个GPU上。对于多GPU系统,可以更改索引(例如/GPU:1)来使用不同的GPU。

    python
    if gpus: result_gpu = compute_on_device('/GPU:0') print("Computed on GPU:", result_gpu)
  5. 再次切换回CPU: 如果需要,可以再次使用/CPU:0来运行同一个操作或不同的操作。

    python
    result_cpu_again = compute_on_device('/CPU:0') print("Computed again on CPU:", result_cpu_again)

总结:

通过这种方式,你可以灵活地控制Tensorflow的计算在不同的设备之间切换。这对于优化性能、管理资源和测试不同硬件配置非常有用。在实际应用中,这种设备管理使得开发者能够更好地控制模型的训练和推理环境。

2024年8月10日 14:00 回复

你的答案