Transformers documentation

TimmWrapper

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

TimmWrapper

概要

transformers ライブラリとそのオートクラスで利用できるように、timm モデルの読み込みを可能にするヘルパークラスです。

from urllib.request import urlopen

import torch
from PIL import Image

from transformers import AutoImageProcessor, AutoModelForImageClassification


# Load image
image = Image.open(urlopen(
    'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/beignets-task-guide.png'
))

# Load model and image processor
checkpoint = "timm/resnet50.a1_in1k"
image_processor = AutoImageProcessor.from_pretrained(checkpoint)
model = AutoModelForImageClassification.from_pretrained(checkpoint).eval( device_map="auto")

# Preprocess image
inputs = image_processor(image)

# Forward pass
with torch.no_grad():
    logits = model(**inputs).logits

# Get top 5 predictions
top5_probabilities, top5_class_indices = torch.topk(logits.softmax(dim=1) * 100, k=5)

リソース

TimmWrapperの入門を支援するための、Hugging Face公式およびコミュニティ(🌎で示されます)のリソースのリストです。

Image Classification

より詳細な概要については、timm統合に関する公式ブログ記事をお読みください。

TimmWrapperConfig

class transformers.TimmWrapperConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonearchitecture: str = 'resnet50'initializer_range: float = 0.02do_pooling: bool = Truemodel_args: dict[str, typing.Any] | None = None )

パラメータ

  • architecture (str、任意、デフォルトは"resnet50") — 読み込むtimmのアーキテクチャです。
  • initializer_range (float、任意、デフォルトは 0.02) — すべての重み行列を初期化するための truncated_normal_initializer の標準偏差です。
  • do_pooling (bool、任意、デフォルトはTrue) — TimmWrapperModelのlast_hidden_stateに対してプーリングを行うかどうかを指定します。
  • model_args (dict[str, Any]、省略可) — timm.create_model 関数に渡す追加のキーワード引数です。例えば、timm/vit_base_patch32_clip_448.laion2b_ft_in12k_in1k で 3 ブロックのモデルを作成するには model_args={"depth": 3} を指定します。デフォルト値は None です。

This is the configuration class to store the configuration of a TimmWrapperModel. It is used to instantiate a Timm Wrapper model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the resnet50

設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。

例:

>>> from transformers import TimmWrapperModel

>>> # Initializing a timm model
>>> model = TimmWrapperModel.from_pretrained("timm/resnet18.a1_in1k")

>>> # Accessing the model configuration
>>> configuration = model.config

TimmWrapperImageProcessor

class transformers.TimmWrapperImageProcessor

< >

( pretrained_cfg: dictarchitecture: str | None = None**kwargs )

パラメータ

  • pretrained_cfg (dict[str, Any]) — 評価およびトレーニングの変換を解決するために使用される事前学習モデルの設定です。
  • architecture (Optional[str]、省略可) — モデルのアーキテクチャ名。

transformers内で使用するためのtimmモデル用のラッパークラスです。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]return_tensors: str | transformers.utils.generic.TensorType | None = 'pt' )

パラメータ

  • images (ImageInput) — 前処理対象の画像。単一の画像またはバッチの画像を想定しています。
  • return_tensors (str または TensorType、省略可) — 返すテンソルの型です。

画像または画像のバッチを前処理します。

TimmWrapperModel

クラス transformers.TimmWrapperModel

< >

( config: TimmWrapperConfig )

transformers で使用するための timm モデル用のラッパークラス。

forward

< >

( pixel_values: FloatTensoroutput_attentions: bool | None = Noneoutput_hidden_states: bool | list[int] | None = Nonereturn_dict: bool | None = Nonedo_pooling: bool | None = Noneuse_cache: bool | None = None**kwargs ) → TimmWrapperModelOutput or tuple(torch.FloatTensor)

パラメータ

  • pixel_values (torch.FloatTensor、shape (batch_size, num_channels, image_size, image_size)) — 入力画像に対応するテンソルです。ピクセル値は TimmWrapperImageProcessor を使用して取得できます。詳細については TimmWrapperImageProcessor.call() を参照してください(processor_class は画像の処理に TimmWrapperImageProcessor を使用します)。
  • output_attentions (bool、省略可) — すべての attention レイヤーの attentions テンソルを返すかどうか。timm でラップされたモデルとは互換性がありません。
  • output_hidden_states (bool, 任意) — すべての層の隠れ状態を返すかどうかを指定します。timm でラップされたモデルとは互換性がありません。
  • return_dict (bool, 任意) — プレーンなタプルではなく ModelOutput を返すかどうか。
  • do_pooling (bool, 省略可) — TimmWrapperModel の last_hidden_state に対してプーリングを行うかどうかを指定します。None が渡された場合、config の do_pooling の値が使用されます。
  • use_cache (bool、任意) — True に設定すると、past_key_values のキーバリュー状態が返され、デコーディングの高速化に利用できます(past_key_values を参照)。

戻り値

TimmWrapperModelOutput または tuple(torch.FloatTensor)

TimmWrapperModelOutput、またはtorch.FloatTensorのタプル(return_dict=Falseが渡された場合、またはconfig.return_dict=Falseの場合)。設定(TimmWrapperConfig)や入力に応じて、さまざまな要素で構成されます。

