forked from deepinsight/insightface
-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.py
73 lines (54 loc) · 1.78 KB
/
graph.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import oneflow as flow
import oneflow.nn as nn
def make_static_grad_scaler():
return flow.amp.StaticGradScaler(flow.env.get_world_size())
def make_grad_scaler():
return flow.amp.GradScaler(
init_scale=2 ** 30, growth_factor=2.0, backoff_factor=0.5, growth_interval=2000,
)
def meter(self, mkey, *args):
assert mkey in self.m
self.m[mkey]["meter"].record(*args)
class TrainGraph(flow.nn.Graph):
def __init__(
self,
model,
cfg,
combine_margin,
cross_entropy,
data_loader,
optimizer,
lr_scheduler=None,
):
super().__init__()
if cfg.fp16:
self.config.enable_amp(True)
self.set_grad_scaler(make_grad_scaler())
elif cfg.scale_grad:
self.set_grad_scaler(make_static_grad_scaler())
self.config.allow_fuse_add_to_output(True)
self.config.allow_fuse_model_update_ops(True)
self.model = model
self.cross_entropy = cross_entropy
self.combine_margin = combine_margin
self.data_loader = data_loader
self.add_optimizer(optimizer, lr_sch=lr_scheduler)
def build(self):
image, label = self.data_loader()
image = image.to("cuda")
label = label.to("cuda")
logits, label = self.model(image, label)
logits = self.combine_margin(logits, label) * 64
loss = self.cross_entropy(logits, label)
loss.backward()
return loss
class EvalGraph(flow.nn.Graph):
def __init__(self, model, cfg):
super().__init__()
self.config.allow_fuse_add_to_output(True)
self.model = model
if cfg.fp16:
self.config.enable_amp(True)
def build(self, image):
logits = self.model(image)
return logits