Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:Trailofbits Fickling PyTorchModelWrapper Init

From Leeroopedia
Knowledge Sources
Domains Security, ML_Safety, File_Format
Last Updated 2026-02-14 14:00 GMT

Overview

Concrete tool for loading and validating PyTorch model files for pickle inspection and manipulation, provided by the Fickling library.

Description

PyTorchModelWrapper takes a path to a .pt file and provides validated, format-aware access to the embedded data.pkl. It identifies the file format via identify_pytorch_file_format(), validates support, and lazily extracts and parses the pickle data. The .pickled property returns a Pickled object ready for analysis or injection.

Usage

Use this as the entry point for PyTorch model analysis or payload injection. Construct with a file path and access .pickled for the parsed pickle data.

Code Reference

Source Location

  • Repository: fickling
  • File: fickling/pytorch.py
  • Lines: L35-122

Signature

class PyTorchModelWrapper:
    def __init__(self, path: Path, force: bool = False):
        """
        Args:
            path: Path to the .pt/.pth PyTorch model file.
            force: If True, suppresses errors for unsupported formats
                   (emits warnings instead).
        """

    def validate_file_format(self) -> set[str]:
        """Identify and validate the file format.

        Returns:
            Set of detected format strings.

        Raises:
            ValueError: If not a PyTorch file (unless force=True).
            NotImplementedError: If format is unsupported (unless force=True).
        """

    @property
    def formats(self) -> set[str]:
        """Detected file formats (lazy, calls validate_file_format)."""

    @property
    def pickled(self) -> Pickled:
        """Extracted and parsed data.pkl from the ZIP archive (lazy).

        Raises:
            ValueError: If data.pkl not found in the archive.
        """

Import

from fickling.pytorch import PyTorchModelWrapper

I/O Contract

Inputs

Name Type Required Description
path Path Yes Path to the .pt/.pth PyTorch model file
force bool No Suppress format errors as warnings (default: False)

Outputs

Name Type Description
.formats set[str] Detected format strings (e.g., {"PyTorch v1.3"})
.pickled Pickled Parsed data.pkl from the ZIP archive
.path Path The file path provided at construction

Usage Examples

Inspect PyTorch Model

from pathlib import Path
from fickling.pytorch import PyTorchModelWrapper

wrapper = PyTorchModelWrapper(Path("model.pt"))

# Check detected formats
print(f"Formats: {wrapper.formats}")

# Access parsed pickle for analysis
pickled = wrapper.pickled
print(f"Opcodes: {len(list(pickled))}")

Force Load Unsupported Format

from pathlib import Path
from fickling.pytorch import PyTorchModelWrapper

# Force loading even for unrecognized formats
wrapper = PyTorchModelWrapper(Path("unusual_model.pt"), force=True)
pickled = wrapper.pickled

Related Pages

Implements Principle

Requires Environment

Uses Heuristic

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment