클러스터 컴퓨팅 환경에서 Python Debugger 사용하기

Mingyeong Shin·2025년 4월 17일

Piece_of_Code

목록 보기
3/3

1. Python 코드에 디버깅을 시작하기 위한 코드를 추가한다.

# train.py (또는 디버깅하려는 스크립트 파일 상단)
import argparse

def parse_arguments():
  parser = argparse.ArgumentParser()
  parser.add_argument('--debug', action='store_true')
  # ... 다른 인자들 ...
  return parser.parse_args()

def main():

  args = parser.parse_args()

  ###### 디버깅을 위한 코드 추가 #####
    if args.debug:
        import debugpy
        debugpy.listen(("0.0.0.0", 5454))  # 포트 번호(5454)는 원하는 번호로 변경
        print("Waiting for debugger attach...")
        debugpy.wait_for_client()
        print("Debugger attached.")
  #################################
  # ...

2. 계산 노드에 접속 후 tmux를 켠다.

salloc --partition=[PARTITION_NAME] --nodes=1 --cpus-per-task=4 --time=1440 --gres=gpu:1

tmux new -s debug

3. tmux에서 가상환경을 활성화 한 다음 디버깅용 코드를 실행한다.

conda activate env1
python train.py --epochs 10 --debug # 반드시  --debug 옵션 포함
  • "Waiting for debugger attach..."가 출력되고 코드가 멈춘다.
  • 이 시점에서 debugpy 포트가 열리게 된다.

4. 새로운 터미널을 열어서 계산 노드로 ssh 접속

ssh -L 5454:localhost:5454 USERNAME@gnode000
  • 로컬 컴퓨터의 127.0.0.1:5678 → 계산노드의 5454 포트로 연결
  • 계산노드의 이름은 hostname 명령으로 확인

5. VSCode에서 launch.json 만들기

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Attach to Remote Debug",
      "type": "python",
      "request": "attach",
      "connect": {
        "host": "127.0.0.1",
        "port": 5454
      },
      "pathMappings": [
        {
          "localRoot": "${fileDirname}",
          "remoteRoot": "/home/USER/path/to/your/file"
        }
      ]
    }
  ]
}

6. VSCode에서 F5 또는 벌레 아이콘 클릭

  • debugpy.wait_for_client() 통과됨
  • breakpoint에서 멈춤 -> 디버깅 가능!

7. 현재 디버깅 세션 종료 후 새로 시작하기

  • debugger 멈추기 (Shift+F5)
  • ssh 연결한 터미널 가서 끊어진 ssh 종료하기 (exit)
  • tmux 터미널에서 디버깅 코드 재실행(python train.py --debug)
  • ssh 터미널 가서 ssh 재접속(ssh -L 5454:localhost:5454 USERNAME@gnode000)
  • debugger 재실행(F5) > launch.file에서 "Attach to Remote Debug" 선택

8. 완전히 종료하기

  • ssh 터미널 세션 종료: exit
  • tmux 터미널에서 exit
  • 세션 종료: tmux kill-session -t debug

전체 요약

순서해야 할 것
1코드에 debugpy.listen(), wait_for_client() 넣기
2salloctmux 들어감
3python your_code.py --debug ... 실행
4새 터미널에서 SSH 포트포워딩
5VSCode에서 attach
6디버깅 종료 후 tmux 정리
profile
Goal: drug design with AI

0개의 댓글