Reinforcement learning training: Configuration and submission

Updated at:

This topic is a complete reference for RL training submission methods and parameter configuration, covering three submission methods (run / YAML / submit_job), Runtime resource configuration, the full grouped table of training hyperparameters, task management (SDK / CLI), and configuration FAQs.

Boundaries relative to other articles

Submit a training job

NoteAfter your first submission or after changing custom functions/data, complete the layered checks in the Reinforcement learning pre-submission checklist first (free local validation → remote function testing → pipeline smoke test), then submit formally.

RL training supports three submission methods. For a quick start, we recommend one-step (run). The three methods offer increasing flexibility:

Method

Description

Ideal for

Step-by-step

Register functions, upload data, and submit the job in separate steps.

Debugging each step individually.

One-step (run)

Automatic registration + upload + submission.

Quickly starting a training job.

YAML configuration

Loads parameters from a configuration file and supports runtime overrides.

Running multiple experiments and managing parameters.

Configuration precedence (later values override earlier ones):

__init__() initialization < YAML configuration file < run() / submit_job() runtime parameters

This method automatically registers functions, uploads data, and submits the job—the fastest way to get started (run() is an async method; the complete script must be wrapped in async def main() and executed with asyncio.run(main())—see the overview for a complete runnable example):

from dashscope.finetune.reinforcement import (
    RolloutFunctionComponent, RewardFunctionComponent,
    FunctionComponentModel, FunctionComponentRuntime,
    TrainingDataset, ValidationDataset, DataSourceType,
)
from dashscope.finetune.agentic_rl import AgenticRL

# Rollout 与 Reward 共用的 runtime 配置(生产须 memory_size >= 4096)
rollout_runtime = {
    "cpu": 2, "memory_size": 4096, "disk_size": 512, "concurrency": 30,
    "capacity": 30, "min_capacity": 30, "max_capacity": 60,
    "memory_scale_threshold": 0.6, "concurrency_scale_threshold": 0.6,
    "env": {},
}

client = AgenticRL()
result = await client.run(
    job_name="agentic-rl",                          # 实验标识
    # ---- 基础模型 ----
    model="qwen3.5-9b",                             # 待训练的基础模型

    # ---- 训练 / 验证数据 ----
    training_datasets=[TrainingDataset(
        data_source_type=DataSourceType.FILE_ID,
        file_name="./data/calc_train_min.jsonl",
    )],
    validation_datasets=[ValidationDataset(
        data_source_type=DataSourceType.FILE_ID,
        file_name="./data/calc_validation_min.jsonl",
    )],

    # ---- Rollout & Reward 函数 ----
    functions=[
        RolloutFunctionComponent(
            name="rollout-1",                      # 函数名称,用于日志和监控
            timeout=600,
            fcmodel=FunctionComponentModel(
                classpath="functions.rollout.rollout.CalcXRolloutProcessor"),  # 入口类(示例占位名,实际类名由您定义)
            runtime=FunctionComponentRuntime(**rollout_runtime)),
        RewardFunctionComponent(
            name="reward-1",                       # 函数名称
            weight=1.0,                            # 多 Reward 时的权重
            timeout=120,
            fcmodel=FunctionComponentModel(
                classpath="functions.reward.reward.DemoRewardProcessor"),
            runtime=FunctionComponentRuntime(
                cpu=2, memory_size=4096, disk_size=512,
                concurrency=30, capacity=30,
                min_capacity=30, max_capacity=60,
                memory_scale_threshold=0.6,
                concurrency_scale_threshold=0.6)),
    ],

    # ---- 计算资源配置 ----
    resources={
        "charge_type": "mtu_postpaid",             # 计费方式:后付费填 mtu_postpaid;预付费填 mtu_prepaid 并提供 instance_id(联系商务经理获取)
        "mtu_spec_code": "MTU4",                   # 训练单元规格
        "mtu_capacity": 24,                        # 本次任务占用的 MTU 数量,不必用满已购容量
    },

    # ---- 超参数(低成本试跑起点;未传参数由服务端自动补全,全量表见下方 §训练超参数) ----
    hyper_parameters={
        "algorithm": "gspo",
        "batch_size": 64,
        "eval_steps": 1,
        "kl_loss_coef": 0.002,
        "learning_rate": 2e-6,
        "lr_scheduler_type": "linear",
        "max_length": 8192,
        "n_epochs": 1,
        "n_rollouts": 8,
        "ppo_mini_batch_size": 8,
        "save_strategy": "steps",
        # ... 参数含义见下方 §训练超参数
    })

YAML configuration

Ideal for scenarios that involve multiple experiments or managing multiple sets of parameters. First define a YAML configuration file, then load and execute it:

## job.yaml
name: agentic-rl-from-yaml                    # 实验标识
model:
  name: qwen3.5-9b                            # 基础模型

datasets:
  - type: "training"
    data_source_type: "file_id"
    file_name: "./data/calc_train_min.jsonl"
  - type: "validation"
    data_source_type: "file_id"
    file_name: "./data/calc_validation_min.jsonl"

