Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
EagerTrainer.nullcontext
  • Loading branch information
lixinqi committed Sep 11, 2022
commit 4fcc67c4e8ea10f7ae1f0c746c4c72a06321d875
29 changes: 17 additions & 12 deletions libai/engine/trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,30 +280,35 @@ def run_step(self, get_batch: Callable, input_placement_device: str = "cuda"):
losses = sum(loss_dict.values()) / self.grad_acc_steps

losses.backward()
with self.thread(tmp_worker_thread):
self.write_metrics(tmp_loss_dict, data_time)

if (self.iter + 1) % self.grad_acc_steps == 0:
self.optimizer.clip_grad()
self.optimizer.step()
self.optimizer.zero_grad()

with self.thread(tmp_worker_thread):
self.write_metrics(tmp_loss_dict, data_time)

def tmp_worker_thread(self):
if not hasattr(flow, 'asyncs'):
return None
if not hasattr(flow.asyncs, 'Thread'):
return None
return flow.asyncs.Thread()
try:
create_asyncs_thread = flow.asyncs.Thread
except AttributeError:
create_asyncs_thread = lambda: None
return create_asyncs_thread()

@contextmanager
def thread(self, t):
if not hasattr(flow, 'asyncs'):
yield
if not hasattr(flow.asyncs, 'thread'):
yield
with flow.asyncs.thread(t):
try:
asyncs_thread = flow.asyncs.thread
except AttributeError:
asyncs_thread = self.nullcontext
with asyncs_thread(t):
yield

@contextmanager
def nullcontext(self, *argc, **kwargs):
yield

class GraphTrainer(TrainerBase):
"""
A simple graph trainer for training and evaluating models in a static graph mode.
Expand Down