|
| 1 | +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. |
| 2 | +
|
| 3 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +you may not use this file except in compliance with the License. |
| 5 | +You may obtain a copy of the License at |
| 6 | +
|
| 7 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +
|
| 9 | +Unless required by applicable law or agreed to in writing, software |
| 10 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +See the License for the specific language governing permissions and |
| 13 | +limitations under the License. |
| 14 | +==============================================================================*/ |
| 15 | + |
| 16 | +//! Parsing for event files containing a stream of `Event` protos. |
| 17 | +
|
| 18 | +use prost::{DecodeError, Message}; |
| 19 | +use std::io::Read; |
| 20 | + |
| 21 | +use crate::proto::tensorboard::Event; |
| 22 | +use crate::tf_record::{ChecksumError, ReadRecordError, TfRecordReader}; |
| 23 | + |
| 24 | +/// A reader for a stream of `Event` protos framed as TFRecords. |
| 25 | +/// |
| 26 | +/// As with [`TfRecordReader`], an event may be read over one or more underlying reads, to support |
| 27 | +/// growing, partially flushed files. |
| 28 | +#[derive(Debug)] |
| 29 | +pub struct EventFileReader<R> { |
| 30 | + /// Wall time of the record most recently read from this event file, or `None` if no records |
| 31 | + /// have been read. Used for determining when to consider this file dead and abandon it. |
| 32 | + last_wall_time: Option<f64>, |
| 33 | + /// Underlying record reader owned by this event file. |
| 34 | + reader: TfRecordReader<R>, |
| 35 | +} |
| 36 | + |
| 37 | +/// Error returned by [`EventFileReader::read_event`]. |
| 38 | +#[derive(Debug)] |
| 39 | +pub enum ReadEventError { |
| 40 | + /// The record failed its checksum. |
| 41 | + InvalidRecord(ChecksumError), |
| 42 | + /// The record passed its checksum, but the contained protocol buffer is invalid. |
| 43 | + InvalidProto(DecodeError), |
| 44 | + /// The record is a valid `Event` proto, but its `wall_time` is `NaN`. |
| 45 | + NanWallTime(Event), |
| 46 | + /// An error occurred reading the record. May or may not be fatal. |
| 47 | + ReadRecordError(ReadRecordError), |
| 48 | +} |
| 49 | + |
| 50 | +impl From<DecodeError> for ReadEventError { |
| 51 | + fn from(e: DecodeError) -> Self { |
| 52 | + ReadEventError::InvalidProto(e) |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +impl From<ChecksumError> for ReadEventError { |
| 57 | + fn from(e: ChecksumError) -> Self { |
| 58 | + ReadEventError::InvalidRecord(e) |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +impl From<ReadRecordError> for ReadEventError { |
| 63 | + fn from(e: ReadRecordError) -> Self { |
| 64 | + ReadEventError::ReadRecordError(e) |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +impl ReadEventError { |
| 69 | + /// Checks whether this error indicates a truncated record. This is a convenience method, since |
| 70 | + /// the end of a file always implies a truncation event. |
| 71 | + pub fn truncated(&self) -> bool { |
| 72 | + matches!( |
| 73 | + self, |
| 74 | + ReadEventError::ReadRecordError(ReadRecordError::Truncated) |
| 75 | + ) |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +impl<R: Read> EventFileReader<R> { |
| 80 | + /// Creates a new `EventFileReader` wrapping the given reader. |
| 81 | + pub fn new(reader: R) -> Self { |
| 82 | + Self { |
| 83 | + last_wall_time: None, |
| 84 | + reader: TfRecordReader::new(reader), |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + /// Reads the next event from the file. |
| 89 | + pub fn read_event(&mut self) -> Result<Event, ReadEventError> { |
| 90 | + let record = self.reader.read_record()?; |
| 91 | + record.checksum()?; |
| 92 | + let event = Event::decode(&record.data[..])?; |
| 93 | + let wall_time = event.wall_time; |
| 94 | + if wall_time.is_nan() { |
| 95 | + return Err(ReadEventError::NanWallTime(event)); |
| 96 | + } |
| 97 | + self.last_wall_time = Some(wall_time); |
| 98 | + Ok(event) |
| 99 | + } |
| 100 | + |
| 101 | + /// Gets the wall time of the event most recently read from the event file, or `None` if no |
| 102 | + /// events have yet been read. |
| 103 | + pub fn last_wall_time(&self) -> &Option<f64> { |
| 104 | + &self.last_wall_time |
| 105 | + } |
| 106 | +} |
| 107 | + |
| 108 | +#[cfg(test)] |
| 109 | +mod tests { |
| 110 | + use super::*; |
| 111 | + use crate::masked_crc::MaskedCrc; |
| 112 | + use crate::proto::tensorboard as pb; |
| 113 | + use crate::scripted_reader::ScriptedReader; |
| 114 | + use crate::tf_record::TfRecord; |
| 115 | + use std::io::Cursor; |
| 116 | + |
| 117 | + /// Encodes an `Event` proto to bytes. |
| 118 | + fn encode_event(e: &Event) -> Vec<u8> { |
| 119 | + let mut encoded = Vec::new(); |
| 120 | + Event::encode(&e, &mut encoded).expect("failed to encode event"); |
| 121 | + encoded |
| 122 | + } |
| 123 | + |
| 124 | + #[test] |
| 125 | + fn test() { |
| 126 | + let good_event = Event { |
| 127 | + what: Some(pb::event::What::FileVersion("good event".to_string())), |
| 128 | + wall_time: 1234.5, |
| 129 | + ..Event::default() |
| 130 | + }; |
| 131 | + let mut nan_event = Event { |
| 132 | + what: Some(pb::event::What::FileVersion("bad wall time".to_string())), |
| 133 | + wall_time: f64::NAN, |
| 134 | + ..Event::default() |
| 135 | + }; |
| 136 | + let records = vec![ |
| 137 | + TfRecord::from_data(encode_event(&good_event)), |
| 138 | + TfRecord::from_data(encode_event(&nan_event)), |
| 139 | + TfRecord::from_data(b"failed proto, OK record".to_vec()), |
| 140 | + TfRecord { |
| 141 | + data: b"failed proto, failed checksum, OK record structure".to_vec(), |
| 142 | + data_crc: MaskedCrc(0x12345678), |
| 143 | + }, |
| 144 | + TfRecord { |
| 145 | + data: encode_event(&good_event), |
| 146 | + data_crc: MaskedCrc(0x12345678), // OK proto, failed checksum, OK record structure |
| 147 | + }, |
| 148 | + ]; |
| 149 | + let mut file = Vec::new(); |
| 150 | + for record in records { |
| 151 | + record.write(&mut file).expect("writing record"); |
| 152 | + } |
| 153 | + let mut reader = EventFileReader::new(Cursor::new(file)); |
| 154 | + |
| 155 | + assert_eq!(reader.last_wall_time(), &None); |
| 156 | + assert_eq!(reader.read_event().unwrap(), good_event); |
| 157 | + assert_eq!(reader.last_wall_time(), &Some(1234.5)); |
| 158 | + match reader.read_event() { |
| 159 | + Err(ReadEventError::NanWallTime(mut e)) => { |
| 160 | + // can't just check `e == nan_event` because `NaN != NaN` |
| 161 | + assert!(e.wall_time.is_nan()); |
| 162 | + e.wall_time = 0.0; |
| 163 | + nan_event.wall_time = 0.0; |
| 164 | + assert_eq!(e, nan_event); |
| 165 | + } |
| 166 | + other => panic!("{:?}", other), |
| 167 | + }; |
| 168 | + assert_eq!(reader.last_wall_time(), &Some(1234.5)); |
| 169 | + match reader.read_event() { |
| 170 | + Err(ReadEventError::InvalidProto(_)) => (), |
| 171 | + other => panic!("{:?}", other), |
| 172 | + }; |
| 173 | + assert_eq!(reader.last_wall_time(), &Some(1234.5)); |
| 174 | + match reader.read_event() { |
| 175 | + Err(ReadEventError::InvalidRecord(ChecksumError { |
| 176 | + got: _, |
| 177 | + want: MaskedCrc(0x12345678), |
| 178 | + })) => (), |
| 179 | + other => panic!("{:?}", other), |
| 180 | + }; |
| 181 | + assert_eq!(reader.last_wall_time(), &Some(1234.5)); |
| 182 | + match reader.read_event() { |
| 183 | + Err(ReadEventError::InvalidRecord(ChecksumError { got, want: _ })) |
| 184 | + if got == MaskedCrc::compute(&encode_event(&good_event)) => |
| 185 | + { |
| 186 | + () |
| 187 | + } |
| 188 | + other => panic!("{:?}", other), |
| 189 | + }; |
| 190 | + assert_eq!(reader.last_wall_time(), &Some(1234.5)); |
| 191 | + // After end of file, should get a truncation error. |
| 192 | + let last = reader.read_event(); |
| 193 | + assert!(last.as_ref().unwrap_err().truncated(), "{:?}", last); |
| 194 | + assert_eq!(reader.last_wall_time(), &Some(1234.5)); |
| 195 | + } |
| 196 | + |
| 197 | + #[test] |
| 198 | + fn test_resume() { |
| 199 | + let event = Event { |
| 200 | + what: Some(pb::event::What::FileVersion("good event".to_string())), |
| 201 | + wall_time: 1234.5, |
| 202 | + ..Event::default() |
| 203 | + }; |
| 204 | + let mut file = Cursor::new(Vec::<u8>::new()); |
| 205 | + TfRecord::from_data(encode_event(&event)) |
| 206 | + .write(&mut file) |
| 207 | + .unwrap(); |
| 208 | + let record_bytes = file.into_inner(); |
| 209 | + let (beginning, end) = record_bytes.split_at(6); |
| 210 | + |
| 211 | + let sr = ScriptedReader::new(vec![beginning.to_vec(), end.to_vec()]); |
| 212 | + let mut reader = EventFileReader::new(sr); |
| 213 | + |
| 214 | + // first read should be truncated |
| 215 | + let result = reader.read_event(); |
| 216 | + assert!(result.as_ref().unwrap_err().truncated(), "{:?}", result); |
| 217 | + assert_eq!(reader.last_wall_time(), &None); |
| 218 | + |
| 219 | + // second read should be the full record |
| 220 | + let result = reader.read_event(); |
| 221 | + assert_eq!(result.unwrap(), event); |
| 222 | + assert_eq!(reader.last_wall_time(), &Some(1234.5)); |
| 223 | + |
| 224 | + // further reads should be truncated again |
| 225 | + let result = reader.read_event(); |
| 226 | + assert!(result.as_ref().unwrap_err().truncated(), "{:?}", result); |
| 227 | + assert_eq!(reader.last_wall_time(), &Some(1234.5)); |
| 228 | + } |
| 229 | +} |
0 commit comments