TimmWrapperModelのforwardメソッドは、__call__特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなくModuleインスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを黙って無視するためです。

  • last_hidden_state (torch.FloatTensor) — 分類ヘッドを適用する前のモデルの最後の隠れ状態です。
  • pooler_output (torch.FloatTensor、任意) — 適用可能な場合、最後の隠れ状態から導出されたプーリング済み出力です。
  • hidden_states (tuple(torch.FloatTensor)、optional、output_hidden_states=True が設定されている場合、または config.output_hidden_states=True の場合に返されます)— モデルの各層または指定された層の出力における中間 hidden states を含むタプルです。
  • attentions (tuple(torch.FloatTensor)、optional、output_attentions=True が設定されている場合、または config.output_attentions=True の場合に返されます。) — モデルの各層の出力における中間アテンション重みを含まれるタプル。 注: 現在、Timm モデルは attentions の出力をサポートしていません。

例:

>>> import torch
>>> from PIL import Image
>>> from urllib.request import urlopen
>>> from transformers import AutoModel, AutoImageProcessor

>>> # Load image
>>> image = Image.open(urlopen(
...     'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/beignets-task-guide.png'
... ))

>>> # Load model and image processor
>>> checkpoint = "timm/resnet50.a1_in1k"
>>> image_processor = AutoImageProcessor.from_pretrained(checkpoint)
>>> model = AutoModel.from_pretrained(checkpoint).eval()

>>> # Preprocess image
>>> inputs = image_processor(image)

>>> # Forward pass
>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> # Get pooled output
>>> pooled_output = outputs.pooler_output

>>> # Get last hidden state
>>> last_hidden_state = outputs.last_hidden_state

TimmWrapperForImageClassification

class transformers.TimmWrapperForImageClassification

< >

( config: TimmWrapperConfig )

画像分類用の transformers で使用される timm モデル用のラッパークラス。

forward

< >

( pixel_values: FloatTensorlabels: typing.Optional[torch.LongTensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | list[int] | None = Nonereturn_dict: bool | None = None**kwargs ) → ImageClassifierOutput or tuple(torch.FloatTensor)

パラメータ

  • pixel_values (torch.FloatTensor、shape (batch_size, num_channels, image_size, image_size)) — 入力画像に対応するテンソルです。ピクセル値は TimmWrapperImageProcessor を使用して取得できます。詳細は TimmWrapperImageProcessor.call() を参照してください(processor_class は画像の処理に TimmWrapperImageProcessor を使用します)。
  • labels (torch.LongTensor、shape (batch_size,)、任意) — 画像分類/回帰の損失を計算するためのラベル。インデックスは [0, ..., config.num_labels - 1] の範囲である必要があります。config.num_labels == 1 の場合は回帰損失(平均二乗誤差)が計算され、config.num_labels > 1 の場合は分類損失(クロスエントロピー)が計算されます。
  • output_attentions (bool、省略可) — すべての attention レイヤーの attentions テンソルを返すかどうか。timm でラップされたモデルとは互換性がありません。
  • output_hidden_states (bool, 任意) — すべての層の隠れ状態を返すかどうかを指定します。timm でラップされたモデルとは互換性がありません。
  • return_dict (bool, オプション) — プレーンなタプルではなく ModelOutput を返すかどうかを指定します。 **kwargs: timm モデルの forward に渡す追加のキーワード引数。

戻り値

ImageClassifierOutput または tuple(torch.FloatTensor)

torch.FloatTensor のタプル、または ImageClassifierOutput を返します(return_dict=False が渡された場合、または config.return_dict=False の場合)。設定(TimmWrapperConfig)や入力に応じて、さまざまな要素が含まれます。

TimmWrapperForImageClassificationのforwardメソッドは、__call__特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなくModuleインスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを黙って無視するためです。

  • loss (torch.FloatTensor、shape (1,)、optional、labels が指定された場合に返されます) — 分類損失(config.num_labels==1 の場合は回帰損失)。

  • logits (torch.FloatTensor、shape (batch_size, config.num_labels)) — SoftMax 適用前の分類スコア(config.num_labels==1 の場合は回帰スコア)。

  • hidden_states (tuple(torch.FloatTensor)、optional、output_hidden_states=True が渡された場合または config.output_hidden_states=True の場合に返されます) — torch.FloatTensor のタプル(埋め込み層を持つモデルの場合、埋め込みの出力用が 1 つ、各ステージの出力用がそれぞれ 1 つずつ)で、形状は (batch_size, sequence_length, hidden_size) です。各ステージの出力におけるモデルの隠れ状態(特徴マップとも呼ばれます)。

  • attentions (tuple(torch.FloatTensor)、optional、output_attentions=True が渡された場合または config.output_attentions=True の場合に返されます)— torch.FloatTensor のタプル(各レイヤーごとに1つ)、形状は (batch_size, num_heads, patch_size, sequence_length)。

    アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

例:

>>> import torch
>>> from PIL import Image
>>> from urllib.request import urlopen
>>> from transformers import AutoModelForImageClassification, AutoImageProcessor

>>> # Load image
>>> image = Image.open(urlopen(
...     'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/beignets-task-guide.png'
... ))

>>> # Load model and image processor
>>> checkpoint = "timm/resnet50.a1_in1k"
>>> image_processor = AutoImageProcessor.from_pretrained(checkpoint)
>>> model = AutoModelForImageClassification.from_pretrained(checkpoint).eval()

>>> # Preprocess image
>>> inputs = image_processor(image)

>>> # Forward pass
>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> # Get top 5 predictions
>>> top5_probabilities, top5_class_indices = torch.topk(logits.softmax(dim=1) * 100, k=5)
Update on GitHub