> ## Documentation Index
> Fetch the complete documentation index at: https://docs.siflow.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 任务管理

目前，训练任务既可以直接使用 create 函数创建，也可以通过提交任务 YAML 配置来创建。

## 创建训练任务

```
from siflow import SiFlow
from siflow.types import (
    TaskVolume,
    TaskEnhancements,
    TaskUserSelectedInstance,
    TaskEnhancementsFaultTolerance,
    TaskEnv
)

client = SiFlow(
    region="cn-beijing",
    cluster="auriga",
)

uuid = client.tasks.create(
    name_prefix="test",
    image="megatron",
    image_version="0.12.1",
    image_url="registry-cn-beijing.siflow.cn/siflow/megatron:0.12.1-a845aa7",
    image_type="preset",
    type="pytorchjob",
    priority="medium",
    cmd="""echo hello world""",
    workers=1,
    resource_pool="cn-beijing-auriga-ai-infra-reserved-shared",
    instances=[
        TaskUserSelectedInstance(name="sci.c23-2", count_per_pod=1),
    ],
    volumes=[
        TaskVolume(mount_dir="/volume/ai-infra", volume_id=1),
    ],
    enhancements=TaskEnhancements(
        fault_tolerance=TaskEnhancementsFaultTolerance(enabled=True, max_retry_count=1),
    ),
    labels={
        "key1": "value1",
        "key2": "value2",
    },
    task_env=[
        TaskEnv(env_key="AA", env_value="aa", hide=True),
        TaskEnv(env_key="BB", env_value="bb", hide=False),
    ],
)
print(uuid)
```

参数说明：

| 参数名            | 类型                                  | 是否必填 | 说明                                                                                                                                                                |
| -------------- | ----------------------------------- | ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name\_prefix   | str                                 | 是    | 训练任务名称前缀                                                                                                                                                          |
| image          | str                                 | 是    | 训练任务使用的镜像名称                                                                                                                                                       |
| image\_version | str                                 | 是    | 镜像版本                                                                                                                                                              |
| image\_type    | str                                 | 是    | 镜像类型，可选值为：preset 或 custom                                                                                                                                         |
| image\_url     | str                                 | 否    | 使用该参数为自定义镜像指定镜像 URL                                                                                                                                               |
| type           | str                                 | 是    | 任务类型，可选值为：pytorchjob、pod                                                                                                                                          |
| priority       | str                                 | 否    | 任务优先级，可选值为：high、medium、low                                                                                                                                        |
| cmd            | str                                 | 是    | 任务入口程序                                                                                                                                                            |
| workers        | int                                 | 是    | 任务 worker 数量，不指定时默认为 1                                                                                                                                            |
| resource\_pool | str                                 | 是    | 使用的实例资源池名称：<br /> 1. 按需共享：`<region>-<cluster>-<tenant>-ondemand-shared` <br />2. 预留共享： `<region>-<cluster>-<tenant>-reserved-shared`<br /> 3. 预留独享: `<pool_name>` |
| instances      | List\[**TaskUserSelectedInstance**] | 是    | 任务 Pod 使用的实例类型及数量。可选择多种实例类型，系统将按录入顺序检查是否有足够配额并据此进行调度。                                                                                                             |
| volumes        | List\[**TaskVolume**]               | 否    | 任务 Pod 需要挂载的存储卷，支持挂载多个存储卷                                                                                                                                         |
| datasets       | List\[**TaskDataset**]              | 否    | 任务所需的数据集，支持同时挂载多个数据集                                                                                                                                              |
| enhancements   | **TaskEnhancements**                | 否    | 启用任务增强功能配置                                                                                                                                                        |
| task\_env      | List\[**TaskEnv**]                  | 否    | - 配置中的键值对将以环境变量的形式反映在 Pod 中 <br /> - hide 参数：设为 True 时，非任务所有者查看任务详情时该值将显示为 \*\*\*\*（主要用于任务共享场景）                                                                   |

### 使用 YAML 创建训练任务

除上述通过 create 函数指定参数的方式外，还可以通过提交任务 YAML 配置来创建任务，其格式与 SiFlow 命令行工具相同。

```
uuid = client.tasks.create(yaml_file="/path/to/task-yaml-file.yml")
print(uuid)
```

**任务 YAML 示例**

````yaml theme={null}
namePrefix: test
image: megatron
imageVersion: "0.12.1"
imageUrl: registry-cn-beijing.siflow.cn/siflow/megatron:0.12.1-a845aa7
type: pytorchjob
priority: medium
cmd: |
  echo hello world
workers: 1
resourcePool: cn-beijing-auriga-ai-infra-reserved-shared
instances:
  - name: sci.c23-2
    countPerPod: 1