functions:
  - type: "rollout"
    name: "rollout-1"
    timeout: 600
    fcmodel:
      zipdir: "./"                            # 打包根目录(函数代码所在目录)
      classpath: "functions.rollout.rollout.CalcXRolloutProcessor"  # 入口类(示例占位名,实际类名由您定义)
      requirements_path: "./requirements.txt" # 依赖清单
    runtime:
      cpu: 2
      memory_size: 4096                      # 内存(MB)
      disk_size: 512                         # 磁盘(MB)
      concurrency: 30                        # 单实例并发数
      capacity: 30                           # 初始实例数
      min_capacity: 30                       # 弹性伸缩下限
      max_capacity: 60                       # 弹性伸缩上限
      memory_scale_threshold: 0.6            # 内存使用率扩容阈值(0~1)
      concurrency_scale_threshold: 0.6       # 并发使用率扩容阈值(0~1)
      env: {}

  - type: "reward"
    name: "reward-1"
    weight: 1.0
    timeout: 120
    fcmodel:
      zipdir: "./"
      classpath: "functions.reward.reward.DemoRewardProcessor"
      requirements_path: "./requirements.txt"
    runtime:
      cpu: 2
      memory_size: 4096
      disk_size: 512
      concurrency: 30
      capacity: 30
      min_capacity: 30
      max_capacity: 60
      memory_scale_threshold: 0.6
      concurrency_scale_threshold: 0.6
      env: {}

training:
  type: "reinforcement"
  hyper_parameters:
    algorithm: "gspo"                          # 训练算法
    batch_size: 64                             # 每步训练样本数
    eval_steps: 1                             # 每隔多少步做一次评估
    kl_loss_coef: 0.002                        # KL 散度惩罚系数
    learning_rate: 2e-6                        # 学习率
    lr_scheduler_type: "linear"               # 学习率调度策略
    max_length: 8192                           # 最大序列长度
    n_epochs: 1                                # 训练轮次
    n_rollouts: 8                              # 每条 prompt 的采样数
    ppo_mini_batch_size: 8                     # PPO mini-batch 大小
    save_steps: 100                            # 每隔多少步保存 checkpoint
    save_strategy: "steps"                   # 保存策略(按步数保存)
    save_total_limit: 1                        # 最多保留 checkpoint 数
  resources:
    charge_type: "mtu_postpaid"               # 计费方式:后付费填 mtu_postpaid;预付费填 mtu_prepaid 并提供 instance_id(联系商务经理获取)
    mtu_spec_code: "MTU4"                      # 训练单元规格
    mtu_capacity: 24                           # 本次任务占用的 MTU 数量,不必用满已购容量

Load and execute:

client = AgenticRL()
## 加载 YAML 配置并初始化(job.yaml 为配置文件;name 标识本次实验)
client.init(config_path="job.yaml", name="agentic-rl-from-yaml")
## 也可把初始化后的配置导出为 YAML 复核(可选)
client.tuning.to_yaml(file_path="init.yaml")
## run() 为异步方法:完整脚本须包在 async main() 中执行(可运行完整示例见概述篇)
result = await client.run()

## 也可以在运行时覆盖部分参数(优先级高于 YAML 配置;调整幅度参考调参决策表)
result = await client.run(hyper_parameters={"learning_rate": 4e-6})

Step-by-step submission (submit_job)

Suitable for scenarios where each step needs to be debugged individually. After the functions are registered and the data is uploaded, submit the job directly by referencing Entity IDs (for the complete function registration workflow, see the Pre-submission Checklist for Reinforcement Learning and the Reinforcement Learning Development Guide):

from dashscope.finetune.reinforcement import (
    AgenticRLFunctionComponent, FunctionType, FunctionComponentRuntime,
    Dataset, DatasetsType, DataSourceType,
)
from dashscope.finetune.agentic_rl import AgenticRL

client = AgenticRL()

## ---- 上传训练/验证数据(返回 file_id 列表) ----
training_ids, validation_ids = await client.upload_datasets(
    training_files=["./data/calc_train_min.jsonl"],
    validation_files=["./data/calc_validation_min.jsonl"])

## ---- 定义函数列表(以 entity_id 引用已注册的函数,无需再传 classpath) ----
## 注意:分步提交的函数组件为 AgenticRLFunctionComponent;
## 多 Reward 权重(weight)在 run() 方式的 RewardFunctionComponent 上配置(见上方示例)
functions = [
    AgenticRLFunctionComponent(
        type=FunctionType.ROLLOUT,
        entity_id="ro-xxxxx",                  # 注册时返回的 entity_id
        runtime=FunctionComponentRuntime(
            cpu=2, memory_size=4096, disk_size=512,
            concurrency=2, capacity=5)),       # 演示用最小配置,生产参考下文 FC 调优
    AgenticRLFunctionComponent(
        type=FunctionType.REWARD,
        name="reward-1",
        entity_id="rw-xxxxx",                  # 注册时返回的 entity_id
        runtime=FunctionComponentRuntime(
            cpu=2, memory_size=4096, disk_size=512,
            concurrency=10, capacity=8)),
]

