再次警告⚠️……没有在小小demo上试验成功的代码不要放到服务器上造垃圾
一、服务器上配置jupyter
1.1 ssh连接到服务器,cd到你想建立jupyer的服务器目录下执行:
$ jupyter notebook --generate-config
然后会出现
1.2生成密码
$ python
>>> from IPython.lib import passwd
>>>passwd()
需要你两次输入你想设置的密码,然后返回一个’argon2:$argon……‘加密之后的字符串将其复制 ctrl+z
退回终端
1.3打开jupyter_notebook_config.py文件,在开头写下面的
直接在ssh连接browse remote host后打开文件复制粘贴哇!!第一次自己在服务器手动敲的
c.NotebookApp.ip='xxx.xx.xx.xxx' #你的服务器ip
c.NotebookApp.password='argon2:$argon2idxxxxxx' #密码
c.NotebookApp.open_browser=False #不在服务器打开浏览器
c.NotebookApp.allow_remote_access=True
c.NotebookApp.port=8888 #端口 这里虽然设置了8888但是如果端口冲突会给你换一个开
c.NotebookApp.notebook_dir = '/home/xxx/xxxxxx' #jupyter的工作目录
1.4运行jupyter notebook
$ jupyter notebook
指定端口号或者ip
$ jupyter notebook --no-browser --port 6000 --ip=192.168.1.100
如果你直接运行这条语句,结果如下图,点击蓝色连接就会进入到jupyter,输入上面设置的密码就可以用了
但是始终占用一个终端命令窗口,你ctrl+z
之后就无法访问,再jupyter notebook之后,会给你打开新的端口
你想用回8888端口访问怎么办?
$ ps -aux | grep jupyter
查看运行中的jupyter 进程,杀死他们的pid,也就是第一列
kill -9 26989
kill -9 26993
kill -9 26999
然后再查看,发现杀不死的话试试$ ps -ef | grep jupyter
查pid
这样太麻烦了,一个是端口号不固定,还有就是不能让进程一直运行
二、后台挂载
nohup jupyter notebook --allow-root > jupyter.log 2>&1 &
会把原本在终端限时的运行状态写到jupyter.log 里
后台挂载后也不能print了,可以把结果写在log里
这样即使关掉ssh连接也会一直在后台运行
然后你不能一直挂载吧,任务结束就用上面的办法查看pid,杀死进程
三、附赠cuda()怎么写
简单来说就是穿进去模型的变量和模型自身要.cuda(),显示结果要.cpu()
因为要在mac和服务器之间反复横跳…,用另一种写法torch.device()
知道两句话你听不懂,我们下面举几个例子
###在最开始设置device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
#找模型定义的地方
model = x.Model(config).to(device)
#可以在生成x,y iter的时候to
'''
class DatasetIterater(object):
def __init__(self, batches, batch_size, device):
self.batch_size = batch_size
self.batches = batches
self.n_batches = len(batches) // batch_size
self.residue = False # 记录batch数量是否为整数
if len(batches) % self.n_batches != 0:
self.residue = True
self.index = 0
self.device = device
'''
def _to_tensor(self, datas):
x = torch.LongTensor([_[0] for _ in datas]).to(self.device)
y = torch.LongTensor([_[1] for _ in datas]).to(self.device)
'''
# pad前的长度(超过pad_size的设为pad_size)
seq_len = torch.LongTensor([_[2] for _ in datas]).to(self.device)
return (x, seq_len), y
'''
#也可以在传进去模型的时候to
inputs, targets = data[0].cuda(), data[1].cuda()
outputs = model(inputs)
#需要输出显示的值.cpu()
target = labels.data.cpu()
predic = torch.max(outputs.data, 1)[1].cpu()
train_acc = metrics.accuracy_score(target, predic)
#在验证或者预测函数(而不是train)需要直接用output 记得detach()
preds.append(outputs.detach().cpu().numpy())
会提示cuda memory不够了的话
我做的办法是先kill掉jupyter 进程……(这样变量会丢失,希望有更方便的方法)
然后检查自己验证函数,它是不需要梯度的
with torch.no_grad():
outputs = model(inputs)