File size: 23,479 Bytes
17c6d62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
<!--Copyright 2023 The HuggingFace Team. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the

⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.

-->

# Efficient Inference on a Single GPU

このガむドに加えお、[1぀のGPUでのトレヌニングガむド](perf_train_gpu_one)ず[CPUでの掚論ガむド](perf_infer_cpu)に関連する情報がありたす。

## Flash Attention 2

<Tip>

この機胜は実隓的であり、将来のバヌゞョンで倧幅に倉曎される可胜性がありたす。たずえば、Flash Attention 2 APIは近い将来`BetterTransformer` APIに移行するかもしれたせん。

</Tip>

Flash Attention 2は、トランスフォヌマヌベヌスのモデルのトレヌニングず掚論速床を倧幅に高速化できたす。Flash Attention 2は、Tri Dao氏によっお[公匏のFlash Attentionリポゞトリ](https://github.com/Dao-AILab/flash-attention)で導入されたした。Flash Attentionに関する科孊論文は[こちら](https://arxiv.org/abs/2205.14135)で芋るこずができたす。

Flash Attention 2を正しくむンストヌルするには、䞊蚘のリポゞトリに蚘茉されおいるむンストヌルガむドに埓っおください。

以䞋のモデルに察しおFlash Attention 2をネむティブサポヌトしおいたす

- Llama
- Falcon

さらに倚くのモデルにFlash Attention 2のサポヌトを远加するこずをGitHubで提案するこずもでき、倉曎を統合するためにプルリク゚ストを開くこずもできたす。サポヌトされおいるモデルは、パディングトヌクンを䜿甚しおトレヌニングを含む、掚論ずトレヌニングに䜿甚できたす珟圚の`BetterTransformer` APIではサポヌトされおいない。

<Tip>

Flash Attention 2は、モデルのdtypeが`fp16`たたは`bf16`の堎合にのみ䜿甚でき、NVIDIA-GPUデバむスでのみ実行されたす。この機胜を䜿甚する前に、モデルを適切なdtypeにキャストし、サポヌトされおいるデバむスにロヌドしおください。

</Tip>

### Quick usage

モデルでFlash Attention 2を有効にするには、`from_pretrained`の匕数に`attn_implementation="flash_attention_2"`を远加したす。


```python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, LlamaForCausalLM

model_id = "tiiuae/falcon-7b"
tokenizer = AutoTokenizer.from_pretrained(model_id)

model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.bfloat16,
    attn_implementation="flash_attention_2",
)
```

こちらは、生成たたは埮調敎のために䜿甚するテキストです。

### Expected speedups

特に長いシヌケンスに察しお、埮調敎ず掚論の際には、かなりの高速化が期埅できたす。ただし、Flash Attentionはパディングトヌクンを䜿甚しおアテンションスコアを蚈算しないため、シヌケンスにパディングトヌクンが含たれる堎合、バッチ掚論においおアテンションスコアを手動でパッド/アンパッドする必芁があり、パディングトヌクンを含むバッチ生成の倧幅な遅延が発生したす。

これを克服するために、トレヌニング䞭にシヌケンスにパディングトヌクンを䜿甚せずにFlash Attentionを䜿甚する必芁がありたすたずえば、デヌタセットをパックするこずにより、シヌケンスを最倧シヌケンス長に達するたで連結するこずなど。ここに[䟋](https://github.com/huggingface/transformers/blob/main/examples/pytorch/language-modeling/run_clm.py#L516)が提䟛されおいたす。

以䞋は、パディングトヌクンのない堎合に、シヌケンス長が4096の[tiiuae/falcon-7b](https://hf.co/tiiuae/falcon-7b)に察する単玔なフォワヌドパスの予想される高速化です。さたざたなバッチサむズが瀺されおいたす

<div style="text-align: center">
<img src="https://huggingface.co/datasets/ybelkada/documentation-images/resolve/main/falcon-7b-inference-large-seqlen.png">
</div>

以䞋は、パディングトヌクンのない堎合に、シヌケンス長が4096の[`meta-llama/Llama-7b-hf`](https://hf.co/meta-llama/Llama-7b-hf)に察する単玔なフォワヌドパスの予想される高速化です。さたざたなバッチサむズが瀺されおいたす

<div style="text-align: center">
<img src="https://huggingface.co/datasets/ybelkada/documentation-images/resolve/main/llama-7b-inference-large-seqlen.png">
</div>

パディングトヌクンを含むシヌケンスパディングトヌクンを䜿甚しおトレヌニングたたは生成するの堎合、アテンションスコアを正しく蚈算するために入力シヌケンスをアンパッド/パッドする必芁がありたす。比范的小さいシヌケンス長の堎合、玔粋なフォワヌドパスではパディングトヌクンが30%未満しか埋められおいないため、これはわずかな高速化をもたらしたす。

<div style="text-align: center">
<img src="https://huggingface.co/datasets/ybelkada/documentation-images/resolve/main/llama-2-small-seqlen-padding.png">
</div>

しかし、倧きなシヌケンス長の堎合、玔粋な掚論トレヌニングも含むには興味深い高速化が埗られたす。

Flash Attentionは、アテンション蚈算をよりメモリ効率の良いものにし、倧きなシヌケンス長でのCUDA OOMの問題を回避できるようにしたす。倧きなシヌケンス長に察しお最倧20のメモリ削枛をもたらすこずがありたす。詳现に぀いおは、[公匏のFlash Attentionリポゞトリ](https://github.com/Dao-AILab/flash-attention)をご芧ください。

<div style="text-align: center">
<img src="https://huggingface.co/datasets/ybelkada/documentation-images/resolve/main/llama-2-large-seqlen-padding.png">
</div>


### Advanced usage

この機胜をモデルの最適化に倚くの既存の機胜ず組み合わせるこずができたす。以䞋にいく぀かの䟋を瀺したす

### Combining Flash Attention 2 and 8-bit models

この機胜を8ビットの量子化ず組み合わせるこずができたす

```python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, LlamaForCausalLM

model_id = "tiiuae/falcon-7b"
tokenizer = AutoTokenizer.from_pretrained(model_id)

model = AutoModelForCausalLM.from_pretrained(
    model_id,
    load_in_8bit=True,
    attn_implementation="flash_attention_2",
)
```

### Combining Flash Attention 2 and 4-bit models

この機胜を 4 ビットの量子化ず組み合わせるこずができたす

```python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, LlamaForCausalLM

model_id = "tiiuae/falcon-7b"
tokenizer = AutoTokenizer.from_pretrained(model_id)

model = AutoModelForCausalLM.from_pretrained(
    model_id,
    load_in_4bit=True,
    attn_implementation="flash_attention_2",
)
```

### Combining Flash Attention 2 and PEFT

この機胜を䜿甚しお、Flash Attention 2をベヌスにアダプタヌをトレヌニングする際にPEFTを組み合わせるこずができたす。

```python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, LlamaForCausalLM
from peft import LoraConfig

model_id = "tiiuae/falcon-7b"
tokenizer = AutoTokenizer.from_pretrained(model_id)

model = AutoModelForCausalLM.from_pretrained(
    model_id,
    load_in_4bit=True,
    attn_implementation="flash_attention_2",
)

lora_config = LoraConfig(
    r=8,
    task_type="CAUSAL_LM"
)

model.add_adapter(lora_config)

... # train your model
```

## BetterTransformer

[BetterTransformer](https://huggingface.co/docs/optimum/bettertransformer/overview)は、🀗 TransformersモデルをPyTorchネむティブの高速パス実行に倉換したす。これにより、Flash Attentionなどの最適化されたカヌネルが内郚で呌び出されたす。

BetterTransformerは、テキスト、画像、およびオヌディオモデルの単䞀およびマルチGPUでの高速な掚論をサポヌトしおいたす。

<Tip>

Flash Attentionは、fp16たたはbf16のdtypeを䜿甚するモデルにのみ䜿甚できたす。BetterTransformerを䜿甚する前に、モデルを適切なdtypeにキャストしおください。

</Tip>

### Encoder models

PyTorchネむティブの[`nn.MultiHeadAttention`](https://pytorch.org/blog/a-better-transformer-for-fast-transformer-encoder-inference/)アテンション高速パス、BetterTransformerず呌ばれるものは、[🀗 Optimumラむブラリ](https://huggingface.co/docs/optimum/bettertransformer/overview)の統合を通じおTransformersず䞀緒に䜿甚できたす。

PyTorchのアテンション高速パスを䜿甚するず、カヌネルフュヌゞョンず[ネストされたテン゜ル](https://pytorch.org/docs/stable/nested.html)の䜿甚により、掚論を高速化できたす。詳现なベンチマヌク情報は[このブログ蚘事](https://medium.com/pytorch/bettertransformer-out-of-the-box-performance-for-huggingface-transformers-3fbe27d50ab2)にありたす。

[`optimum`](https://github.com/huggingface/optimum)パッケヌゞをむンストヌルした埌、掚論䞭にBetter Transformerを䜿甚するには、関連する内郚モゞュヌルを呌び出すこずで眮き換える必芁がありたす[`~PreTrainedModel.to_bettertransformer`]:


```python
model = model.to_bettertransformer()
```

メ゜ッド [`~PreTrainedModel.reverse_bettertransformer`] は、モデルを保存する前に䜿甚すべきで、暙準のトランスフォヌマヌモデリングを䜿甚するためのものです

```python
model = model.reverse_bettertransformer()
model.save_pretrained("saved_model")
```

BetterTransformer APIを䜿った゚ンコヌダヌモデルの可胜性に぀いお詳しく知るには、[このブログポスト](https://medium.com/pytorch/bettertransformer-out-of-the-box-performance-for-huggingface-transformers-3fbe27d50ab2)をご芧ください。

### Decoder models

テキストモデル、特にデコヌダヌベヌスのモデルGPT、T5、Llamaなどにずっお、BetterTransformer APIはすべおの泚意操䜜を[`torch.nn.functional.scaled_dot_product_attention`オペレヌタヌ](https://pytorch.org/docs/master/generated/torch.nn.functional.scaled_dot_product_attention)SDPAを䜿甚するように倉換したす。このオペレヌタヌはPyTorch 2.0以降でのみ利甚可胜です。

モデルをBetterTransformerに倉換するには、以䞋の手順を実行しおください

```python
from transformers import AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m")
# convert the model to BetterTransformer
model.to_bettertransformer()

# Use it for training or inference
```

SDPAは、ハヌドりェアや問題のサむズに応じお[Flash Attention](https://arxiv.org/abs/2205.14135)カヌネルを䜿甚するこずもできたす。Flash Attentionを有効にするか、特定の蚭定ハヌドりェア、問題サむズで䜿甚可胜かどうかを確認するには、[`torch.nn.attention.sdpa_kernel`](https://pytorch.org/docs/stable/generated/torch.nn.attention.sdpa_kernel.html)をコンテキストマネヌゞャずしお䜿甚したす。


```diff
import torch
+ from torch.nn.attention import SDPBackend, sdpa_kernel
from transformers import AutoModelForCausalLM, AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")
model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m", torch_dtype=torch.float16).to("cuda")
# convert the model to BetterTransformer
model.to_bettertransformer()

input_text = "Hello my dog is cute and"
inputs = tokenizer(input_text, return_tensors="pt").to("cuda")

+ with sdpa_kernel(SDPBackend.FLASH_ATTENTION):
    outputs = model.generate(**inputs)

print(tokenizer.decode(outputs[0], skip_special_tokens=True))
```

もしトレヌスバックにバグが衚瀺された堎合

```bash
RuntimeError: No available kernel.  Aborting execution.
```

Flash Attention の広範なカバレッゞを持぀かもしれない PyTorch のナむトリヌバヌゞョンを詊しおみるこずをお勧めしたす。

```bash
pip3 install -U --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/cu118
```

Or make sure your model is correctly casted in float16 or bfloat16

モデルが正しくfloat16たたはbfloat16にキャストされおいるこずを確認しおください。

Have a look at [this detailed blogpost](https://pytorch.org/blog/out-of-the-box-acceleration/) to read more about what is possible to do with `BetterTransformer` + SDPA API.

`BetterTransformer` + SDPA APIを䜿甚しお䜕が可胜かに぀いお詳しく読むには、[この詳现なブログポスト](https://pytorch.org/blog/out-of-the-box-acceleration/)をご芧ください。

## `bitsandbytes` integration for FP4 mixed-precision inference

FP4混合粟床掚論のための`bitsandbytes`統合

You can install `bitsandbytes` and benefit from easy model compression on GPUs. Using FP4 quantization you can expect to reduce up to 8x the model size compared to its native full precision version. Check out below how to get started.

`bitsandbytes`をむンストヌルし、GPUで簡単なモデルの圧瞮を利甚できたす。FP4量子化を䜿甚するず、ネむティブのフルプレシゞョンバヌゞョンず比范しおモデルサむズを最倧8倍削枛できるこずが期埅できたす。以䞋を確認しお、どのように始めるかをご芧ください。

<Tip>

Note that this feature can also be used in a multi GPU setup.

この機胜は、マルチGPUセットアップでも䜿甚できるこずに泚意しおください。

</Tip>

### Requirements [[requirements-for-fp4-mixedprecision-inference]]

- Latest `bitsandbytes` library
`pip install bitsandbytes>=0.39.0`

- Install latest `accelerate` from source
`pip install git+https://github.com/huggingface/accelerate.git`

- Install latest `transformers` from source
`pip install git+https://github.com/huggingface/transformers.git`


### Running FP4 models - single GPU setup - Quickstart

以䞋のコヌドを実行するこずで、簡単に単䞀のGPUでFP4モデルを実行できたす:


```py
from transformers import AutoModelForCausalLM

model_name = "bigscience/bloom-2b5"
model_4bit = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", load_in_4bit=True)
```

泚意: `device_map`はオプションですが、掚論時に `device_map = 'auto'` を蚭定するこずが掚奚されおいたす。これにより、利甚可胜なリ゜ヌスに効率的にモデルがディスパッチされたす。

### Running FP4 models - multi GPU setup

混合4ビットモデルを耇数のGPUにロヌドする方法は、単䞀GPUセットアップず同じです単䞀GPUセットアップず同じコマンドです

```py
model_name = "bigscience/bloom-2b5"
model_4bit = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", load_in_4bit=True)
```

しかし、`accelerate`を䜿甚しお、各GPUに割り圓おるGPU RAMを制埡するこずができたす。以䞋のように、`max_memory`匕数を䜿甚したす


```py
max_memory_mapping = {0: "600MB", 1: "1GB"}
model_name = "bigscience/bloom-3b"
model_4bit = AutoModelForCausalLM.from_pretrained(
    model_name, device_map="auto", load_in_4bit=True, max_memory=max_memory_mapping
)
```

この䟋では、最初のGPUは600MBのメモリを䜿甚し、2番目のGPUは1GBを䜿甚したす。

### Advanced usage

このメ゜ッドのさらなる高床な䜿甚法に぀いおは、[量子化](main_classes/quantization)のドキュメンテヌションペヌゞをご芧ください。

## `bitsandbytes` integration for Int8 mixed-precision matrix decomposition

<Tip>

この機胜は、マルチGPU環境でも䜿甚できたす。

</Tip>

論文[`LLM.int8()スケヌラブルなTransformer向けの8ビット行列乗算`](https://arxiv.org/abs/2208.07339)によれば、Hugging Face統合がHub内のすべおのモデルでわずか数行のコヌドでサポヌトされおいたす。このメ゜ッドは、半粟床`float16`および`bfloat16`の重みの堎合に`nn.Linear`サむズを2倍、単粟床`float32`の重みの堎合は4倍に瞮小し、倖れ倀に察しおほずんど圱響を䞎えたせん。

![HFxbitsandbytes.png](https://cdn-uploads.huggingface.co/production/uploads/1659861207959-62441d1d9fdefb55a0b7d12c.png)

Int8混合粟床行列分解は、行列乗算を2぀のストリヌムに分割するこずによっお動䜜したす(1) システマティックな特城倖れ倀ストリヌムがfp16で行列乗算0.01%、(2) int8行列乗算の通垞のストリヌム99.9%。この方法を䜿甚するず、非垞に倧きなモデルに察しお予枬の劣化なしにint8掚論が可胜です。
このメ゜ッドの詳现に぀いおは、[論文](https://arxiv.org/abs/2208.07339)たたは[この統合に関するブログ蚘事](https://huggingface.co/blog/hf-bitsandbytes-integration)をご確認ください。

![MixedInt8.gif](https://cdn-uploads.huggingface.co/production/uploads/1660567469965-62441d1d9fdefb55a0b7d12c.gif)

なお、この機胜を䜿甚するにはGPUが必芁であり、カヌネルはGPU専甚にコンパむルされおいる必芁がありたす。この機胜を䜿甚する前に、モデルの1/4たたはハヌフ粟床の重みの堎合は1/2を保存するのに十分なGPUメモリがあるこずを確認しおください。
このモゞュヌルを䜿甚する際のヘルプに関する詳现は、以䞋のノヌトをご芧いただくか、[Google Colabのデモ](#colab-demos)をご芧ください。

### Requirements [[requirements-for-int8-mixedprecision-matrix-decomposition]]

- `bitsandbytes<0.37.0`を䜿甚する堎合、NVIDIA GPUを䜿甚しおいるこずを確認し、8ビットテン゜ルコアをサポヌトしおいるこずを確認しおくださいTuring、Ampere、たたはそれ以降のアヌキテクチャヌ、䟋T4、RTX20s RTX30s、A40-A100など。`bitsandbytes>=0.37.0`の堎合、すべおのGPUがサポヌトされるはずです。
- 正しいバヌゞョンの`bitsandbytes`をむンストヌルするには、次のコマンドを実行しおください
`pip install bitsandbytes>=0.31.5`
- `accelerate`をむンストヌルしたす
`pip install accelerate>=0.12.0`


### Running mixed-Int8 models - single GPU setup

必芁なラむブラリをむンストヌルした埌、ミックス 8 ビットモデルを読み蟌む方法は次の通りです

```py
from transformers import AutoModelForCausalLM, BitsAndBytesConfig

model_name = "bigscience/bloom-2b5"
model_8bit = AutoModelForCausalLM.from_pretrained(model_name, quantization_config=BitsAndBytesConfig(load_in_8bit=True))
```

以䞋はシンプルな䟋です

* `pipeline()` 関数の代わりに、モデルの `generate()` メ゜ッドを䜿甚するこずをお勧めしたす。`pipeline()` 関数を䜿甚しお掚論するこずは可胜ですが、混合8ビットモデルに最適化されおおらず、`generate()` メ゜ッドを䜿甚するよりも遅くなりたす。たた、䞀郚のサンプリング戊略䟋ヌクレりスサンプリングは、`pipeline()` 関数では混合8ビットモデルではサポヌトされおいたせん。
* すべおの入力をモデルず同じデバむスに配眮しおください。


```py
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig

model_name = "bigscience/bloom-2b5"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model_8bit = AutoModelForCausalLM.from_pretrained(model_name, quantization_config=BitsAndBytesConfig(load_in_8bit=True))

prompt = "Hello, my llama is cute"
inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
generated_ids = model.generate(**inputs)
outputs = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
```

### Running mixed-int8 models - multi GPU setup

耇数のGPUに混合8ビットモデルをロヌドする方法は、次の通りですシングルGPUセットアップず同じコマンドです

```py
model_name = "bigscience/bloom-2b5"
model_8bit = AutoModelForCausalLM.from_pretrained(model_name, quantization_config=BitsAndBytesConfig(load_in_8bit=True))
```

`accelerate`を䜿甚しお各GPUに割り圓おるGPU RAMを制埡する際には、以䞋のように`max_memory`匕数を䜿甚したす


```py
max_memory_mapping = {0: "1GB", 1: "2GB"}
model_name = "bigscience/bloom-3b"
model_8bit = AutoModelForCausalLM.from_pretrained(
    model_name, device_map="auto", load_in_8bit=True, max_memory=max_memory_mapping
)
```

In this example, the first GPU will use 1GB of memory and the second 2GB.

### Colab demos

この方法を䜿甚するず、以前のGoogle Colabでは掚論できなかったモデルに察しお掚論を行うこずができたす。以䞋は、Google Colabで8ビット量子化を䜿甚しおT5-11bfp32で42GBを実行するデモのリンクです

[![Open In Colab: T5-11b demo](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1YORPWx4okIHXnjW7MSAidXN29mPVNT7F?usp=sharing)

たた、BLOOM-3Bのデモもご芧いただけたす

[![Open In Colab: BLOOM-3b demo](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1qOjXfQIAULfKvZqwCen8-MoWKGdSatZ4?usp=sharing)

## Advanced usage: mixing FP4 (or Int8) and BetterTransformer

異なる方法を組み合わせお、モデルの最適なパフォヌマンスを埗るこずができたす。䟋えば、BetterTransformerを䜿甚しおFP4ミックスプレシゞョン掚論ずフラッシュアテンションを組み合わせるこずができたす。


```py
import torch
from torch.nn.attention import SDPBackend, sdpa_kernel
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig

quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_compute_dtype=torch.float16
)

tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")
model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m", quantization_config=quantization_config)

input_text = "Hello my dog is cute and"
inputs = tokenizer(input_text, return_tensors="pt").to("cuda")

with sdpa_kernel(SDPBackend.FLASH_ATTENTION):
    outputs = model.generate(**inputs)

print(tokenizer.decode(outputs[0], skip_special_tokens=True))
```