Skip to content

Commit 1c44e08

Browse files
author
“Cortexelus”
committed
lint: ruff fixes — __all__ re-exports, rename ambiguous test vars, format
1 parent d2232dd commit 1c44e08

4 files changed

Lines changed: 56 additions & 14 deletions

File tree

stable_audio_3/utils/__init__.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,11 @@
55
make_grad_scaler,
66
resolve_device,
77
)
8+
9+
__all__ = [
10+
"autocast_context",
11+
"disable_autocast",
12+
"empty_device_cache",
13+
"make_grad_scaler",
14+
"resolve_device",
15+
]

stable_audio_3/utils/device.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
- @autocast("cuda", enabled=False) does NOT disable an active MPS autocast,
1313
so fp32 islands need the device-aware `disable_autocast` below.
1414
"""
15+
1516
import functools
1617

1718
import torch

tests/test_fast_lora_forward.py

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
forward: same outputs, same gradients, same state_dict layout, and graceful
66
fallback everywhere the reformulation doesn't apply.
77
"""
8+
89
import copy
910
from functools import partial
1011

@@ -64,7 +65,9 @@ def randomize_lora(model, seed=1, magnitude_jitter=0.3):
6465
for name in ("magnitude",):
6566
if hasattr(mod, name):
6667
p = getattr(mod, name)
67-
p.mul_(1.0 + magnitude_jitter * torch.rand(p.shape, generator=g).to(p))
68+
p.mul_(
69+
1.0 + magnitude_jitter * torch.rand(p.shape, generator=g).to(p)
70+
)
6871

6972

7073
def lora_trainables(model):
@@ -147,7 +150,9 @@ def test_gradient_parity_mps_fp16_autocast(adapter):
147150
y_naive, g_naive = run_fwd_bwd(naive, x, proj)
148151
out_err = rel_err(y_fast.float(), y_naive.float())
149152
worst = max(rel_err(g_fast[k].float(), g_naive[k].float()) for k in g_naive)
150-
print(f"[autocast fp16 {adapter}] output rel err = {out_err:.3e}, worst grad rel err = {worst:.3e}")
153+
print(
154+
f"[autocast fp16 {adapter}] output rel err = {out_err:.3e}, worst grad rel err = {worst:.3e}"
155+
)
151156
# fp16 GEMM noise dominates; ~1e-2-class is the expected scale, this bound is a regression guard
152157
assert out_err <= 3e-2
153158
assert worst <= 5e-2
@@ -166,7 +171,9 @@ def test_strength_buffer(adapter, device):
166171
base = make_model(bias=True, device=device) # same seed -> identical base weights
167172
y_fast = fast(x)
168173
y_base = base(x)
169-
assert torch.equal(y_fast, y_base), f"strength=0 must be bit-exact to the base ({adapter}/{device})"
174+
assert torch.equal(y_fast, y_base), (
175+
f"strength=0 must be bit-exact to the base ({adapter}/{device})"
176+
)
170177

171178

172179
@pytest.mark.parametrize("device", DEVICES)
@@ -179,9 +186,12 @@ def test_stacked_parametrization_falls_back(device):
179186
for m in (fast, naive):
180187
torch.manual_seed(7)
181188
for mod in m.modules():
182-
if isinstance(mod, nn.Linear) and parametrize.is_parametrized(mod, "weight"):
189+
if isinstance(mod, nn.Linear) and parametrize.is_parametrized(
190+
mod, "weight"
191+
):
183192
p2 = LoRAParametrization.from_linear(
184-
mod, rank=4, lora_alpha=8, adapter_type="dora-rows", lora_index=1)
193+
mod, rank=4, lora_alpha=8, adapter_type="dora-rows", lora_index=1
194+
)
185195
with torch.no_grad():
186196
p2.lora_B.copy_(torch.randn_like(p2.lora_B) * 0.05)
187197
parametrize.register_parametrization(mod, "weight", p2, unsafe=True)
@@ -192,7 +202,7 @@ def test_stacked_parametrization_falls_back(device):
192202
assert len(mod.parametrizations["weight"]) == 2
193203

194204
x = torch.randn(2, 9, 64, device=device)
195-
y_fast = fast(x) # wrapper must detect the stack and fall back per-forward
205+
y_fast = fast(x) # wrapper must detect the stack and fall back per-forward
196206
y_naive = naive(x)
197207
assert torch.equal(y_fast, y_naive), "stacked modules must use the exact naive path"
198208

@@ -229,7 +239,9 @@ def test_state_dict_layout_unchanged(adapter, monkeypatch):
229239
monkeypatch.setenv("SA3_FAST_LORA", "0")
230240
naive = make_model()
231241
add_lora(naive, lora_config(adapter))
232-
assert not naive[0].__dict__.get("_fast_lora_wrapped", False), "SA3_FAST_LORA=0 must disable wrapping"
242+
assert not naive[0].__dict__.get("_fast_lora_wrapped", False), (
243+
"SA3_FAST_LORA=0 must disable wrapping"
244+
)
233245

