# LASR

## 概要

LASRは、Google Health AIが医療用音声入力の事前学習のために開発した音声認識モデルであるMedASRの基盤となるアーキテクチャです。[Conformerアーキテクチャ](https://huggingface.co/papers/2005.08100)をベースとしており、放射線科の音声入力のように医療用語を含む音声入力ツールを開発する開発者向けの起点として設計されています。MedASRは医療音声に対して高い性能を発揮しますが、トレーニングデータに含まれない用語、例えば非標準的な薬剤名や時間的な参照（日付、時刻、期間など）については、処理が困難な場合があります。

## 使用方法

### 基本的な使用方法

```python
from transformers import pipeline

pipe = pipeline("automatic-speech-recognition", model="google/medasr")
out = pipe("path/to/audio.mp3")
print(out)
```

```python
from datasets import Audio, load_dataset

from transformers import AutoModelForCTC, AutoProcessor

processor = AutoProcessor.from_pretrained("google/medasr")
model = AutoModelForCTC.from_pretrained("google/medasr", device_map="auto")

ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
speech_samples = [el['array'] for el in ds["audio"][:5]]

inputs = processor(speech_samples, sampling_rate=processor.feature_extractor.sampling_rate)
inputs.to(model.device, dtype=model.dtype)
outputs = model.generate(**inputs)
print(processor.batch_decode(outputs))
```

### トレーニング

以下の例では、音声とテキストのバッチを準備し、LASR/MedASRモデルに渡して、トレーニング損失を計算します。

```python
from datasets import Audio, load_dataset

from transformers import AutoModelForCTC, AutoProcessor

# Load processor and model
processor = AutoProcessor.from_pretrained("google/medasr")
model = AutoModelForCTC.from_pretrained("google/medasr", device_map="auto")

# Load a small example dataset and prepare batch
ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
speech_samples = [el["array"] for el in ds["audio"][:5]]
text_samples = [el for el in ds["text"][:5]]

# Passing `text` to the processor will prepare the `labels`
inputs = processor(audio=speech_samples, text=text_samples, sampling_rate=processor.feature_extractor.sampling_rate)
inputs.to(device, dtype=model.dtype)

outputs = model(**inputs)
outputs.loss.backward()
```

## LasrTokenizer[[transformers.LasrTokenizer]]

#### transformers.LasrTokenizer[[transformers.LasrTokenizer]]

```python
transformers.LasrTokenizer(eos_token = '</s>', unk_token = '<unk>', pad_token = '<pad>', _spm_precompiled_charsmap = None, extra_ids = 100, additional_special_tokens = None, vocab = None, vocab_file = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/lasr/tokenization_lasr.py#L33)

**パラメータ:**

vocab_file (`str`、*任意*) : トークナイザーをインスタンス化するために必要な語彙を含む [SentencePiece](https://github.com/google/sentencepiece) ファイル（通常は *.spm* 拡張子を持っています）。

eos_token (`str`、*任意*、デフォルトは`"</s>"`) : シーケンスの終了トークン。特殊トークンを使用してシーケンスを構築する場合は、シーケンスの終了に使用されるトークンではありません。使用されるトークンは`sep_token`です。

unk_token (`str`、*任意*、デフォルトは `"<unk>"`) : 不明トークン。語彙に存在しないトークンは ID に変換できず、代わりにこのトークンが設定されます。

pad_token (`str`、*任意*、デフォルトは `"<pad>"`) : パディングに使用されるトークンです。長さの異なるシーケンスをバッチ処理する場合などに使用します。

extra_ids (`int`、*optional*、デフォルト値は 100) : センチネルとして使用するために語彙に追加する追加 ID の数を指定します。これらのトークンは、"{%d}" が 0 から extra_ids-1 までの数値である "" としてアクセスできます。これらのトークンは get_sentinel_tokens メソッドを呼び出すことで取得でき、トークン ID は get_sentinel_token_ids メソッドを呼び出すことで取得できます。

additional_special_tokens (`list[str]`、*任意*) : トークナイザーで使用される追加の特殊トークン。

vocab (`str`、`dict`または`list`、*省略可*) : カスタムの語彙辞書。指定しない場合、特殊トークンを使用して最小限の語彙が作成されます。

HuggingFaceの*tokenizers*ライブラリをベースにしたLASRトークナイザーを構築します。[Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models)に基づいています。

このトークナイザーは、[TokenizersBackend](/docs/transformers/main/ja/main_classes/tokenizer#transformers.TokenizersBackend) を継承しており、主要なメソッドの大部分がそこに含まれています。これらのメソッドに関する詳細については、このスーパークラスを参照してください。

#### get_sentinel_token_ids[[transformers.LasrTokenizer.get_sentinel_token_ids]]

```python
get_sentinel_token_ids()
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/lasr/tokenization_lasr.py#L157)

センチネルトークンのトークンIDを取得します。

#### get_sentinel_tokens[[transformers.LasrTokenizer.get_sentinel_tokens]]

```python
get_sentinel_tokens()
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/lasr/tokenization_lasr.py#L151)

additional_special_tokens から、sentinel トークン（extra_id トークン）のリストを取得します。

## LasrFeatureExtractor[[transformers.LasrFeatureExtractor]]

#### transformers.LasrFeatureExtractor[[transformers.LasrFeatureExtractor]]

```python
transformers.LasrFeatureExtractor(feature_size = 128, sampling_rate = 16000, hop_length = 160, n_fft = 512, win_length = 400, padding_value = 0.0, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/lasr/feature_extraction_lasr.py#L70)

**パラメータ:**

feature_size (`int`、*任意*、デフォルトは 128) : 抽出された特徴量の次元数。

sampling_rate (`int`、*optional*、デフォルトは 16000) : 音声ファイルをデジタル化するためのサンプリングレート（ヘルツ (Hz) 単位）。

hop_length (`int`, *optional*, デフォルトは 160) : Mel 周波数係数を取得するために使用される STFT の、重複ウィンドウの長さ。

n_fft (`int`, *任意*, デフォルトは 512) : フーリエ変換のサイズ。

win_length (`int`、*任意*、デフォルトは 400) : STFT 計算のウィンドウ長です。

padding_value (`float`、*optional*、デフォルト値は 0.0) : 音声のパディングに使用される値です。無音に対応する値である必要があります。

LASRのフィーチャーエクストラクターを構築します。

このフィーチャーエクストラクターは、主要なメソッドの大部分を含む [SequenceFeatureExtractor](/docs/transformers/main/ja/main_classes/feature_extractor#transformers.SequenceFeatureExtractor) を継承しています。これらのメソッドに関する詳細については、このスーパークラスを参照してください。

このクラスは、`Short Time Fourier Transform` のカスタムな numpy 実装を使用して、生音声からメルフィルタバンク特徴量を抽出します。この実装は、PyTorch の `torch.stft` と同等の結果を出力するようになっています。

#### __call__[[transformers.LasrFeatureExtractor.__call__]]

```python
__call__(raw_speech: numpy.ndarray | list[float] | list[numpy.ndarray] | list[list[float]], truncation: bool = False, pad_to_multiple_of: int | None = None, return_tensors: str | transformers.utils.generic.TensorType | None = None, return_attention_mask: bool | None = None, padding: str | None = 'longest', max_length: int | None = None, sampling_rate: int | None = None, do_normalize: bool | None = None, device: str | None = 'cpu', return_token_timestamps: bool | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/lasr/feature_extraction_lasr.py#L142)

**パラメータ:**

raw_speech (`np.ndarray`、`list[float]`、`list[np.ndarray]`、`list[list[float]]`) : パディング対象のシーケンスまたはシーケンスのバッチです。各シーケンスは、NumPy 配列、浮動小数点数のリスト、NumPy 配列のリスト、または浮動小数点数のリストのリストであることができます。ステレオではなくモノラルのオーディオで、つまり 1 タイムステップあたり 1 つの浮動小数点数である必要があります。

truncation (`bool`、*任意*、デフォルトは`True`) : 入力シーケンスの切り詰め処理を有効にし、*max_length*を超える長さのシーケンスを*max_length*まで短くします。

pad_to_multiple_of (`int`、*任意*、デフォルトは None) : 設定すると、シーケンスを指定された値の倍数にパディングします。これは、計算能力 `>= 7.5` (Volta) を持つ NVIDIA ハードウェアで Tensor Cores を使用可能にするため、また、シーケンス長が 128 の倍数であることで恩恵を受ける TPU において、特に有用です。

return_attention_mask (`bool`, *任意*) : attention mask を返すかどうか。デフォルトのままにすると、特定の feature_extractor のデフォルトに従って attention mask を返します。 [attention mask とは?](../glossary#attention-mask)    Parakeet モデルでは、微妙なバグを避けるために、バッチ推論では常に `attention_mask` を渡す必要があります。

return_tensors (`str` または [TensorType](/docs/transformers/main/ja/internal/file_utils#transformers.TensorType)、*optional*) : 設定されている場合、Python の整数のリストではなくテンソルを返します。指定可能な値は以下の通りです:  - `'tf'`: TensorFlow の `tf.constant` オブジェクトを返します。 - `'pt'`: PyTorch の `torch.Tensor` オブジェクトを返します。 - `'np'`: Numpy の `np.ndarray` オブジェクトを返します。

sampling_rate (`int`, *任意*) : `raw_speech` 入力がサンプリングされたレートです。サイレントエラーを防ぎ、自動音声認識パイプラインを有効にするため、forward 呼び出し時に `sampling_rate` を渡すことを強く推奨します。

padding_value (`float`、*任意*、デフォルト値は 0.0) : パディングの値やベクトルに埋められる値。

do_normalize (`bool`、*任意*、デフォルトは`False`) : 入力を平均0・分散1に正規化するかどうかを指定します。正規化を行うことで、モデルの性能が大幅に向上する場合があります。

device (`str`、*任意*、デフォルトは `'cpu'`) : `_torch_extract_fbank_features` メソッドにおいて、音声信号の log-mel スペクトログラムを計算する際に使用するデバイスを指定します（例: "cpu"、"cuda"）。

return_token_timestamps (`bool`、*任意*、デフォルトは`None`) : 非推奨です。代わりに`return_attention_mask`を使用してください。これによりフレーム数を推定できます。 入力であるraw_speechのフレーム数を返すかどうかを指定します。これらのnum_framesは、モデルが単語レベルのタイムスタンプを計算するために使用できます。

1つ以上のシーケンスを特徴量化し、モデル用に準備するための主要なメソッドです。実装では、利用可能な場合はSTFTの計算にPyTorchを使用し、利用できない場合はより低速なNumPyベースの処理を使用します。

## LasrProcessor[[transformers.LasrProcessor]]

#### transformers.LasrProcessor[[transformers.LasrProcessor]]

```python
transformers.LasrProcessor(feature_extractor, tokenizer)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/lasr/processing_lasr.py#L48)

**パラメータ:**

feature_extractor (`feature_extractor_class`) : 特徴量抽出器は必須の入力です。

tokenizer (`tokenizer_class`) : トークナイザーは必須の入力です。

LasrProcessor を構築し、フィーチャーエクストラクターとトークナイザーを単一のプロセッサーにラップします。

[LasrProcessor](/docs/transformers/main/ja/model_doc/lasr#transformers.LasrProcessor) は、`feature_extractor_class` と `tokenizer_class` のすべての機能を提供します。詳細については、`~feature_extractor_class` および `~tokenizer_class` を参照してください。

#### __call__[[transformers.LasrProcessor.__call__]]

```python
__call__(audio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor']], text: str | list[str] | list[list[str]] | None = None, sampling_rate: int | None = None, **kwargs: *<class 'transformers.models.lasr.processing_lasr.LasrProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/lasr/processing_lasr.py#L54)

**パラメータ:**

audio (`Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]]`) : 準備対象のオーディオまたはオーディオのバッチです。各オーディオは NumPy 配列または PyTorch テンソルであることができます。NumPy 配列/PyTorch テンソルの場合、各オーディオの形状は (C, T) である必要があります。ここで、C はチャネル数、T はオーディオのサンプル長を表します。

text (`Union[str, list[str], list[list[str]]]`、*任意*) : エンコード対象のシーケンスまたはシーケンスのバッチです。各シーケンスは文字列、または文字列のリスト（プレトークナイズ済み文字列）であることができます。プレトークナイズ済み入力を渡す場合は、バッチ入力との曖昧さを避けるために `is_split_into_words=True` を設定してください。

sampling_rate (`int`, *optional*) : 入力オーディオのサンプリングレート（Hz）。これは、フィーチャーエクストラクターが想定するサンプリングレートと一致する必要があります（デフォルトは 16000 Hz）。指定された場合、プロセッサが想定するサンプリングレートと照合され、一致しない場合はエラーが発生します。指定されなかった場合、警告が発行され、デフォルトのサンプリングレートが使用されます。

return_tensors (`str` または [TensorType](/docs/transformers/main/ja/internal/file_utils#transformers.TensorType)、*optional*) : 設定されている場合、特定のフレームワークのテンソルを返します。受け入れ可能な値は以下の通りです:  - `'pt'`: PyTorch の `torch.Tensor` オブジェクトを返します。 - `'np'`: NumPy の `np.ndarray` オブジェクトを返します。

- ****kwargs** ([ProcessingKwargs](/docs/transformers/main/ja/main_classes/processors#transformers.ProcessingKwargs), *optional*) : 各モダリティ（テキスト、画像、動画、音声）の追加処理オプション。モデル固有のパラメータは上記にリストされています。サポートされている引数の完全なリストについては、TypedDict クラスを参照してください。

#### batch_decode[[transformers.LasrProcessor.batch_decode]]

```python
batch_decode(*args, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/processing_utils.py#L1948)

このメソッドは、すべての引数を PreTrainedTokenizer の [batch_decode()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.batch_decode) に転送します。詳細については、このメソッドのドキュメント文字列を参照してください。

#### decode[[transformers.LasrProcessor.decode]]

```python
decode(*args, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/processing_utils.py#L1957)

このメソッドは、すべての引数を PreTrainedTokenizer の [decode()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.decode) に転送します。詳細については、このメソッドのドキュメント文字列を参照してください。

## LasrEncoderConfig[[transformers.LasrEncoderConfig]]

#### transformers.LasrEncoderConfig[[transformers.LasrEncoderConfig]]

```python
transformers.LasrEncoderConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, hidden_size: int = 512, num_hidden_layers: int = 17, num_attention_heads: int = 8, intermediate_size: int = 2048, hidden_act: str = 'silu', attention_bias: bool = False, convolution_bias: bool = False, conv_kernel_size: int = 32, subsampling_conv_channels: int = 256, num_mel_bins: int = 128, subsampling_conv_kernel_size: int = 5, subsampling_conv_stride: int = 2, dropout: float | int = 0.1, dropout_positions: float | int = 0.0, layerdrop: float | int = 0.1, activation_dropout: float | int = 0.1, attention_dropout: float | int = 0.1, max_position_embeddings: int = 10000, initializer_range: float = 0.02, layer_norm_eps: float = 1e-06, feed_forward_residual_weights: list[float] | tuple[float, ...] = (1.5, 0.5), conv_residual_weights: list[float] | tuple[float, ...] = (2.0, 1.0), batch_norm_momentum: float = 0.01, rope_parameters: dict | None = None)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/lasr/configuration_lasr.py#L29)

**パラメータ:**

hidden_size (`int`、*任意*、デフォルトは`512`) : 隠れ表現の次元数。

num_hidden_layers (`int`, *任意*, デフォルトは `17`) : Transformer デコーダーの隠れ層の数。

num_attention_heads (`int`、*任意*、デフォルトは `8`) : Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。

intermediate_size (`int`、*任意*、デフォルトは`2048`) : MLP 表現の次元数。

hidden_act (`str`、*任意*、デフォルトは`silu`) : デコーダーで使用する非線形活性化関数（関数または文字列）。例えば、`"gelu"`、`"relu"`、`"silu"`など。

attention_bias (`bool`、*任意*、デフォルトは`False`) : セルフアテンションにおけるクエリ、キー、バリュー、出力の投影層でバイアスを使用するかどうか。

convolution_bias (`bool`、*任意*、デフォルトは`False`) : conformer の畳み込みモジュールの畳み込みでバイアスを使用するかどうか。

conv_kernel_size (`int`、*optional*、デフォルトは 32) : Conformer ブロック内の畳み込み層のカーネルサイズです。

subsampling_conv_channels (`int`、*任意*、デフォルトは 256) : サブサンプリング畳み込み層のチャネル数。

num_mel_bins (`int`、*任意*、デフォルトは`128`) : 入力フレームごとに使用されるメル特徴の数を指定します。`AutoFeatureExtractor`クラスで使用される値と一致させる必要があります。

subsampling_conv_kernel_size (`int`、*optional*、デフォルトは 5) : サブサンプリング用畳み込み層のカーネルサイズです。

subsampling_conv_stride (`int`、*optional*、デフォルトは 2) : サブサンプリング畳み込み層のストライドです。

dropout (`Union[float, int]`、*任意*、デフォルトは`0.1`) : すべての dropout 層の比率。

dropout_positions (`float`、*任意*、デフォルトは 0.0) : 入力シーケンスの位置に対する dropout 率です。

layerdrop (`Union[float, int]`、*任意*、デフォルトは`0.1`) : LayerDrop の確率です。詳細については、[LayerDrop の論文](see https://huggingface.co/papers/1909.11556)を参照してください。

activation_dropout (`Union[float, int]`、*任意*、デフォルトは `0.1`) : 全結合層内の活性化の dropout 率。

attention_dropout (`Union[float, int]`、*任意*、デフォルトは`0.1`) : 注意確率のドロップアウト率。

max_position_embeddings (`int`、*任意*、デフォルトは`10000`) : このモデルが使用される可能性のある最大シーケンス長です。

initializer_range (`float`、*任意*、デフォルトは`0.02`) : すべての重み行列を初期化するためのtruncated_normal_initializerの標準偏差です。

layer_norm_eps (`float`、*任意*、デフォルトは`1e-06`) : Layer Normalization 層で使用する epsilon です。

feed_forward_residual_weights (`tuple[float, float]`、*optional*、デフォルトは`[1.5, 0.5]`) : フィードフォワード層の残差重み。

conv_residual_weights (`tuple[float, float]`、*optional*、デフォルトは`[2.0, 1.0]`) : 畳み込み層の残差重み。

batch_norm_momentum (`float`、*任意*、デフォルトは 0.01) : バッチ正規化レイヤーのモーメンタム

rope_parameters (`dict`, *任意*) : RoPE 埋め込みの設定パラメータを含む辞書です。この辞書には `rope_theta` の値が含まれており、より長い `max_position_embeddings` で RoPE を使用する場合にスケーリングに使用されるパラメータが任意で含まれます。

これは LasrModel の設定を保存するための設定クラスです。指定された引数に基づいて Lasr モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[google/medasr](https://huggingface.co/google/medasr) と同様の設定が得られます。

設定オブジェクトは [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) のドキュメントを参照してください。

例:
```python
>>> from transformers import LasrEncoderModel, LasrEncoderConfig

>>> # Initializing a `LasrEncoder` configuration
>>> configuration = LasrEncoderConfig()

>>> # Initializing a model from the configuration
>>> model = LasrEncoderModel(configuration)

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

この設定クラスは、Google Health AI の LasrEncoder アーキテクチャに基づいています。詳細や事前学習済みモデルについては、[google/medasr](https://huggingface.co/google/medasr) をご覧ください。

## LasrCTCConfig[[transformers.LasrCTCConfig]]

#### transformers.LasrCTCConfig[[transformers.LasrCTCConfig]]

```python
transformers.LasrCTCConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, vocab_size: int = 512, ctc_loss_reduction: str = 'mean', ctc_zero_infinity: bool = True, encoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, pad_token_id: int = 0)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/lasr/configuration_lasr.py#L103)

**パラメータ:**

vocab_size (`int`、*任意*、デフォルトは`512`) : モデルの語彙サイズ。`input_ids`で表現できるトークンの種類数を定義します。

ctc_loss_reduction (`str`、*任意*、デフォルトは`"mean"`) : `torch.nn.CTCLoss`の出力に適用する集約方法を指定します。[LasrForCTC](/docs/transformers/main/ja/model_doc/lasr#transformers.LasrForCTC)のインスタンスを学習する場合にのみ関連します。

ctc_zero_infinity (`bool`、*任意*、デフォルトは`True`) : `torch.nn.CTCLoss`の無限損失および関連する勾配をゼロにするかどうかを指定します。無限損失は、入力がターゲットにアラインされるほど短すぎる場合に主に発生します。[LasrForCTC](/docs/transformers/main/ja/model_doc/lasr#transformers.LasrForCTC)のインスタンスをトレーニングする場合にのみ関連します。

encoder_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`、*optional*) : エンコーダーのバックボーンの設定オブジェクトまたは辞書。

pad_token_id (`int`, *任意*, デフォルトは `0`) : 語彙内でパディングに使用されるトークン ID。

これは LasrModel の設定を保存するための設定クラスです。指定された引数に基づいて Lasr モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[google/medasr](https://huggingface.co/google/medasr) と同様の設定が得られます。

設定オブジェクトは [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) のドキュメントを参照してください。

例:
```python
>>> from transformers import LasrForCTC, LasrCTCConfig
>>> # Initializing a Lasr configuration
>>> configuration = LasrCTCConfig()
>>> # Initializing a model from the configuration
>>> model = LasrForCTC(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```

この設定クラスは、Google Health AI の Lasr CTC アーキテクチャに基づいています。詳細や事前学習済みモデルについては、[google/medasr](https://huggingface.co/google/medasr) をご覧ください。

## LasrEncoder[[transformers.LasrEncoder]]

#### transformers.LasrEncoder[[transformers.LasrEncoder]]

```python
transformers.LasrEncoder(config: LasrEncoderConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/lasr/modeling_lasr.py#L465)

**パラメータ:**

config ([LasrEncoderConfig](/docs/transformers/main/ja/model_doc/lasr#transformers.LasrEncoderConfig)) : モデルのすべてのパラメータを含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを参照してください。

Conformerアーキテクチャに基づいたLasrEncoderモデル](https://arxiv.org/abs/2005.08100)。

このモデルは [PreTrainedModel](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.LasrEncoder.forward]]

```python
forward(input_features: Tensor, attention_mask: typing.Optional[torch.Tensor] = None, output_attention_mask: bool | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/lasr/modeling_lasr.py#L486)

**パラメータ:**

input_features (`torch.Tensor`、形状 `(batch_size, sequence_length, feature_dim)`) : 入力音声特徴に対応するテンソルです。音声特徴は `feature_extractor_class` を使用して取得できます。詳細は `feature_extractor_class.__call__` を参照してください（`processor_class` は音声の処理に `feature_extractor_class` を使用します）。

attention_mask (`torch.Tensor`、shape `(batch_size, sequence_length)`、*任意*) : padding トークンのインデックスに対する attention を回避するためのマスクです。マスクの値は `[0, 1]` から選択されます:  - **マスクされない**トークンは 1、- **マスクされる**トークンは 0。  [attention マスクとは?](../glossary#attention-mask)

output_attention_mask (`bool`, *任意*) : 出力の注意マスクを返すかどうか。

**戻り値:** `LasrEncoderModelOutput` または `tuple(torch.Tensor)`

`None` や入力に応じて、さまざまな要素で構成される`LasrEncoderModelOutput`、または`torch.Tensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。

[LasrEncoder](/docs/transformers/main/ja/model_doc/lasr#transformers.LasrEncoder)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

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

- **last_hidden_state** (`torch.Tensor`、形状 `(batch_size, sequence_length, hidden_size)`) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **pooler_output** (`torch.Tensor`、形状 `(batch_size, hidden_size)`) -- 補助的な事前学習タスクに使用される層をさらに通して処理された後、シーケンスの最初のトークン（分類トークン）の最終層の隠れ状態です。例えば、BERT系のモデルでは、線形層とtanh活性化関数を経て処理された後の分類トークンを返します。この線形層の重みは、事前学習中の次の文予測（分類）目的から学習されます。
- **hidden_states** (`tuple(torch.Tensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（モデルに埋め込み層がある場合はその出力用 1 つ、各層の出力用 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple(torch.Tensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
- **attention_mask** (`torch.Tensor`、形状 `(batch_size, sequence_length)`、*任意*) -- シーケンス圧縮後に、パディングトークンのインデックスに対してアテンションを実行しないためのマスクです。シーケンス長が入力シーケンス長と異なる可能性があるため、返されます。マスクの値は `[0, 1]` から選択されます:

  - **マスクされていない**トークンに対して1
  - **マスク**されたトークンに対しては 0 です。

例:

```python
>>> from transformers import AutoProcessor, LasrEncoder
>>> from datasets import load_dataset, Audio

>>> model_id = "google/medasr"
>>> processor = AutoProcessor.from_pretrained(model_id)
>>> encoder = ParakeetEncoder.from_pretrained(model_id)

>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))

>>> inputs = processor(ds[0]["audio"]["array"])
>>> encoder_outputs = encoder(**inputs)

>>> print(encoder_outputs.last_hidden_state.shape)
```

## LasrForCTC[[transformers.LasrForCTC]]

#### transformers.LasrForCTC[[transformers.LasrForCTC]]

```python
transformers.LasrForCTC(config: LasrCTCConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/lasr/modeling_lasr.py#L601)

**パラメータ:**

config ([LasrCTCConfig](/docs/transformers/main/ja/model_doc/lasr#transformers.LasrCTCConfig)) : モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを確認してください。

Connectionist Temporal Classification (CTC) ヘッドを備えた Lasr Encoder。

このモデルは [PreTrainedModel](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.LasrForCTC.forward]]

```python
forward(input_features: Tensor, attention_mask: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/lasr/modeling_lasr.py#L612)

**パラメータ:**

input_features (`torch.Tensor`、形状 `(batch_size, sequence_length, feature_dim)`) : 入力音声特徴に対応するテンソルです。音声特徴は `feature_extractor_class` を使用して取得できます。詳細は `feature_extractor_class.__call__` を参照してください（`processor_class` は音声の処理に `feature_extractor_class` を使用します）。

attention_mask (`torch.Tensor`、shape `(batch_size, sequence_length)`、*任意*) : padding トークンのインデックスに対する attention を回避するためのマスクです。マスクの値は `[0, 1]` から選択されます:  - **マスクされない**トークンは 1、- **マスクされる**トークンは 0。  [attention マスクとは?](../glossary#attention-mask)

labels (`torch.Tensor`、形状 `(batch_size, sequence_length)`、*任意*) : マスク言語モデリング損失を計算するためのラベル。インデックスは `[0, ..., config.vocab_size]` の範囲内であるか、-100 である必要があります（`input_ids` のドキュメント文字列を参照）。インデックスが `-100` に設定されたトークンは無視（マスク）され、損失は `[0, ..., config.vocab_size]` の範囲内のラベルを持つトークンに対してのみ計算されます。

**戻り値:** [CausalLMOutput](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.CausalLMOutput) または `tuple(torch.Tensor)`

`None` や入力に応じて、さまざまな要素で構成される [CausalLMOutput](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.CausalLMOutput) または `torch.Tensor` のタプル（`return_dict=False` が渡された場合、または `config.return_dict=False` の場合）。

[LasrForCTC](/docs/transformers/main/ja/model_doc/lasr#transformers.LasrForCTC)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

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

- **loss** (`torch.Tensor`、形状 `(1,)`、*任意*、`labels` が指定された場合に返されます) -- 言語モデリングの損失(次のトークンの予測用)。
- **logits** (`torch.Tensor`、形状 `(batch_size, sequence_length, config.vocab_size)`) -- 言語モデリングヘッドの予測スコア（SoftMax 適用前の各語彙トークンのスコア）。
- **hidden_states** (`tuple(torch.Tensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（モデルに埋め込み層がある場合はその出力用 1 つ、各層の出力用 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple(torch.Tensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

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

例:

```python
>>> from transformers import AutoProcessor, LasrForCTC
>>> from datasets import load_dataset, Audio

>>> model_id = "nvidia/lasr-ctc-1.1b"
>>> processor = AutoProcessor.from_pretrained(model_id)
>>> model = LasrForCTC.from_pretrained(model_id)

>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))

>>> inputs = processor(ds[0]["audio"]["array"], text=ds[0]["text"])
>>> outputs = model(**inputs)

>>> print(outputs.loss)
```

#### generate[[transformers.LasrForCTC.generate]]

```python
generate(input_features: Tensor, attention_mask: typing.Optional[torch.Tensor] = None, return_dict_in_generate: bool = False, compile_config: transformers.generation.configuration_utils.CompileConfig | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/lasr/modeling_lasr.py#L672)

例:

```python
>>> from transformers import AutoProcessor, LasrForCTC
>>> from datasets import load_dataset, Audio

>>> model_id = "google/medasr"
>>> processor = AutoProcessor.from_pretrained(model_id)
>>> model = LasrForCTC.from_pretrained(model_id)

>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))

>>> inputs = processor(ds[0]["audio"]["array"], text=ds[0]["text"])
>>> predicted_ids = model.generate(**inputs)
>>> transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)

>>> print(transcription)
```