volumes:
  - volumeId: 1
    mountDir: /volume/ai-infra
enhancements:
  faultTolerance:
    enabled: true
    maxRetryCount: 1
    ```
````

## 删除训练任务

删除单个任务：

```python theme={null}
uuid = client.tasks.delete(uuid="e86c99a1-08a4-95db-9ac2-67fc4b43e7fd")
print(uuid)
```

批量删除任务：

```python theme={null}
uuids = client.tasks.batch_delete(uuids=[
    "e86c99a1-08a4-95db-9ac2-67fc4b43e7fd",
])
print(uuids)
```

## 停止训练任务

```python theme={null}
uuid = client.tasks.stop(uuid="e86c99a1-08a4-95db-9ac2-67fc4b43e7fd")
print(uuid)

uuids = client.tasks.batch_stop(uuids=["e86c99a1-08a4-95db-9ac2-67fc4b43e7fd"])
print(uuid)
```

### 根据 ID 获取任务详情

```python theme={null}
task = client.tasks.get(uuid="e86c99a1-08a4-95db-9ac2-67fc4b43e7fd")
print(task.name, task.status, task.created_at)
# test-2XsAaXW3 Running "2024-10-01 10:00:00"
```

返回值请参见"相关类型定义"中的 Task。

### 获取任务列表

````python theme={null}
tasks = client.tasks.list()

for task in tasks:
    print(task.uuid, task.name, task.status)
    ```
````

list 参数：

| 参数名                              | 类型     | 是否必填 | 说明                   |
| -------------------------------- | ------ | ---- | -------------------- |
| status                           | string | 否    | 根据 status 字段过滤要查询的任务 |
| count                            | int    | 否    | 本次查询返回的最大任务数量        |
| 返回值中的每一项请参见"相关类型定义"中的 TaskBrief。 |        |      |                      |

### 重新提交任务

```python theme={null}
uuids = client.tasks.resubmit(uuids=[
    "e86c99a1-08a4-95db-9ac2-67fc4b43e7fd",
])
print(uuids)
```

### 结构定义

#### TaskBrief

| 字段                  | 类型                                    | 说明                       |
| ------------------- | ------------------------------------- | ------------------------ |
| uuid                | string                                | 任务的 UUID；使用该 ID 查询任务状态详情 |
| cluster             | string                                | 任务所在的集群                  |
| name                | string                                | 任务名称                     |
| resource\_pool      | string                                | 任务使用的实例资源池               |
| instances           | List\[**TaskUserSelectedInstance**]   | 提交任务时选择的实例类型及数量          |
| selected\_instances | List\[**TaskSystemSelectedInstance**] | 任务实际使用的实例类型及数量           |
| volumes             | List\[**TaskVolume**]                 | 任务 Pod 挂载的存储卷            |
| image               | string                                | 任务使用的镜像名称                |
| image\_version      | string                                | 镜像版本                     |
| image\_url          | string                                | 镜像 URL                   |
| image\_type         | string                                | 镜像类型，preset 或 custom     |
| status              | string                                | 任务状态                     |
| status\_msg         | string                                | 任务状态详情                   |
| created\_time       | string                                | 任务创建时间                   |
| updated\_time       | string                                | 任务更新时间                   |
| start\_time         | string                                | 任务开始时间                   |
| end\_time           | string                                | 任务结束时间                   |
| duration            | string                                | 任务运行时长                   |
| priority            | string                                | 任务优先级                    |
| queue\_info         | **TaskQueueInfo**                     | 任务排队状态                   |

#### Task

| 字段                  | 类型                                    | 说明                       |
| ------------------- | ------------------------------------- | ------------------------ |
| uuid                | string                                | 任务的 UUID；使用该 ID 查询任务状态详情 |
| cluster             | string                                | 任务所在的集群                  |
| name                | string                                | 任务名称                     |
| name\_prefix        | string                                | 任务名称前缀                   |
| resource\_pool      | string                                | 任务使用的实例资源池               |
| instances           | List\[**TaskUserSelectedInstance**]   | 提交任务时选择的实例类型及数量          |
| selected\_instances | List\[**TaskSystemSelectedInstance**] | 任务实际使用的实例类型及数量           |
| volumes             | List\[**TaskVolume**]                 | 任务 Pod 挂载的存储卷            |
| image               | string                                | 任务使用的镜像名称                |
| image\_version      | string                                | 镜像版本                     |
| image\_url          | string                                | 镜像 URL                   |
| image\_type         | string                                | 镜像类型，preset 或 custom     |
| status              | string                                | 任务状态                     |
| status\_msg         | string                                | 任务状态详情                   |
| created\_time       | string                                | 任务创建时间                   |
| updated\_time       | string                                | 任务更新时间                   |
| start\_time         | string                                | 任务开始时间                   |
| end\_time           | string                                | 任务结束时间                   |
| duration            | string                                | 任务运行时长                   |
| type                | string                                | 任务类型：pytorchjob 或 pod    |
| workers             | int                                   | 任务 worker 数量             |
| cmd                 | string                                | 任务入口命令                   |
| datasets            | List\[**TaskDataset**]                | 挂载到任务 Pod 的数据集           |
| models              | List\[**TaskModel**]                  | 挂载到任务 Pod 的模型            |
| enhancements        | **TaskEnhancements**                  | 任务增强相关配置                 |

