bunsen 0.34.0

bunsen is a batteries included common library for burn
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! # Shard sets on disk
//!
//! A [`ShardSetDescriptor`] bound to a directory, with the disk cache to
//! bring shards in.

use std::{
    fs,
    path::{
        Path,
        PathBuf,
    },
};

use super::{
    ShardId,
    ShardSetDescriptor,
};
#[cfg(feature = "fetch")]
use crate::data::cache::{
    FetchJob,
    FetchPolicy,
    FetchReport,
};
use crate::{
    data::cache::BunsenDiskCache,
    errors::{
        BunsenError,
        BunsenResult,
    },
};

/// The directory under the data dir that holds shard sets, one per name.
pub const SHARDS_DIR: &str = "shards";

/// A shard set bound to a directory.
///
/// Two ways to bind: [`in_cache`](Self::in_cache) puts the set under the
/// cache's data directory, at `<data_dir>/shards/<name>/`;
/// [`at_dir`](Self::at_dir) uses a directory the caller names, where the
/// shard files sit directly. The second is what a `--dataset-dir` flag maps
/// to, and it keeps a tree downloaded before this type existed valid.
pub struct ShardSet<'c> {
    cache: &'c BunsenDiskCache,
    desc: ShardSetDescriptor,
    root: PathBuf,
}

impl<'c> ShardSet<'c> {
    /// Binds `desc` under the cache's data directory.
    pub fn in_cache(
        cache: &'c BunsenDiskCache,
        desc: ShardSetDescriptor,
    ) -> Self {
        let root = cache.data_path(&[SHARDS_DIR], &desc.name);
        Self { cache, desc, root }
    }

    /// Binds `desc` to `dir`, where its shard files sit directly.
    pub fn at_dir(
        cache: &'c BunsenDiskCache,
        desc: ShardSetDescriptor,
        dir: impl Into<PathBuf>,
    ) -> Self {
        Self {
            cache,
            desc,
            root: dir.into(),
        }
    }

    /// The set.
    pub fn descriptor(&self) -> &ShardSetDescriptor {
        &self.desc
    }

    /// The disk cache the shards come in through.
    pub fn cache(&self) -> &BunsenDiskCache {
        self.cache
    }

    /// The directory the shard files sit in.
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Where shard `id` sits, present or not.
    pub fn path(
        &self,
        id: ShardId,
    ) -> PathBuf {
        self.root.join(self.desc.file_name(id))
    }

    /// `true` when shard `id` is on disk.
    pub fn is_cached(
        &self,
        id: ShardId,
    ) -> bool {
        self.path(id).is_file()
    }

    /// The ids of the shards on disk, in order. A root that does not exist
    /// yet holds none.
    ///
    /// # Errors
    /// [`BunsenError::External`] if the root cannot be read.
    pub fn cached_ids(&self) -> BunsenResult<Vec<ShardId>> {
        let entries = match fs::read_dir(&self.root) {
            Ok(entries) => entries,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
            Err(e) => return Err(BunsenError::external(e)),
        };
        let mut ids = Vec::new();
        for entry in entries {
            let entry = entry.map_err(BunsenError::external)?;
            if !entry.file_type().map_err(BunsenError::external)?.is_file() {
                continue;
            }
            let name = entry.file_name();
            if let Some(id) = name.to_str().and_then(|n| self.desc.parse_file_name(n)) {
                ids.push(id);
            }
        }
        ids.sort_unstable();
        Ok(ids)
    }

    /// Shard `id`'s path: on disk already, or fetched when `download` is on.
    ///
    /// # Errors
    /// [`BunsenError::Invalid`] for an id outside the set;
    /// [`BunsenError::ResourceNotFound`] if it is not on disk and `download`
    /// is off; otherwise as [`fetch`](Self::fetch).
    pub fn locate(
        &self,
        id: ShardId,
        download: bool,
    ) -> BunsenResult<PathBuf> {
        self.check(id)?;
        let path = self.path(id);
        if path.is_file() {
            return Ok(path);
        }
        if !download {
            return Err(BunsenError::ResourceNotFound(format!(
                "{}: shard {id} is not at {}",
                self.desc.name,
                path.display()
            )));
        }
        self.fetch(id)
    }

