Skip to content

Train

rotated.Trainer

Rotated Object Detection 모델을 학습하기 위한 Trainer 클래스입니다.

Usage

demo/train.py 참고

build(config, data) classmethod

Trainer class의 instance를 생성합니다.

Parameters:

Name Type Description Default
config dict

Trainer를 build 하기 위한 config가 담겨 있는 dictionary 입니다.

{
    "network_type": str,  # "v2_fast"만 지원합니다.
    "total_iterations": int,  # total training iterations
    "n_classes": int,  # number of data classes
    "rotation_mode": str,  # 물체의 대칭성을 고려하여 학습을 진행합니다.
                        90도 단위로 회전했을 때 object가 똑같다면 "no_direction",
                        180도 단위로 회전했을 때 object 똑같다면 "two_way_direction",
                        회전시 object가 달라진다면 "one_way_direction"를 사용할 수 있습니다. (default "one_way_direction")
    "batch_size": int,  # number of train batch size (default 12)
    "roi": dict | None,  # roi 세팅. ROIHandlerAPI의 build config와 동일합니다. None이면 ROI 적용 안함. (default None)
    "image_resize_wh": list[int] | tuple[int, int],  # training image resize (default (640, 640))
    "augmentation": list[dict] | None,  # 학습에 사용할 augmentation config들을 모은 list 입니다. (default None)
    "multipage": dict | None,  # multipage 설정. None인 경우 multipage 사용 안 함. (default None, 현재 미지원)
    "num_workers": int,  # number of train data worker processes (default 0)
    "iou_threshold": float,  # Rotated IoU 임계치. Validation Metric 측정 시 실제 라벨과 추정 결과를 동일한 것으로 간주할 수 있는 두 박스이 겹치는 비율입니다. (default 0.8)
}

required
data dict

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

{
    "train_images": {
        "{image_id}": {
            "path": str,
            "width": int,
            "height": int,
            "labels": [
                {
                    "class_index": int,
                    "bounding_rot_box": list[float],  # cxcywh_360 [center_x, center_y, width, height, radian]
                },
                ...,  # times number of labels in the image
            ],
        },
        ...,  # times number of images
    },
    "validation_images": dict[str, dict] | None, # validation data. train_images와 동일한 구조. (default None)
}

required

Returns:

Name Type Description
Trainer Trainer

build가 완료된 classification.Trainer class의 instance를 반환합니다.

to_device(device)

Trainer의 device를 변경합니다. (cpu/gpu)

Parameters:

Name Type Description Default
device device | str | int

변경하고자 하는 device 입니다. int의 경우 해당 번호의 GPU를, "cpu" 문자열의 경우 cpu를 사용합니다.

required

Returns:

Name Type Description
None None

None

train_one_step()

학습을 1스텝 수행하고, 결과를 반환합니다.

Returns:

Name Type Description
dict dict

학습 결과가 들어있는 dictionary를 반환합니다.

validation_enabled()

Trainer가 validation이 가능한지 bool로 반환합니다.

Returns:

Name Type Description
bool bool

Trainer가 validation이 가능하면 True를, 불가능하다면 False를 반환합니다.

validate()

Validation을 수행하고, 결과를 리턴합니다.

Returns:

Name Type Description
dict dict

validation 결과가 들어있는 dictionary를 반환합니다.

{
    "object/mean_f1": float,  # mean f1 value.
    "object/class_{idx}_f1": float,  # 각 {idx} class 별 f1 value.
}

post_train_process()

train 후처리를 수행하고, 해당 모델의 default inference options을 리턴합니다.

Returns:

Name Type Description
dict dict

각 parameter에 대한 설명은 InferenceHandler.get_default_inference_option를 참고해주세요.

{
    "params.batch_size": int,
    "params.apply_nms": bool,
    "params.object_score_threshold": list[int],
    "params.object_area_threshold": list[int],
    "params.max_num_of_detected_objects": list[int],
}

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

현재 Trainer의 상태를 암호화하여 저장합니다.

Parameters:

Name Type Description Default
checkpoint_path str

checkpoint를 저장할 path 입니다.

required
metadata dict | None

checkpoint에 저장할 추가 metadata. Defaults to None.

None
password str | None

checkpoint 파일에서 중요한 정보를 암호화 하는데 사용되는 password 입니다. None이면 암호화하지 않습니다. Defaults to None.

None

Returns: None: None

pause(checkpoint_path, metadata=None, password=None)

완료된 step의 학습 상태를 저장하고 일시정지합니다.

