Skip to content

Train

segmentation.Trainer

Segmentation 모델을 학습시키기 위한 Trainer class 입니다.

모든 public API는 (error_code, error_message, result)를 반환합니다. 성공 시 (0, "Success", result), 실패 시 (음수 error_code, error_message, None)입니다. 각 method의 Returns는 이 tuple의 세 번째 값인 result를 설명합니다.

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,  # "v1_shallow" / "v1_standard" / "v1_deep" / "v2_fast" / "v2_standard" / "v2_accurate" 중 하나를 지원합니다.
    "total_iterations": int,  # total training iterations
    "n_classes": int,  # number of data classes (including background class, n_classes >= 2)
    "batch_size": int,  # number of train batch size (default 12)
    "roi": dict | None,  # roi 세팅. ROIHandlerAPI의 build config와 동일합니다. None이면 ROI 적용 안함. (default None)
    "crop_wh": list[int] | tuple[int, int],  # crop size for cropper (default (256, 256))
    "resize_factor": float,  # training image resize scale (default 1.0)
    "augmentation": list[dict] | None,  # 학습에 사용할 augmentation config들을 모은 list 입니다. (default None)
    "num_workers": int,  # number of train data worker processes (default 8)
    "resumable": bool,  # pause/resume 활성화. 기본값 False는 기존 학습 경로를 사용합니다.
    "multipage": dict  | None,  # multipage 설정. None인 경우 multipage 사용 안 함. (default None)
        {
            "image_mode": list[str],  # multipage 이미지들의 모드 리스트. 리스트 길이 = 병합할 이미지 수.
                                      # 모드는 "RGB" 또는 "L" 사용 가능.
                                      # ex) ["RGB", "L", "RGB", ...] - 첫 번째 이미지는 color, 두 번째 이미지는 gray, ...
        }
    "inspection_size_wh": list[int] | tuple[int, int] | None,  # validation에서 사용할 inspection_size_wh 입니다.
                                                # 자세한 정보는 InferenceHandler의 get_default_inference_option 함수 설명에 나와있습니다.
    "oversized_image_handling": str | None,  # validation에서 사용할 oversized_image_handling 입니다.
                                                # 자세한 정보는 InferenceHandler의 get_default_inference_option 함수 설명에 나와있습니다.
    "cache_directory": str | None,  # 전처리된 데이터를 저장할 경로입니다. 각 학습마다 다른 경로로 설정하고, 학습이 종료되면 해당 경로를 삭제해야합니다.
                                       # None으로 세팅하는 경우 데이터를 디스크에 쓰지 않고 메모리에 올려둡니다.
}

required
data dict

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

{
    "train_images": {
        # 1: basic structure
        "{image_id}": {
            "path": str | list[str],  # 이미지 경로 (multipage인 경우 경로 리스트)
            "width": int,  # image width
            "height": int,  # image height
            "labels": [  # 2가지 타입 지원: "bounding_box" + "bitmap" 타입 / "contours" 타입
                {  # "bounding_box" + "bitmap" 타입
                    "class_index": int,  # class index (0: background)
                    "bounding_box": list[int],  # [left, top, width, height]
                    "bitmap": str,  # base64 encoded png image string (shape: (h_label, w_label))
                },
                {  # "contours" 타입
                    "class_index": int,  # class index (0: background)
                    "contours": [  # cv2 형식의 contours. 0번째 contour가 outer, 나머지는 모두 inner.
                        ndarray(int32, shape=(num_points_0, 1, 2)),
                        ndarray(int32, shape=(num_points_1, 1, 2)),
                        ndarray(int32, shape=(num_points_2, 1, 2)),
                        ...  # contour 개수 만큼 반복
                    ],
                },
                ...,  # times number of labels in the image
            ],
        },
        # 2: label path structure
        "{image_id}": {
            "path": str | list[str],  # 이미지 경로 (multipage인 경우 경로 리스트)
            "width": int,  # image width
            "height": int,  # image height
            "labels_count": int,  # len(labels)
            "labels_path": str,  # pickle path to "labels"
        },
        ...,  # times number of images
    },
    "validation_images": {...},
}

required

Returns:

Name Type Description
Trainer Trainer

build가 완료된 segmentation.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: None: None

