Skip to content

fix: rewind file pointer and handle AttributeError on JIT load fallback - #550

Open
reginaldalfret wants to merge 1 commit into
openai:mainfrom
reginaldalfret:fix/issue-494-load-fallback
Open

reginaldalfret wants to merge 1 commit into
openai:mainfrom
reginaldalfret:fix/issue-494-load-fallback

Conversation

@reginaldalfret

Copy link
Copy Markdown

Summary

In clip.load(), when attempting to load a checkpoint file, the function first tries torch.jit.load():

        try:
            # loading JIT archive
            model = torch.jit.load(opened_file, map_location=device if jit else "cpu").eval()
            state_dict = None
        except RuntimeError:
            ...
            state_dict = torch.load(opened_file, map_location="cpu")

If torch.jit.load() encounters an incompatibility (such as an AttributeError from missing script attributes in certain environments) or fails after reading initial bytes from the stream:

  1. AttributeError was uncaught, causing an unhandled crash rather than falling back to loading a plain PyTorch state_dict.
  2. The open file stream pointer was not rewound (opened_file.seek(0)), causing torch.load() to read from an offset position and fail during unpickling.

Fix

  • Catch (RuntimeError, AttributeError) in the fallback handler.
  • Rewind the file stream with opened_file.seek(0) before calling torch.load(opened_file).

Validation

  • Added unit test tests/test_model_fallback.py verifying that when torch.jit.load raises AttributeError, clip.load catches it, rewinds the file stream, and loads the model via torch.load.
  • Test passes cleanly.

Closes #494

When torch.jit.load fails to load a model checkpoint (e.g. non-JIT archive
checkpoints or PyTorch environments where torch.jit raises an AttributeError
such as RecursiveScriptModule._construct), the exception handler attempts to
fall back to loading the file as a plain state dict using torch.load.

However, two issues occurred:
1. Only RuntimeError was caught, leaving AttributeErrors unhandled.
2. If torch.jit.load partially read bytes from the file stream before failing,
   the file pointer was not rewound, causing subsequent unpickling in torch.load
   to read corrupted/offset bytes or fail with EOF.

Add AttributeError to the caught exceptions and seek back to 0 before calling
torch.load.

Fixes openai#494

Signed-off-by: reginaldalfret <reginaldalfret@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AttributeError: type object 'RecursiveScriptModule' has no attribute '_construct'

1 participant