## ---- 提交训练任务(submit_job 为同步调用;数据以 datasets 引用已上传的 file_id) ----
result = client.submit_job(
    model="qwen3.5-9b",                       # 基础模型
    datasets=[
        Dataset(type=DatasetsType.TRAINING,
                data_source_type=DataSourceType.FILE_ID,
                file_id=training_ids[0]),      # 已上传数据返回的 file_id
        Dataset(type=DatasetsType.VALIDATION,
                data_source_type=DataSourceType.FILE_ID,
                file_id=validation_ids[0]),
    ],
    functions=functions,
    resources={
        "charge_type": "mtu_postpaid",         # 计费方式:后付费填 mtu_postpaid;预付费填 mtu_prepaid 并提供 instance_id(联系商务经理获取)
        "mtu_spec_code": "MTU4",               # 训练单元规格
        "mtu_capacity": 24,                    # 本次任务占用的 MTU 数量,不必用满已购容量
    },
    hyper_parameters={
        "algorithm": "gspo",
        "batch_size": 64,
        "eval_steps": 1,
        "kl_loss_coef": 0.002,
        "learning_rate": 2e-6,
        "lr_scheduler_type": "linear",
        "max_length": 8192,
        "n_epochs": 1,
        "n_rollouts": 8,
        "ppo_mini_batch_size": 8,
        "save_strategy": "steps",
        # ... 字段同上方 run() 示例
    })

print(f"Job ID: {result.output.job_id}")

CLI command reference

All three methods can also be completed through the CLI. Common commands:

NoteCommands on this page use the dashscope prefix in examples (applicable to dashscope 2.0.x). If dashscope 2.1.0 or later is installed, all CLI commands in this document must be used with the dashscope1 prefix (for example, dashscope1 rl get "ft-xxx"), with unchanged parameters. Commands in the table show minimal parameters; full parameters such as hyperparameters and resource configuration are best passed via job.yaml (dashscope rl run -c job.yaml).

Action

Command

Description

One-step

dashscope rl run --model "model_name" --rollout-classpaths "classpath" --reward-classpaths "classpath" --training-files "file_path" --verbose

Automatic registration + upload + submission.

YAML configuration

dashscope rl run -c job.yaml -o json

Loads the configuration from a YAML file

Step-by-step submission

dashscope rl submit --model "model_name" --rollout-id "ro-xxx" --reward-ids '["rw-xxx"]' --training-file-ids "file-xxx"

Submits a job using registered Entity IDs

Upload data

dashscope rl upload_data --training-files "file_path" --validation-files "file_path" -o json

Uploads data only and returns File IDs

Training parameter configuration

Runtime resource configuration

Configure compute resources for the Rollout and Reward functions (FunctionComponentRuntime):

Field

Type

Default

Description

cpu

int

1

Number of vCPUs per instance.

memory_size

int

10

Memory (MB).

disk_size

int

10

Disk (MB).

concurrency

int

2

Maximum number of concurrent requests per instance.

capacity

int

10

Initial number of instances.

min_capacity

int

-

Minimum number of instances (auto scaling lower bound).

max_capacity

int

50

Maximum number of instances (auto scaling upper bound).

memory_scale_threshold

float

-

Memory utilization threshold (0~1) that triggers a scale-out.

concurrency_scale_threshold

float

-

Concurrency utilization threshold (0~1) that triggers a scale-out.

env

dict

{}

Environment variables (e.g., ENABLE_TRAJECTORY).

enable_vpc_config

bool

-

VPC network switch. To enable it, contact your account manager.

Note: The default values of memory_size and disk_size in the table (10 MB) are the system minimums of Function Compute (FC). The actual memory usage of RL training is much higher. For production tasks you must raise memory_size to at least 4096 MB and disk_size to at least 512 MB.

Example:

from dashscope.finetune.reinforcement import FunctionComponentRuntime

rollout_runtime = FunctionComponentRuntime(
    cpu=2,
    memory_size=4096,
    disk_size=512,
    concurrency=30,
    capacity=30,
    min_capacity=30,
    max_capacity=60,
    memory_scale_threshold=0.6,
    concurrency_scale_threshold=0.6,
    env={"ENABLE_TRAJECTORY": "true"},
)

Advanced FC runtime tuning

FunctionComponentRuntime is a key factor in the throughput and stability of RL training. To avoid "startup exceptions", you must understand the four-corner relationship, the elasticity policy, and the differentiated configuration of Rollout/Reward.

Four-corner relationship: cpu × memory_size × concurrency × capacity
  • Single-instance throughput = concurrency (constrained by the capacity of cpu / memory_size)
  • Cluster throughput = concurrency × capacity (the effective concurrency upper limit during the Rollout phase)
  • FC system defaults (memory_size=10MB / concurrency=2 / capacity=10) must be changed for production: memory_size ≥ 4096 / disk_size ≥ 512
  • capacity is the initial number of instances and forms an elasticity range together with min_capacity / max_capacity