train_one_step()

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

Model 계산 단계에서 실패한 뒤에는 재호출할 수 있지만, 실패한 step의 batch 소비나 model/optimizer 변경을 자동으로 되돌리지는 않습니다. Resumable 모드에서 데이터 로딩 실패로 iterator가 닫히면, 실패 원인을 해결한 뒤 이전 pause() 파일을 resume()해야 다시 학습할 수 있습니다. 저장된 pause() 파일이 없으면 새 Trainer로 처음부터 학습해야 합니다. 다른 단계의 실패도 정확한 복구에는 이전 pause() 파일을 resume()합니다. 실패 직후에는 pause()할 수 없으며, 성공한 step 또는 resume() 이후 다시 가능합니다.

Returns:

Name Type Description
dict dict

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

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

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를 반환합니다.

{
    "pixel/mean_iou": float,  # 각 class 별 iou 평균 (class의 균형을 강조)
    "pixel/overall_iou": float,  # 전체 클래스의 TP, FP, FN을 합산한 후 한 번만 IoU 계산한 값 (보조 지표로써 활용) -> TP / (TP + FP + FN)
    "pixel/class_{idx}_iou": float,  # 각 {idx} class 별 pixel iou value.
    "pixel/mean_auroc": float,  # 유효 defect class 들의 평균 AUROC (배경 제외, 미정의 = -1).
    "pixel/class_{idx}_auroc": float,  # 각 {idx} class pixel-level AUROC. (배경·미정의 = -1)
    "pixel/class_{idx}_roc": {  # 각 {idx} class ROC 곡선 raw data. (미정의 시 None)
        "fpr": list[float],
        "tpr": list[float],
        "thresholds": list[float],  # scoremap 점수 grid (256 ~ 0).
    },
}

post_train_process()

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

Returns:

Name Type Description
dict dict

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

{
    "params.object_boundary_threshold": list[int],
    "params.calc_object_area_and_apply_threshold": bool,
    "params.calc_object_score_and_apply_threshold": bool,
    "params.object_area_threshold": list[int],
    "params.object_score_threshold": list[float],
    "params.batch_size": int,
    "params.inspection_size_wh": list[int] | tuple[int, int] | None,
    "params.oversized_image_handling": str,
}

get_class_label_counts()

학습에 사용된 클래스별 라벨(어노테이션 인스턴스) 개수를 반환합니다.

Returns:

Type Description
list[int]

list[int]: list index = class_index, 값 = 해당 class 로 학습에 사용된 라벨(어노테이션) 개수 입니다.

[0, 85, 200]  # class 1: 85개, class 2: 200개 (index 0 = background)

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

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

Parameters:

Name Type Description Default
checkpoint_path str

checkpoint를 저장할 path 입니다.

required
metadata dict | None

호출자가 정의하는 추가 정보입니다. 정해진 key나 자동으로 추가되는 key는 없으며, None이면 {}를 저장합니다. load_checkpoint()에서 저장한 metadata를 반환합니다. Defaults to None. 아래는 demo/train.py에서 사용하는 예시이며 필수 key가 아닙니다.

{
    "description": str,  # 호출자가 저장한 checkpoint 설명. 예: "demo"
}

None
password str | None

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

None

Returns: None: None

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

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

build() config에 resumable=True를 지정해야 합니다. 기본값 False에서는 기존 loader 경로를 사용하며, resume용 config signature를 계산하지 않습니다. 지원되는 sampler/loader 조합을 resumable=False로 build한 Trainer의 pause()/resume()은 error_code -412204를 반환합니다. 미지원 sampler/loader 조합이면 -412202를 반환합니다. 미지원 조합에 resumable=True를 지정하면 build 단계에서 -412202로 거절합니다. pause()는 상태를 저장하고 학습을 멈출 뿐, 프로세스를 종료하거나 GPU 메모리를 해제하지 않습니다. 성공을 반환한 뒤에는 같은 Trainer에서 resume()하거나, 프로세스를 종료하고 새 프로세스에서 resume()할 수 있습니다. 기존 save_checkpoint() 형식은 유지되며, 재개용 파일은 별도 경로에 저장합니다. 시작 전이나 train_one_step()이 성공한 경계에서 호출합니다. AMP가 optimizer update를 건너뛰어도 정상 완료된 학습 step은 저장할 수 있습니다. Model, optimizer, scheduler, AMP scaler, RNG, loader 위치와 step/epoch, 남은 crop buffer 및 validation 상태를 저장합니다. Epoch 중간에도 저장할 수 있으며, resume() 후 다음 batch부터 이어서 학습합니다. InfiniteRandomSampler를 사용하는 MemorySafeDataLoader/Full2PatchDataLoader를 지원하며, ClassBalancedInfiniteRandomSampler는 pause/resume을 지원하지 않습니다.