#### TaskUserSelectedInstance

| 参数名             | 类型  | 是否必填 | 说明                             |
| --------------- | --- | ---- | ------------------------------ |
| name            | str | 是    | 可在网页上查看各集群支持的实例类型，例如 sci.c23-2 |
| count\_per\_pod | int | 是    | 每个任务 Pod 使用的实例数量               |

#### TaskSystemSelectedInstance

| 参数名             | 类型  | 是否必填 | 说明                             |
| --------------- | --- | ---- | ------------------------------ |
| name            | str | 是    | 可在网页上查看各集群支持的实例类型，例如 sci.c23-2 |
| count\_per\_pod | int | 是    | 每个任务 Pod 使用的实例数量               |

#### TaskVolume

| 参数名          | 类型  | 是否必填 | 说明                                             |
| ------------ | --- | ---- | ---------------------------------------------- |
| volume\_id   | int | 否    | 存储卷的 ID：volume\_id 与 volume\_name 两个参数中至少需提供一个 |
| volume\_name | str | 否    | 存储卷名称                                          |
| mount\_dir   | str | 是    | 存储卷在任务 Pod 中的挂载路径                              |

#### TaskDataset

| 参数名         | 类型  | 是否必填 | 说明                          |
| ----------- | --- | ---- | --------------------------- |
| name        | str | 是    | 要挂载到任务 Pod 的数据集名称           |
| version     | str | 否    | 数据集版本                       |
| type        | str | 是    | 数据集类型，可选参数为：preset 或 custom |
| pvc\_name   | str | 是    | 数据集所在存储卷对应的 PVC 名称          |
| sub\_path   | str | 是    | 数据集在存储卷中的相对路径               |
| mount\_path | str | 是    | 数据集挂载到任务 Pod 中的路径           |

#### TaskModel

| 参数名         | 类型  | 是否必填 | 说明                          |
| ----------- | --- | ---- | --------------------------- |
| name        | str | 是    | 要挂载到任务 Pod 的数据集名称           |
| version     | str | 否    | 数据集版本                       |
| type        | str | 是    | 数据集类型，可选参数为：preset 或 custom |
| pvc\_name   | str | 是    | 数据集所在存储卷对应的 PVC 名称          |
| sub\_path   | str | 是    | 数据集在存储卷中的相对路径               |
| mount\_path | str | 是    | 数据集挂载到任务 Pod 中的路径           |

#### TaskEnhancements

| 参数名              | 类型                 | 是否必填 | 说明       |
| ---------------- | ------------------ | ---- | -------- |
| fault\_tolerance | **FaultTolerance** | 否    | 任务容错相关配置 |

#### TaskEnhancementsFaultTolerance

| 参数名               | 类型         | 是否必填 | 说明                       |
| ----------------- | ---------- | ---- | ------------------------ |
| enabled           | bool       | 否    | 是否启用任务容错功能               |
| max\_retry\_count | int        | 否    | 任务失败时的最大重试次数             |
| recourds          | List\[str] | 否    | 任务自动容错记录，创建时无需填写，获取时自动填充 |

**TaskQueueInfo**

| 参数名             | 类型                      | 说明                  |
| --------------- | ----------------------- | ------------------- |
| rank\_in\_pool  | int                     | 当前任务在资源池中的排队位置      |
| ahead\_in\_pool | **TasksAheadBreakdown** | 当前任务在资源池中前序任务的详细信息  |
| rank\_in\_user  | int                     | 当前任务在用户任务中的排队位置     |
| ahead\_in\_user | **TasksAheadBreakdown** | 当前任务在用户任务中前序任务的详细信息 |

**TasksAheadBreakdown**

| 参数名    | 类型  | 说明                 |
| ------ | --- | ------------------ |
| high   | int | 排在当前任务之前的高优先级任务数量  |
| medium | int | 排在当前任务之前的普通优先级任务数量 |
| low    | int | 排在当前任务之前的低优先级任务数量  |
