Safe Loading in RF-DETR: How and When to Use trust_checkpoint
RF-DETR implements a three-stage safe loading mechanism via _safe_torch_load to prevent arbitrary code execution from malicious PyTorch checkpoints, and you should only set trust_checkpoint=True when loading checkpoints from trusted sources such as your own training outputs or official RF-DETR releases.
Safe loading in RF-DETR protects against deserialization attacks (CWE-502) when loading model parameters from *.pth files. The library defaults to strict security controls that prevent pickle-based code execution, while the trust_checkpoint parameter provides an opt-in escape hatch for legacy checkpoints and trusted model weights. This article explains the technical implementation in the RF-DETR source code and provides clear guidelines on when to enable the trust flag.
How Safe Loading Works in RF-DETR
The safe loading mechanism is implemented in src/rfdetr/utilities/io.py inside the private helper _safe_torch_load. This function attempts to load checkpoints through three progressively permissive stages:
-
Strict safe load – The loader first attempts
torch.load(..., weights_only=True), which restricts deserialization to tensors and a minimal built-in scalar whitelist. This prevents execution of arbitrary Python code. -
Scoped safe globals – If strict loading fails, the loader retries within
torch.serialization.safe_globals([argparse.Namespace, types.SimpleNamespace]). This allows legacy checkpoints containing configuration namespaces to load without falling back to full pickle deserialization. -
Full pickle (opt-in only) – If both previous stages fail, the loader falls back to
weights_only=Falseonly when the caller setstrust=True. This triggers a loudUserWarningalerting that arbitrary code execution is possible.
The trust_checkpoint Parameter
The public API exposes this behavior through the trust_checkpoint boolean parameter in RFDETR.from_checkpoint(). According to the implementation in src/rfdetr/detr.py, the method signature accepts trust_checkpoint: bool = False, meaning the library never executes untrusted pickle code by default.
When trust_checkpoint=False, the loader stops after stage two and raises a RuntimeError if the checkpoint cannot be read safely. Setting trust_checkpoint=True propagates the trust flag through load_pretrain_weights in src/rfdetr/models/weights.py and ultimately to _safe_torch_load, allowing the stage three fallback to execute.
When to Use trust_checkpoint
You should configure trust_checkpoint based on the provenance of your checkpoint file:
Enable trust_checkpoint=True when:
- Loading checkpoints you produced yourself during training runs (e.g.,
outputs/checkpoint_best_total.pth). You control the serialization context, making full pickle safe. - Loading official pretrained weights shipped with the RF-DETR repository or model zoo. These curated releases may contain non-tensor metadata and are cryptographically verified as safe.
Keep trust_checkpoint=False (default) when:
- Loading checkpoints from untrusted users or external community sources. This prevents malicious pickled objects from executing during deserialization.
- The checkpoint's origin is unknown or you are unsure about its serialization contents. The safe-load path will fail fast with a clear error rather than risk code execution.
Code Examples
The following examples demonstrate secure checkpoint loading patterns in RF-DETR:
# Loading your own training checkpoint (trusted source)
from rfdetr import RFDETR
model = RFDETR.from_checkpoint(
"outputs/checkpoint_best_total.pth",
trust_checkpoint=True, # Safe: you generated this file
)
# Loading official pretrained weights (trusted source)
from rfdetr import RFDETRSmall
model = RFDETRSmall.from_checkpoint(
"rf-detr-small.pth", # Official release from RF-DETR
trust_checkpoint=True,
)
# Loading an external checkpoint from an untrusted source
try:
model = RFDETR.from_checkpoint("some_user_file.pth")
# trust_checkpoint defaults to False
except RuntimeError as e:
print("Unsafe checkpoint rejected:", e)
Key Implementation Files
The safe loading pipeline spans four critical files in the RF-DETR codebase:
-
src/rfdetr/utilities/io.py– Contains_safe_torch_load(lines 28-110), defining the three-stage loading logic and warning messages. -
src/rfdetr/detr.py– ImplementsRFDETR.from_checkpoint(lines 38-66), exposing thetrust_checkpointargument to users. -
src/rfdetr/models/weights.py– Definesload_pretrain_weights(lines 313-374), which forwards the trust flag to_safe_torch_loadwhen initializing model weights. -
src/rfdetr/inference.py– Contains_build_model_context(lines 109-123), propagatingtrust_checkpointfrom high-level inference APIs down to the weight loading functions.
Summary
- Safe loading in RF-DETR uses a defense-in-depth strategy: strict tensor-only loading, scoped globals for legacy namespaces, and optional full pickle only with explicit consent.
trust_checkpoint=False(default) prevents arbitrary code execution by refusing to load checkpoints that require full pickle deserialization.- Set
trust_checkpoint=Trueonly for checkpoints from verified sources, such as your own training outputs or official RF-DETR model zoo releases. - The implementation spans
rfdetr.utilities.io,rfdetr.detr,rfdetr.models.weights, andrfdetr.inference, ensuring consistent security across loading paths.
Frequently Asked Questions
What happens if I try to load a checkpoint with non-tensor objects without trust_checkpoint?
The loader attempts strict weights_only=True loading and then retries with safe_globals for argparse.Namespace objects. If both fail, the library raises a RuntimeError stating the checkpoint cannot be loaded safely, preventing potential code execution from malicious pickle payloads.
Is it safe to set trust_checkpoint=True for RF-DETR's official pretrained models?
Yes. Official RF-DETR releases are cryptographically verified and curated by the maintainers. These checkpoints may contain legitimate metadata objects that require full pickle loading, making trust_checkpoint=True necessary and safe for these specific files.
Why does RF-DETR use three loading stages instead of just weights_only=True?
The three-stage approach balances security with backward compatibility. Stage one blocks all code execution; stage two allows legacy training checkpoints that embed configuration namespaces; stage three supports older RF-DETR formats while requiring explicit user consent via trust_checkpoint=True to mitigate CWE-502 risks.
Where is the safe loading logic implemented in the codebase?
The core logic resides in src/rfdetr/utilities/io.py inside the _safe_torch_load function. This helper is called by load_pretrain_weights in src/rfdetr/models/weights.py, which receives the trust_checkpoint flag from RFDETR.from_checkpoint in src/rfdetr/detr.py and _build_model_context in src/rfdetr/inference.py.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →