faultscope-collection 0.2.11

Native logical error-rate collection and scheduling for FaultScope
Documentation
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Instant;

use faultscope_core::{CompiledDemSamplingPlan, NativeDecoderWorker, NpError, NpResult, SmallRng};

use crate::api::{
    task_is_complete, validate_stop_counter_for_tasks, validate_task, validate_unique_strong_ids,
    DemLogicalCollectionOptions, DemLogicalCollectionRunOptions, DemLogicalCollectionStats,
    DemLogicalCollectionTask, LogicalCollectionTask, ValidatedStopCounter,
};
use crate::counting::{
    count_detailed_sampling_result, prepare_dem_count_plan, CountOptions, PreparedDemCountPlan,
};
use crate::scheduler::{batch_seed, next_batch_size, resolve_run_seed, task_run_seed};
use crate::worker_decoder::WorkerDecoderCache;
use crate::worker_executor::{WorkSender, WorkerExecutor};

#[derive(Debug, Clone, PartialEq)]
pub struct DemHotspotCollectionResult {
    pub stats: DemLogicalCollectionStats,
    pub batch_stats: Vec<DemLogicalCollectionStats>,
    pub edge_sensitivities: Vec<f64>,
}

#[derive(Clone)]
struct HotspotWork {
    task_index: usize,
    ordinal: usize,
    shots: usize,
    seed: u64,
    task: Arc<DemLogicalCollectionTask>,
    run_options: Arc<DemLogicalCollectionRunOptions>,
    prepared_plan: Arc<CompiledDemSamplingPlan>,
}

struct HotspotBatchResult {
    task_index: usize,
    ordinal: usize,
    stats: DemLogicalCollectionStats,
    edge_sensitivities: Vec<f64>,
}

struct HotspotCommitState {
    stats: DemLogicalCollectionStats,
    batch_stats: Vec<DemLogicalCollectionStats>,
    sensitivity_sums: Vec<f64>,
    pending: HashMap<usize, HotspotBatchResult>,
    next_ordinal: usize,
    completion_options: DemLogicalCollectionOptions,
    complete: bool,
    started: Option<Instant>,
    completed_seconds: Option<f64>,
}

struct HotspotTaskCursor {
    task: Arc<DemLogicalCollectionTask>,
    seed: u64,
    shots_scheduled: usize,
    next_ordinal: usize,
    prepared_plan: Arc<CompiledDemSamplingPlan>,
}

struct HotspotWorkQueue {
    tasks: Vec<HotspotTaskCursor>,
    next_task: usize,
    total_batches: usize,
    run_options: Arc<DemLogicalCollectionRunOptions>,
}

impl HotspotWorkQueue {
    fn new(
        tasks: Vec<DemLogicalCollectionTask>,
        run_options: Arc<DemLogicalCollectionRunOptions>,
        run_seed: u64,
    ) -> NpResult<Self> {
        let total_batches = tasks.iter().fold(0usize, |total, task| {
            total.saturating_add(fixed_hotspot_batch_count(task.options))
        });
        let tasks = tasks
            .into_iter()
            .map(|task| {
                let seed = task_run_seed(&LogicalCollectionTask::from(task.clone()), run_seed);
                let count_options = CountOptions {
                    postselection_mask: task.postselection_mask.as_deref(),
                    postselected_observables_mask: task.postselected_observables_mask.as_deref(),
                    count_observable_error_combos: run_options.count_observable_error_combos,
                    count_detection_events: run_options.count_detection_events,
                };
                let prepared = prepare_dem_count_plan(
                    &task.sampler,
                    task.decoder
                        .as_deref()
                        .map(|factory| (factory.detector_ids(), factory.batch_formats())),
                    &count_options,
                    true,
                )?;
                let PreparedDemCountPlan::Decoder(prepared_plan) = prepared else {
                    return Err(NpError::new(
                        "hotspot collection requires a decoder sampling plan",
                    ));
                };
                Ok(HotspotTaskCursor {
                    task: Arc::new(task),
                    seed,
                    shots_scheduled: 0,
                    next_ordinal: 0,
                    prepared_plan: Arc::new(prepared_plan),
                })
            })
            .collect::<NpResult<Vec<_>>>()?;
        Ok(Self {
            tasks,
            next_task: 0,
            total_batches,
            run_options,
        })
    }

    fn next_work(
        &mut self,
        states: &[HotspotCommitState],
        worker_count: usize,
    ) -> Option<HotspotWork> {
        for _ in 0..self.tasks.len() {
            let task_index = self.next_task;
            let cursor = &mut self.tasks[task_index];
            if states[task_index].complete
                || cursor.shots_scheduled >= cursor.task.options.max_shots
            {
                self.next_task = (self.next_task + 1) % self.tasks.len();
                continue;
            }
            if cursor.next_ordinal >= states[task_index].next_ordinal + worker_count {
                return None;
            }

            let shots = next_batch_size(cursor.task.options, cursor.shots_scheduled, None);
            let work = HotspotWork {
                task_index,
                ordinal: cursor.next_ordinal,
                shots,
                seed: cursor.seed,
                task: cursor.task.clone(),
                run_options: self.run_options.clone(),
                prepared_plan: cursor.prepared_plan.clone(),
            };
            cursor.shots_scheduled += shots;
            cursor.next_ordinal += 1;
            self.next_task = (self.next_task + 1) % self.tasks.len();
            return Some(work);
        }
        None
    }
}