SaigeToolkit >=2.8.3,<2.9.0의 training resume 기능을 사용합니다. Model, optimizer, scheduler, AMP scaler, RNG, dataloader 위치와 step/epoch counter를 함께 저장합니다. Epoch 중간, 마지막 작은 batch와 micro batch의 소비 위치를 유지합니다.

성공한 뒤 제품에서 프로세스를 종료할 수 있습니다. 실패하거나 미완료된 step은 저장할 수 없으며, 일시정지한 Trainer는 resume() 전까지 학습할 수 없습니다. 기존 save_checkpoint() 형식은 유지되며, 재개용 파일은 별도 경로에 저장합니다.

학습 실패 시 누적 gradient를 비웁니다. Optimizer/scaler 갱신 단계 이후 실패하면 resume()으로 복원해야 다시 학습할 수 있습니다. Pause 성공 후 training loader를 닫습니다.

Parameters:

Name Type Description Default
checkpoint_path str

재개용 checkpoint를 저장할 path입니다.

required
metadata dict[str, Any] | None

resume()에서 돌려받을 제품 측 상태입니다. 예를 들어 완료한 iteration 수를 저장할 수 있습니다. Defaults to None.

None
password str | None

checkpoint 암호화에 사용할 password입니다. None이면 암호화하지 않습니다. Defaults to None.

None

Returns:

Name Type Description
None None

외부 API는 기존 (error, message, result) 형식으로 반환합니다.

Example
error, message, _ = trainer.pause(
    "training.pause", metadata={"completed_steps": completed_steps}
)
if error < 0:
    raise RuntimeError(message)
# 성공을 확인한 뒤 제품에서 기존 프로세스를 종료할 수 있습니다.

resume(checkpoint_path, password=None)

동일한 config/data 및 device/AMP로 build한 Trainer에서 학습을 재개합니다.

Module major/minor와 지원하는 training state format_version이 같아야 하며, patch 버전 차이는 양방향으로 허용합니다. 새 프로세스에서 같은 config, data 순서, module major/minor version, rotation mode로 Trainer를 build하고, 저장할 때와 같은 CPU/CUDA 종류와 AMP 설정으로 to_device()를 호출한 뒤 재개합니다. Scheduler를 결정하는 total_iterations도 그대로 유지합니다. Config는 nested dict의 key 삽입 순서까지 비교하지만 이미지 파일 내용의 hash는 검사하지 않습니다. Caller의 원본 config/data는 다시 사용할 수 있습니다.

pause()로 저장한 checkpoint만 허용하며 다음 batch부터 이어갑니다. 일반 checkpoint와 load_checkpoint()는 이 학습 재개 기능을 대신하지 않습니다. 기본 API의 naive 및 Toolkit class_balance/balance batch sampler를 지원합니다. 다른 sampler에서는 pause()/resume()이 오류 code -420336을 반환합니다. Sample별 Python/NumPy/Torch CPU 기본 RNG를 복원하며, custom transform의 자체 generator, stateful transform, stochastic validation의 worker RNG는 별도 지원이 필요합니다. Windows/spawn 실행 코드는 if name == "main": 안에 둡니다.

Parameters:

Name Type Description Default
checkpoint_path str

pause()로 저장한 checkpoint path입니다.

required
password str | None

pause()에서 사용한 password입니다. Defaults to None.

None

Returns:

Type Description
dict[str, Any]

dict[str, Any]: pause()에 전달한 metadata입니다. 생략했다면 빈 dict입니다. 외부 API는 기존 (error, message, result) 형식으로 반환합니다.

Example
error, message, trainer = Trainer.build(config, data)
if error < 0:
    raise RuntimeError(message)
error, message, _ = trainer.to_device(device)
if error < 0:
    raise RuntimeError(message)
error, message, metadata = trainer.resume("training.pause")
if error < 0:
    raise RuntimeError(message)
# metadata의 completed_steps 등 제품 측 상태도 복원한 뒤 학습을 이어갑니다.

load_checkpoint(checkpoint_path, password=None)

저장한 checkpoint로부터 Trainer의 상태를 불러오고, metadata를 반환합니다.

Parameters:

Name Type Description Default
checkpoint_path str

load할 checkpoint가 저장 되어 있는 path 입니다.

required
password str | None

checkpoint 파일에서 중요한 정보를 복호화 하는데 사용되는 password 입니다. None이면 복호화하지 않습니다. Defaults to None.

None

Returns:

Name Type Description
dict dict

save_checkpoint에서 저장했던 metadata 입니다.