timm documentation

모델 적응 및 내보내기

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

모델 적응 및 내보내기

입력 채널

in_chans를 모델이 수신할 채널 수로 설정합니다. RGB가 아닌 체크포인트의 경우, 사전 학습된 구성의 input_size[0]은 소스 체크포인트의 채널 수를 설명해야 합니다. 예를 들어, 13밴드 이미지가 2개 쌓인 것을 일치하는 13밴드 ResNet-18 체크포인트와 함께 사용하려면:

import timm

model = timm.create_model(
    'resnet18',
    pretrained=True,
    in_chans=26,
    num_classes=10,
    pretrained_cfg_overlay={
        'file': 'path/to/your_13_band_resnet18.pth',
        'input_size': (13, 224, 224),
        'num_classes': 10,
    },
)

이 예제는 해당 아키텍처와 소스 클래스 수를 가진 자체 체크포인트가 필요합니다. 입력 컨볼루션 가중치는 채널 순서대로 반복되거나 잘린 후, 소스에서 타겟으로의 채널 비율을 곱합니다. 따라서 13에서 26으로의 변환은 가중치를 두 번 반복하고 1/2로 스케일링하며, 동일한 프레임의 반복된 사본은 입력 컨볼루션의 응답을 유지합니다. 13에서 11로 변환하는 경우 첫 11개 채널을 유지하고 13/11로 스케일링합니다. 채널 수가 일치하면 변경 없이 로드됩니다. 1채널로 변환하는 경우 소스 채널 가중치를 합산합니다.

직접적인 가중치 변환을 위해 동일한 소스 정보를 명시적으로 지정합니다:

from timm.models import adapt_input_conv

temporal_weights = adapt_input_conv(26, pretrained_weights, base_chans=13)

base_chans describes physical image channels, which can differ from a space-to-depth stem’s convolution input dimension. The existing RGB default and space-to-depth grayscale conversion remain supported; other space-to-depth channel conversions still use the unsupported-format fallback during loading. Band-specific selection, semantic band matching, and normalization are not inferred: arrange the bands and preprocessing for your sensor and task.

적응된 모델 저장

model.pretrained_cfg는 적응 후에도 소스 체크포인트를 계속 설명합니다. 현재 모델은 in_chans와 num_classes를 노출합니다. 인스턴스가 소유한 _traits 사전은 명목상 img_size, fixed_input_size 제약 조건, first_conv 경로를 기록합니다. 별도의 _model_args 사전은 내보내기를 위한 생성 인수를 기록합니다. 지원되는 set_input_size() 메서드는 트레잇과 재구성 인수를 함께 업데이트합니다.

timm.models.get_model_traits(model)을 사용하여 traits의 사본과 현재 in_chans, num_classes 속성을 검사할 수 있습니다. 이러한 카운트는 _traits에 중복 저장되는 대신 속성에서 읽히므로, classifier 리셋이 반영됩니다. timm.models.get_model_input_config(model)은 이러한 traits에서 입력 구성을 해석하고, timm.models.get_model_args(model)은 재구성 인수를 반환합니다.

Hub export는 라이브 소스 구성을 변경하지 않고 저장된 가중치를 설명하는 새로운 구성을 작성합니다. 적응된 모델에 사용된 전처리를 전달하세요:

from timm.models import save_for_hf

save_for_hf(model, 'my_model', data_config=data_config)
restored = timm.create_model('local-dir:my_model', pretrained=True)

내장된 학습, 검증, 추론, 벤치마크 스크립트는 현재 모델에 대해 입력 설정을 해석합니다. 기존 resolve_data_config 및 resolve_model_data_config 헬퍼는 소스 구성 동작을 유지합니다.

내보낸 구성 인수

팩토리는 activation, normalization, embedding 차원과 같은 구성 인자를 기록합니다. Export는 device/dtype 배치와 캡처된 학습 정규화를 제외합니다: drop_rate, drop_path_rate, drop_block_rate, *_drop_rate. 따라서 다시 로드할 때는 호출자가 새로운 값을 제공하지 않는 한 아키텍처의 정규화 기본값이 사용됩니다. 의도적으로 특정 rate를 유지하려면 명시적인 export model_args를 사용할 수 있습니다.

Callable 인자는 신뢰할 수 있게 직렬화할 수 없습니다. 모델을 구성할 때는 등록된 문자열 이름을 사용하는 것이 좋으며, 내보낼 때는 동등한 이름을 제공하세요:

import torch.nn as nn

model = timm.create_model('resnet18', act_layer=nn.SiLU)
save_for_hf(model, 'my_silu_resnet', model_args={'act_layer': 'silu'})

직렬화 가능한 대체물이 없으면 export는 해당 인수를 명시하며 오류를 발생시킵니다. 이를 조용히 제거하면 가중치가 성공적으로 로드되더라도 다른 모델이 재구성될 수 있습니다.

Update on GitHub