    /// Brings shard `id` in if it is not on disk, and returns its path.
    /// Needs the `fetch` feature; without it a shard not on disk is
    /// [`BunsenError::ResourceNotFound`].
    ///
    /// Mirrors are tried in order, the shard is checked against its digest
    /// when the set is pinned, and the transfer reports to the cache's
    /// observers.
    ///
    /// # Errors
    /// [`BunsenError::Invalid`] for an id outside the set; otherwise
    /// as [`BunsenDiskCache::fetch_from_urls`].
    #[cfg(feature = "fetch")]
    pub fn fetch(
        &self,
        id: ShardId,
    ) -> BunsenResult<PathBuf> {
        self.check(id)?;
        let path = self.path(id);
        if path.is_file() {
            return Ok(path);
        }
        let urls = self.desc.urls(id);
        let urls: Vec<&str> = urls.iter().map(String::as_str).collect();
        self.cache
            .fetch_from_urls(&urls, &path, self.desc.digest(id))?;
        Ok(path)
    }

    /// Without the `fetch` feature there is no network.
    #[cfg(not(feature = "fetch"))]
    pub fn fetch(
        &self,
        id: ShardId,
    ) -> BunsenResult<PathBuf> {
        self.check(id)?;
        let path = self.path(id);
        if path.is_file() {
            return Ok(path);
        }
        Err(BunsenError::ResourceNotFound(format!(
            "{}: shard {id} is not at {}, and fetching needs the `fetch` feature",
            self.desc.name,
            path.display()
        )))
    }

    #[cfg(feature = "fetch")]
    /// The fetch jobs for `ids`, in the order given.
    ///
    /// # Errors
    /// [`BunsenError::Invalid`] for an id outside the set.
    pub fn jobs(
        &self,
        ids: &[ShardId],
    ) -> BunsenResult<Vec<FetchJob>> {
        ids.iter()
            .map(|&id| {
                self.check(id)?;
                let mut job = FetchJob::new(self.desc.urls(id), self.path(id));
                job.sha256 = self.desc.digest(id).map(str::to_string);
                Ok(job)
            })
            .collect()
    }

    #[cfg(feature = "fetch")]
    /// Brings shards `ids` in under `policy`, and reports on each. Shards
    /// already on disk are reported as cached.
    ///
    /// # Errors
    /// [`BunsenError::Invalid`] for an id outside the set. A shard
    /// that fails to land is in the report, not an error here.
    pub fn fetch_many(
        &self,
        ids: &[ShardId],
        policy: &FetchPolicy,
    ) -> BunsenResult<FetchReport> {
        let jobs = self.jobs(ids)?;
        Ok(self.cache.fetch_many(&jobs, policy))
    }

    fn check(
        &self,
        id: ShardId,
    ) -> BunsenResult<()> {
        if self.desc.contains(id) {
            Ok(())
        } else {
            Err(BunsenError::Invalid(format!(
                "{}: shard {id} is out of range; the set has {} shards",
                self.desc.name, self.desc.count
            )))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(feature = "fetch")]
    use crate::data::cache::{
        FetchOutcome,
        OnFailure,
        testing::{
            ABC_SHA256,
            refused_url,
            serve_n,
        },
    };
    use crate::data::{
        cache::BunsenDiskCacheOptions,
        shards::{
            StaticShardDigests,
            StaticShardSetDescriptor,
        },
    };

    fn cache_in(dir: &Path) -> BunsenDiskCache {
        BunsenDiskCache::new(
            BunsenDiskCacheOptions::default()
                .with_cache_dir(Some(dir.join("cache")))
                .with_data_dir(Some(dir.join("data")))
                .without_transfer_observers(),
        )
        .unwrap()
    }

    /// A set whose shards all resolve to the same `serve_n` body.
    fn served(
        base_urls: &'static [&'static str],
        count: usize,
        digests: StaticShardDigests<'static>,
    ) -> ShardSetDescriptor {
        StaticShardSetDescriptor {
            name: "served",
            description: "served off a loopback port",
            license: None,
            origin: None,
            base_urls,
            template: "shard_{index}.bin",
            index_width: 2,
            count,
            format: "bin",
            digests,
        }
        .to_descriptor()
    }