Elasticity policy: scale_threshold and min/max_capacity
  • A scale-out is triggered as soon as either memory_scale_threshold / concurrency_scale_threshold (0~1) is reached; 0.6~0.7 is recommended (too high leaves no time to scale out, too low wastes instances)
  • Cold starts add a delay of several seconds; set min_capacity to the lower bound of your normal workload to avoid waiting on the first step
  • max_capacity is the last line of defense against abnormal concurrency inflating your bill (MTU controls training resources, capacity controls function resources, and the two are decoupled)
Differentiated configuration for Rollout and Reward

Function type

Resource profile

Recommended configuration

Rollout

I/O-intensive (LLM/tool calls)

Raise concurrency (30+); a high CPU count is not required; timeout starts at 600s

Reward

CPU/compute-intensive (scoring/regular expressions/model-based scoring)

Set concurrency based on the scoring duration; lower the concurrency based on the rate limit when an LLM is called for scoring; timeout starts at 120s

Configure Runtime separately for multiple Reward functions.

Concurrency estimation formula:

  • Target concurrency ≈ batch_size × n_rollouts × average rollout latency (s) / expected time per step (s) (the number of concurrently in-flight rollout requests)
  • Working backwards: concurrency × capacity ≥ target concurrency × 1.2 buffer

Training hyperparameters

RL training hyperparameters are defined uniformly by server-side hyperparameter groups: qwen3.5-9b maps to qwen-rl-v1 (34 items); the 35B series (qwen3.6-flash-2026-04-16 / qwen3.5-flash-2026-02-23 / qwen3.6-35b-a3b) maps to qwen-rl-m35b-v1 (36 items, including 2 MoE parallelism parameters that 9B does not have). The hyperparameter group is matched automatically based on the selected model at submission, so you do not need to specify a group name.

You do not need to pass in all hyperparameters when submitting a task: in the console form, all fields are required except clip_ratio_low, tau_pos, tau_neg, and inference_gpu_memory_utilization; when submitting via API, any parameter not passed in is automatically filled by the server (clip_ratio_low, tau_pos, and tau_neg are not echoed in the task details). qwen3.5-flash-2026-02-23 is an exception: for this model you must explicitly pass in nnodes_rollout (see the recommended training configuration table below for values).

The first console screen shows only basic parameters (n_epochs, learning_rate, batch_size, plus expert_model_parallel_size for 35B); the rest are advanced parameters, collapsed by default and pre-filled, so you can submit directly.

Parameters are divided into 6 groups by function: algorithm and optimization, batch and sampling, sequence length, learning rate and scheduling, evaluation and saving, and distributed parallelism and resources.

Algorithm and Optimization

Parameter

Description

algorithm

RL training algorithm (grpo / dapo / gspo / sapo / cispo); for selection guidance see "Algorithm selection"

use_kl_loss

Whether to add a KL regularization term to the loss, constraining the policy from deviating too far from the reference model

kl_loss_coef

KL loss coefficient; the larger the value, the stronger the constraint on the reference model

clip_ratio_high

Upper-bound clipping magnitude for the importance sampling ratio; works with clip_ratio_low to control the magnitude of policy updates

clip_ratio_low

Lower-bound clipping magnitude for the importance sampling ratio

tau_pos

SAPO gating temperature, applied to positive-advantage samples (see SAPO-specific hyperparameters)

tau_neg

SAPO gating temperature, applied to negative-advantage samples (see SAPO-specific hyperparameters)

max_off_policy_threshold

Maximum allowed degree of off-policy for a sample (measured as the version gap between the rollout policy and the current policy; samples beyond it are dropped)

max_off_policy_strategy

How samples exceeding the threshold are handled; currently only discarding is supported

Batch and Sampling

Parameter

Description

batch_size

Prompt batch size sampled at each training step

n_rollouts

Number of responses generated per prompt, used for within-group advantage estimation

ppo_mini_batch_size

Mini-batch size for policy updates (counted in prompts)

n_epochs

Number of training epochs (number of passes over the dataset)

num_warmup_batches

Number of warm-up batches before formal training; 0 means no warm-up

Sampling parameters on the rollout generation side (temperature, top_p, etc.) are not part of the hyperparameters above; they are set in the Rollout function code (read via input.sampling_params with fallback defaults—for the pass-through pattern, see the trace_client sampling parameter pass-through in Reinforcement learning observability and metrics).

Sequence Length

Parameter

Description

max_prompt_length

Maximum token length of the prompt

max_length

Maximum total token length of a single sample (prompt + response); must be no less than max_prompt_length

enable_thinking

Whether to allow the model to output reasoning content in responses; when enabled, responses become significantly longer, so re-evaluate max_length accordingly

Learning rate and scheduling

Parameter

Description

learning_rate

Learning rate

lr_scheduler_type

Learning rate scheduling policy (linear / cosine / inverse_square_root / constant)

lr_warmup_steps

Number of learning rate warmup steps; -1 means the training framework decides

