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
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
use std::fs::{create_dir_all, File};
use std::io::{self, BufWriter, ErrorKind, Write};
use std::path::PathBuf;

use crate::event_writer::event::What;
use crate::event_writer::summary::value::Value::SimpleValue;
use crate::event_writer::summary::Value;
use crate::event_writer::{EventWriter, Summary};
use std::time::{SystemTime, UNIX_EPOCH};

/// TensorBoard summary writer.
pub struct SummaryWriter<W> {
    writer: EventWriter<W>,
}

impl SummaryWriter<BufWriter<File>> {
    /// Construct a writer from a path prefix.
    ///
    /// For instance, a path such as `tensorboard/bert/opt` will create
    /// the directory `tensorboard/bert` if it does not exist. Within that
    /// directory, it will write to the file
    /// `opt.out.tfevents.<timestamp>.<hostname>`.
    pub fn from_prefix(path: impl Into<PathBuf>) -> io::Result<Self> {
        let path = path.into();

        if path.components().count() == 0 {
            return Err(io::Error::new(
                ErrorKind::NotFound,
                "summary prefix must not be empty".to_string(),
            ));
        }

        if let Some(dir) = path.parent() {
            create_dir_all(dir)?;
        }

        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_micros();
        let hostname = hostname::get()?;

        let mut path_string = path.into_os_string();
        path_string.push(format!(".out.tfevents.{}.", timestamp));
        path_string.push(hostname);

        SummaryWriter::new(BufWriter::new(File::create(path_string)?))
    }
}

impl<W> SummaryWriter<W>
where
    W: Write,
{
    /// Construct a writer from a `Write` type.
    pub fn new(write: W) -> io::Result<Self> {
        let writer = EventWriter::new(write)?;
        Ok(SummaryWriter { writer })
    }

    /// Create a writer that uses the given wall time in the version record.
    ///
    /// This constructor is provided for unit tests.
    #[allow(dead_code)]
    fn new_with_wall_time(write: W, wall_time: f64) -> io::Result<Self> {
        let writer = EventWriter::new_with_wall_time(write, wall_time)?;
        Ok(SummaryWriter { writer })
    }

    /// Write a scalar.
    pub fn write_scalar(
        &mut self,
        tag: impl Into<String>,
        step: i64,
        scalar: f32,
    ) -> std::io::Result<()> {
        self.writer.write_event(
            step,
            What::Summary(Summary {
                value: vec![Value {
                    node_name: "".to_string(),
                    tag: tag.into(),
                    value: Some(SimpleValue(scalar)),
                }],
            }),
        )
    }

    /// Write a scalar with the given wall time.
    ///
    /// This method is provided for unit tests.
    #[allow(dead_code)]
    fn write_scalar_with_wall_time(
        &mut self,
        wall_time: f64,
        tag: impl Into<String>,
        step: i64,
        scalar: f32,
    ) -> std::io::Result<()> {
        self.writer.write_event_with_wall_time(
            wall_time,
            step,
            What::Summary(Summary {
                value: vec![Value {
                    node_name: "".to_string(),
                    tag: tag.into(),
                    value: Some(SimpleValue(scalar)),
                }],
            }),
        )
    }
}

#[cfg(test)]
mod tests {
    use crate::SummaryWriter;

    static CHECK_OUTPUT: [u8; 126] = [
        24, 0, 0, 0, 0, 0, 0, 0, 163, 127, 75, 34, 9, 0, 0, 128, 54, 111, 246, 215, 65, 26, 13, 98,
        114, 97, 105, 110, 46, 69, 118, 101, 110, 116, 58, 50, 136, 162, 101, 134, 27, 0, 0, 0, 0,
        0, 0, 0, 26, 13, 158, 19, 9, 188, 119, 164, 54, 111, 246, 215, 65, 16, 10, 42, 14, 10, 12,
        10, 5, 104, 101, 108, 108, 111, 21, 0, 0, 40, 66, 93, 240, 111, 128, 27, 0, 0, 0, 0, 0, 0,
        0, 26, 13, 158, 19, 9, 48, 127, 164, 54, 111, 246, 215, 65, 16, 20, 42, 14, 10, 12, 10, 5,
        119, 111, 114, 108, 100, 21, 0, 0, 128, 63, 5, 210, 83, 151,
    ];

    #[test]
    fn writes_the_same_output_as_tensorflow() {
        let mut data = vec![];
        let mut writer = SummaryWriter::new_with_wall_time(&mut data, 1608105178.).unwrap();
        writer
            .write_scalar_with_wall_time(1608105178.569808, "hello", 10, 42.)
            .unwrap();
        writer
            .write_scalar_with_wall_time(1608105178.570263, "world", 20, 1.)
            .unwrap();

        assert_eq!(data, CHECK_OUTPUT);
    }
}