forked from epfml/landmark-attention
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathutils.py
executable file
·43 lines (36 loc) · 1.76 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Copyright 2023 Amirkeivan Mohtashami, Martin Jaggi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import torch
import torch.nn.functional as F
from contextlib import nullcontext, contextmanager, ExitStack
def get_batch(data, seq_length, batch_size, device='cpu'):
ix = torch.randint(len(data) - seq_length - 1, (batch_size,))
x = torch.stack([torch.from_numpy((data[i:i+seq_length]).astype(np.int64)) for i in ix])
y = torch.stack([torch.from_numpy((data[i+1:i+1+seq_length+1]).astype(np.int64)) for i in ix])
y = torch.where(y[:, :-1] == 50260, y[:, 1:], y[:, :-1])
y = torch.where((x == 50260) | (x == 50256) , -1, y)
if device != 'cpu':
# pin arrays x,y, which allows us to move them to GPU asynchronously (non_blocking=True)
x, y = x.pin_memory().to(device, non_blocking=True), y.pin_memory().to(device, non_blocking=True)
#x, y = x.to(device), y.to(device)
return x, y
def save_checkpoint(distributed_backend, model, opt, scheduler, itr, ckpt_path, **extra_args):
checkpoint = dict({
'model': distributed_backend.get_raw_model(model).state_dict(),
'optimizer': opt.state_dict(),
'scheduler': scheduler.state_dict(),
'itr': itr,
}, **extra_args)
torch.save(checkpoint, ckpt_path)