Skip to main content

Reinforcement learning pre-submission self-check

Use the test_functions testing system to complete the pre-submission self-check for RL training: from the testing tools bundled with the Demo package, to custom function tests, and finally to pre-submission smoke verification.

RL training is billed by Training units hours (taking the IV type with 24 instances on pay-as-you-go as an example, approximately 984 CNY/hour), and errors that surface only after the task starts are the most costly. The pre-submission self-check revolves around the test_functions testing system: first use the testing tools bundled with the Demo package to verify the environment and pipeline, then test custom functions, and finally confirm the configuration with a smoke submission that is canceled immediately — local testing is free, a smoke submission starts at about 16 CNY, and only submit the formal task after it passes.

Demo package testing tools overview

The Demo package (Prepare data and code) comes with a complete set of function testing facilities:

Tool

Purpose

test_functions.py

Test script: provides an independent, complete "registration → remote testing → log retrieval" closed loop for each of the four function types: Rollout / Reward / decorator Reward / Group Reward

resources/*.json (4 files)

Sample test inputs for the four function types (rollout_input / reward_input / reward_decorator_input / group_reward_input); see the detailed field descriptions below

cli.sh

A collection of local testing and query commands (equivalent CLI entry points)

scripts/start_local_*.sh

Script for starting the function service locally (usable for Reward functions; the classpath of the Rollout version points to a nonexistent module and fails to start — start it with the environment variable method instead)

The field structure of the test input JSON is identical to the requests delivered by the framework during training; a passing test indicates that the function's invocation behavior during training meets expectations.

Test the Demo functions

Run test_functions.py

In the project root directory (the DASHSCOPE_API_KEY environment variable must be set; see environment preparation), run:
python test_functions.py
By default the script only runs the Rollout test (the other three types are commented out in __main__); to test the other functions, uncomment the corresponding lines or call them yourself:
# test_functions.py 末尾 —— 四个测试函数完全独立,删除任一调用不影响其余
asyncio.run(test_rollout(
    classpath="functions.rollout.rollout_only.DemoRolloutProcessor",
    input_path="./resources/rollout_input.json"))
# asyncio.run(test_reward(
#     classpath="functions.reward.reward.DemoRewardProcessor",
#     input_path="./resources/reward_input.json"))
# asyncio.run(test_reward_decorator(
#     classpath="functions/reward/reward_decorator.py:SafetyProcessor",
#     input_path="./resources/reward_decorator_input.json"))
# asyncio.run(test_group_reward(
#     classpath="functions.reward.group_reward.DemoGroupRewardProcessor",
#     input_path="./resources/group_reward_input.json"))
Each test function internally forms a complete closed loop:
注册函数(register_functions,lazy_load=False 立即拉起实例)
    → 拿到 instance_id
    → 远程调用(test_functions 发送测试输入)
    → 拉取实例日志(query_all_function_instance_logs)

Test input field reference

Top-level fields of the four test inputs:

Field

Applicable functions

Description

func_type

All

Function type: rollout / reward / group_reward (for decorator Reward, enter reward)

messages

Rollout

List of conversation messages; during training it comes from the messages field of each row in the dataset

ground_truth

All

Reference answer, readable by scoring logic (for the value flow during training, see the RewardInput field description in the developer guide)

rollout_extra

Rollout

Pass-through content of the dataset rollout_extra field; custom business data

sampling_params

Rollout

Sampling parameters: temperature, max_tokens, max_turns, timeout

model_resource

Rollout

Inference endpoints: model_name, base_url, api_key (automatically injected by the framework during training; you must fill in a usable endpoint when testing. For example values, see Development guide — Test input format)

agent_output

Reward class

Agent outputs to be scored: messages, rollout_extra, rollout_metrics, reward_score

agent_outputs

Group Reward

An array of multiple outputs for the same sample (plural), distinguished from the single agent_output

request_metadata

Optional

Framework metadata (job_id, sample_id, etc.); can be omitted or filled with placeholder values during testing

tools

Rollout optional

List of available tools; pass null if there are no tools

additional_field

Optional

Any custom additional fields, passed through as-is by the framework

Expected return values

Actual returns from the four demo test inputs (consistent between the local service and cloud test_functions on both ends):

Test input

Function under test

Expected return

rollout_input.json

DemoRolloutProcessor

status=success, reward_score=0.95 (Rollout embeds the scoring logic; the test input uses a placeholder inference endpoint and does not actually call inference)

reward_input.json

DemoRewardProcessor

status=success, reward_score=0.0, reward_metrics contains test1/test2

reward_decorator_input.json

SafetyProcessor (decorator)

status=success, reward_score=0.85 (weighted aggregation result of sub-dimensions)

group_reward_input.json

DemoGroupRewardProcessor

status=success, the rewards array length matches agent_outputs, with a single value of 0.5

When a return value does not match the expectation, first check whether the test input has been modified; if the input is unchanged but the result still differs, locate the issue through log query.

Test custom functions

Once all four types of demo function tests pass, the environment and pipeline have been verified. Replace the classpath with your custom function and the test input with your own constructed cases, then follow the same test path. Place the custom function source code in the project functions/ directory (the classpath is the module path relative to the project root, e.g., functions/reward/my_reward.py corresponds to functions.reward.my_reward.MyRewardProcessor); during registration, the SDK packages the project code and requirements.txt for upload, so all dependencies must be listed in requirements.txt.

Construct test cases

Construct 3 test inputs for your custom scoring logic whose expected scores can be manually computed — the expected scores are determined by your custom scoring logic:

Test case

Construction method

Expected score

Full-score sample

Put a response in messages that is guaranteed to hit the scoring conditions (contains the correct answer, meets the format), and fill ground_truth with the corresponding ground truth

The full score of the scoring logic (for example, 1.0)

Zero-score sample

Put a response in messages that is guaranteed to miss (wrong answer, format mismatch)

0.0

Boundary sample

The forms most likely to be misjudged: empty messages, extremely long responses, partially matching answers, different casing

Based on the defined boundary behaviors (if a boundary behavior is undefined, first add its definition in the scoring logic)

Save the three inputs separately (e.g., my_reward_test_full.json, my_reward_test_zero.json, my_reward_test_edge.json). Reward class input template (see Test input field details for the field structure):
{
  "func_type": "reward",
  "ground_truth": "42",
  "agent_output": {
    "messages": [
      {"role": "user", "content": "计算 6 × 7"},
      {"role": "assistant", "content": "### ANSWER: 42 ###"}
    ]
  }
}

Local service verification

Before remote testing, first run your custom function locally as a service and verify the three cases (see Test input field details for the Rollout input structure). The service takes a few seconds to start; if you get connection refused, wait briefly and retry:
# 终端 1:启动本地函数服务(bash,PROCESSOR_CLASS 换为自定义类)
FUNC_TYPE=reward PROCESSOR_CLASS=functions.reward.my_reward.MyRewardProcessor \
PYTHONPATH=. python -m dashscope.finetune.reinforcement.component.server.server

# 终端 2:逐个发送三份测试用例
curl -X POST http://localhost:8000/api/v1 \
  -H "Content-Type: application/json" \
  -d @my_reward_test_full.json
Windows PowerShell equivalent command:
# 终端 1
$env:FUNC_TYPE="reward"
$env:PROCESSOR_CLASS="functions.reward.my_reward.MyRewardProcessor"
$env:PYTHONPATH="."
python -m dashscope.finetune.reinforcement.component.server.server

# 终端 2(Windows PowerShell 下 curl 为 Invoke-WebRequest 别名,@file 语法不可用;推荐统一使用 Invoke-RestMethod)
Invoke-RestMethod -Method Post -Uri http://localhost:8000/api/v1 `
  -ContentType "application/json" -InFile my_reward_test_full.json
Example expected return:
{"reward": {"reward_score": 1.0, "reward_metrics": {"accuracy": 1.0}},
 "status": "success", "error": null, "error_code": null}
Pass criteria: the returned status for all three inputs is success, and each reward_score in reward matches the expected score; any mismatch indicates a defect in the scoring logic, which must be fixed before proceeding to remote testing. A score of 0 is a valid result — TaskStatus returns SUCCESS; only transient errors (timeout, network jitter) return FAILED (see Development guide — TaskStatus determination for scoring scenarios for details). To test the rollout function locally, replace model_resource in the test input with an available inference endpoint and API Key: you must use an API Key that supports inference calls (created on the API-KEY page of the Model Studio console, with the sk- prefix). If the credentials used for the training submission do not support inference calls, a 401 (Incorrect API key) will be returned here. During training, there is no need to configure an inference endpoint yourself — the endpoint and key are automatically injected at runtime by the training framework (see RolloutInput key fields). At the reward logic design level, two self-checks are recommended before submission: self-check before writing the Reward function (10 questions); and prepare a gold set of 50-200 manually annotated entries (gold-standard answer set) for the reward consistency self-check. Also keep the field names in reward_metrics stable — renaming them will break the continuity of the metric curves in the console.

Remote testing of custom functions

Register the functions to the cloud and execute them in a real FC container — differences between the local and container environments (dependency installation, packaging paths, runtime behavior) can only be exposed by this step (the DASHSCOPE_API_KEY environment variable must be set, see environment preparation). The first registration includes building the function dependency layer, which takes about 1-3 minutes with no output during that period — this is normal.
import asyncio, json
from dashscope.finetune.reinforcement import (
    AgenticRLFunctionComponent, FunctionType, FunctionComponentModel)
from dashscope.finetune.agentic_rl import AgenticRL

async def main():
    client = AgenticRL()
    # 注册自定义函数(classpath 与本地服务为同一字符串)
    ids = await client.register_functions(
        functions=[AgenticRLFunctionComponent(
            type=FunctionType.REWARD,
            fcmodel=FunctionComponentModel(
                classpath="functions.reward.my_reward.MyRewardProcessor"))],
        lazy_load=False)   # 立即拉起实例用于测试
    # ids 为 6 元组:(rollout_entity, reward_entity, group_reward_entity,
    #  rollout_instance, reward_instance, group_reward_instance) 的 ID 列表
    reward_entity_ids, reward_instance_ids = ids[1], ids[4]

    # 逐个发送本地验证过的三份测试用例(input_data 接受 dict)
    for case in ["my_reward_test_full.json", "my_reward_test_zero.json",
                 "my_reward_test_edge.json"]:
        with open(case, "r", encoding="utf-8") as f:
            input_data = json.load(f)
        result = await AgenticRL.test_functions(
            instance_id=reward_instance_ids[0],
            functype=FunctionType.REWARD,
            input_data=input_data,
        )
        print(case, result)

asyncio.run(main())
Each register_functions call and each submission registers new function entities that accumulate in your account (the local project root directory will generate start.sh and temporary packaging files, which can be ignored or deleted). Function instances created by tests can be viewed and managed on the FC page of the console. Pass criteria: the return results of the three test cases match the local verification results item by item. If they do not match, first check requirements.txt (the container installs dependencies based on it), then locate the issue through the instance logs (see log query) — if a function instance fails during the startup phase, logs may not have been generated yet (an empty list is returned); in that case, rely on the error message in the test_functions return result.

test_functions details

SDK signature

result = await AgenticRL.test_functions(
    instance_id="rw-ins-xxx",     # 注册返回的函数实例 ID
    functype=FunctionType.REWARD, # 函数类型枚举
    input_data=input_data,        # 测试输入(dict,结构见测试输入字段详解)
    pull_logs=True,               # 可选:返回时顺带拉取实例日志
)

Parameter

Description

instance_id

Function instance ID (ro-ins- / rw-ins- / grw-ins- prefix), from the register_functions return value, or from the CLI registration command output

functype

FunctionType enum: ROLLOUT / REWARD / GROUP_REWARD; note that the SDK parameter name is functype (the CLI parameter name is --type)

input_data

Test input, of dict type (loaded from a JSON file via json.load, or constructed by yourself according to the field details)

pull_logs

Optional; when True, the return result includes instance logs

register_functions returns a 6-tuple (lists of entity and instance IDs for the three types rollout/reward/group_reward; unregistered types are empty lists); for the semantics of lazy_load values and a complete unpacking example, see development guide — register functions.

CLI comparison

Commands on this page are shown with the dashscope prefix (applicable to dashscope 2.0.x). If you have installed dashscope 2.1.0 or later, use the dashscope1 prefix for all CLI commands in this document (e.g., dashscope1 rl get "ft-xxx"); the parameters remain unchanged.

Actions

Command

Test functions

dashscope rl test_functions "rw-ins-xxx" --type reward --input my_reward_test_full.json (--type values: rollout / reward / group_reward)

Upload data

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

Query task

dashscope rl get "ft-xxx" -o json (list / cancel / logs use the same form)

Log query

When a test fails, pull the function instance logs (query_all_function_instance_logs): the logs take about 30 seconds to become ready (the test function in test_functions.py has this step built in); if a function instance fails during the startup phase, logs may not have been generated yet (an empty list is returned); in that case, rely on the error message in the test_functions return result. For how to call it and a complete example, see development guide — remote testing.

Submission smoke test

After all function tests pass, make one real submission to confirm the server accepts all the configurations, then cancel it immediately. Apart from the two changes below, the parameters are exactly the same as a formal submission: set batch_size to 8 and replace the data with a slimmed-down file of about 10 rows (for the data format, see data format). For the complete parameter syntax, see configuration — one-step completion (run). Billing basis: taking 24 pay-as-you-go instances as an example, the cost is about 984 CNY/hour (the minimum billing granularity for pay-as-you-go is 1 minute, i.e., about 16 CNY/minute); keeping the time from submission to cancellation within 1 minute costs about 16 CNY minimum, and every additional minute of delay in canceling adds about 16 CNY.
import asyncio
from dashscope.finetune.agentic_rl import AgenticRL

async def main():
    client = AgenticRL()
    # run 为 async;参数为正式提交的完整参数(函数/数据/超参/资源)
    result = await client.run(
        model="your-model",
        functions=[...], training_datasets=[...], validation_datasets=[...],
        hyper_parameters={...}, resources={...})

    # 先确认提交结果再取 job_id(提交被拒时 output 为空,直接取值会报错)
    if result.status_code != 200:
        print(f"提交被拒: {result.message}")   # 服务端拒绝原因(如 batch_size 超范围)
        return

    # ---- 拿到 job_id 后立即执行以下两行(get/cancel 为同步方法,无需 await)----
    job_id = result.output.job_id
    g = AgenticRL.get(job_id=job_id)      # 回显任务详情,核对超参与资源配置
    c = AgenticRL.cancel(job_id=job_id)   # 立即取消,控制费用

asyncio.run(main())
Pass criteria:
  • run returns normally (status_code is 200) and job_id is non-empty — the full pipeline of function registration, data upload, and parameter validation is accepted by the server
  • In the hyper_parameters echoed by get, fields not explicitly filled in are automatically populated by the server (such as enable_thinking, max_off_policy_strategy, etc.) — verify that the populated values do not conflict with your expectations
  • Verify two resource configurations: mtu_capacity = nnodes_rollout × n_gpus_rollout + nnodes_training × n_gpus_training (Distributed parallelism and resources); function Runtime memory_size ≥ 4096 and disk_size ≥ 512 (Runtime resource configuration)
  • Smoke test data volume works with batch_size: a small amount of data (such as 10 rows) is enough; the data volume is then below the formal batch_size, so batch_size must be lowered to no more than the number of data rows (the server requires a value range of 8~2048, see the Batch and sampling parameter table); setting it to 8 for smoke tests is sufficient
Execute cancel immediately after obtaining the job_id—uncanceled jobs queue up to enter RUNNING and are billed by training unit hours. If the script throws an error before cancel (for example, misusing await on a synchronous method), the job may have been submitted but the script lost the job_id; in that case, use AgenticRL.list() to retrieve the latest job and cancel it.

Cost and duration of the first training

This section provides the acceptance criteria for the first training after submission (not a pre-submission step): actually execute a training run with the minimum data volume + 1 epoch to confirm that the first step produces trajectories and metrics, and that Reward has gradients (not constantly 0 or 1). Expected duration (based on actual measurements with demo streamlined data of 128 entries, batch_size=64, and 24 postpaid instances):
  • Approximately 1 minute from submission to entering RUNNING (when resource queuing is normal)
  • Producing trajectories and metrics for the first step typically takes more than 30 minutes (the first step must complete all Rollout sampling; it is normal to see no output within 25 minutes in actual tests, so do not prematurely determine failure)
  • Approximately 1 hour 45 minutes for a complete run to SUCCEEDED
Cost basis (billed by training unit hours; for unit prices, see Training unit prices):
  • Stopping at the point where "first step metrics appear and are normal" typically costs several hundred CNY; a complete run costs approximately 1,000+ CNY
  • Cancelling a task before training begins incurs no charge (measured usage is 0); after training starts, billing is based on actual usage, and the usage field in task details displays the cumulative usage
  • Full training cost estimation: Instances × estimated duration × hourly unit price—the estimated duration can be roughly calculated as "data volume / batch_size × time per step × n_epochs", or by proportionally scaling up the measured duration of a streamlined first run
For the criteria for judging whether the first step metrics are normal (health indicators such as critic/rewards/mean and actor/entropy), see Observability configuration — key metrics quick reference. For concrete practices (lean datasets, n_epochs=1), see Reinforcement learning training overview — getting started tips. After completing the self-check process, if only some items are changed, there is no need to repeat all self-check items:
  • Changing data (new dataset or data expansion) → simply run a smoke test before resubmitting
  • Modifying function code → restart from local service verification
  • Only adjusting hyperparameters or resource configuration → restart from the submission smoke test (approximately 16 CNY to verify that the new configuration is accepted by the server)

Common error quick reference

This section covers high-frequency errors from testing to submission. For error attribution after a task has entered training (first step crash, sampling timeout, garbled output, etc.), see Observability configuration — troubleshooting decision tree.

Stage

Error message

Cause analysis

Resolution

Local service

401 Incorrect API key (Rollout live test)

The API key in use does not support inference calls

Switch to an sk- prefixed inference key created in the Model Studio console (see local service verification)

Remote testing

Invalid classpath for startup script (reported immediately upon registration, with backslashes in the path), or Precondition Failed (returned by test_functions; logs are empty when the instance exits immediately upon startup)

Windows packaging compatibility issue (the CLI and SDK share the same packaging pipeline, and the issue reproduces on both sides; the Temp file cleanup failed warning during registration can be ignored)

Running in a WSL or Linux environment completely avoids this issue (if WSL is not installed, it can be installed via wsl --install); this issue has been reported to the DashScope SDK maintainers

Remote testing

ModuleNotFoundError (in instance logs)

requirements.txt is missing dependencies, or the package structure cannot be resolved inside the container

Complete requirements.txt and go back to the local service to reproduce

Submit

ValidationError: extra inputs are not permitted (e.g. weight)

This parameter does not belong to the current component type (weight is a field of RewardFunctionComponent, not on AgenticRLFunctionComponent)

Verify the component type and field ownership; step-by-step submission does not include weight

Submit

[3005] Job submission failed: TypeError(unexpected keyword argument)

Called a non-existent method parameter (for example, run(lazy_load=...) or submit_job(training_file_ids=...))

For the dataset, pass in all three parameters in full with datasets=[Dataset(type=DatasetsType.VALIDATION, data_source_type=DataSourceType.FILE_ID, file_id=...)]; for other parameters, follow the examples on this page and in Submit training tasks

Submit

[400] InvalidParameter:batch_size need to be in range [8, 2048]

batch_size is outside the range allowed by the server (during a smoke test the data volume is small, so batch_size must be adjusted to 8)

Adjust batch_size to 8~2048; for smoke test scenarios, pair it with a small data volume

Submit

[1002] I/O error: Failed to load from dict

YAML dialect error (unsupported top-level key or field type)

Use the job.yaml template structure from the YAML configuration

Submit

TypeError: object FineTune can't be used in 'await' expression

Misusing await on synchronous methods (submit_job / get / cancel / list / logs)

Remove await; note that run/register_functions/upload_datasets/test_functions are async, while job management methods are synchronous

Next steps