Skip to main content

utils

Utility functions for Hugging Face models.

Module​

Functions​

create_loss_functions​

def create_loss_functions(    args: TIMMTrainingConfig,    device: torch.device,    *,    mixup_active: bool,    aug_splits: int = 0,) ‑> tuple[torch.nn.modules.module.Module, torch.nn.modules.module.Module]:

Create training and validation loss functions.

Arguments

  • args: TIMM training configuration.
  • device: Device to place loss functions on.
  • mixup_active: Whether mixup/cutmix augmentation is active.
  • aug_splits: Number of augmentation splits (for JSD loss). Default 0.

Returns A tuple of (train_loss_fn, validate_loss_fn).

create_train_eval_dataloaders​

def create_train_eval_dataloaders(    datasource: BaseSource,    data_splitter: Optional[DatasetSplitter],    args: TIMMTrainingConfig,    image_column_name: Optional[str],    target_column_name: Optional[str],    batch_transformations: Any,    labels2id: Optional[dict[Optional[str], dict[str, int]]],) ‑> tuple[typing.Any, typing.Any, dict[str, list[str | None]]]:

Create train and validation data loaders.

Arguments

  • datasource: The data source to load data from.
  • data_splitter: Optional dataset splitter.
  • args: TIMM training configuration.
  • image_column_name: Column name for image data.
  • target_column_name: Column name for target labels.
  • batch_transformations: Batch-level transformations to apply.
  • labels2id: Optional mapping from label strings to integer IDs.

Returns A tuple of (train_dataloader, eval_dataloader, semantic_types).

get_device_for_model​

def get_device_for_model():

Get the device for the model to run on.

Options are: "cpu", "mps", "cuda".

train_one_epoch​

def train_one_epoch(    epoch: int,    model: nn.Module,    loader: DataLoader,    optimizer: torch.optim.Optimizer,    loss_fn: nn.Module,    args: TIMMTrainingConfig,    device: torch.device,    lr_scheduler: Optional[torch.optim.lr_scheduler._LRScheduler] = None,    saver: Optional[utils.CheckpointSaver] = None,    output_dir: Optional[str] = None,    amp_autocast: AbstractContextManager = contextlib.suppress,    loss_scaler: Optional[ApexScaler] = None,    model_ema: Optional[utils.ModelEmaV2] = None,    mixup_fn: Optional[Mixup] = None,) ‑> dict[str, typing.Any]:

Performs one epoch of training and returns loss.

Borrowed with permission from https://github.com/huggingface/pytorch-image-models. Copyright 2020 Ross Wightman (https://github.com/rwightman)

validate​

def validate(    model: nn.Module,    loader: DataLoader,    loss_fn: nn.Module,    args: TIMMTrainingConfig,    device: torch.device,    amp_autocast: AbstractContextManager = contextlib.suppress,    log_suffix: str = '',) ‑> dict[str, typing.Any]:

Performs validation of the model and returns metrics.

Borrowed with permission from https://github.com/huggingface/pytorch-image-models. Copyright 2020 Ross Wightman (https://github.com/rwightman)

Classes​

TIMMTrainingConfig​