Parameters:

Name Type Description Default
checkpoint_path str

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

required
metadata dict[str, Any] | None

호출자가 정의하는 추가 정보입니다. 정해진 key나 자동으로 추가되는 key는 없으며, None이면 {}를 저장합니다. resume()에서 저장한 metadata를 반환합니다. Defaults to None. 아래는 demo/train.py에서 사용하는 예시이며 필수 key가 아닙니다.

{
    "step": int,  # train_one_step() 결과의 누적 완료 step을 호출자가 직접 저장
}
Trainer의 실제 step/epoch 등 학습 상태는 metadata와 별도로 자동 저장합니다.

None
password str | None

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

None

Returns:

Name Type Description
None None

성공 시 (0, "Success", None)을 반환합니다.

resume(checkpoint_path, password=None)

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

같은 Trainer 또는 새로 build한 Trainer에서 사용할 수 있습니다. 두 경우 모두 build() config에 resumable=True가 필요합니다. resume()은 재개용 파일을 삭제하지 않습니다. Step 실패 후 같은 파일로 다시 복구할 수 있으며, 학습 완료 후 파일 정리는 호출자가 합니다. 저장할 때와 같은 module 버전, config, data 내용과 순서, CPU/CUDA 종류 및 AMP 설정이 필요합니다. to_device()로 device를 설정한 뒤 호출하며, pause() checkpoint만 허용합니다. Cache 경로와 loader의 worker 수, persistent_workers, prefetch, pin_memory, multiprocessing_context, timeout은 변경할 수 있습니다. Validation은 학습 RNG를 보존하며, validation의 custom stochastic transform 결과까지 동일하게 보장하지는 않습니다. Sample별 Python/NumPy/Torch CPU 기본 RNG를 복원하며, custom transform의 자체 generator나 여러 thread의 RNG 동시 사용은 별도 state 관리가 필요합니다. CUDA 연산 자체의 비결정성 때문에 이후 loss/weight의 bitwise 일치를 보장하지는 않습니다.

Parameters:

Name Type Description Default
checkpoint_path str

pause()로 저장한 재개용 checkpoint의 path입니다.

required
password str | None

저장할 때 사용한 password입니다. 암호화하지 않은 파일은 None을 사용합니다. Defaults to None.

None

Returns:

Name Type Description
metadata dict[str, Any]

pause()에 전달했던 사용자 정의 metadata입니다. 실제 호출은 error_code, error_message, metadata = trainer.resume(...) 형식입니다. 성공한 경우 정해진 반환 key는 없으며, metadata를 생략했으면 {}입니다. 아래는 demo/train.py에서 직접 저장한 예시이며 항상 존재하는 key가 아닙니다.

{
    "step": int,  # pause(metadata={"step": ...})로 직접 저장한 누적 완료 step
}
Model, optimizer, scheduler, loader 위치와 step/epoch 등은 Trainer 내부에 복원하며, metadata에 자동으로 추가하지 않습니다. 실패 시 metadata는 None입니다.

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
metadata dict

save_checkpoint()에 전달했던 사용자 정의 metadata입니다. 실제 호출은 error_code, error_message, metadata = trainer.load_checkpoint(...) 형식입니다. 성공한 경우 정해진 반환 key는 없으며, metadata를 생략했으면 {}입니다. 아래는 demo/train.py에서 사용하는 예시이며 항상 존재하는 key가 아닙니다.

{
    "description": str,  # save_checkpoint(metadata={"description": ...})로 저장한 설명
}
실패 시 metadata는 None입니다. 학습 state 전체를 재개하려면 pause()/resume()을 사용합니다.