Skip to main content

burn_store/pytorch/
store.rs

1//! PyTorch store implementation for saving and loading models in PyTorch format.
2
3use crate::{
4    ApplyResult, KeyRemapper, ModuleSnapshot, ModuleStore, PathFilter, PyTorchToBurnAdapter,
5    bridge, map_indices_contiguous_except,
6};
7
8use alloc::collections::BTreeMap;
9
10use burn_pack::Tensor as PackTensor;
11
12use alloc::format;
13use alloc::string::{String, ToString};
14use alloc::vec::Vec;
15use core::fmt;
16use std::path::PathBuf;
17
18use pytorch_reader::{PytorchError as ReaderError, PytorchReader};
19
20/// Errors that can occur during PyTorch operations.
21#[derive(Debug)]
22pub enum PytorchStoreError {
23    /// Reader error.
24    Reader(ReaderError),
25
26    /// I/O error.
27    Io(std::io::Error),
28
29    /// Tensor not found.
30    TensorNotFound(String),
31
32    /// Validation failed.
33    ValidationFailed(String),
34
35    /// Other error.
36    Other(String),
37}
38
39impl fmt::Display for PytorchStoreError {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        match self {
42            Self::Reader(e) => write!(f, "PyTorch reader error: {}", e),
43            Self::Io(e) => write!(f, "I/O error: {}", e),
44            Self::TensorNotFound(name) => write!(f, "Tensor not found: {}", name),
45            Self::ValidationFailed(msg) => write!(f, "Validation failed: {}", msg),
46            Self::Other(msg) => write!(f, "{}", msg),
47        }
48    }
49}
50
51impl std::error::Error for PytorchStoreError {}
52
53impl From<ReaderError> for PytorchStoreError {
54    fn from(e: ReaderError) -> Self {
55        PytorchStoreError::Reader(e)
56    }
57}
58
59impl From<std::io::Error> for PytorchStoreError {
60    fn from(e: std::io::Error) -> Self {
61        PytorchStoreError::Io(e)
62    }
63}
64
65/// PyTorch store for file-based storage only.
66///
67/// This store allows loading models from PyTorch checkpoint files (.pt/.pth)
68/// with automatic weight transformation using `PyTorchToBurnAdapter`.
69/// Linear weights are automatically transposed and normalization parameters
70/// are renamed (gamma -> weight, beta -> bias).
71///
72/// Note that saving to PyTorch format is not yet supported.
73pub struct PytorchStore {
74    pub(crate) path: PathBuf,
75    pub(crate) filter: PathFilter,
76    pub(crate) remapper: KeyRemapper,
77    pub(crate) validate: bool,
78    pub(crate) allow_partial: bool,
79    pub(crate) top_level_key: Option<String>,
80    pub(crate) skip_enum_variants: bool,
81    /// Enable contiguous mapping of layer indices (default: true)
82    pub(crate) map_indices_contiguous: bool,
83    /// Prefixes whose indices contiguous mapping leaves untouched
84    pub(crate) keep_indices: PathFilter,
85    /// Cached tensors (parsed once, reused until a builder that feeds the cache is called)
86    tensors_cache: Option<BTreeMap<String, PackTensor>>,
87}
88
89impl PytorchStore {
90    /// Create a store for loading from a PyTorch file.
91    ///
92    /// # Arguments
93    /// * `path` - Path to the PyTorch checkpoint file (.pt or .pth)
94    ///
95    /// # Example
96    /// ```rust,no_run
97    /// use burn_store::PytorchStore;
98    ///
99    /// let store = PytorchStore::from_file("model.pth");
100    /// ```
101    pub fn from_file(path: impl Into<PathBuf>) -> Self {
102        Self {
103            path: path.into(),
104            filter: PathFilter::new(),
105            remapper: KeyRemapper::new(),
106            validate: true,
107            allow_partial: false,
108            top_level_key: None,
109            // PyTorch models never include enum variant names in paths
110            skip_enum_variants: true,
111            // Enable contiguous index mapping by default for PyTorch files
112            // This handles nn.Sequential models with gaps in layer indices
113            map_indices_contiguous: true,
114            keep_indices: PathFilter::new(),
115            tensors_cache: None,
116        }
117    }
118
119    /// Set a top-level key to extract tensors from.
120    ///
121    /// PyTorch files often contain nested dictionaries. Use this to extract
122    /// tensors from a specific top-level key like "state_dict" or "model_state_dict".
123    ///
124    /// # Example
125    /// ```rust,no_run
126    /// # use burn_store::PytorchStore;
127    /// let store = PytorchStore::from_file("checkpoint.pth")
128    ///     .with_top_level_key("model_state_dict");
129    /// ```
130    pub fn with_top_level_key(mut self, key: impl Into<String>) -> Self {
131        self.top_level_key = Some(key.into());
132        self.tensors_cache = None;
133        self
134    }
135
136    /// Filter which tensors to load.
137    pub fn filter(mut self, filter: PathFilter) -> Self {
138        self.filter = filter;
139        self
140    }
141
142    /// Add a regex pattern to filter tensors.
143    ///
144    /// Multiple patterns can be added and they work with OR logic.
145    ///
146    /// # Panics
147    ///
148    /// Panics if `pattern` is not a valid regular expression.
149    ///
150    /// # Example
151    /// ```rust,no_run
152    /// # use burn_store::PytorchStore;
153    /// let store = PytorchStore::from_file("model.pth")
154    ///     .with_regex(r"^encoder\..*")  // Match all encoder tensors
155    ///     .with_regex(r".*\.weight$");   // OR match any weight tensors
156    /// ```
157    pub fn with_regex<S: AsRef<str>>(mut self, pattern: S) -> Self {
158        self.filter = self.filter.with_regex(pattern);
159        self
160    }
161
162    /// Add multiple regex patterns to filter tensors.
163    ///
164    /// # Panics
165    ///
166    /// Panics if any pattern is not a valid regular expression.
167    pub fn with_regexes<I, S>(mut self, patterns: I) -> Self
168    where
169        I: IntoIterator<Item = S>,
170        S: AsRef<str>,
171    {
172        self.filter = self.filter.with_regexes(patterns);
173        self
174    }
175
176    /// Add an exact full path to match.
177    ///
178    /// # Example
179    /// ```rust,no_run
180    /// # use burn_store::PytorchStore;
181    /// let store = PytorchStore::from_file("model.pth")
182    ///     .with_full_path("encoder.layer1.weight")
183    ///     .with_full_path("decoder.output.bias");
184    /// ```
185    pub fn with_full_path<S: Into<String>>(mut self, path: S) -> Self {
186        self.filter = self.filter.with_full_path(path);
187        self
188    }
189
190    /// Add multiple exact full paths to match.
191    pub fn with_full_paths<I, S>(mut self, paths: I) -> Self
192    where
193        I: IntoIterator<Item = S>,
194        S: Into<String>,
195    {
196        self.filter = self.filter.with_full_paths(paths);
197        self
198    }
199
200    /// Add a predicate function for custom filtering logic.
201    ///
202    /// The predicate receives the tensor path and container path.
203    ///
204    /// # Example
205    /// ```rust,no_run
206    /// # use burn_store::PytorchStore;
207    /// let store = PytorchStore::from_file("model.pth")
208    ///     .with_predicate(|path, _| path.starts_with("encoder.") || path.ends_with(".bias"));
209    /// ```
210    pub fn with_predicate(mut self, predicate: fn(&str, &str) -> bool) -> Self {
211        self.filter = self.filter.with_predicate(predicate);
212        self
213    }
214
215    /// Add multiple predicate functions.
216    pub fn with_predicates<I>(mut self, predicates: I) -> Self
217    where
218        I: IntoIterator<Item = fn(&str, &str) -> bool>,
219    {
220        self.filter = self.filter.with_predicates(predicates);
221        self
222    }
223
224    /// Set the filter to match all paths (disables filtering).
225    pub fn match_all(mut self) -> Self {
226        self.filter = self.filter.match_all();
227        self
228    }
229
230    /// Remap tensor names during load.
231    pub fn remap(mut self, remapper: KeyRemapper) -> Self {
232        self.remapper = remapper;
233        self.tensors_cache = None;
234        self
235    }
236
237    /// Add a regex pattern to remap tensor names during load.
238    ///
239    /// # Example
240    /// ```rust,no_run
241    /// # use burn_store::PytorchStore;
242    /// let store = PytorchStore::from_file("model.pth")
243    ///     .with_key_remapping(r"^encoder\.", "transformer.encoder.")  // encoder.X -> transformer.encoder.X
244    ///     .with_key_remapping(r"\.gamma$", ".weight");               // X.gamma -> X.weight
245    /// ```
246    pub fn with_key_remapping(
247        mut self,
248        from_pattern: impl AsRef<str>,
249        to_pattern: impl Into<String>,
250    ) -> Self {
251        self.remapper = self
252            .remapper
253            .add_pattern(from_pattern, to_pattern)
254            .expect("Invalid regex pattern");
255        self.tensors_cache = None;
256        self
257    }
258
259    /// Set whether to validate tensors during loading (default: true).
260    pub fn validate(mut self, validate: bool) -> Self {
261        self.validate = validate;
262        self
263    }
264
265    /// Allow partial loading of tensors (continue even if some tensors are missing).
266    pub fn allow_partial(mut self, allow: bool) -> Self {
267        self.allow_partial = allow;
268        self
269    }
270
271    /// Skip enum variant names when matching tensor paths (default: true).
272    ///
273    /// When enabled, tensor paths from PyTorch that don't include enum variants
274    /// can be matched against Burn module paths that do include them.
275    /// For example, PyTorch path "feature.weight" can match Burn path "feature.BaseConv.weight".
276    ///
277    /// This defaults to `true` for PytorchStore since PyTorch models never include
278    /// enum variant names in their parameter paths.
279    ///
280    /// # Example
281    /// ```rust,no_run
282    /// # use burn_store::PytorchStore;
283    /// // Disable enum variant skipping (not typical)
284    /// let store = PytorchStore::from_file("model.pth")
285    ///     .skip_enum_variants(false);
286    /// ```
287    pub fn skip_enum_variants(mut self, skip: bool) -> Self {
288        self.skip_enum_variants = skip;
289        self
290    }
291
292    /// Enable or disable automatic contiguous mapping of layer indices (default: true).
293    ///
294    /// When enabled, non-contiguous numeric indices in tensor paths are renumbered
295    /// to be contiguous. This is useful when loading PyTorch models that have gaps
296    /// in layer numbering, such as when using `nn.Sequential` with mixed layer types
297    /// (e.g., Conv2d layers at indices 0, 2, 4 with ReLU layers at 1, 3, 5).
298    ///
299    /// # Example
300    ///
301    /// With index mapping enabled (default):
302    /// - `fc.0.weight` → `fc.0.weight`
303    /// - `fc.2.weight` → `fc.1.weight` (gap filled)
304    /// - `fc.4.weight` → `fc.2.weight` (gap filled)
305    ///
306    /// # Arguments
307    ///
308    /// * `map` - `true` to enable contiguous index mapping, `false` to disable
309    ///
310    /// # Example
311    /// ```rust,no_run
312    /// # use burn_store::PytorchStore;
313    /// // Disable contiguous index mapping if your model already has contiguous indices
314    /// let store = PytorchStore::from_file("model.pth")
315    ///     .map_indices_contiguous(false);
316    /// ```
317    pub fn map_indices_contiguous(mut self, map: bool) -> Self {
318        self.map_indices_contiguous = map;
319        self.tensors_cache = None;
320        self
321    }
322
323    /// Leave the indices under prefixes matching `pattern` untouched when contiguous
324    /// index mapping is enabled.
325    ///
326    /// The regex is matched against the prefix before a numeric segment (`flows` for
327    /// `flows.2.weight`), so anchor it to keep exactly one list. Can be called multiple
328    /// times. See [`map_indices_contiguous_except`] for the prefix rules.
329    ///
330    /// # Example
331    /// ```rust,no_run
332    /// # use burn_store::PytorchStore;
333    /// // flows.{0,2,4} stay as-is, every other list is still renumbered
334    /// let store = PytorchStore::from_file("model.pth")
335    ///     .map_indices_contiguous_except(r"^model_g\.flow\.flows$");
336    /// ```
337    ///
338    /// # Panics
339    ///
340    /// Panics if `pattern` is not a valid regular expression.
341    pub fn map_indices_contiguous_except<S: AsRef<str>>(mut self, pattern: S) -> Self {
342        self.keep_indices = self.keep_indices.with_regex(pattern);
343        self.tensors_cache = None;
344        self
345    }
346
347    /// Apply remapping to tensors.
348    fn apply_remapping(&self, tensors: Vec<PackTensor>) -> Vec<PackTensor> {
349        if self.remapper.is_empty() {
350            return tensors;
351        }
352
353        let (remapped, _) = self.remapper.remap(tensors);
354        remapped
355    }
356
357    /// Create a PytorchReader for the configured path and options.
358    fn create_reader(&self) -> Result<PytorchReader, PytorchStoreError> {
359        let reader = if let Some(ref key) = self.top_level_key {
360            PytorchReader::with_top_level_key(&self.path, key)?
361        } else {
362            PytorchReader::new(&self.path)?
363        };
364        Ok(reader)
365    }
366}
367
368impl ModuleStore for PytorchStore {
369    type Error = PytorchStoreError;
370
371    fn collect_from<M: ModuleSnapshot>(&mut self, _module: &M) -> Result<(), Self::Error> {
372        // Saving to PyTorch format is not yet supported
373        Err(PytorchStoreError::Other(
374            "Saving to PyTorch format is not yet supported. Use other formats for saving."
375                .to_string(),
376        ))
377    }
378
379    fn apply_to<M: ModuleSnapshot>(&mut self, module: &mut M) -> Result<ApplyResult, Self::Error> {
380        // Get tensors from cache
381        let tensors: Vec<PackTensor> = self.get_all_tensors()?.values().cloned().collect();
382
383        // Get filter (convert to Option for apply)
384        let filter_opt = if self.filter.is_empty() {
385            None
386        } else {
387            Some(self.filter.clone())
388        };
389
390        // Apply to module with PyTorchToBurnAdapter (always used for PyTorch files)
391        // This adapter handles:
392        // - Transposing linear weights from PyTorch format to Burn format
393        // - Renaming normalization parameters (gamma -> weight, beta -> bias)
394        // Filter is applied here during apply, not during cache population
395        let result = module.apply(
396            tensors,
397            filter_opt,
398            Some(Box::new(PyTorchToBurnAdapter)),
399            self.skip_enum_variants,
400        );
401
402        // Validate if needed
403        if self.validate && !result.errors.is_empty() {
404            return Err(PytorchStoreError::ValidationFailed(format!(
405                "Import errors:\n{}",
406                result
407            )));
408        }
409
410        if !self.allow_partial && !result.missing.is_empty() {
411            return Err(PytorchStoreError::TensorNotFound(format!(
412                "\n{}\n\nHint: Use `.allow_partial(true)` on the store to get an `ApplyResult` \
413                with structured missing/error info instead of a hard failure.",
414                result
415            )));
416        }
417
418        Ok(result)
419    }
420
421    fn get_tensor(&mut self, name: &str) -> Result<Option<&PackTensor>, Self::Error> {
422        self.ensure_tensors_cache()?;
423        Ok(self.tensors_cache.as_ref().unwrap().get(name))
424    }
425
426    fn get_all_tensors(&mut self) -> Result<&BTreeMap<String, PackTensor>, Self::Error> {
427        self.ensure_tensors_cache()?;
428        Ok(self.tensors_cache.as_ref().unwrap())
429    }
430
431    fn keys(&mut self) -> Result<Vec<String>, Self::Error> {
432        // Always use the cache to ensure remapping is applied consistently
433        Ok(self.get_all_tensors()?.keys().cloned().collect())
434    }
435}
436
437impl PytorchStore {
438    /// Ensure the tensors cache is populated
439    fn ensure_tensors_cache(&mut self) -> Result<(), PytorchStoreError> {
440        if self.tensors_cache.is_some() {
441            return Ok(());
442        }
443
444        let reader = self.create_reader()?;
445
446        // The reader already names each tensor by its key, so nothing has to be patched up
447        // here beyond wrapping each one for the applier.
448        let mut tensors: Vec<PackTensor> = reader
449            .into_tensors()
450            .into_values()
451            .map(bridge::from_pytorch)
452            .collect();
453
454        // Apply remapping (but NOT filtering - that's done at apply time)
455        tensors = self.apply_remapping(tensors);
456
457        // Apply contiguous index mapping if enabled
458        // This must be done after remapping so that remapped paths are mapped
459        if self.map_indices_contiguous {
460            let (mapped, _) =
461                map_indices_contiguous_except(tensors, |prefix| self.keep_indices.matches(prefix));
462            tensors = mapped;
463        }
464
465        // Build cache as BTreeMap
466        let cache: BTreeMap<String, PackTensor> =
467            tensors.into_iter().map(|t| (t.name.clone(), t)).collect();
468
469        self.tensors_cache = Some(cache);
470        Ok(())
471    }
472}