Skip to main content

fuel_formats/
pickle.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Python pickle parser — minimum subset needed to read PyTorch
3//! `.pth` checkpoint files.
4//!
5//! This is **not** a general-purpose pickle parser. It implements just
6//! enough of [protocol 2](https://docs.python.org/3/library/pickle.html)
7//! to extract `state_dict`-style tensor metadata from PyTorch
8//! checkpoints. The recognized object types are hard-coded around
9//! `torch._utils._rebuild_tensor_v2` and friends.
10//!
11//! The Tensor-construction layer (`PthTensors::get`, `read_all`,
12//! `read_all_with_key`) lives in `fuel-core/src/pickle.rs` since it
13//! materializes `Tensor`s from raw storage bytes; this module
14//! produces the metadata index.
15
16use std::collections::HashMap;
17use std::io::BufRead;
18
19use byteorder::{LittleEndian, ReadBytesExt};
20use fuel_ir::{Context, DType, Error as E, Layout, Result, Shape, bail};
21
22const VERBOSE: bool = false;
23
24/// Subset of Python pickle opcodes recognized by this reader.
25///
26/// Reference: <https://docs.juliahub.com/Pickle/LAUNc/0.1.0/opcode/>.
27/// CPython opcode reference:
28/// <https://github.com/python/cpython/blob/ed25f097160b5cbb0c9a1f9a746d2f1bbc96515a/Lib/pickletools.py#L2123>
29#[repr(u8)]
30#[derive(Debug, Eq, PartialEq, Clone)]
31pub enum OpCode {
32    Proto = 0x80,
33    Global = b'c',
34    BinPut = b'q',
35    LongBinPut = b'r',
36    EmptyTuple = b')',
37    Reduce = b'R',
38    Mark = b'(',
39    BinUnicode = b'X',
40    BinInt = b'J',
41    Tuple = b't',
42    BinPersId = b'Q',
43    BinInt1 = b'K',
44    BinInt2 = b'M',
45    Tuple1 = 0x85,
46    Tuple2 = 0x86,
47    Tuple3 = 0x87,
48    NewTrue = 0x88,
49    NewFalse = 0x89,
50    None = b'N',
51    BinGet = b'h',
52    LongBinGet = b'j',
53    SetItem = b's',
54    SetItems = b'u',
55    EmptyDict = b'}',
56    Dict = b'd',
57    Build = b'b',
58    Stop = b'.',
59    NewObj = 0x81,
60    EmptyList = b']',
61    BinFloat = b'G',
62    Append = b'a',
63    Appends = b'e',
64    Long1 = 0x8a,
65}
66
67impl TryFrom<u8> for OpCode {
68    type Error = u8;
69    fn try_from(value: u8) -> std::result::Result<Self, Self::Error> {
70        match value {
71            0x80 => Ok(Self::Proto),
72            b'c' => Ok(Self::Global),
73            b'q' => Ok(Self::BinPut),
74            b'r' => Ok(Self::LongBinPut),
75            b')' => Ok(Self::EmptyTuple),
76            b'R' => Ok(Self::Reduce),
77            b'(' => Ok(Self::Mark),
78            b'X' => Ok(Self::BinUnicode),
79            b'J' => Ok(Self::BinInt),
80            b't' => Ok(Self::Tuple),
81            b'Q' => Ok(Self::BinPersId),
82            b'K' => Ok(Self::BinInt1),
83            b'M' => Ok(Self::BinInt2),
84            b'N' => Ok(Self::None),
85            0x85 => Ok(Self::Tuple1),
86            0x86 => Ok(Self::Tuple2),
87            0x87 => Ok(Self::Tuple3),
88            0x88 => Ok(Self::NewTrue),
89            0x89 => Ok(Self::NewFalse),
90            b'h' => Ok(Self::BinGet),
91            b'j' => Ok(Self::LongBinGet),
92            b's' => Ok(Self::SetItem),
93            b'u' => Ok(Self::SetItems),
94            b'}' => Ok(Self::EmptyDict),
95            b'd' => Ok(Self::EmptyDict),
96            b'b' => Ok(Self::Build),
97            b'.' => Ok(Self::Stop),
98            0x81 => Ok(Self::NewObj),
99            b']' => Ok(Self::EmptyList),
100            b'G' => Ok(Self::BinFloat),
101            b'a' => Ok(Self::Append),
102            b'e' => Ok(Self::Appends),
103            0x8a => Ok(Self::Long1),
104            value => Err(value),
105        }
106    }
107}
108
109fn read_to_newline<R: BufRead>(r: &mut R) -> Result<Vec<u8>> {
110    let mut data: Vec<u8> = Vec::with_capacity(32);
111    r.read_until(b'\n', &mut data)?;
112    data.pop();
113    if data.last() == Some(&b'\r') {
114        data.pop();
115    }
116    Ok(data)
117}
118
119/// A deserialized Python object encountered during pickle parsing.
120#[derive(Debug, Clone, PartialEq)]
121pub enum Object {
122    Class {
123        module_name: String,
124        class_name: String,
125    },
126    Int(i32),
127    Long(i64),
128    Float(f64),
129    Unicode(String),
130    Bool(bool),
131    None,
132    Tuple(Vec<Object>),
133    List(Vec<Object>),
134    Mark,
135    Dict(Vec<(Object, Object)>),
136    Reduce {
137        callable: Box<Object>,
138        args: Box<Object>,
139    },
140    Build {
141        callable: Box<Object>,
142        args: Box<Object>,
143    },
144    PersistentLoad(Box<Object>),
145}
146
147type OResult<T> = std::result::Result<T, Object>;
148
149impl Object {
150    /// The text of a `Unicode` object; otherwise returns the object unchanged as the error.
151    pub fn unicode(self) -> OResult<String> {
152        match self {
153            Self::Unicode(t) => Ok(t),
154            _ => Err(self),
155        }
156    }
157
158    /// The `(callable, args)` pair of a `Reduce` object; otherwise returns the object unchanged as the error.
159    pub fn reduce(self) -> OResult<(Self, Self)> {
160        match self {
161            Self::Reduce { callable, args } => Ok((*callable, *args)),
162            _ => Err(self),
163        }
164    }
165
166    /// `Ok(())` for the `None` object; otherwise returns the object unchanged as the error.
167    pub fn none(self) -> OResult<()> {
168        match self {
169            Self::None => Ok(()),
170            _ => Err(self),
171        }
172    }
173
174    /// The wrapped object of a `PersistentLoad`; otherwise returns the object unchanged as the error.
175    pub fn persistent_load(self) -> OResult<Self> {
176        match self {
177            Self::PersistentLoad(t) => Ok(*t),
178            _ => Err(self),
179        }
180    }
181
182    /// The value of a `Bool` object; otherwise returns the object unchanged as the error.
183    pub fn bool(self) -> OResult<bool> {
184        match self {
185            Self::Bool(t) => Ok(t),
186            _ => Err(self),
187        }
188    }
189
190    /// The value of an `Int` object; otherwise returns the object unchanged as the error.
191    pub fn int(self) -> OResult<i32> {
192        match self {
193            Self::Int(t) => Ok(t),
194            _ => Err(self),
195        }
196    }
197
198    /// The value of an `Int` (widened) or `Long` object; otherwise returns the object unchanged as the error.
199    pub fn int_or_long(self) -> OResult<i64> {
200        match self {
201            Self::Int(t) => Ok(t as i64),
202            Self::Long(t) => Ok(t),
203            _ => Err(self),
204        }
205    }
206
207    /// The elements of a `Tuple` object; otherwise returns the object unchanged as the error.
208    pub fn tuple(self) -> OResult<Vec<Self>> {
209        match self {
210            Self::Tuple(t) => Ok(t),
211            _ => Err(self),
212        }
213    }
214
215    /// The key/value pairs of a `Dict` object; otherwise returns the object unchanged as the error.
216    pub fn dict(self) -> OResult<Vec<(Self, Self)>> {
217        match self {
218            Self::Dict(t) => Ok(t),
219            _ => Err(self),
220        }
221    }
222
223    /// The `(module_name, class_name)` of a `Class` object; otherwise returns the object unchanged as the error.
224    pub fn class(self) -> OResult<(String, String)> {
225        match self {
226            Self::Class {
227                module_name,
228                class_name,
229            } => Ok((module_name, class_name)),
230            _ => Err(self),
231        }
232    }
233
234    /// Attempt to interpret this object as a PyTorch tensor reconstruction call and extract
235    /// its [`TensorInfo`]. Returns `Ok(None)` if the object does not match the expected
236    /// pattern (e.g. it is not a `_rebuild_tensor_v2` call).
237    pub fn into_tensor_info(
238        self,
239        name: Self,
240        dir_name: &std::path::Path,
241    ) -> Result<Option<TensorInfo>> {
242        let name = match name.unicode() {
243            Ok(name) => name,
244            Err(_) => return Ok(None),
245        };
246        let (callable, args) = match self.reduce() {
247            Ok(callable_args) => callable_args,
248            _ => return Ok(None),
249        };
250        let (callable, args) = match callable {
251            Object::Class {
252                module_name,
253                class_name,
254            } if module_name == "torch._tensor" && class_name == "_rebuild_from_type_v2" => {
255                let mut args = args.tuple()?;
256                let callable = args.remove(0);
257                let args = args.remove(1);
258                (callable, args)
259            }
260            Object::Class {
261                module_name,
262                class_name,
263            } if module_name == "torch._utils" && class_name == "_rebuild_parameter" => {
264                let mut args = args.tuple()?;
265                args.remove(0).reduce()?
266            }
267            _ => (callable, args),
268        };
269        match callable {
270            Object::Class {
271                module_name,
272                class_name,
273            } if module_name == "torch._utils" && class_name == "_rebuild_tensor_v2" => {}
274            _ => return Ok(None),
275        };
276        let (layout, dtype, file_path, storage_size) = rebuild_args(args)?;
277        Ok(Some(TensorInfo {
278            name,
279            dtype,
280            layout,
281            path: format!("{}/{}", dir_name.to_string_lossy(), file_path),
282            storage_size,
283        }))
284    }
285}
286
287impl TryFrom<Object> for String {
288    type Error = Object;
289    fn try_from(value: Object) -> std::result::Result<Self, Self::Error> {
290        match value {
291            Object::Unicode(s) => Ok(s),
292            other => Err(other),
293        }
294    }
295}
296
297impl TryFrom<Object> for usize {
298    type Error = Object;
299    fn try_from(value: Object) -> std::result::Result<Self, Self::Error> {
300        match value {
301            Object::Int(s) if s >= 0 => Ok(s as usize),
302            other => Err(other),
303        }
304    }
305}
306
307impl<T: TryFrom<Object, Error = Object>> TryFrom<Object> for Vec<T> {
308    type Error = Object;
309    fn try_from(value: Object) -> std::result::Result<Self, Self::Error> {
310        match value {
311            Object::Tuple(values) => values
312                .into_iter()
313                .map(|v| T::try_from(v))
314                .collect::<std::result::Result<Vec<T>, Self::Error>>(),
315            other => Err(other),
316        }
317    }
318}
319
320/// The pickle virtual machine's execution stack.
321#[derive(Debug)]
322pub struct Stack {
323    stack: Vec<Object>,
324    memo: HashMap<u32, Object>,
325}
326
327impl Stack {
328    /// A stack with no objects and an empty memo.
329    pub fn empty() -> Self {
330        Self {
331            stack: Vec::with_capacity(512),
332            memo: HashMap::new(),
333        }
334    }
335
336    /// The objects currently on the stack, bottom first.
337    pub fn stack(&self) -> &[Object] {
338        self.stack.as_slice()
339    }
340
341    /// Read and execute pickle opcodes from `r` until a `STOP` opcode is encountered.
342    pub fn read_loop<R: BufRead>(&mut self, r: &mut R) -> Result<()> {
343        loop {
344            if self.read(r)? {
345                break;
346            }
347        }
348        Ok(())
349    }
350
351    /// Consume the stack and return the single top-level object.
352    pub fn finalize(mut self) -> Result<Object> {
353        self.pop()
354    }
355
356    fn push(&mut self, obj: Object) {
357        self.stack.push(obj)
358    }
359
360    fn pop(&mut self) -> Result<Object> {
361        match self.stack.pop() {
362            None => bail!("unexpected empty stack"),
363            Some(obj) => Ok(obj),
364        }
365    }
366
367    // https://docs.juliahub.com/Pickle/LAUNc/0.1.0/opcode/#Pickle.OpCodes.BUILD
368    fn build(&mut self) -> Result<()> {
369        let args = self.pop()?;
370        let obj = self.pop()?;
371        let obj = match (obj, args) {
372            (Object::Dict(mut obj), Object::Dict(mut args)) => {
373                obj.append(&mut args);
374                Object::Dict(obj)
375            }
376            (obj, args) => Object::Build {
377                callable: Box::new(obj),
378                args: Box::new(args),
379            },
380        };
381        self.push(obj);
382        Ok(())
383    }
384
385    fn reduce(&mut self) -> Result<()> {
386        let args = self.pop()?;
387        let callable = self.pop()?;
388        #[allow(clippy::single_match)]
389        let reduced = match &callable {
390            Object::Class {
391                module_name,
392                class_name,
393            } => {
394                if module_name == "collections"
395                    && (class_name == "OrderedDict" || class_name == "defaultdict")
396                {
397                    // TODO: have a separate ordered dict and a separate default dict.
398                    Some(Object::Dict(vec![]))
399                } else {
400                    None
401                }
402            }
403            _ => None,
404        };
405        let reduced = reduced.unwrap_or_else(|| Object::Reduce {
406            callable: Box::new(callable),
407            args: Box::new(args),
408        });
409        self.push(reduced);
410        Ok(())
411    }
412
413    fn last(&mut self) -> Result<&mut Object> {
414        match self.stack.last_mut() {
415            None => bail!("unexpected empty stack"),
416            Some(obj) => Ok(obj),
417        }
418    }
419
420    fn memo_get(&self, id: u32) -> Result<Object> {
421        match self.memo.get(&id) {
422            None => bail!("missing object in memo {id}"),
423            Some(obj) => Ok(obj.clone()),
424        }
425    }
426
427    fn memo_put(&mut self, id: u32) -> Result<()> {
428        let obj = self.last()?.clone();
429        self.memo.insert(id, obj);
430        Ok(())
431    }
432
433    fn persistent_load(&self, id: Object) -> Result<Object> {
434        Ok(Object::PersistentLoad(Box::new(id)))
435    }
436
437    fn new_obj(&self, class: Object, args: Object) -> Result<Object> {
438        Ok(Object::Reduce {
439            callable: Box::new(class),
440            args: Box::new(args),
441        })
442    }
443
444    fn pop_to_marker(&mut self) -> Result<Vec<Object>> {
445        let mut mark_idx = None;
446        for (idx, obj) in self.stack.iter().enumerate().rev() {
447            if obj == &Object::Mark {
448                mark_idx = Some(idx);
449                break;
450            }
451        }
452        match mark_idx {
453            Some(mark_idx) => {
454                let objs = self.stack.split_off(mark_idx + 1);
455                self.stack.pop();
456                Ok(objs)
457            }
458            None => bail!("marker object not found"),
459        }
460    }
461
462    /// Read and execute a single pickle opcode. Returns `Ok(true)` when a `STOP` opcode is
463    /// encountered, indicating the stream is complete.
464    pub fn read<R: BufRead>(&mut self, r: &mut R) -> Result<bool> {
465        let op_code = match OpCode::try_from(r.read_u8()?) {
466            Ok(op_code) => op_code,
467            Err(op_code) => bail!("unknown op-code {op_code}"),
468        };
469        match op_code {
470            OpCode::Proto => {
471                let version = r.read_u8()?;
472                if VERBOSE {
473                    println!("proto {version}");
474                }
475            }
476            OpCode::Global => {
477                let module_name = read_to_newline(r)?;
478                let class_name = read_to_newline(r)?;
479                let module_name = String::from_utf8_lossy(&module_name).to_string();
480                let class_name = String::from_utf8_lossy(&class_name).to_string();
481                self.push(Object::Class {
482                    module_name,
483                    class_name,
484                })
485            }
486            OpCode::BinInt1 => {
487                let arg = r.read_u8()?;
488                self.push(Object::Int(arg as i32))
489            }
490            OpCode::BinInt2 => {
491                let arg = r.read_u16::<LittleEndian>()?;
492                self.push(Object::Int(arg as i32))
493            }
494            OpCode::BinInt => {
495                let arg = r.read_i32::<LittleEndian>()?;
496                self.push(Object::Int(arg))
497            }
498            OpCode::BinFloat => {
499                // Floats are encoded big-endian whereas int types use little-endian.
500                // https://github.com/python/cpython/blob/0c80da4c14d904a367968955544dd6ae58c8101c/Lib/pickletools.py#L855
501                // https://github.com/pytorch/pytorch/blob/372d078f361e726bb4ac0884ac334b04c58179ef/torch/_weights_only_unpickler.py#L243
502                let arg = r.read_f64::<byteorder::BigEndian>()?;
503                self.push(Object::Float(arg))
504            }
505            OpCode::BinUnicode => {
506                let len = r.read_u32::<LittleEndian>()?;
507                let mut data = vec![0u8; len as usize];
508                r.read_exact(&mut data)?;
509                let data = String::from_utf8(data).map_err(E::wrap)?;
510                self.push(Object::Unicode(data))
511            }
512            OpCode::BinPersId => {
513                let id = self.pop()?;
514                let obj = self.persistent_load(id)?;
515                self.push(obj)
516            }
517            OpCode::Tuple => {
518                let objs = self.pop_to_marker()?;
519                self.push(Object::Tuple(objs))
520            }
521            OpCode::Tuple1 => {
522                let obj = self.pop()?;
523                self.push(Object::Tuple(vec![obj]))
524            }
525            OpCode::Tuple2 => {
526                let obj2 = self.pop()?;
527                let obj1 = self.pop()?;
528                self.push(Object::Tuple(vec![obj1, obj2]))
529            }
530            OpCode::Tuple3 => {
531                let obj3 = self.pop()?;
532                let obj2 = self.pop()?;
533                let obj1 = self.pop()?;
534                self.push(Object::Tuple(vec![obj1, obj2, obj3]))
535            }
536            OpCode::NewTrue => self.push(Object::Bool(true)),
537            OpCode::NewFalse => self.push(Object::Bool(false)),
538            OpCode::Append => {
539                let value = self.pop()?;
540                let pylist = self.last()?;
541                if let Object::List(d) = pylist {
542                    d.push(value)
543                } else {
544                    bail!("expected a list, got {pylist:?}")
545                }
546            }
547            OpCode::Appends => {
548                let objs = self.pop_to_marker()?;
549                let pylist = self.last()?;
550                if let Object::List(d) = pylist {
551                    d.extend(objs)
552                } else {
553                    bail!("expected a list, got {pylist:?}")
554                }
555            }
556            OpCode::SetItem => {
557                let value = self.pop()?;
558                let key = self.pop()?;
559                let pydict = self.last()?;
560                if let Object::Dict(d) = pydict {
561                    d.push((key, value))
562                } else {
563                    bail!("expected a dict, got {pydict:?}")
564                }
565            }
566            OpCode::SetItems => {
567                let mut objs = self.pop_to_marker()?;
568                let pydict = self.last()?;
569                if let Object::Dict(d) = pydict {
570                    if objs.len() % 2 != 0 {
571                        bail!("setitems: not an even number of objects")
572                    }
573                    while let Some(value) = objs.pop() {
574                        let key = objs.pop().context("empty objs")?;
575                        d.push((key, value))
576                    }
577                } else {
578                    bail!("expected a dict, got {pydict:?}")
579                }
580            }
581            OpCode::None => self.push(Object::None),
582            OpCode::Stop => return Ok(true),
583            OpCode::Build => self.build()?,
584            OpCode::EmptyDict => self.push(Object::Dict(vec![])),
585            OpCode::Dict => {
586                let mut objs = self.pop_to_marker()?;
587                let mut pydict = vec![];
588                if objs.len() % 2 != 0 {
589                    bail!("setitems: not an even number of objects")
590                }
591                while let Some(value) = objs.pop() {
592                    let key = objs.pop().context("empty objs")?;
593                    pydict.push((key, value))
594                }
595                self.push(Object::Dict(pydict))
596            }
597            OpCode::Mark => self.push(Object::Mark),
598            OpCode::Reduce => self.reduce()?,
599            OpCode::EmptyTuple => self.push(Object::Tuple(vec![])),
600            OpCode::EmptyList => self.push(Object::List(vec![])),
601            OpCode::BinGet => {
602                let arg = r.read_u8()?;
603                let obj = self.memo_get(arg as u32)?;
604                self.push(obj)
605            }
606            OpCode::LongBinGet => {
607                let arg = r.read_u32::<LittleEndian>()?;
608                let obj = self.memo_get(arg)?;
609                self.push(obj)
610            }
611            OpCode::BinPut => {
612                let arg = r.read_u8()?;
613                self.memo_put(arg as u32)?
614            }
615            OpCode::LongBinPut => {
616                let arg = r.read_u32::<LittleEndian>()?;
617                self.memo_put(arg)?
618            }
619            OpCode::NewObj => {
620                let args = self.pop()?;
621                let class = self.pop()?;
622                let obj = self.new_obj(class, args)?;
623                self.push(obj)
624            }
625            OpCode::Long1 => {
626                let n_bytes = r.read_u8()?;
627                let mut v = 0;
628                // Decode the next n bytes in little endian
629                for i in 0..n_bytes {
630                    v |= (r.read_u8()? as i64) << (i * 8);
631                }
632                self.push(Object::Long(v))
633            }
634        }
635        Ok(false)
636    }
637}
638
639impl From<Object> for E {
640    fn from(value: Object) -> Self {
641        E::Msg(format!("conversion error on {value:?}"))
642    }
643}
644
645// https://github.com/pytorch/pytorch/blob/4eac43d046ded0f0a5a5fa8db03eb40f45bf656e/torch/_utils.py#L198
646// Arguments: storage, storage_offset, size, stride, requires_grad, backward_hooks
647fn rebuild_args(args: Object) -> Result<(Layout, DType, String, usize)> {
648    let mut args = args.tuple()?;
649    let stride_usize = Vec::<usize>::try_from(args.remove(3))?;
650    let stride: fuel_ir::StrideVec = stride_usize.iter().map(|&s| s as isize).collect();
651    let size = Vec::<usize>::try_from(args.remove(2))?;
652    let offset = args.remove(1).int_or_long()? as usize;
653    let storage = args.remove(0).persistent_load()?;
654    let mut storage = storage.tuple()?;
655    let storage_size = storage.remove(4).int_or_long()? as usize;
656    let path = storage.remove(2).unicode()?;
657    let (_module_name, class_name) = storage.remove(1).class()?;
658    let dtype = match class_name.as_str() {
659        "FloatStorage" => DType::F32,
660        "DoubleStorage" => DType::F64,
661        "HalfStorage" => DType::F16,
662        "BFloat16Storage" => DType::BF16,
663        "ByteStorage" => DType::U8,
664        "LongStorage" => DType::I64,
665        other => bail!("unsupported storage type {other}"),
666    };
667    let layout = Layout::new(Shape::from(size), stride, offset * dtype.size_in_bytes());
668    Ok((layout, dtype, path, storage_size))
669}
670
671/// Metadata describing a single tensor inside a PyTorch `.pth` archive.
672///
673/// Produced by [`read_pth_tensor_info`]. The `path` field contains the
674/// zip-internal path to the raw data file — fuel-core's `PthTensors`
675/// uses it to materialize the actual `Tensor`.
676#[derive(Debug, Clone)]
677pub struct TensorInfo {
678    /// The parameter name (e.g. `"model.layers.0.weight"`).
679    pub name: String,
680    /// The element data type.
681    pub dtype: DType,
682    /// Shape, stride, and storage offset.
683    pub layout: Layout,
684    /// Zip-internal path to the raw storage file.
685    pub path: String,
686    /// Number of elements in the storage (may be larger than the tensor if storage is shared).
687    pub storage_size: usize,
688}
689
690/// Parse PyTorch `.pth` archive metadata, returning one [`TensorInfo`]
691/// per tensor in the embedded `state_dict`.
692///
693/// Walks every `data.pkl` entry in the zip archive, runs the pickle VM
694/// to recover the top-level Python object, optionally drills into a
695/// `key` (e.g. `"state_dict"`), then extracts a [`TensorInfo`] from
696/// each `_rebuild_tensor_v2` call.
697pub fn read_pth_tensor_info<P: AsRef<std::path::Path>>(
698    file: P,
699    verbose: bool,
700    key: Option<&str>,
701) -> Result<Vec<TensorInfo>> {
702    let file = std::fs::File::open(file)?;
703    let zip_reader = std::io::BufReader::new(file);
704    let mut zip = zip::ZipArchive::new(zip_reader)?;
705    let zip_file_names = zip
706        .file_names()
707        .map(|f| f.map(|name| name.to_string()))
708        .collect::<std::result::Result<Vec<String>, _>>()?;
709
710    let mut tensor_infos = vec![];
711    for file_name in zip_file_names.iter() {
712        if !file_name.ends_with("data.pkl") {
713            continue;
714        }
715        let dir_name = std::path::PathBuf::from(file_name.strip_suffix(".pkl").context("no .pkl")?);
716        let reader = zip.by_name(file_name)?;
717        let mut reader = std::io::BufReader::new(reader);
718        let mut stack = Stack::empty();
719        stack.read_loop(&mut reader)?;
720        let obj = stack.finalize()?;
721        if VERBOSE || verbose {
722            println!("{obj:#?}");
723        }
724
725        let obj = match obj {
726            Object::Build { callable, args } => match *callable {
727                Object::Reduce { callable, args: _ } => match *callable {
728                    Object::Class {
729                        module_name,
730                        class_name,
731                    } if module_name == "__torch__" && class_name == "Module" => *args,
732                    _ => continue,
733                },
734                _ => continue,
735            },
736            obj => obj,
737        };
738
739        // If key is provided, extract the state_dict from the object.
740        let obj = if let Some(key) = key {
741            if let Object::Dict(key_values) = obj {
742                key_values
743                    .into_iter()
744                    .find(|(k, _)| *k == Object::Unicode(key.to_owned()))
745                    .map(|(_, v)| v)
746                    .ok_or_else(|| E::Msg(format!("key {key} not found")))?
747            } else {
748                obj
749            }
750        } else {
751            obj
752        };
753
754        // Assuming `obj` is now state_dict.
755        if let Object::Dict(key_values) = obj {
756            for (name, value) in key_values.into_iter() {
757                match value.into_tensor_info(name, &dir_name) {
758                    Ok(Some(tensor_info)) => tensor_infos.push(tensor_info),
759                    Ok(None) => {}
760                    Err(err) => eprintln!("skipping: {err:?}"),
761                }
762            }
763        }
764    }
765    Ok(tensor_infos)
766}