> For the complete documentation index, see [llms.txt](https://kerasnoone.gitbook.io/garnet/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kerasnoone.gitbook.io/garnet/shi-jian-ji-qiao/xian-cun-you-hua/tensorflow-xian-zhi-xian-cun-shi-yong-liang.md).

# TensorFlow限制显存使用量

## 显式地设置显存使用比例

Tensorflow默认会完全占用满指定GPU的显存, 而线上部署后, 只需要进行推测, 是不需要占用完整块GPU显存的. 需要在代码中控制显存.

### 设置静态值

使用`per_process_gpu_memory_fraction`参数, 显式的指定每块GPU使用的内存比例, 设置的范围为0\~1, 代表占用上限为0\~100%.

```python
import tensorflow as tf
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.3
set_session(tf.Session(config=config))
```

keras需要使用`set_session`函数设置Session.

### 按需分配

```python
import tensorflow as tf
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
set_session(tf.Session(config=config))
```

使用`allow_growth`设置显存按需分配, 动态增长. 但注意一旦当前服务获取到了一定数量的显存, 后面是不会再还给系统的, 即使因为某些原因显存使用降低了. 总结来说, 这是一个**不可逆的过程**.

## 参考资料

* [限制TensorFlow显存使用量](https://zhuanlan.zhihu.com/p/57654552)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kerasnoone.gitbook.io/garnet/shi-jian-ji-qiao/xian-cun-you-hua/tensorflow-xian-zhi-xian-cun-shi-yong-liang.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