    #[test]
    fn test_roots_and_paths() {
        let dir = tempfile::tempdir().unwrap();
        let cache = cache_in(dir.path());
        let desc = served(&["https://a.example"], 3, StaticShardDigests::Unpinned);

        let set = ShardSet::in_cache(&cache, desc.clone());
        assert_eq!(
            set.root(),
            dir.path().join("data").join("shards").join("served")
        );
        assert_eq!(set.path(ShardId(2)), set.root().join("shard_02.bin"));
        assert_eq!(set.descriptor(), &desc);
        assert_eq!(set.cached_ids().unwrap(), vec![], "no root yet");

        let set = ShardSet::at_dir(&cache, desc, dir.path().join("elsewhere"));
        assert_eq!(set.root(), dir.path().join("elsewhere"));
        assert!(!set.is_cached(ShardId(0)));
        assert!(matches!(
            set.locate(ShardId(0), false),
            Err(BunsenError::ResourceNotFound(_))
        ));
        assert!(matches!(
            set.locate(ShardId(3), true),
            Err(BunsenError::Invalid(_))
        ));
        assert!(matches!(
            set.fetch(ShardId(3)),
            Err(BunsenError::Invalid(_))
        ));
    }

    /// `cached_ids` reads what is on disk through the template, ignoring
    /// partials, other files and directories.
    #[test]
    fn test_cached_ids_reads_the_root() {
        let dir = tempfile::tempdir().unwrap();
        let cache = cache_in(dir.path());
        let set = ShardSet::at_dir(
            &cache,
            served(&["https://a.example"], 10, StaticShardDigests::Unpinned),
            dir.path(),
        );

        for name in [
            "shard_07.bin",
            "shard_02.bin",
            "shard_02.bin.partial",
            "notes.txt",
        ] {
            fs::write(dir.path().join(name), b"x").unwrap();
        }
        fs::create_dir(dir.path().join("shard_05.bin")).unwrap();

        assert_eq!(set.cached_ids().unwrap(), vec![ShardId(2), ShardId(7)]);
        assert!(set.is_cached(ShardId(7)));
        assert!(!set.is_cached(ShardId(5)), "a directory is not a shard");
        assert_eq!(
            set.locate(ShardId(7), false).unwrap(),
            dir.path().join("shard_07.bin")
        );
    }

    /// `fetch` brings one shard in off the first live mirror; `fetch_many`
    /// brings the rest in under the policy and reports the one on disk as
    /// cached.
    #[cfg(feature = "fetch")]
    #[test]
    fn test_fetch_and_fetch_many() {
        let dir = tempfile::tempdir().unwrap();
        let cache = cache_in(dir.path());
        let dead = refused_url("");
        let live = serve_n("", b"abc", 3);
        let bases: &'static [&'static str] = Box::leak(
            vec![
                Box::leak(dead.into_boxed_str()) as &str,
                Box::leak(live.into_boxed_str()) as &str,
            ]
            .into_boxed_slice(),
        );
        let set = ShardSet::in_cache(&cache, served(bases, 3, StaticShardDigests::Unpinned));

        let path = set.fetch(ShardId(1)).unwrap();
        assert_eq!(path, set.path(ShardId(1)));
        assert_eq!(fs::read(&path).unwrap(), b"abc");
        assert_eq!(set.locate(ShardId(1), false).unwrap(), path);

        let ids = set
            .descriptor()
            .select(&[burn::tensor::Slice::from(..)])
            .unwrap();
        let jobs = set.jobs(&ids).unwrap();
        assert_eq!(jobs.len(), 3);
        assert_eq!(jobs[0].urls.len(), 2);
        assert_eq!(jobs[0].sha256, None);

