Muon
- class paddle.optimizer. Muon ( learning_rate=0.02, parameters=None, momentum=0.95, adam_beta1=0.9, adam_beta2=0.95, weight_decay=0.01, ns_steps=5, ns_coeff_type='simple', ns_coeffs=None, nesterov=True, adam_epsilon=1e-09, grad_clip=None, lr_ratio: Callable[[Tensor], float] | None = None, apply_decay_param_fun: Callable[[str], bool] | None = None, muon_version=1, muon_exclude_patterns=None, muon_extra_scale_factor=0.2, muon_param_info_map: MuonParamInfoMap | None = None, ns_matmul_dtype=None, multi_precision=False, name=None, muon_max_group_bytes=2147483648, use_symmetric_gemm=False, symmetric_gemm_min_short_edge=1024, symmetric_gemm_min_step_flops=200000000000.0, **kwargs ) [source]
-
Muon optimizer for MuonShardingOptimizer (Sharding Stage1 V3) usage.
For 2-D weight matrices (identified by
_default_should_use_muon()), Muon applies orthogonal gradient updates via Newton-Schulz iteration. For all other parameters (embeddings, biases, expert weights, …) it falls back to a standard AdamW update.Designed for
MuonShardingOptimizer(Sharding Stage1 V3), where 2D parameters are assigned as whole tensors to ranks. Currently we do not support TP=1, no sharding gather or TP communication is needed during the optimizer step.- Parameters
-
learning_rate (float | LRScheduler) – Learning rate. Default:
0.02.parameters (list[Tensor]) – Flat list of parameters to optimize.
momentum (float) – Momentum coefficient for the Muon update. Default:
0.95.adam_beta1 (float) – β₁ for the AdamW fallback. Default:
0.9.adam_beta2 (float) – β₂ for the AdamW fallback. Default:
0.95.weight_decay (float) – Decoupled weight decay. Default:
0.01.ns_steps (int) – Newton-Schulz iteration steps. Default:
5.ns_coeff_type (str) – Preset name for Newton-Schulz coefficients. Options:
"simple","quintic","polar_express","aol","deepseekv4","custom". Default:"simple".ns_coeffs (list[tuple[float, float, float]] | None) – Custom Newton-Schulz coefficient set. Each tuple is
(a, b, c)for one iteration step. Default:None. Only used when ns_coeff_type=``custom``.nesterov (bool) – Use Nesterov momentum in Muon. Default:
True.adam_epsilon (float) – ε for numerical stability in AdamW. Default:
1e-9.grad_clip (GradientClipBase | None) – Gradient clipping. Default:
None.apply_decay_param_fun (callable | None) – Function to select which parameters receive weight decay. Default:
None.muon_version (int) – Scaling-function version (1/2/3). Default:
1.muon_exclude_patterns (list[str] | None) – Parameter names containing any of these substrings will use AdamW instead of Muon. Example:
['embed', 'bias', 'lm_head', 'mlp.gate']. Default:None.muon_extra_scale_factor (float) – Extra multiplicative scale applied after the dimension-dependent scaling in
_scaling_fn. Default:0.2.muon_param_info_map (MuonParamInfoMap | None) – Per-parameter metadata dict mapping param name to
MuonParamInfo(use_muon, split_concat_func). Built by Trainer and passed in. Default:None.ns_matmul_dtype (paddle.dtype | None) – Dtype for Newton-Schulz matmul iterations.
None= auto-detect: bfloat16 on Ampere+ (capability >= 8.0), float32 on V100 and older. Passpaddle.float32explicitly to force float32. Default:None.use_symmetric_gemm (bool) – Compute the two symmetric matmuls of each Newton-Schulz step with quack’s SYRK-style
gemm_symmetrickernel. Default:False.symmetric_gemm_min_short_edge (int) – Minimum short edge of a Newton-Schulz fragment for the symmetric-GEMM path. Below this the kernel cannot fill the GPU and loses to cuBLAS. Only consulted when
use_symmetric_gemm=True. The default was measured on sm_10x; raise or lower it if the crossover point moves. Default:1024.symmetric_gemm_min_step_flops (float) – Minimum FLOPs of one full Newton-Schulz step,
batch * (4 * m^2 * n + 2 * m^3), for the symmetric-GEMM path. Screens out fragments too small to amortise the launch overhead. Only consulted whenuse_symmetric_gemm=True. Default:2e11.multi_precision (bool) – Maintain FP32 master weights when training in BF16/FP16. Default:
False.name (str | None) – Optional name for the optimizer instance.
-
append_regularization_ops
(
parameters_and_grads: list[tuple[Tensor, Tensor]],
regularization: WeightDecayRegularizer | None = None
)
list[tuple[Tensor, Tensor]]
append_regularization_ops¶
-
Create and add backward regularization Operators
Creates and adds backward regularization operators in the BlockDesc. This will add gradients of the regularizer function to the gradients of the parameters and return these modified gradients. This is the same as implementing weight decay in optimizers for regularization.
- Parameters
-
parameters_and_grads (list[tuple[Tensor,Tensor]]) – A list of (parameters, gradients) pairs that need to be regularized.
regularization (WeightDecayRegularizer|None, optional) – A global regularizer. If the parameter is not set. It will be applied with regularizer.
- Returns
-
- list of (parameters, gradients)
-
pair with the regularized gradient
- Return type
-
list[tuple[Tensor,Tensor]]
- Raises
-
Exception – Unknown regularization type
-
clear_grad
(
set_to_zero: bool = True
)
None
clear_grad¶
-
Clear the gradients of all optimized parameters for model.
If not, new gradient will accumulat on previous gradient.
There are two method to clear grad: set_to_zero or delete grad.
- Parameters
-
set_to_zero (bool, optional) – If set grads to zero or not, default is True.
- Returns
-
None
Examples
>>> import paddle >>> a = paddle.arange(26, dtype="float32").reshape([2, 13]) >>> linear = paddle.nn.Linear(13, 5) >>> # This can be any optimizer supported by dygraph. >>> adam = paddle.optimizer.Adam( ... learning_rate=0.01, ... parameters=linear.parameters(), ... ) >>> out = linear(a) >>> out.backward() >>> adam.step() >>> adam.clear_grad()
-
get_lr
(
)
float
get_lr¶
-
Get current learning rate of optimizer. If ‘LRScheduler’ is not used, the return value is all the same. If ‘LRScheduler’ is used, the return value is the current scheduled learning rete.
- Returns
-
float, The current learning rate of optimizer.
Examples
>>> # train on default dynamic graph mode >>> import paddle >>> import numpy as np >>> emb = paddle.nn.Embedding(10, 3) >>> ## example1: LRScheduler is not used, return the same value is all the same >>> adam = paddle.optimizer.Adam(0.01, parameters=emb.parameters()) >>> for batch in range(10): ... input = paddle.randint(low=0, high=5, size=[5]) ... out = emb(input) ... out.backward() ... print("Learning rate of step{}: {}".format(batch, adam.get_lr())) # 0.01 ... adam.step() Learning rate of step0: 0.01 Learning rate of step1: 0.01 Learning rate of step2: 0.01 Learning rate of step3: 0.01 Learning rate of step4: 0.01 Learning rate of step5: 0.01 Learning rate of step6: 0.01 Learning rate of step7: 0.01 Learning rate of step8: 0.01 Learning rate of step9: 0.01 >>> ## example2: StepDecay is used, return the scheduled learning rate >>> scheduler = paddle.optimizer.lr.StepDecay(learning_rate=0.5, step_size=2, gamma=0.1) >>> adam = paddle.optimizer.Adam(scheduler, parameters=emb.parameters()) >>> for batch in range(10): ... input = paddle.randint(low=0, high=5, size=[5]) ... out = emb(input) ... out.backward() ... print("Learning rate of step{}: {}".format(batch, adam.get_lr())) # 0.5->0.05... ... adam.step() ... scheduler.step() Learning rate of step0: 0.5 Learning rate of step1: 0.5 Learning rate of step2: 0.05 Learning rate of step3: 0.05 Learning rate of step4: 0.005000000000000001 Learning rate of step5: 0.005000000000000001 Learning rate of step6: 0.0005000000000000001 Learning rate of step7: 0.0005000000000000001 Learning rate of step8: 5.000000000000001e-05 Learning rate of step9: 5.000000000000001e-05 >>> # train on static graph mode >>> paddle.enable_static() >>> main_prog = paddle.static.Program() >>> start_prog = paddle.static.Program() >>> with paddle.static.program_guard(main_prog, start_prog): ... x = paddle.static.data(name='x', shape=[None, 10]) ... z = paddle.static.nn.fc(x, 100) ... loss = paddle.mean(z) ... scheduler = paddle.optimizer.lr.StepDecay(learning_rate=0.5, step_size=2, gamma=0.1) ... adam = paddle.optimizer.Adam(learning_rate=scheduler) ... adam.minimize(loss) >>> exe = paddle.static.Executor() >>> exe.run(start_prog) >>> for batch in range(10): ... print("Learning rate of step{}: {}".format(batch, adam.get_lr())) # 0.5->0.05->0.005... ... out = exe.run(main_prog, feed={'x': np.random.randn(3, 10).astype('float32')}) ... scheduler.step() Learning rate of step0: 0.5 Learning rate of step1: 0.5 Learning rate of step2: 0.05 Learning rate of step3: 0.05 Learning rate of step4: 0.005000000000000001 Learning rate of step5: 0.005000000000000001 Learning rate of step6: 0.0005000000000000001 Learning rate of step7: 0.0005000000000000001 Learning rate of step8: 5.000000000000001e-05 Learning rate of step9: 5.000000000000001e-05
-
load_state_dict
(
state_dict: dict[str, Tensor]
)
None
load_state_dict¶
-
Load optimizer state dict. For Adam optimizer, contains beta1, beta2, momentum etc. If LRScheduler have been used, global_step will be changed.
- Parameters
-
state_dict (dict) – Dict contains all the Tensor needed by optimizer
- Returns
-
None
Examples
>>> import paddle >>> emb = paddle.nn.Embedding(10, 10) >>> layer_state_dict = emb.state_dict() >>> paddle.save(layer_state_dict, "emb.pdparams") >>> scheduler = paddle.optimizer.lr.NoamDecay( ... d_model=100, ... warmup_steps=100, ... verbose=True, ... ) >>> adam = paddle.optimizer.Adam( ... learning_rate=scheduler, ... parameters=emb.parameters(), ... ) >>> opt_state_dict = adam.state_dict() >>> paddle.save(opt_state_dict, "adam.pdopt") >>> opti_state_dict = paddle.load("adam.pdopt") >>> adam.set_state_dict(opti_state_dict)
-
minimize
(
loss: Tensor,
startup_program: Program | None = None,
parameters: list[Tensor] | list[str] | None = None,
no_grad_set: set[Tensor] | set[str] | None = None
)
tuple[list[Operator], list[tuple[Tensor, Tensor]]]
minimize¶
-
Add operations to minimize
lossby updatingparameters.- Parameters
-
loss (Tensor) – A
Tensorcontaining the value to minimize.startup_program (Program|None, optional) – Program for initializing parameters in
parameters. The default value is None, at this time default_startup_program will be used.parameters (list[Tensor]|list[str]|None, optional) – List of
TensororTensor.nameto update to minimizeloss. The default value is None, at this time all parameters will be updated.no_grad_set (set[Tensor]|set[str]|None, optional) – Set of
TensororTensor.namethat don’t need to be updated. The default value is None.
- Returns
-
- tuple[list[Operator],list[tuple[Tensor, Tensor]]], A list of operators appended
-
by minimize and a list of (param, grad) tensor pairs, param is
Parameter, grad is the gradient value corresponding to the parameter. In static graph mode, the returned tuple can be passed tofetch_listinExecutor.run()to indicate program pruning. If so, the program will be pruned byfeedandfetch_listbefore run, see details inExecutor.
Examples
>>> import paddle >>> linear = paddle.nn.Linear(10, 10) >>> input = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1) >>> out = linear(input) >>> loss = paddle.mean(out) >>> beta1 = paddle.to_tensor([0.9], dtype="float32") >>> beta2 = paddle.to_tensor([0.99], dtype="float32") >>> adam = paddle.optimizer.Adam( ... learning_rate=0.1, ... parameters=linear.parameters(), ... weight_decay=0.01, ... ) >>> loss.backward() >>> adam.minimize(loss) >>> adam.clear_grad()
-
set_lr
(
value: float
)
None
set_lr¶
-
- Api_attr
-
imperative
Set the value of the learning rate manually in the optimizer. If the optimizer use LRScheduler, this API cannot be invoked, because it will lead to conflict.
- Parameters
-
value (float) – the value of learning rate.
- Returns
-
None
Examples
>>> import paddle >>> linear = paddle.nn.Linear(10, 10) >>> adam = paddle.optimizer.Adam(0.1, parameters=linear.parameters()) >>> # set learning rate manually by python float value >>> lr_list = [0.2, 0.3, 0.4, 0.5, 0.6] >>> for i in range(5): ... adam.set_lr(lr_list[i]) ... lr = adam.get_lr() ... print("current lr is {}".format(lr)) current lr is 0.2 current lr is 0.3 current lr is 0.4 current lr is 0.5 current lr is 0.6
-
set_lr_scheduler
(
scheduler: LRScheduler
)
None
set_lr_scheduler¶
-
- Api_attr
-
imperative
Set the LRScheduler of the learning rate manually in the optimizer. If the optimizer already used LRScheduler previously, this API will set it be the new one.
- Parameters
-
scheduler (LRScheduler) – the LRScheduler of learning rate
- Returns
-
None
Examples
>>> import paddle >>> linear = paddle.nn.Linear(10, 10) >>> adam = paddle.optimizer.Adam(0.1, parameters=linear.parameters()) >>> # set learning rate manually by class LRScheduler >>> scheduler = paddle.optimizer.lr.MultiStepDecay( ... learning_rate=0.5, ... milestones=[2, 4, 6], ... gamma=0.8, ... ) >>> adam.set_lr_scheduler(scheduler) >>> lr = adam.get_lr() >>> print("current lr is {}".format(lr)) current lr is 0.5 >>> # set learning rate manually by another LRScheduler >>> scheduler = paddle.optimizer.lr.StepDecay(learning_rate=0.1, step_size=5, gamma=0.6) >>> adam.set_lr_scheduler(scheduler) >>> lr = adam.get_lr() >>> print("current lr is {}".format(lr)) current lr is 0.1
-
set_state_dict
(
state_dict: dict[str, Tensor]
)
None
set_state_dict¶
-
Load optimizer state dict. For Adam optimizer, contains beta1, beta2, momentum etc. If LRScheduler have been used, global_step will be changed.
- Parameters
-
state_dict (dict) – Dict contains all the Tensor needed by optimizer
- Returns
-
None
Examples
>>> import paddle >>> emb = paddle.nn.Embedding(10, 10) >>> layer_state_dict = emb.state_dict() >>> paddle.save(layer_state_dict, "emb.pdparams") >>> scheduler = paddle.optimizer.lr.NoamDecay( ... d_model=100, ... warmup_steps=100, ... verbose=True, ... ) >>> adam = paddle.optimizer.Adam( ... learning_rate=scheduler, ... parameters=emb.parameters(), ... ) >>> opt_state_dict = adam.state_dict() >>> paddle.save(opt_state_dict, "adam.pdopt") >>> opti_state_dict = paddle.load("adam.pdopt") >>> adam.set_state_dict(opti_state_dict)
-
state_dict
(
)
dict[str, Tensor]
state_dict¶
-
Get state dict information from optimizer. It contain all the tensor used by optimizer. For Adam optimizer, contains beta1, beta2, momentum etc. If LRScheduler have been used, global_step will be include in state dict. If the optimizer never be called(minimize function), the state_dict is empty.
- Returns
-
dict[str,Tensor], dict contains all the Tensor used by optimizer
Examples
>>> import paddle >>> emb = paddle.nn.Embedding(10, 10) >>> adam = paddle.optimizer.Adam(0.001, parameters=emb.parameters()) >>> state_dict = adam.state_dict()
-
step
(
)
None
step¶
-
Execute the optimizer and update parameters once.
- Returns
-
None
Examples
>>> import paddle >>> a = paddle.arange(26, dtype="float32").reshape([2, 13]) >>> linear = paddle.nn.Linear(13, 5) >>> # This can be any optimizer supported by dygraph. >>> adam = paddle.optimizer.Adam( ... learning_rate=0.01, ... parameters=linear.parameters(), ... ) >>> out = linear(a) >>> out.backward() >>> adam.step() >>> adam.clear_grad()
-
sharded_state_dict
(
model_sharded_state_dict: Union[dict[str, paddle.distributed.flex_checkpoint.dcp.sharded_weight.ShardedWeight], OrderedDict[str, ShardedWeight]]
)
Union[dict[str, paddle.distributed.flex_checkpoint.dcp.sharded_weight.ShardedWeight], OrderedDict[str, ShardedWeight]]
sharded_state_dict¶
-
Build a sharded optimizer state dict for flex checkpoint save/load.
The layout mirrors
paddle.optimizer.AdamW’s implementation so that the samedist.save_state_dict/dist.load_state_dictpath works for Muon checkpoints.- Parameters
-
model_sharded_state_dict – Sharded model state dict produced by
model.sharded_state_dict(). - Returns
-
A dict mapping
"<struct_name>.<state_type>"keys toShardedWeightobjects.
