timm documentation

适配并导出模型

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v1.0.30).
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 波段图像以及与之匹配的 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 进行缩放。通道数量匹配时,权重将保持不变地加载。转换为单通道时,会对源通道权重求和。

对于直接的权重转换,请显式指定相同的源信息:

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() 方法会同时更新 traits 和重建参数。

使用 timm.models.get_model_traits(model) 可以查看 traits 的副本以及当前的 in_chans 和 num_classes 属性。这些计数是从属性中读取的,而不是在 _traits 中重复存储,因此分类器重置后的变化会反映出来。timm.models.get_model_input_config(model) 从这些 traits 中解析输入配置,而 timm.models.get_model_args(model) 返回重建参数。

Hub 导出会写入一个描述已保存权重的新配置,而不会更改实时源配置。请传入用于适配模型的预处理:

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 辅助函数保留其源配置行为。

导出的构造参数

工厂会记录诸如激活函数、归一化以及嵌入维度等构建参数。导出时会排除设备/数据类型配置以及捕获的训练正则化参数:drop_rate、drop_path_rate、drop_block_rate 和 *_drop_rate。因此,重新加载时会使用架构的正则化默认值,除非调用者提供了新的值。显式导出的 model_args 可以在有意保留某个比率时将其保留下来。

可调用参数无法可靠地序列化。在构建模型时,建议优先使用已注册的字符串名称,或在导出时提供等效的名称:

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