class TIMMTrainingConfig(    pretrained: bool = True,    initial_checkpoint: str = '',    num_classes: Optional[int] = None,    gp: Optional[str] = None,    img_size: Optional[int] = None,    in_chans: Optional[int] = None,    input_size: Optional[tuple[int, int, int]] = None,    crop_pct: Optional[float] = None,    mean: Optional[list[float]] = None,    std: Optional[list[float]] = None,    interpolation: str = '',    batch_size: int = 16,    validation_batch_size: Optional[int] = None,    channels_last: bool = False,    fuser: str = '',    grad_accum_steps: int = 1,    grad_checkpointing: bool = False,    fast_norm: bool = False,    model_kwargs: dict[str, Any] = {},    head_init_scale: Optional[float] = None,    head_init_bias: Optional[float] = None,    torchscript: bool = False,    torchcompile: Optional[str] = None,    opt: str = 'sgd',    opt_eps: Optional[float] = None,    opt_betas: Optional[list[float]] = None,    momentum: float = 0.9,    weight_decay: float = 0.05,    clip_grad: Optional[float] = None,    clip_mode: str = 'norm',    layer_decay: Optional[float] = 0.65,    opt_kwargs: dict[str, Any] = {},    sched: str = 'constant_with_warmup',    sched_on_updates: bool = False,    lr: Optional[float] = 1e-05,    lr_base: float = 0.005,    lr_base_size: int = 256,    lr_base_scale: str = '',    lr_noise: Optional[list[float]] = None,    lr_noise_pct: float = 0.67,    lr_noise_std: float = 1.0,    lr_cycle_mul: float = 1.0,    lr_cycle_decay: float = 0.5,    lr_cycle_limit: int = 1,    lr_k_decay: float = 1.0,    warmup_lr: float = 1e-05,    min_lr: float = 0,    epochs: int = 300,    epoch_repeats: float = 0.0,    start_epoch: Optional[int] = None,    decay_milestones: list[int] = [90, 180, 270],    decay_epochs: float = 90,    warmup_epochs: int = 5,    warmup_prefix: bool = False,    cooldown_epochs: int = 0,    patience_epochs: int = 10,    decay_rate: float = 1.0,    aug_splits: int = 0,    jsd_loss: bool = False,    bce_loss: bool = False,    bce_target_thresh: Optional[float] = None,    resplit: bool = False,    mixup: float = 0.0,    cutmix: float = 0.0,    cutmix_minmax: Optional[list[float]] = None,    mixup_prob: float = 1.0,    mixup_switch_prob: float = 0.5,    mixup_mode: str = 'batch',    mixup_off_epoch: int = 0,    smoothing: float = 0.1,    drop: float = 0.0,    drop_connect: Optional[float] = None,    drop_path: Optional[float] = 0.2,    drop_block: Optional[float] = None,    bn_momentum: Optional[float] = None,    bn_eps: Optional[float] = None,    sync_bn: bool = False,    dist_bn: str = 'reduce',    split_bn: bool = False,    model_ema: bool = False,    model_ema_force_cpu: bool = False,    model_ema_decay: float = 0.9998,    seed: int = 42,    log_interval: int = 50,    recovery_interval: int = 0,    checkpoint_hist: int = 10,    workers: int = 4,    save_images: bool = False,    amp: bool = False,    amp_dtype: str = 'float16',    amp_impl: str = 'native',    no_ddp_bb: bool = False,    synchronize_step: bool = False,    no_prefetcher: bool = False,    eval_metric: str = 'top1',    tta: int = 0,    local_rank: int = 0,):

Configuration for training a TIMM model.

Variables​

  • amp : bool
  • amp_dtype : str
  • amp_impl : str
  • aug_splits : int
  • batch_size : int
  • bce_loss : bool
  • bce_target_thresh : float | None
  • bn_eps : float | None
  • bn_momentum : float | None
  • channels_last : bool
  • checkpoint_hist : int
  • clip_grad : float | None
  • clip_mode : str
  • cooldown_epochs : int
  • crop_pct : float | None
  • cutmix : float
  • cutmix_minmax : list[float] | None
  • decay_epochs : float
  • decay_milestones : list[int]
  • decay_rate : float
  • dist_bn : str
  • drop : float
  • drop_block : float | None
  • drop_connect : float | None
  • drop_path : float | None
  • epoch_repeats : float
  • epochs : int
  • eval_metric : str
  • fast_norm : bool
  • fuser : str
  • gp : str | None
  • grad_accum_steps : int
  • grad_checkpointing : bool
  • head_init_bias : float | None
  • head_init_scale : float | None
  • img_size : int | None
  • in_chans : int | None
  • initial_checkpoint : str
  • input_size : tuple[int, int, int] | None
  • interpolation : str
  • jsd_loss : bool
  • layer_decay : float | None
  • local_rank : int
  • log_interval : int
  • lr : float | None
  • lr_base : float
  • lr_base_scale : str
  • lr_base_size : int
  • lr_cycle_decay : float
  • lr_cycle_limit : int
  • lr_cycle_mul : float
  • lr_k_decay : float
  • lr_noise : list[float] | None
  • lr_noise_pct : float
  • lr_noise_std : float
  • mean : list[float] | None
  • min_lr : float
  • mixup : float
  • mixup_mode : str
  • mixup_off_epoch : int
  • mixup_prob : float
  • mixup_switch_prob : float
  • model_ema : bool
  • model_ema_decay : float
  • model_ema_force_cpu : bool
  • momentum : float
  • no_ddp_bb : bool
  • no_prefetcher : bool
  • num_classes : int | None
  • opt : str
  • opt_betas : list[float] | None
  • opt_eps : float | None
  • patience_epochs : int
  • pretrained : bool
  • recovery_interval : int
  • resplit : bool
  • save_images : bool
  • sched : str
  • sched_on_updates : bool
  • seed : int
  • smoothing : float
  • split_bn : bool
  • start_epoch : int | None
  • std : list[float] | None
  • sync_bn : bool
  • synchronize_step : bool
  • torchcompile : str | None
  • torchscript : bool
  • tta : int
  • validation_batch_size : int | None
  • warmup_epochs : int
  • warmup_lr : float
  • warmup_prefix : bool
  • weight_decay : float
  • workers : int