Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add async flag to CSVWriter #635

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
16 changes: 16 additions & 0 deletions tests/utils/loggers/test_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,19 @@ def test_csv_log(self) -> None:
# pyre-fixme[16]: `_DictReadMapping` has no attribute `__getitem__`.
self.assertEqual(float(output[0][log_name]), log_value)
self.assertEqual(int(output[0]["step"]), log_step)

def test_csv_log_async(self) -> None:
with TemporaryDirectory() as tmpdir:
csv_path = Path(tmpdir, "test.csv").as_posix()
logger = CSVLogger(csv_path, steps_before_flushing=1, async_write=True)
log_name = "asdf"
log_value = 123.0
log_step = 10
logger.log(log_name, log_value, log_step)
logger.close()

with open(csv_path) as f:
output = list(csv.DictReader(f))
# pyre-fixme[16]: `_DictReadMapping` has no attribute `__getitem__`.
self.assertEqual(float(output[0][log_name]), log_value)
self.assertEqual(int(output[0]["step"]), log_step)
42 changes: 32 additions & 10 deletions torchtnt/utils/loggers/csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

import csv
import logging
from threading import Thread
from typing import Dict, List, Optional

from fsspec import open as fs_open
from torchtnt.utils.loggers.file import FileLogger
Expand All @@ -23,28 +25,48 @@ class CSVLogger(FileLogger, MetricLogger):
path (str): path to write logs to
steps_before_flushing: (int, optional): Number of steps to buffer in logger before flushing
log_all_ranks: (bool, optional): Log all ranks if true, else log only on rank 0.
async_write: (bool, optional): Whether to write asynchronously or not. Defaults to False.
"""

def __init__(
self,
path: str,
steps_before_flushing: int = 100,
log_all_ranks: bool = False,
async_write: bool = False,
) -> None:
super().__init__(path, steps_before_flushing, log_all_ranks)

def flush(self) -> None:
data = self._log_buffer
if not data:
logger.debug("No logs to write.")
return
self._async_write = async_write
self._thread: Optional[Thread] = None

def flush(self) -> None:
if self._rank == 0 or self._log_all_ranks:
with fs_open(self.path, "w") as f:
data_list = list(data.values())
w = csv.DictWriter(f, data_list[0].keys())
w.writeheader()
w.writerows(data_list)
buffer = self._log_buffer
if not buffer:
logger.debug("No logs to write.")
return

if self._thread:
# ensure previous thread is completed before next write
self._thread.join()

data_list = list(buffer.values())
if not self._async_write:
_write_csv(self.path, data_list)
return

self._thread = Thread(target=_write_csv, args=(self.path, data_list))
self._thread.start()

def close(self) -> None:
# toggle off async writing for final flush
self._async_write = False
self.flush()


def _write_csv(path: str, data_list: List[Dict[str, float]]) -> None:
with fs_open(path, "w") as f:
w = csv.DictWriter(f, data_list[0].keys())
w.writeheader()
w.writerows(data_list)
Loading