Skip to content

fix: enter autocast context manager in T5/text conditioner#252

Open
rodriguescarson wants to merge 1 commit into
Stability-AI:mainfrom
rodriguescarson:fix/conditioner-autocast-context-manager
Open

fix: enter autocast context manager in T5/text conditioner#252
rodriguescarson wants to merge 1 commit into
Stability-AI:mainfrom
rodriguescarson:fix/conditioner-autocast-context-manager

Conversation

@rodriguescarson

Copy link
Copy Markdown

Fixes #238

Problem

In stable_audio_tools/models/conditioners.py:

with torch.amp.autocast('cuda', dtype=torch.float16) and torch.set_grad_enabled(self.enable_grad):

Python evaluates the and expression before the with binds anything. torch.amp.autocast(...) returns a truthy object, so A and B short-circuits to its right operand, torch.set_grad_enabled(...). The with statement therefore enters only set_grad_enabledautocast.__enter__() is never called, so fp16 autocast is silently inactive for this conditioner's forward pass (it runs in the ambient dtype instead of float16).

Fix

Separate the two context managers with a comma so both are entered, which is the intended behaviour:

with torch.amp.autocast('cuda', dtype=torch.float16), torch.set_grad_enabled(self.enable_grad):

One-token change, verifiable by inspection — this is the classic with A and B: context-manager pitfall. It's the only occurrence of the pattern in the repo.

🤖 Generated with Claude Code

conditioners.py used `with autocast(...) and set_grad_enabled(...):`. Python
evaluates the `and` expression first; the autocast object is truthy, so `and`
returns only its right operand (set_grad_enabled). The `with` therefore enters
just set_grad_enabled and never calls autocast.__enter__ — fp16 autocast is
silently inactive for the model forward pass.

Use a comma to enter both context managers, as intended.

Fixes Stability-AI#238
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.

Possible incorrect use of and with multiple context managers

1 participant