Module 07: Why are we closing the writer before all epochs are finished? #1370
Replies: 1 comment
|
Your reading of the indentation is correct: in the section 6.1 snippet, writer.close() is inside the epoch loop. It should normally be called after the loop (or by the code that created the writer). The corrected shape is: for epoch in tqdm(range(epochs)):
# train_step/test_step, print, append results ...
if writer:
writer.add_scalars(
main_tag="Loss",
tag_scalar_dict={"train_loss": train_loss, "test_loss": test_loss},
global_step=epoch,
)
writer.add_scalars(
main_tag="Accuracy",
tag_scalar_dict={"train_acc": train_acc, "test_acc": test_acc},
global_step=epoch,
)
# same indentation as the for statement, not as add_scalars
if writer:
writer.close()
return resultsSo the sequence is: write every epoch, then close once when training has finished. One subtlety: with current PyTorch, later epochs are not necessarily silently discarded. SummaryWriter._get_file_writer() recreates a file writer if it was closed, so a later add_scalars() can reopen it. But closing/reopening on every epoch is unnecessary, creates extra event-file churn, and is not the lifecycle you should rely on. PyTorch's own example writes in the loop and closes after it (docs). There is also a useful confirmation in the same course page: the earlier training example around section 4 has writer.close() outside the loop, whereas the section 6.1 version has it inside. That makes this look like an indentation mistake in that later snippet, not an intentional TensorBoard technique. For reusable code, an even cleaner ownership rule is: whoever constructs the writer closes it: with SummaryWriter(log_dir=...) as writer:
results = train(..., writer=writer)Then train() only logs, and the context manager closes once after train() returns. |
Uh oh!
There was an error while loading. Please reload this page.
Hi, I am new to machine learning. I am writing this to ask in below given code snippet, why are we closing the writer "writer.close()" before all the epochs are run? I might be wrong but because we are closing the writer, on epoch 2, 3, 4, .... won't the accuracy and results would be silently dropped or not written etc?
Area of interest:
Full code snippet:
Link to the page on learnpytorch.io
All reactions