pub fn collect_dem_hotspot_tasks(
    tasks: Vec<DemLogicalCollectionTask>,
    run_options: DemLogicalCollectionRunOptions,
) -> NpResult<Vec<DemHotspotCollectionResult>> {
    if run_options.num_workers == 0 {
        return Err(NpError::new("num_workers must be positive"));
    }
    let counter_schema = run_options.counter_schema();
    counter_schema.validate()?;
    let logical_tasks = tasks
        .iter()
        .cloned()
        .map(LogicalCollectionTask::from)
        .collect::<Vec<_>>();
    for (task, logical_task) in tasks.iter().zip(&logical_tasks) {
        validate_task(logical_task)?;
        if task.options.max_batch_seconds.is_some() {
            return Err(NpError::new(
                "hotspot collection does not support adaptive batch sizing",
            ));
        }
    }
    let stop_counter = validate_stop_counter_for_tasks(&logical_tasks, &run_options)?;
    validate_unique_strong_ids(&logical_tasks)?;
    if tasks.is_empty() {
        return Ok(Vec::new());
    }

    let run_options = Arc::new(run_options);
    let mut states = tasks
        .iter()
        .zip(&logical_tasks)
        .map(|(task, logical_task)| {
            let stats =
                DemLogicalCollectionStats::empty_for_logical_task(logical_task, counter_schema);
            let complete = task_is_complete(&stats, &task.options, &stop_counter)?;
            Ok(HotspotCommitState {
                stats,
                batch_stats: Vec::new(),
                sensitivity_sums: vec![0.0; task.sampler.edge_count()],
                pending: HashMap::new(),
                next_ordinal: 0,
                completion_options: task.options,
                complete,
                started: None,
                completed_seconds: None,
            })
        })
        .collect::<NpResult<Vec<_>>>()?;
    if states.iter().all(|state| state.complete) {
        return states.into_iter().map(finish_hotspot_state).collect();
    }
    let run_seed = resolve_run_seed(run_options.seed);
    let mut work_queue = HotspotWorkQueue::new(tasks, run_options.clone(), run_seed)?;
    let worker_count = run_options.num_workers.min(work_queue.total_batches).max(1);
    let executor = WorkerExecutor::new(
        worker_count,
        WorkerDecoderCache::new,
        |work, decoder_cache, _| {
            decoder_cache
                .resolve(work.task_index, work.task.decoder.as_ref())
                .and_then(|decoder| run_hotspot_batch(work, decoder))
        },
        hotspot_worker_context,
        hotspot_worker_context,
    );
    let mut in_flight = 0usize;
    schedule_hotspot_work(
        &mut work_queue,
        &mut states,
        worker_count,
        executor.sender(),
        &mut in_flight,
    )?;
    let mut first_error = None;
    executor.drain(
        &mut in_flight,
        &mut first_error,
        "hotspot collection worker result channel closed",
        |_| true,
        |result, work_tx, in_flight| {
            commit_hotspot_result(result, &mut states, &stop_counter)?;
            schedule_hotspot_work(
                &mut work_queue,
                &mut states,
                worker_count,
                work_tx,
                in_flight,
            )
        },
        |_| {},
    );
    executor.finish(first_error, "hotspot collection worker thread panicked")?;

    states.into_iter().map(finish_hotspot_state).collect()
}

fn schedule_hotspot_work(
    work_queue: &mut HotspotWorkQueue,
    states: &mut [HotspotCommitState],
    worker_count: usize,
    work_tx: &WorkSender<HotspotWork>,
    in_flight: &mut usize,
) -> NpResult<()> {
    while *in_flight < worker_count {
        let Some(work) = work_queue.next_work(states, worker_count) else {
            break;
        };
        if states[work.task_index].started.is_none() {
            states[work.task_index].started = Some(Instant::now());
        }
        work_tx
            .send(work)
            .map_err(|_| NpError::new("hotspot collection worker channel closed"))?;
        *in_flight += 1;
    }
    Ok(())
}

fn fixed_hotspot_batch_count(options: crate::api::DemLogicalCollectionOptions) -> usize {
    if options.max_shots == 0 {
        return 0;
    }
    let first_batch = next_batch_size(options, 0, None);
    let regular_batch = options
        .batch_size
        .min(options.max_batch_size.unwrap_or(options.batch_size))
        .max(1);
    1 + (options.max_shots - first_batch).div_ceil(regular_batch)
}

