> For the complete documentation index, see [llms.txt](https://gsds.gitbook.io/gsds/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gsds.gitbook.io/gsds/tips/slurm-advanced.md).

# Slurm - Advanced

현재 GSDS 서버는 다수의 사용자들이 서버를 사용할 수 있도록 개인이 사용할 수 있는 자원에 제한이 있습니다. 예를 들어, 작업 당 최대 12시간이라는 시간 제한이 걸려있습니다. 하지만, 상황에 따라 12시간이 넘는 작업을 실행해야 하는 경우가 있습니다.  이러한 경우 다시 slurm 에 작업을 제출해야 합니다. 또한 인당 4노드 (16 GPU) 보다 많은 자원을 사용하는 것을 지양하고 있기 때문에, 많은 작업을 나눠서 올려야 합니다.

아래는 slurm 에서 제공하는 기능을 사용해서 이를 조금 더 편하게 할 수 있는 방법들입니다.

{% hint style="info" %}
아래 소개 드리는 방법들은 sbatch 를 사용하는 경우에만 사용  가능합니다.
{% endhint %}

{% hint style="warning" %}
아래 소개 드리는 방법들은 "프로그램을 새로 돌리는 방법" 입니다. 때문에 학습  시 체크포인트 저장, 로드가 잘 안되어 있는 경우 아래 방법을 사용할 수 없으니 주의하시기 바랍니다.
{% endhint %}

## Requeue

Requeue 는 12시간이 넘는 작업에 대해서 사용할 수 있는 방법입니다. 해당 방법은 "언제 끝날지 모르는 작업"에 가장 적합한 방법입니다.

Sbatch 명령어를 사용하면 작업이 먼저 큐에 들어가게 되고, 큐에 들어온 순서에 따라 자원을 할당받고 작업을 실행하게 됩니다. Requeue 는 동작  중인 작업이 특정 조건을 만족하게 되면 작업을 다시 큐에 추가하는 방법입니다.

Requeue 를 사용해 12시간이 넘는 작업이 동작하는 과정은 다음과 같습니다.

1. `--signal` 옵션을 사용하여 작업이 끝나기 얼마 전에 특정 signal 이 발생하도록 합니다.
2. `trap` 명령어를 사용하여 특정 signal 이 감지되면 현재 작업이 다시 queue 에 들어가도록 합니다.
3. 작업을 `&` 를 사용하여  백그라운드에서 동작합니다.
4. 작업이 시간 제한 안에 끝나지 않았다면, 특정 signal 일 발생하고, trap 에 의해  현재 작업은 종료되고 다시 queue 에 들어가 다시 자원을 할당받을 수 있도록 합니다.
5. ( optional) `max_starts` 를 지정하여, 코드가 일정 횟수까지만 동작하도록 할 수 있습니다.

Requeue 에 의해 동작하는 작업은 동일한 "job\_id" 를 가지게 됩니다. output file 을 새로 작성하는 것이 아닌 기존 파일에 이어서 작업하고 싶은 경우 `--open-mode=append` 를 꼭 설정해주시기 바랍니다.

Requeue 를 사용하는 코드는 아래와 같습니다.

```
// sbatch_requeue.sh

#!/bin/bash

#SBATCH --job-name=example                    # Submit a job named "example"
#SBATCH --nodes=1                             # Using 1 node
#SBATCH --gres=gpu:1                          # Using 1 gpu
#SBATCH --time=0-01:00:00                     # 1 hour timelimit
#SBATCH --mem=10000MB                         # Using 10GB CPU Memory
#SBATCH --partition=A                         # Using "A" partition
#SBATCH --cpus-per-task=4                     # Using 4 maximum processor
#SBATCH --signal=B:SIGUSR1@30                 # Send SIGUSR1 within 30s of its end time
#SBATCH --output=slurm_log/%x-%j.out          # Save standard output file (%x=job name, %j=job id)
#SBATCH --open-mode=append                    # Open the output and error files using append mode

source ${HOME}/.bashrc
source ${HOME}/anaconda3/bin/activate
conda activate {conda env}

max_restarts=2
scontext=$(scontrol show job ${SLURM_JOB_ID})
restarts=$(echo ${scontext} | grep -o 'Restarts=[0-9]*****' | cut -d= -f2)

function resubmit()
{
    if [[ $restarts -lt $max_restarts ]]; then
        scontrol requeue ${SLURM_JOB_ID}
        exit 0
    else
        echo "Your job is over the Maximum restarts limit"
        exit 1
    fi
}

trap 'resubmit' SIGUSR1

{your job} &
wait
exit 0
```

## Dependency

Dependency 는 (1) 여러 작업을 한번에 queue 에 올리지만, 한번에 일부 작업만 동작 가능하게 하거나 (2) 12시간이 넘는 작업이지만, 최종적으로 몇 시간이 걸릴지 알지 못하는 경우 사용할 수 있는 방법입니다.

Dependency 는 sbatch 를 이용해서 작업들에 대해서 dependency 를 부여하는 방법입니다. 예를 들어 먼저 A 라는 작업을 queue 에 올렸을 때, B 는 A 가 정상적으로 끝난 경우에만 동작하도록 하거나, C 는 A 가 비정상적으로 끝난 경우에만 동작하도록 하는 것이 가능합니다.

작업 간 dependency 는 `--dependency` 를 사용하여 줄 수 있습니다. 아래는 dependency 옵션의 사용 예시입니다.

```
--dependency=afterok:job1_id:job2_id,afternotok:job3_id
```

이외에 자세한 dependency 옵션이나 내용은 [공식문서](https://slurm.schedmd.com/sbatch.html#OPT_dependency)를 참고하시기 바랍니다.

다음은 dependency 를 사용한 sbatch 예시입니다.

```
// sbatch_dependency.sh

#!/bin/bash

#SBATCH --job-name=example                    # Submit a job named "example"
#SBATCH --nodes=1                             # Using 1 node
#SBATCH --gres=gpu:1                          # Using 1 gpu
#SBATCH --time=0-01:00:00                     # 1 hour timelimit
#SBATCH --mem=10000MB                         # Using 10GB CPU Memory
#SBATCH --partition=A                         # Using "A" partition
#SBATCH --cpus-per-task=4                     # Using 4 maximum processor
#SBATCH --dependency=afterok:{other_job_id}   # Execute Job after other job exits with code of zero

source ${HOME}/.bashrc
source ${HOME}/anaconda3/bin/activate
conda activate {conda env}

{your job}
```

{% hint style="danger" %}
Dependency 가 많아도 slurm 동작에 부하를 주어 서버가 느려지는 일은 없습니다. 다만 너무 많은 작업(10,000 개 이상)을 한번에 올려 queue 에 너무 많은 작업이 올라가게 되면 slurm 시스템이 멈추게 되니 주의해주시기 바랍니다.
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gsds.gitbook.io/gsds/tips/slurm-advanced.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