Evaluation and checkpoint saving

Parameter

Description

eval_steps

Run an evaluation every N training steps

save_strategy

Checkpoint saving policy; currently only step-based saving is supported

save_steps

Save a checkpoint every N training steps

save_total_limit

Maximum number of checkpoints to keep; the oldest are deleted when the limit is exceeded

Distributed parallelism and resources

Parameter

Description

nnodes_training

Number of training nodes (1 / 2 / 4 / 8)

n_gpus_training

GPUs per training node (1 / 2 / 4 / 8); total training GPUs = nnodes_training × n_gpus_training

tensor_model_parallel_size

Training tensor model parallelism (TP, 1 / 2 / 4 / 8)

pipeline_model_parallel_size

Training pipeline model parallelism (PP, 1 / 2 / 4 / 8)

sequence_parallel_size

Context Parallel (CP) degree (1 / 2 / 4 / 8); splits along the sequence dimension to share long-sequence memory

expert_model_parallel_size

MoE expert model parallelism (EP, 1 / 2 / 4 / 8 / 16 / 32 / 64 / 128); must divide the number of model experts; available only for the 35B series

nnodes_rollout

Number of inference (rollout) nodes (1 / 2 / 4 / 8)

n_gpus_rollout

GPUs per inference node (1 / 2 / 4 / 8); total inference GPUs = nnodes_rollout × n_gpus_rollout

inference_tensor_parallel_size

Inference engine tensor parallelism (1 / 2 / 4 / 8)

inference_expert_parallel_size

Inference engine expert parallelism (1 / 2 / 4 / 8 / 16), available only for the 35B series

inference_gpu_memory_utilization

Fraction of inference engine GPU memory used (for KV cache, etc.); a higher value increases throughput but also the risk of OOM

enable_last_assistant_rollback

Whether to enable rollback of the last assistant message during rollout generation in the Agent framework; true means enabled; enabled by default

Parameter constraints (the server validates the following combinations at submission time; actual validation results prevail):

  • batch_size must be in [8, 2048] and a multiple of 8; ppo_mini_batch_size must be in [1, 256]; max_length / max_prompt_length must be in [128, 131072]
  • batch_size = N × ppo_mini_batch_size (N is a positive integer); batch_size, n_rollouts, and ppo_mini_batch_size must satisfy divisibility relations so that mini-batches are evenly split across data parallel workers
  • max_length ≥ max_prompt_length; increasing either significantly increases GPU memory usage
  • The total number of training GPUs (nnodes_training × n_gpus_training) must be divisible by TP × PP × CP, with the quotient being the data parallelism; MoE models must also satisfy divisibility between EP and the total GPU count
  • The total number of inference GPUs (nnodes_rollout × n_gpus_rollout) must match the product of the parallelism degrees on the inference side

Warningmtu_capacity (the number of MTUs in resources) must strictly equal the sum of the resource scale of the two phases: mtu_capacity = nnodes_rollout × n_gpus_rollout + nnodes_training × n_gpus_training. After changing any parameter, you must update mtu_capacity accordingly to keep them strictly equal.

Tiered by context length, the recommended training configuration for each model is as follows:

16k context

Each model has a 16k context; submit with the configuration in the following table (hyperparameters not listed in the table do not need to be passed in); switch tabs if you need a 128k context:

Parameter

qwen3.5-9b

35B series (incl. flash)

nnodes_rollout

1

1

n_gpus_rollout

8

8

nnodes_training

2

4

n_gpus_training

8

8

tensor_model_parallel_size

8

4

expert_model_parallel_size

-

8

inference_expert_parallel_size

-

1

Corresponding mtu_capacity

24

40

128k context

When training data requires a 128k context length (max_length = 131072), use the following configuration in hyper_parameters depending on the model:

Parameter

qwen3.5-9b

qwen3.6-35b-a3b

max_prompt_length

130048

130048

max_length

131072

131072

nnodes_training

4

4

nnodes_rollout

2

2

tensor_model_parallel_size

2

2

pipeline_model_parallel_size

2

2

sequence_parallel_size

8

8

expert_model_parallel_size

-

8

inference_gpu_memory_utilization

-

0.75

inference_tensor_parallel_size

1

2

inference_expert_parallel_size

-

2

Corresponding mtu_capacity

48

48