fn run_hotspot_batch(
    work: &HotspotWork,
    decoder: Option<&mut dyn NativeDecoderWorker>,
) -> NpResult<HotspotBatchResult> {
    let started = Instant::now();
    let mut rng = SmallRng::new(batch_seed(work.seed, 0, work.ordinal));
    let sampled = work
        .prepared_plan
        .run_sampling_result_with_rng(work.shots, &mut rng)?;
    let count_options = CountOptions {
        postselection_mask: work.task.postselection_mask.as_deref(),
        postselected_observables_mask: work.task.postselected_observables_mask.as_deref(),
        count_observable_error_combos: work.run_options.count_observable_error_combos,
        count_detection_events: work.run_options.count_detection_events,
    };
    let detailed =
        count_detailed_sampling_result(&work.task.sampler, &sampled, decoder, &count_options)?;
    let trace = sampled
        .attribution()
        .ok_or_else(|| NpError::new("hotspot sampling plan did not record an attribution trace"))?;
    let estimate =
        work.task
            .sampler
            .estimate_from_attribution(trace, &detailed.loss_mask, None, 0)?;
    let stats = DemLogicalCollectionStats {
        task_id: work.task.task_id.clone(),
        strong_id: work.task.strong_id.clone(),
        decoder: work.task.decoder_name.clone(),
        metadata_json: work.task.metadata_json.clone(),
        shots: detailed.stats.shots,
        errors: detailed.stats.errors,
        discards: detailed.stats.discards,
        seconds: started.elapsed().as_secs_f64(),
        counter_schema: work.run_options.counter_schema(),
        custom_counts: detailed.stats.custom_counts,
    };
    Ok(HotspotBatchResult {
        task_index: work.task_index,
        ordinal: work.ordinal,
        stats,
        edge_sensitivities: estimate.edge_sensitivities,
    })
}

fn hotspot_worker_context(work: &HotspotWork) -> String {
    let backend = work
        .task
        .decoder
        .as_deref()
        .map(|factory| factory.name())
        .unwrap_or("none");
    format!(
        "hotspot collection worker failed while processing task key {} (`{}`) with backend `{backend}`",
        work.task_index, work.task.task_id
    )
}

fn commit_hotspot_result(
    result: HotspotBatchResult,
    states: &mut [HotspotCommitState],
    stop_counter: &ValidatedStopCounter,
) -> NpResult<()> {
    let state = states
        .get_mut(result.task_index)
        .ok_or_else(|| NpError::new("hotspot collection returned invalid task index"))?;
    if state.complete {
        return Ok(());
    }
    state.pending.insert(result.ordinal, result);
    while let Some(batch) = state.pending.remove(&state.next_ordinal) {
        if state.sensitivity_sums.is_empty() {
            state.sensitivity_sums = vec![0.0; batch.edge_sensitivities.len()];
        }
        if batch.edge_sensitivities.len() != state.sensitivity_sums.len() {
            return Err(NpError::new(
                "hotspot collection edge sensitivity shape changed between batches",
            ));
        }
        let shots = batch.stats.shots;
        state.stats.add_assign_checked(&batch.stats)?;
        for (sum, sensitivity) in state
            .sensitivity_sums
            .iter_mut()
            .zip(batch.edge_sensitivities)
        {
            *sum += sensitivity * shots as f64;
        }
        state.batch_stats.push(batch.stats);
        state.next_ordinal += 1;
        if task_is_complete(&state.stats, &state.completion_options, stop_counter)? {
            state.complete = true;
            state.completed_seconds = state.started.map(|started| started.elapsed().as_secs_f64());
            break;
        }
    }
    Ok(())
}

fn finish_hotspot_state(mut state: HotspotCommitState) -> NpResult<DemHotspotCollectionResult> {
    if !state.complete {
        return Err(NpError::new("hotspot collection did not complete a task"));
    }
    state.stats.seconds = state.completed_seconds.unwrap_or(0.0);
    let edge_sensitivities = if state.stats.shots == 0 {
        state.sensitivity_sums
    } else {
        state
            .sensitivity_sums
            .into_iter()
            .map(|sum| sum / state.stats.shots as f64)
            .collect()
    };
    Ok(DemHotspotCollectionResult {
        stats: state.stats,
        batch_stats: state.batch_stats,
        edge_sensitivities,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::api::DemLogicalCollectionOptions;

    #[test]
    fn lazy_hotspot_batch_count_matches_eager_sequence() {
        let cases = [
            DemLogicalCollectionOptions {
                max_shots: 0,
                min_shots: 0,
                max_errors: None,
                batch_size: 100,
                seed: None,
                start_batch_size: None,
                max_batch_size: None,
                max_batch_seconds: None,
            },
            DemLogicalCollectionOptions {
                max_shots: 1_001,
                min_shots: 0,
                max_errors: None,
                batch_size: 128,
                seed: Some(7),
                start_batch_size: Some(17),
                max_batch_size: Some(64),
                max_batch_seconds: None,
            },
            DemLogicalCollectionOptions {
                max_shots: 5_000_000,
                min_shots: 0,
                max_errors: None,
                batch_size: 100,
                seed: None,
                start_batch_size: Some(1),
                max_batch_size: Some(1_000),
                max_batch_seconds: None,
            },
        ];

        for options in cases {
            let mut shots_done = 0usize;
            let mut expected = 0usize;
            while shots_done < options.max_shots {
                shots_done += next_batch_size(options, shots_done, None);
                expected += 1;
            }
            assert_eq!(fixed_hotspot_batch_count(options), expected);
        }
    }
}