回答編集履歴
1
(★)以降のコードを実行せずとも、正常にメモリ抑制ができた為。
answer
CHANGED
@@ -4,7 +4,7 @@
|
|
4
4
|
- os.environ["TF_FORCE_GPU_ALLOW_GROWTH"]= "true" を、import tensorflowの前に実行すること
|
5
5
|
|
6
6
|
正直、(★)以降のコードについては、かなり色んなサイトやブログで紹介されていますが
|
7
|
-
|
7
|
+
(★)以降のコードを実行せずとも、tensorflowをimportする前に 環境変数 TF_FORCE_GPU_ALLOW_GROWTHをTrueに設定すれば、正常にメモリ抑制できました。
|
8
8
|
|
9
9
|
```Code
|
10
10
|
# この部分は必ずTensorflowをimportする前に実行する
|
@@ -24,28 +24,29 @@
|
|
24
24
|
# TFのメモリ制限が有効か確認(trueが返ったら有効、Noneが返ったら無効)
|
25
25
|
print(os.getenv('TF_FORCE_GPU_ALLOW_GROWTH'))
|
26
26
|
|
27
|
+
#(★)
|
27
|
-
# Tensorflowのバージョンに応じて、メモリ使用量を抑えるコードを実行
|
28
|
+
# Tensorflowのバージョンに応じて、メモリ使用量を抑えるコードを実行
|
28
|
-
gpu_id = 0
|
29
|
+
# gpu_id = 0
|
29
|
-
print(tf.__version__)
|
30
|
+
# print(tf.__version__)
|
30
|
-
if tf.__version__ >= "2.1.0":
|
31
|
+
# if tf.__version__ >= "2.1.0":
|
31
|
-
physical_devices = tf.config.list_physical_devices('GPU')
|
32
|
+
# physical_devices = tf.config.list_physical_devices('GPU')
|
32
|
-
tf.config.list_physical_devices('GPU')
|
33
|
+
# tf.config.list_physical_devices('GPU')
|
33
|
-
tf.config.set_visible_devices(physical_devices[gpu_id], 'GPU')
|
34
|
+
# tf.config.set_visible_devices(physical_devices[gpu_id], 'GPU')
|
34
|
-
tf.config.experimental.set_memory_growth(physical_devices[gpu_id], True)
|
35
|
+
# tf.config.experimental.set_memory_growth(physical_devices[gpu_id], True)
|
35
36
|
|
36
|
-
elif tf.__version__ >= "2.0.0":
|
37
|
+
# elif tf.__version__ >= "2.0.0":
|
37
|
-
#TF2.0
|
38
|
+
# #TF2.0
|
38
|
-
physical_devices = tf.config.experimental.list_physical_devices('GPU')
|
39
|
+
# physical_devices = tf.config.experimental.list_physical_devices('GPU')
|
39
|
-
tf.config.experimental.set_visible_devices(physical_devices[gpu_id], 'GPU')
|
40
|
+
# tf.config.experimental.set_visible_devices(physical_devices[gpu_id], 'GPU')
|
40
|
-
tf.config.experimental.set_memory_growth(physical_devices[gpu_id], True)
|
41
|
+
# tf.config.experimental.set_memory_growth(physical_devices[gpu_id], True)
|
41
42
|
|
42
|
-
else:
|
43
|
+
# else:
|
43
|
-
from tensorflow.keras.backend import set_session
|
44
|
+
# from tensorflow.keras.backend import set_session
|
44
|
-
config = tf.ConfigProto(
|
45
|
+
# config = tf.ConfigProto(
|
45
|
-
gpu_options=tf.GPUOptions(
|
46
|
+
# gpu_options=tf.GPUOptions(
|
46
|
-
visible_device_list=str(gpu_id), # specify GPU number
|
47
|
+
# visible_device_list=str(gpu_id), # specify GPU number
|
47
|
-
allow_growth=True
|
48
|
+
# allow_growth=True
|
49
|
+
# )
|
48
|
-
|
50
|
+
# )
|
49
|
-
)
|
50
|
-
set_session(tf.Session(config=config))
|
51
|
+
# set_session(tf.Session(config=config))
|
51
52
|
```
|