| 1 |
# Copyright 2024 The HuggingFace Inc. team. All rights reserved. |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
import torch |
| 15 |
from transformers import AutoModelForCausalLM, AutoTokenizer |
| 16 |
|
| 17 |
from accelerate import PartialState, prepare_pippy |
| 18 |
|
| 19 |
|
| 20 |
# sdpa implementation which is the default torch>2.1.2 fails with the tracing + attention mask kwarg |
| 21 |
# with attn_implementation="eager" mode, the forward is very slow for some reason |
| 22 |
model = AutoModelForCausalLM.from_pretrained( |
| 23 |
"meta-llama/Llama-2-7b-chat-hf", low_cpu_mem_usage=True, attn_implementation="sdpa" |
| 24 |
) |
| 25 |
model.eval() |
| 26 |
|
| 27 |
# Input configs |
| 28 |
# Create example inputs for the model |
| 29 |
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf") |
| 30 |
prompts = ("I would like to", "I really like to") # bs = 2, sending 2 per process |
| 31 |
tokenizer.pad_token = tokenizer.eos_token |
| 32 |
inputs = tokenizer(prompts, return_tensors="pt", padding=True) |
| 33 |
|
| 34 |
# Create a pipeline stage from the model |
| 35 |
# Using `auto` is equivalent to letting `device_map="auto"` figure |
| 36 |
# out device mapping and will also split the model according to the |
| 37 |
# number of total GPUs available if it fits on one GPU |
| 38 |
model = prepare_pippy(model, split_points="auto", example_kwargs=inputs) |
| 39 |
|
| 40 |
# You can pass `gather_output=True` to have the output from the model |
| 41 |
# available on all GPUs |
| 42 |
# model = prepare_pippy(model, split_points="auto", example_args=(input,), gather_output=True) |
| 43 |
|
| 44 |
# currently we don't support `model.generate` |
| 45 |
# output = model.generate(**inputs, max_new_tokens=1) |
| 46 |
prompts = ("I would like to", "I really like to", "The weather is pretty") # bs = 3 |
| 47 |
inputs = tokenizer(prompts, return_tensors="pt", padding=True) |
| 48 |
inputs = inputs.to(0) |
| 49 |
with torch.no_grad(): |
| 50 |
output = model(**inputs) |
| 51 |
|
| 52 |
# The outputs are only on the final process by default |
| 53 |
if PartialState().is_last_process: |
| 54 |
next_token_logits = output[0][:, -1, :] |
| 55 |
next_token = torch.argmax(next_token_logits, dim=-1) |
| 56 |
print(tokenizer.batch_decode(next_token)) |
| 57 |
PartialState().destroy_process_group() |