Skip to content

Commit 7111ee6

Browse files
author
Jianhan Mei
committed
Add gradient clipping to Flux and WAN trainers
1 parent 68e0696 commit 7111ee6

2 files changed

Lines changed: 41 additions & 0 deletions

File tree

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
diff --git a/src/maxdiffusion/trainers/flux_trainer.py b/src/maxdiffusion/trainers/flux_trainer.py
2+
--- a/src/maxdiffusion/trainers/flux_trainer.py
3+
+++ b/src/maxdiffusion/trainers/flux_trainer.py
4+
@@ -20,5 +20,6 @@
5+
import time
6+
import numpy as np
7+
import jax
8+
import jax.numpy as jnp
9+
+import optax
10+
from jax.sharding import NamedSharding, PartitionSpec as P
11+
@@ -442,6 +442,9 @@
12+
grad_fn = jax.value_and_grad(compute_loss)
13+
loss, grad = grad_fn(state_params)
14+
15+
+ if config.max_grad_norm > 0:
16+
+ grad, _ = optax.clip_by_global_norm(config.max_grad_norm).update(grad, flux_state, None)
17+
+
18+
new_state = flux_state.apply_gradients(grads=grad[FLUX_STATE_KEY])
19+
20+
metrics = {"scalar": {"learning/loss": loss}, "scalars": {}}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
diff --git a/src/maxdiffusion/trainers/wan_trainer.py b/src/maxdiffusion/trainers/wan_trainer.py
2+
--- a/src/maxdiffusion/trainers/wan_trainer.py
3+
+++ b/src/maxdiffusion/trainers/wan_trainer.py
4+
@@ -24,5 +24,6 @@
5+
import tensorflow as tf
6+
import jax.numpy as jnp
7+
import jax
8+
+import optax
9+
from jax.sharding import PartitionSpec as P
10+
from flax import nnx
11+
@@ -481,6 +481,10 @@
12+
13+
grad_fn = nnx.value_and_grad(loss_fn)
14+
loss, grads = grad_fn(state.params)
15+
+
16+
+ if config.max_grad_norm > 0:
17+
+ grads, _ = optax.clip_by_global_norm(config.max_grad_norm).update(grads, state.params, None)
18+
+
19+
new_state = state.apply_gradients(grads=grads)
20+
metrics = {"scalar": {"learning/loss": loss}, "scalars": {}}
21+
return new_state, scheduler_state, metrics, new_rng

0 commit comments

Comments
 (0)