NoteThe 9b model has no MoE-related parallelism parameters (indicated by - in the table; inference&#95;gpu&#95;memory&#95;utilization shown as - means it does not need to be passed in). n&#95;gpus&#95;rollout and n&#95;gpus&#95;training keep the default of 8 (2×8 + 4×8 = 48); mtu_capacity is 48, so the number of training units in resources must be adjusted accordingly when submitting. If the flash series (qwen3.6-flash-2026-04-16 / qwen3.5-flash-2026-02-23) requires 128k context, refer to the qwen3.6-35b-a3b column for configuration.

Important35B tuning suggestions: for 35B series models, the GSPO algorithm is recommended first; learning_rate can be reduced to 1/2~2/3 of the 9B value; n_rollouts can be raised to 8~16 to amortize sampling overhead; if expert_model_parallel_size needs to be explicitly reduced, start from 2/4; inference_tensor_parallel_size can be raised to 4.

Code example

For your first training run, it is recommended to first verify the pipeline with the following low-cost trial configuration; once it passes, let the server fill in the remaining hyperparameters for formal training:

# 验证链路用:小 batch + 单 epoch 快速确认配置可提交,跑通后由服务端补全超参
hyper_parameters = {
    "algorithm": "gspo",
    "learning_rate": 2e-6,
    "n_epochs": 1,
    "batch_size": 64,
    "n_rollouts": 8,
    "ppo_mini_batch_size": 8,        # 64 = 8 × 8
    "kl_loss_coef": 0.002,
    "lr_scheduler_type": "linear",
    "lr_warmup_steps": -1,
    "max_length": 8192,
    "max_prompt_length": 1024,
    "eval_steps": 1,
    "save_strategy": "steps",
    "save_steps": 100,
    "save_total_limit": 1,
}

Algorithm selection: GSPO / GRPO / DAPO / SAPO / CISPO

The server-side default algorithm is grpo (applied automatically when algorithm is not specified); as a conservative baseline it suits beginners and short-response scenarios. For long sequences and MoE scenarios, explicitly specifying gspo is recommended (general recommendation); other switches require a clear motivation (reproduction / long CoT / convergence anomalies). Code examples in this document uniformly specify gspo explicitly; using the default grpo for your first successful run is also fine.

  • GRPO (DeepSeekMath 2024): Token-level importance sampling + intra-group relative advantage, no critic
  • GSPO (Qwen 2025, general recommendation): Sequence-level importance sampling, lower variance, better stability for long-sequence training
  • DAPO: GRPO + Clip-Higher (clip_ratio_low=0.2 / clip_ratio_high=0.28) + Dynamic Sampling + Token-level Loss + Overlong Reward Shaping, optimized for long CoT reasoning
  • SAPO (arXiv 2511.20347): replaces PPO's hard clipping with smooth gating — the gradient decays smoothly once the importance ratio r deviates from 1, instead of dropping to zero as with hard clipping; the larger the gating temperature, the faster the decay and the closer to hard clipping, while the smaller it is, the gentler the decay and the closer to unclipped PG
  • CISPO (arXiv 2506.13585): truncates the importance sampling weights rather than the updates themselves — tokens whose r exceeds the upper bound still retain their gradients (PPO zeroes the gradients of these tokens)

R3 (expert routing replay): enabled by default for all RL algorithms (GSPO / GRPO / DAPO / SAPO / CISPO)—during rollout inference, the MoE expert routing is recorded and replayed during training, which significantly narrows the logprob difference between the training and inference sides, with a corresponding end-to-end accuracy gain. It takes effect by default and requires no configuration; no option to disable it is currently provided (for technical background, see arXiv 2510.11370 and verl Router Replay).

Dimension

GRPO

GSPO

DAPO

Importance sampling granularity

Token-level

Sequence-level

Token-level + Clip-Higher

Typical KL constraint usage

≈ 0.04

≈ 0.001

0

MoE stability

Prone to instability

Natively stable

Requires tuning

Long CoT friendliness

Average

Good

Best

Server-side default

Yes

No

No

Recommended scenarios

Short responses / getting started

General first choice / long sequences

Long-chain reasoning / math / code

Selection decision path:

  • Default grpo (the server-side default when algorithm is not specified); GSPO is recommended for long sequences or MoE (qwen3.6-35b-a3b), with its advantages mainly in long-sequence training stability
  • Switch to GRPO: when token-level fine-grained signals are needed / alignment with community GRPO implementations is required
  • Switch to DAPO: response length > 4K / reward collapse where everything is right or wrong / late-stage entropy collapse
  • Switch to SAPO: when you want smooth, controllable policy update magnitudes (no hard clipping), using tau_pos / tau_neg to separately tune how conservative the updates are for positive / negative advantage tokens
  • Switch to CISPO: when you want out-of-bound tokens to retain gradients (truncating IS weights instead of hard zeroing); the default truncation interval is [0, 1.2], with no extra parameters needed

The clipping mechanisms of SAPO / CISPO (smooth gating / IS weight truncation) use different dimensions than the three algorithms in the table above, so the table does not apply directly to them. For changes in metric semantics after switching to either algorithm, see Observability Configuration and Metrics Reference for Reinforcement Learning § algorithm-related metric calibers.

SAPO-specific hyperparameters

Parameter

Description

tau_pos

SAPO gating temperature, applied to tokens with advantage > 0

tau_neg

SAPO gating temperature, applied to tokens with advantage ≤ 0

Warningtau_pos / tau_neg must be positive (the gating computation includes 4/tau; non-positive values cause division by zero or flip the gradient sign). We recommend tau_pos ≥ 1.0 and tau_neg &gt; tau_pos (updates of negative-advantage tokens are more conservative).

Configuration example (specified in hyper_parameters):

CISPO

# IS 权重截断区间默认 [0, 1.2],其余参数不用动
"algorithm": "cispo"

SAPO (default tau)

# 默认使用论文的 tau,无需显式指定
"algorithm": "sapo"

SAPO (increased tau_neg)

# 希望负优势 token 的更新更保守时,调大 tau_neg
"algorithm": "sapo", "tau_pos": 1.0, "tau_neg": 1.3

Tuning decision table (symptom → what to adjust → how)

When metrics are abnormal, refer to this table to select the primary action and its magnitude (for local methods of checking reward discrimination, see Pre-submission Checklist for Reinforcement Learning); for the complete P1~P9 troubleshooting, see the troubleshooting decision tree in Reinforcement learning observability and metrics.

Symptom

Primary action

Adjustment magnitude

Fallback

P1 no convergence

Check reward discrimination first, then learning_rate ↑

× 1.5~2

Check data volume and duplication

P2 oscillation

learning_rate ↓

×0.5

If still oscillating, batch_size ×2; n_rollouts ↑

P3 KL explosion

kl_loss_coef ↑

× 5~10

Lower the lr

KL ≈ 0, not learning

Check reward discrimination (local test_functions, zero cost)

—

Same as P1: data / lr checks

P4 entropy collapse

clip_ratio_high ↑

0.2 → 0.28

Switch to DAPO or n_rollouts ↑

Slow rollout

n_rollouts ↓ / tighten max_length

—

Add n_gpus_rollout (see advanced parallelism) or FC concurrency (see FC tuning)

OOM (training side)

ppo_mini_batch_size ↓

× 0.5

max_length ↓ / tensor_mp ↑ (see advanced parallelism; rollout-side OOM also covered there)

P9 high truncation rate

max_length ↑

+ 2048

Check max_prompt_length

P6 overfitting

Cut losses by picking an earlier checkpoint to publish

—

Next experiment: reduce n_epochs to 1~2

Tuning recommendations

  • Change only one variable at a time: tuning learning_rate and batch_size simultaneously makes attribution impossible
  • Run at leasteval_steps × 3 evaluation cycles and no fewer than 150 steps before judging: 50 steps show no trend — RL is not SFT, the curves are noisy

Tuning priority is implied in the "Primary action" column of the tuning decision table. For details on retaining intermediate checkpoints, see §Resuming training, checkpoints, and progressive training.

Hyperparameter anti-patterns

Anti-pattern

Consequence

Using the SFT lr starting point (5e-5) for RL

Training is likely to diverge—RL is far more sensitive to lr than SFT

Setting n_epochs to 10+ hoping to "train it through"

RL is not SFT; too many epochs trigger P6 validation set collapse

kl_loss_coef=0 with n_epochs > 1 or a large lr

No KL backstop, the policy drifts easily (KL=0 is itself viable—DAPO uses no KL and controls drift via ratio clipping, but requires on-policy and a conservative lr)

n_rollouts=1

Within-group advantage is always 0 and the policy never updates (GRPO/GSPO/DAPO and other within-group relative advantage algorithms all require ≥2; zero gradient also occurs when within-group rewards have no variance)

Under the default parallelism, max_length=32K to play it safe

GPU memory blows up + rollout slows down; set it just high enough for your scenario (for 128k context see recommended training configuration)

Advanced parallelism parameters and GPU memory estimation

For the descriptions of each parallelism parameter, see the "Distributed Parallelism and Resources" group table; below, tensor_mp / inference_tp / expert_mp / CP are shorthand for tensor_model_parallel_size / inference_tensor_parallel_size / expert_model_parallel_size / sequence_parallel_size (Context Parallel), respectively.

When to adjust the resource configuration (5 triggers; OOM is split into training side / rollout side):

  • Training-side OOM → tensor_mp ↑ or ppo_mini_batch_size ↓
  • Rollout-side OOM → inference_gpu_memory_utilization ↓ 0.1 (rollout and training run on different nodes; lowering it only affects the per-GPU KV cache limit on the rollout side)
  • Slow rollout → add n_gpus_rollout; consider inference_tp ↑ only for long-context / large-model scenarios
  • Slow single-step training → add n_gpus_training; for long sequences, add sequence_parallel_size
  • MoE models → expert_model_parallel_size must be tuned

GPU memory estimation notes:

  • Per-GPU memory ≈ model weights (bf16 ≈ 2 bytes/param) + optimizer (AdamW ≈ 8 bytes/param, excluding fp32 master weights) + activations (scale with bs × seq_len) + KV cache
  • 9B dense weights + optimizer ≈ 90 GB per instance (excluding activations and KV cache), which must be sharded via TP
  • Lowering inference_gpu_memory_utilization lowers the per-GPU KV cache limit on the rollout side and reduces OOM risk
  • Do not blindly add nodes; partition with TP first. Common counter-examples: raising tensor_mp when the model is small and GPUs are plentiful → communication eats the gains, inference_gpu_memory_utilization=0.95 → OOM jitter, setting expert_mp > 1 for a Dense model → error, a product of parallelism degrees exceeding total training GPUs → invalid configuration

Job management

Action

SDK

CLI

Query status

AgenticRL.get(job_id="ft-xxx")

dashscope rl get "ft-xxx" -o json

List jobs

AgenticRL.list()

dashscope rl list --page 1 --size 10 -o json

Cancel job

AgenticRL.cancel(job_id="ft-xxx")

dashscope rl cancel "ft-xxx"

View logs

AgenticRL.logs(job_id="ft-xxx", lines=100)

dashscope rl logs "ft-xxx" --offset 1 --lines 100

Experiment management

YAML multi-experiment mode

  • job_name identifies the experiment and tuned_model_name identifies the output model; changing just these two for each run is enough to isolate experiments
  • YAML centralizes the management of model/datasets/functions/runtime/hyper_parameters, which facilitates Git versioning
  • Precedence: __init__() < YAML < runtime parameters in run()/submit_job()—for controlled experiments, change only the outermost layer

Why choose submit_job for hyperparameter sweeps / CI integration

Scenario-based decisions among the three submission methods:

  • Hyperparameter sweeps / CI: when functions are stable and only hyperparameters change → submit_job(entity_id=...) skips repeated registration + upload (10x+ speedup)
  • First run / debugging the Reward: use run(), which automatically re-registers on each run to prevent code from getting out of sync
  • Entity IDs (ro- Rollout / rw- Reward) are taken from the return value of the first registration and can be added to CI configuration for long-term reuse

CI integration and command reference

  • After submitting with dashscope rl run -c job.yaml -o json, parse the job_id from the output and poll the status; if it is FAILED, pull the logs immediately and raise an alert; -o json is essential for CI parsing

Resuming training, checkpoints, and progressive training

A completed training job is not the same as a successful one—you must select the right checkpoint before publishing.

Checkpoint retention and selection

  • save_strategy=steps + save_steps=100 + save_total_limit=3: keeps at most 3 checkpoints; when the limit is exceeded, the oldest is cleaned up automatically
  • Which checkpoint to select: you must pick the best point based on validation/data/reward/mean@1, which is not necessarily the last one
  • Keep 3~5 checkpoints to balance space and rollback needs

Resuming training from a published checkpoint

  • Resuming training = submitting again with the previously produced model as the model input parameter; hyperparameters can be fine-tuned (lr is usually reduced)
  • Applicable to: data increments / Reward adjustments / gradual convergence over long pipelines
  • Note: the foundation model version must be the same; resuming training directly across different base models is not supported
  • In a multi-stage training pipeline, the output of each stage can serve as the model input for the next stage, progressing level by level (for CPT/SFT/DPO/RL concepts, see Reinforcement Learning Training Overview)

FAQ

Function registration fails

  • Check that the classpath is correct (format: module.path.ClassName)
  • Confirm that requirements.txt exists in the project root directory
  • Confirm that all dependencies are listed in requirements.txt

Job submission fails

  • Check that the Entity ID and File ID are valid
  • Confirm that the base model is available in the current region
  • Check that the runtime configuration of each Reward component in the functions list is complete; when submitting via CLI, confirm that reward-related parameters match the number of function components

How to optimize performance

  • Use async def process for I/O-intensive tasks
  • Raise concurrency within the limits allowed by CPU/memory
  • ENABLE_TRAJECTORY adds storage and latency; enable it as needed for formal training

How to troubleshoot invisible traces

For troubleshooting steps, see How to troubleshoot when Trace is not visible in Reinforcement learning observability and metrics (covering the complete workflow of ARMS authorization, the ENABLE_TRAJECTORY switch, and dependency checks).

How to view training logs

  • SDK: AgenticRL.logs(job_id="ft-xxx", lines=100)
  • CLI: dashscope rl logs "ft-xxx" --offset 1 --lines 100
  • You can also view them on the training detail page in the Model Studio console

How to publish a checkpoint as a usable model

  • Go to the output tab of the training detail page in the Model Studio console, find the target checkpoint, and click the "Publish" button
  • After publishing, the model can be called directly through the API by its model name

How to troubleshoot a training reward that does not increase

A reward that does not increase falls into the "P1 no convergence" scenario. Troubleshoot in the following order:

  1. Check the primary signals: critic/rewards/mean on a long plateau + actor/ppo_kl ≈ 0 + very small actor/grad_norm → P1
  2. Common root causes (from lowest to highest troubleshooting cost): the Reward function always returns the same value (zero-cost to check locally with test_functions) → insufficient or duplicated data → lr too small
  3. Recommended first action: first confirm locally with test_functions that the scores have discrimination (not always 0 or always 1—see the Pre-submission Checklist for Reinforcement Learning); once discrimination is confirmed, learning_rate × 1.5~2 (see the tuning decision table)
  4. Fallback: check data volume and duplication

For the complete P1~P9 troubleshooting decision tree, see the troubleshooting decision tree in Reinforcement learning observability and metrics.

Next steps