콘텐츠로 이동

Training

Cycle Counter 모델 학습은 config(YAML) 기반입니다. 외부에서 지정하는 것은 모델 종류(model_type)와 데이터 관련 설정뿐이며, backbone·sequence_length·optimizer·AMP 등 나머지 학습 recipe는 model_type에 따라 내부에서 검증된 값으로 자동 결정됩니다.

학습 실행

# 재현성을 위해 PYTHONHASHSEED를 trainer.random_seed와 동일하게 설정
PYTHONHASHSEED=<seed> python run.py --mode train --config config/train_arm_1.yml

또는 Developer App(웹 GUI)의 Training 탭에서 model_type을 선택해 학습할 수 있습니다.

model_type — 모델 종류

standard accurate
backbone ResNet18 (2D) r3d_18 (3D video)
streaming - causal_3d (chunk 경계에서도 streaming==offline)
AMP off on (fp16 autocast + GradScaler)
학습 sequence_length 256 128 (3D 메모리 제약)
추론 window (max_seq_len) 256 256
  • model_type 미지정 시 standard 로 처리되므로, 이 필드가 없던 기존 config·체크포인트는 그대로 동작합니다.
  • 구 값 normal/deep은 자동 변환이 제거되었으니 standard/accurate로 교체하세요(normalstandard, deepaccurate). 미지원 값을 명시하면 거부됩니다.
  • 여기서의 model_type은 cycle counter 학습 전용이며, anomaly 모듈의 model_type(det/iad/cell_checker)과는 별개입니다.
  • 선택 기준: standard는 경량 2D로 대부분의 경우 권장이고, accurate는 더 높은 정확도가 필요하며 3D 메모리·연산 비용을 감수할 수 있을 때 선택합니다.
  • model_type은 프로그래매틱 API(Trainer.build)와 Developer App에서 모델 종류를 고르는 추상화입니다. CLI(run.py) 학습은 config YAML을 직접 선택합니다 — accurate(3D)는 config/train_arm_1_deep.example.yml을 베이스로, standard는 config/train_arm_1.yml을 사용하세요. (CLI config에 model_type: 키를 추가해도 읽지 않으므로 무시됩니다.)

프로그래매틱 빌드 입력 (TrainerBuildConfig)

API(cycle_counter.engine.api.Trainer.build)로 빌드할 때 외부 입력은 아래 키들뿐입니다 (extra="forbid" — 그 외 키는 무시되지 않고 거부됩니다).

타입 기본값 설명
model_type Literal["standard", "accurate"] "standard" 모델 종류 (위 표 참조)
roi Optional[tuple[int, int, int, int] \| list[int]] None ROI 좌표 (x1, y1, x2, y2) (4-int list도 허용)
roi_mask_first bool False ROI 바깥 영역을 먼저 0으로 마스킹한 뒤 처리할지
augmentation list[dict] 내부 default 5종 adjust_brightness/adjust_contrast/color_jitter/jpeg_compression/random_resized_crop_and_pad가 항상 적용됩니다. 지정한 항목은 여기에 append되며, default와 _target_이 겹치면 거부됩니다

n_classes는 입력하지 않습니다 — data의 각 target_frames 항목에 필수class_index에서 자동 도출됩니다(max(class_index) + 1, 배경/normal = 0). class_index를 누락하면 입력 검증에서 거부됩니다.

cycle_counter.engine.api.Trainer

Cycle Counter 모델을 학습하기 위한 Trainer 클래스입니다.

참고

공개 메서드는 @error_handler로 감싸져 호출 시 (error_code: int, message: str, payload: Any) 형태로 반환됩니다. 각 메서드의 Returns 설명은 기본적으로 payload를 기준으로 작성되어 있습니다.

Usage

외부 입력 계약은 TrainerBuildConfig를 참고하세요 (model_type + roi / roi_mask_first / augmentation). CLI 학습은 python run.py --mode train --config config/train_arm_1.yml.

build(config, data) classmethod

Trainer 인스턴스를 생성합니다.

Parameters:

Name Type Description Default
config dict

Trainer를 build 하기 위한 config가 담긴 dictionary 입니다.

{
    "model_type": Literal["standard", "accurate"],  # 모델 종류 (기본 "standard").
    #   standard = 2D backbone(ResNet18) + transformer
    #   accurate = 3D backbone(r3d_18) + causal_3d streaming + AMP
    # 이 값으로 backbone/sequence_length/optimizer/AMP 등 학습 recipe가 내부에서 자동 결정됩니다.
    "roi": Optional[tuple[int, int, int, int] | list[int]],  # ROI 좌표 (x1, y1, x2, y2). 4-int list도 허용.
    "roi_mask_first": bool,  # ROI 바깥 영역을 먼저 마스킹(0)한 뒤 처리할지 (기본 False)
    "augmentation": Optional[List[Dict]],  # augmentation 설정, None 이면 내부 default를 사용합니다.
}
# 외부 입력은 위 키들뿐입니다(extra="forbid"). `n_classes`는 data에서 자동 도출되고,
# optimizer/sequence_length 등 나머지 recipe는 model_type별 검증값으로 자동 결정됩니다.
# 전체 입력 계약은 `TrainerBuildConfig`를 참조하세요.

required
data list[dict]

Trainer가 사용할 train data가 담겨있는 dictionary 입니다.

[
    {
        "clip_path": str,
        "target_frames": list[dict],
            [
                {
                    "start_frame_idx": int,
                    "end_frame_idx": int,
                    "class_index": int,  # 필수. 배경/normal = 0. n_classes는 max(class_index)+1로 도출됩니다.
                },
                ...
            ]
    },
    ...
]

required

Returns:

Name Type Description
Trainer Trainer

build가 완료된 cycle_counter.Trainer 클래스의 인스턴스를 반환합니다.

to_device(device)

Trainer의 모델을 device에 올립니다.

Parameters:

Name Type Description Default
device Union[device, str, int]

GPU 번호 (int) 또는 "cpu" (str) 입니다.

required

Returns:

Type Description
None

None

train_one_step()

Trainer의 모델을 한 step 학습합니다.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: 학습 결과를 담고 있는 dictionary 입니다. 다음과 같은 키를 가집니다.

{
    "step": int,  # 현재까지 진행된 총 학습 step.
    "epoch": int,  # 현재까지 진행된 총 학습 epoch.
    "epoch_step": int,  # 현재 epoch에서 몇 번째 step인지를 나타냄.
    "loss": float,  # 학습에 사용되는 모든 loss를 모두 더한 값.
    "step_time(sec)": float,  # 학습을 1 step 진행하는데 걸린 총 시간
    "data_time(sec)": float,  # 데이터를 로딩하는데 걸린 시간
    "model_time(sec)": float,  # 모델 학습에 걸린 시간
}

save_checkpoint(checkpoint_path, metadata=None, password=None, **options)

Trainer의 모델을 checkpoint_path에 저장합니다.

Parameters:

Name Type Description Default
checkpoint_path str

체크포인트 경로

required
metadata Optional[dict]

메타데이터

None
password Optional[str]

패스워드

None

Returns: None