234246
# populate the norm-constant cache before snapshotting
235247
fast(torch.randn(2, 4, 64))
@@ -249,8 +261,13 @@ def test_dropout_shared_between_direction_and_norm(device):
249261
forward; under a fixed RNG seed both paths must consume the same draws."""
250262
cfg = {
251263
nn.Linear: {
252-
"weight": partial(LoRAParametrization.from_linear, rank=8, lora_alpha=16,
253-
adapter_type="dora-rows", lora_dropout_p=0.5),
264+
"weight": partial(
265+
LoRAParametrization.from_linear,
266+
rank=8,
267+
lora_alpha=16,
268+
adapter_type="dora-rows",
269+
lora_dropout_p=0.5,
270+
),
254271
},
255272
}
256273
model = make_model(device=device)

tests/test_mps_training_smoke.py

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
Skipped entirely when MPS is unavailable. Runnable standalone:
1616
python tests/test_mps_training_smoke.py
1717
"""
18+
1819
import os
1920
import sys
2021
from functools import partial
@@ -36,19 +37,25 @@
3637
# underfit loss (real module when importable, faithful mirror otherwise)
3738
# ---------------------------------------------------------------------------
3839

40+
3941
def _underfit_loss_fns():
4042
try:
4143
from underfit.training.loss import compute_masked_loss, compute_normalized_mse
44+
4245
return compute_normalized_mse, compute_masked_loss
4346
except ImportError:
4447
pass
4548

4649
# Mirror of underfit/training/loss.py (loss_normalization="none",
4750
# mask_padding_attention=True → signal-only masked MSE).
48-
def compute_normalized_mse(pred, target, loss_mask, loss_normalization="none", loss_norm_eps=1e-6):
51+
def compute_normalized_mse(
52+
pred, target, loss_mask, loss_normalization="none", loss_norm_eps=1e-6
53+
):
4954
return (pred - target) ** 2
5055

51-
def compute_masked_loss(loss_full, loss_mask, mask_padding_attention, mask_loss_weight=0.0):
56+
def compute_masked_loss(
57+
loss_full, loss_mask, mask_padding_attention, mask_loss_weight=0.0
58+
):
5259
signal = torch.where(loss_mask.unsqueeze(1), loss_full, 0.0)
5360
signal_sum = signal.sum(dim=(1, 2))
5461
n_channels = loss_full.shape[1]
@@ -65,6 +72,7 @@ def compute_masked_loss(loss_full, loss_mask, mask_padding_attention, mask_loss_
6572
# Device helper probes
6673
# ---------------------------------------------------------------------------
6774

75+
6876
def test_resolve_device_prefers_mps_without_cuda():
6977
from stable_audio_3.utils.device import resolve_device
7078

@@ -120,6 +128,7 @@ def test_fp32_islands_hold_under_mps_autocast():
120128
# End-to-end: tiny DiT + LoRA, 3 training steps on MPS
121129
# ---------------------------------------------------------------------------
122130

131+
123132
def _build_tiny_dit_with_lora():
124133
from stable_audio_3.models.dit import DiffusionTransformer
125134
from stable_audio_3.models.lora import LoRAParametrization, add_lora
@@ -206,7 +215,9 @@ def test_lora_training_steps_on_mps():
206215
scaler.update()
207216
losses.append(loss.item())
208217

209-
assert all(l == l and abs(l) != float("inf") for l in losses), f"non-finite loss: {losses}"
218+
assert all(x == x and abs(x) != float("inf") for x in losses), (
219+
f"non-finite loss: {losses}"
220+
)
210221
assert losses[-1] != losses[0], f"loss did not change over 3 steps: {losses}"
211222
# On a fixed batch with lr=1e-2 the loss should trend down.
212223
assert losses[-1] < losses[0] * 1.05, f"loss did not decrease: {losses}"
@@ -228,7 +239,10 @@ def test_full_wrapper_training_step_on_mps():
228239
(underfit's pre_encoded path never calls pretransform.encode).
229240
"""
230241
from stable_audio_3.models.conditioners import MultiConditioner, NumberConditioner
231-
from stable_audio_3.models.diffusion import ConditionedDiffusionModelWrapper, DiTWrapper
242+
from stable_audio_3.models.diffusion import (
243+
ConditionedDiffusionModelWrapper,
244+
DiTWrapper,
245+
)
232246
from stable_audio_3.models.lora import LoRAParametrization, add_lora
233247
from stable_audio_3.utils.device import autocast_context, make_grad_scaler
234248

@@ -310,7 +324,9 @@ def test_full_wrapper_training_step_on_mps():
310324
scaler.update()
311325
losses.append(loss.item())
312326

313-
assert all(l == l and abs(l) != float("inf") for l in losses), f"non-finite loss: {losses}"
327+
assert all(x == x and abs(x) != float("inf") for x in losses), (
328+
f"non-finite loss: {losses}"
329+
)
314330
assert len(set(losses)) > 1, f"loss frozen across steps: {losses}"
315331

316332

0 commit comments

Comments
 (0)