-
-
Notifications
You must be signed in to change notification settings - Fork 105
/
Copy pathstats.rs
190 lines (169 loc) · 5.18 KB
/
stats.rs
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
use std::{
cmp::{max, min},
fmt,
fs::{File, OpenOptions},
io,
io::{Read as _, Seek as _, Write as _},
num::NonZeroUsize,
path::PathBuf,
time::Duration,
};
use serde::{Deserialize, Serialize};
use crate::configure::StatsOpt;
fn default_stats_file() -> Option<PathBuf> {
home::home_dir().map(|dir| dir.join(".fishnet-stats"))
}
pub struct StatsRecorder {
pub stats: Stats,
pub nnue_nps: NpsRecorder,
store: Option<(PathBuf, File)>,
cores: NonZeroUsize,
}
#[derive(Default, Clone, Serialize, Deserialize)]
pub struct Stats {
pub total_batches: u64,
pub total_positions: u64,
pub total_nodes: u64,
}
impl Stats {
fn load_from(file: &mut File) -> io::Result<Option<Stats>> {
file.rewind()?;
let mut buf = Vec::new();
file.read_to_end(&mut buf)?;
Ok(if buf.is_empty() {
None
} else {
Some(
serde_json::from_slice(&buf)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err.to_string()))?,
)
})
}
fn save_to(&self, file: &mut File) -> io::Result<()> {
file.set_len(0)?;
file.rewind()?;
file.write_all(
serde_json::to_string_pretty(&self)
.expect("serialize stats")
.as_bytes(),
)?;
Ok(())
}
}
impl StatsRecorder {
pub fn new(opt: StatsOpt, cores: NonZeroUsize) -> StatsRecorder {
let nnue_nps = NpsRecorder::new();
if opt.no_stats_file {
return StatsRecorder {
stats: Stats::default(),
store: None,
nnue_nps,
cores,
};
}
let path = if let Some(path) = opt.stats_file.or_else(default_stats_file) {
path
} else {
eprintln!("E: Could not resolve ~/.fishnet-stats");
return StatsRecorder {
stats: Stats::default(),
store: None,
nnue_nps,
cores,
};
};
let (stats, store) = match OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&path)
{
Ok(mut file) => (
match Stats::load_from(&mut file) {
Ok(Some(stats)) => {
println!("Resuming from {path:?} ...");
stats
}
Ok(None) => {
println!("Recording to new stats file {path:?} ...");
Stats::default()
}
Err(err) => {
eprintln!("E: Failed to resume from {path:?}: {err}. Resetting ...");
Stats::default()
}
},
Some((path, file)),
),
Err(err) => {
eprintln!("E: Failed to open {path:?}: {err}");
(Stats::default(), None)
}
};
StatsRecorder {
stats,
store,
nnue_nps,
cores,
}
}
pub fn record_batch(&mut self, positions: u64, nodes: u64, nnue_nps: Option<u32>) {
self.stats.total_batches += 1;
self.stats.total_positions += positions;
self.stats.total_nodes += nodes;
if let Some(nnue_nps) = nnue_nps {
self.nnue_nps.record(nnue_nps);
}
if let Some((ref path, ref mut stats_file)) = self.store {
if let Err(err) = self.stats.save_to(stats_file) {
eprintln!("E: Failed to write stats to {path:?}: {err}");
}
}
}
pub fn min_user_backlog(&self) -> Duration {
// Estimate how long this client would take for the next batch of
// 60 positions at 1_450_000 nodes each.
let estimated_batch_seconds = u64::from(min(
7 * 60, // deadline
60 * 1_450_000 / self.cores.get() as u32 / max(1, self.nnue_nps.nps),
));
// Top end clients take no longer than 35 seconds. Its worth joining if
// estimated time < top client time on empty queue + queue wait time.
let top_batch_seconds = 35;
Duration::from_secs(estimated_batch_seconds.saturating_sub(top_batch_seconds))
}
}
#[derive(Clone)]
pub struct NpsRecorder {
pub nps: u32,
pub uncertainty: f64,
}
impl NpsRecorder {
fn new() -> NpsRecorder {
NpsRecorder {
nps: 400_000, // start with an optimistic estimate
uncertainty: 1.0,
}
}
fn record(&mut self, nps: u32) {
let alpha = 0.9;
self.uncertainty *= alpha;
self.nps = (f64::from(self.nps) * alpha + f64::from(nps) * (1.0 - alpha)) as u32;
}
}
impl fmt::Display for NpsRecorder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} knps/core", self.nps / 1000)?;
if self.uncertainty > 0.1 {
write!(f, " ?")?;
}
if self.uncertainty > 0.4 {
write!(f, "?")?;
}
if self.uncertainty > 0.7 {
write!(f, "?")?;
}
Ok(())
}
}