        let policy = FetchPolicy::default()
            .with_parallel(2)
            .with_on_failure(OnFailure::Continue);
        let report = set.fetch_many(&ids, &policy).unwrap();
        assert!(
            matches!(report.outcomes[1], FetchOutcome::Cached(_)),
            "{report}"
        );
        assert!(report.is_complete(), "{report}");
        assert_eq!(
            report.paths().unwrap(),
            ids.iter().map(|&id| set.path(id)).collect::<Vec<_>>()
        );
        assert_eq!(set.cached_ids().unwrap(), ids);
    }

    /// A pinned set checks every shard as it lands: the one whose bytes match
    /// its digest is kept, the one whose do not is refused and leaves nothing,
    /// and the batch reports the same.
    #[cfg(feature = "fetch")]
    #[test]
    fn test_pinned_set_verifies_each_shard() {
        static PINNED: [&str; 2] = [
            ABC_SHA256,
            "0000000000000000000000000000000000000000000000000000000000000000",
        ];
        let dir = tempfile::tempdir().unwrap();
        let cache = cache_in(dir.path());
        let live = serve_n("", b"abc", 3);
        let bases: &'static [&'static str] =
            Box::leak(vec![Box::leak(live.into_boxed_str()) as &str].into_boxed_slice());
        let set = ShardSet::in_cache(&cache, served(bases, 2, StaticShardDigests::Table(&PINNED)));
        assert!(set.descriptor().is_pinned());

        let good = set.fetch(ShardId(0)).unwrap();
        assert_eq!(fs::read(&good).unwrap(), b"abc");

        let bad = set.fetch(ShardId(1));
        assert!(matches!(bad, Err(BunsenError::Invalid(_))), "{bad:?}");
        assert!(!set.path(ShardId(1)).exists());

        let jobs = set.jobs(&[ShardId(0), ShardId(1)]).unwrap();
        assert_eq!(jobs[0].sha256.as_deref(), Some(ABC_SHA256));
        assert_eq!(jobs[1].sha256.as_deref(), Some(PINNED[1]));
        let policy = FetchPolicy::default().with_on_failure(OnFailure::Continue);
        let report = set.fetch_many(&[ShardId(0), ShardId(1)], &policy).unwrap();
        assert!(
            matches!(report.outcomes[0], FetchOutcome::Cached(_)),
            "{report}"
        );
        assert!(
            matches!(report.outcomes[1], FetchOutcome::Failed { .. }),
            "{report}"
        );
        assert_eq!(set.cached_ids().unwrap(), vec![ShardId(0)]);
    }

    /// A set's shards, as a resource map, come in through the pretrained
    /// cache together, and are cached there on the next load.
    #[cfg(feature = "fetch")]
    #[test]
    fn test_a_set_loads_as_a_map_through_the_pretrained_cache() {
        use crate::data::pretrained::{
            PretrainedCache,
            PretrainedCacheOptions,
            Provenance,
        };
        let dir = tempfile::tempdir().unwrap();
        let live = serve_n("", b"abc", 2);
        let bases: &'static [&'static str] =
            Box::leak(vec![Box::leak(live.into_boxed_str()) as &str].into_boxed_slice());
        let desc = served(bases, 2, StaticShardDigests::Unpinned);
        let map = desc.to_resource_map(&[ShardId(0), ShardId(1)]).unwrap();
        assert_eq!(map.keys(), ["shard_00.bin", "shard_01.bin"]);

        let cache = PretrainedCache::new(
            PretrainedCacheOptions::default().with_disk(
                BunsenDiskCacheOptions::default()
                    .with_cache_dir(Some(dir.path().join("cache")))
                    .without_transfer_observers(),
            ),
        )
        .unwrap();
        let loaded = cache.load("shards", &map).unwrap();
        for (key, part) in loaded.iter() {
            assert_eq!(part.provenance, Provenance::Downloaded, "{key}");
            assert_eq!(fs::read(&part.path).unwrap(), b"abc", "{key}");
            assert!(
                part.path
                    .starts_with(dir.path().join("cache").join("pretrained"))
            );
        }
        let again = cache.load("shards", &map).unwrap();
        for (_, part) in again.iter() {
            assert_eq!(part.provenance, Provenance::Cached);
        }
    }
}