> ## Content Index
> Fetch the complete content index at: https://yinguobing.com/blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# 使用VSCode Remote实现TensorFlow模型的远程开发
- URL: https://yinguobing.com/blog/remote-development-of-tensorflow-models-with-vscode-remote/
- Published: 2021-06-02T09:24:23.000Z
- Updated: 2021-06-08T13:05:20.000Z
- Description: 在特殊的开发环境下要用特殊的方法
- Author: 尹国冰
- Tags: TensorFlow, 新手入门

对于深度学习模型开发者，最常见的开发环境大概是这样的。一台安装了高性能GPU的本地PC机，熟悉的深度学习框架以及开发环境，这里以TensorFlow为例。

![](https://yinguobing.com/blog/content/images/2021/06/remote-01.jpg)

单机开发

但是在某些特殊场合，为了节省成本以及其它原因，你需要与他人共享一台性能强大的服务器来实现模型训练。为了照顾到不同的使用者，服务器上使用Docker容器服务实现了开发环境的隔离。此时你手头只有一台不支持GPU运算、或者虽然支持但是性能受限的机器。大概是下图这样。

![](https://yinguobing.com/blog/content/images/2021/06/remote-02.jpg)

需要与他人共享计算设备

此时，你可以考虑使用VS Code的Remote功能，实现远程模型开发。如下图所示。本地PC通过ssh的方式与远程服务器中的对应容器连接。

![](https://yinguobing.com/blog/content/images/2021/06/remote-03.jpg)

远程模型开发示意图

对于使用VS Code的开发者，这种开发方式与本地开发基本上感觉不出差异。而且本地PC的配置随意，支持VS Code即可。主要是服务器端需要的适配工作稍微复杂，这里列出示例如下。

### 激活TensorFlow Docker镜像

在服务器端执行

```bash
# 需要root权限
docker run -it -p 5085:22 --runtime=nvidia tensorflow/tensorflow:latest-gpu
```

这条命令会自动拉取TensorFlow GPU最新版镜像，并将容器的22端口与服务器的5085端口绑定。

### 启用SSH服务

在容器启动后，安装openssh-server。

```bash
apt install openssh-server
```

安装完成后启用服务。

```bash
service ssh start
```

TensorFlow docker容器推荐使用非root账户。此时可以暂停一下，新建一个使用用户。

用户建立完成后，可以尝试在本地机器通过ssh连接远程docker容器。

```bash
ssh username@ip -p5085
```

其中的\`username\`为你刚才建立的用户名。\`ip\`为容器所在服务器的ip地址。参数\`-p5085\`为激活容器时指定的外部端口。

如果连接成功，进入下一步。

### 安装VS Code Remote-SSH

在本地机器上打开VS Code，在左侧的 Extentions 中找到该插件。或者点击这个链接：

[Remote - SSH - Visual Studio MarketplaceExtension for Visual Studio Code - Open any folder on a remote machine using SSH and take advantage of VS Code’s full feature set.![](https://ms-vscode-remote.gallerycdn.vsassets.io/extensions/ms-vscode-remote/remote-ssh/0.65.6/1621481443536/Microsoft.VisualStudio.Services.Icons.Default)](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-ssh&ref=yinguobing.com)

插件安装完成后，点击VS Code左下角的Remote连接图标。

![](https://yinguobing.com/blog/content/images/2021/06/remote-04.jpg)

绿色的Remote图标

在弹出的对话框中选择\`Connect to host...\` - \`Add New SSH Host...\`，然后将之前使用过的连接命令填入并回车。

![](https://yinguobing.com/blog/content/images/2021/06/remote-05.jpg)

填入ssh连接命令

之后一路回车，直到系统提示Host添加成功。

![](https://yinguobing.com/blog/content/images/2021/06/remote-06.jpg)

添加host成功

此时可以点击 `Connect` 连接远程容器，并在弹出的对话框中输入连接密码。这个过程中VS Code会执行一些自动配置。最后在终端栏中显示如下信息。代表配置成功。

![](https://yinguobing.com/blog/content/images/2021/06/remote-08.jpg)

连接成功后在VS Code中开启的终端都自动连接到该Docker容器的终端。此时便可以像往常一样clone代码，传输数据实现模型训练了。

> Tips: 你可以使用 `scp` 将文件拷贝到该容器内部，或者使用 `docker cp` 命令拷贝该服务器上的文件到容器内部。