python - 在 Tensorflow 中限制 GPU 设备

标签 python python-2.7 tensorflow cuda gpu

我正在用 Python 开发一个使用 Tensorflow 的应用程序和另一个使用 GPU 的模型。 我有一台带有许多 GPU 的 PC (3xNVIDIA GTX1080),由于所有模型都尝试使用所有可用的 GPU,导致 OUT_OF_MEMORY_ERROR,我发现您可以将特定的 GPU 分配给 Python 脚本

os.environ['CUDA_VISIBLE_DEVICES'] = '1'

在这里我附上了我的 FCN 类的片段

class FCN:
  def __init__(self):
    os.environ['CUDA_VISIBLE_DEVICES'] = '1'
    self.keep_probability = tf.placeholder(tf.float32, name="keep_probabilty")
    self.image = tf.placeholder(tf.float32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 3], name="input_image")
    self.annotation = tf.placeholder(tf.int32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 1], name="annotation")

    self.pred_annotation, logits = inference(self.image, self.keep_probability)
    tf.summary.image("input_image", self.image, max_outputs=2)
    tf.summary.image("ground_truth", tf.cast(self.annotation, tf.uint8), max_outputs=2)
    tf.summary.image("pred_annotation", tf.cast(self.pred_annotation, tf.uint8), max_outputs=2)
    self.loss = tf.reduce_mean((tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits,
                                                                               labels=tf.squeeze(self.annotation,
                                                                                                 squeeze_dims=[3]),
                                                                               name="entropy")))
    tf.summary.scalar("entropy", self.loss)

...

在同一个文件 FCN.py 中,我有一个使用该类的小 main,当 Tensorflow 打印输出时,我可以看到只使用了 1 个 GPU,正如我预期的那样。

if __name__ == "__main__":
  fcn = FCN()
  fcn.train_model()

  images_dir = '/home/super/datasets/MeterDataset/full-dataset-gas-images/'
  for img_file in os.listdir(images_dir):
    fcn.segment(os.path.join(images_dir, img_file))

输出:

2018-01-09 11:31:57.351029: I tensorflow/core/common_runtime/gpu/gpu_device.cc:955] Found device 0 with properties: 
name: GeForce GTX 1080
major: 6 minor: 1 memoryClockRate (GHz) 1.7335
pciBusID 0000:09:00.0
Total memory: 7.92GiB
Free memory: 7.60GiB
2018-01-09 11:31:57.351047: I tensorflow/core/common_runtime/gpu/gpu_device.cc:976] DMA: 0 
2018-01-09 11:31:57.351051: I tensorflow/core/common_runtime/gpu/gpu_device.cc:986] 0:   Y 
2018-01-09 11:31:57.351057: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 1080, pci bus id: 0000:09:00.0)

当我尝试从另一个脚本实例化 FCN 对象时出现问题。

def main(args):
  start_time = datetime.now()

  font = cv2.FONT_HERSHEY_SIMPLEX

  results_file = "../results.txt"
  if os.path.exists(results_file):
    os.remove(results_file)

  results_file = open(results_file, "a")

  fcn = FCN()

这里对象的创建总是使用所有 3 个 GPU,而不是使用唯一分配给 __init__() 方法的 GPU。

这里是不需要的输出:

2018-01-09 11:41:02.537548: I 

tensorflow/core/common_runtime/gpu/gpu_device.cc:976] DMA: 0 1 2 
2018-01-09 11:41:02.537555: I tensorflow/core/common_runtime/gpu/gpu_device.cc:986] 0:   Y Y Y 
2018-01-09 11:41:02.537558: I tensorflow/core/common_runtime/gpu/gpu_device.cc:986] 1:   Y Y Y 
2018-01-09 11:41:02.537561: I tensorflow/core/common_runtime/gpu/gpu_device.cc:986] 2:   Y Y Y 
2018-01-09 11:41:02.537567: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 1080, pci bus id: 0000:0b:00.0)
2018-01-09 11:41:02.537571: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:1) -> (device: 1, name: GeForce GTX 1080, pci bus id: 0000:09:00.0)
2018-01-09 11:41:02.537574: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:2) -> (device: 2, name: GeForce GTX 1080, pci bus id: 0000:05:00.0)

最佳答案

以下是您可以执行的操作:

  • 使用已设置的 CUDA_VISIBLE_DEVICES 环境变量运行脚本,如 discussed here :

    CUDA_VISIBLE_DEVICES=1 python another_script.py
    
  • Session构造函数提供显式配置:

    config = tf.ConfigProto(device_count={'GPU': 1})
    sess = tf.Session(config=config)
    

    ... 强制 tensorflow 只使用一个 GPU,无论有多少可用。您还可以通过 visible_device_list 设置细粒度的设备列表(有关详细信息,请参阅 config.proto)。

关于python - 在 Tensorflow 中限制 GPU 设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48166440/

相关文章:

python - App Engine NDB 评论模型有哪些好的例子?

python - pympler 引发 TypeError

python - 在 tf.train.AdamOptimizer 中手动更改 learning_rate

python - 从 pandas df 列的预设字符串列表中拆分字符串

tensorflow - 对黑白图片的深度学习目标检测有何期望?

python - 在类构造函数中初始化 tensorflow session

python - docker 中的 celery worker 将无法获得正确的消息代理

python - Django 1.3,如何像在 ebay 上一样在帖子结束时发出信号?

python - PyTorch torch.no_grad() 与 requires_grad=False

python - 面向对象编程初学者;更多方法与类