見出し画像

Metal Performance Shaders framework: cudaの代わりに mps 指定

以下のポストが目に止まりました。

特に惹かれたのが次の一文 "Bonus: Swap "cuda" with "mps" to run it on your mac! ✨"
HuggingfaceのLLMのモデルカードのサンプルコードに書かれているのは、cudaがいつも指定されていたので、サンプルコードはNvidiaのグラフィックボードがないと走らないと思っていました。

mpsをdeviceに指定すれば、Macでも走ると書いてあったので驚いて、さっそく試してみました。
コメントを追加して、ポストからコピーしたスクリプトは以下の通りで、mpsを指定しました。

# GPU Poor Models from Qwen: powered by transformers! 🔥
# https://x.com/reach_vb/status/1754581852399022240?s=20
# Bonus: Swap "cuda" with "mps" to run it on your mac! ✨

from transformers import AutoModelForCausalLM, AutoTokenizer
device = "mps" # the device to load the model onto

# Step 1: Load the model

model = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen1.5-4B-Chat",
    device_map="auto"
)

tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen1.5-4B-Chat")

# Step 2: Define your prompt 

prompt = "Give me a short introduction to large language model."

messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": prompt}
]

text = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True
)

# Step 3: Tokenise your prompt

model_inputs = tokenizer([text], return_tensors="pt").to(device)

# Step 4: Generate the response

generated_ids = model.generate(
    model_inputs.input_ids,
    max_new_tokens=512  
)

generated_ids = [
    output_ids[len(input_ids):] for input_ids, output_ids in 
  zip(model_inputs.input_ids, generated_ids)
]

# Step 5: Decode the response

response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]

print(response)

llama-cpp-pythonを入れたconda環境で、このスクリプトを走らせます。

最初はこのエラー; ModuleNotFoundError: No module named 'transformers'
なので次のコマンドでインストール: conda install transformers

次のエラーは、AutoModelForCausalLM requires the PyTorch library but it was not found in your environment. 
ここでPyTorchがないと言われたので、下記からダウンロード

cuda環境なので、cudaでの指定"conda install pytorch::pytorch torchvision torchaudio -c pytorch"でインストールしてから走らせたら、以下のエラーがでました。

raise KeyError(key)
KeyError: 'qwen2'

次は、condaではまだサポートされてないようなので、"pip install --upgrade transformers" で transformersをアップグレード。

次に出たエラーは、こちら:ImportError: Using `low_cpu_mem_usage=True` or a `device_map` requires Accelerate: `pip install accelerate`

指定に従って、pip install accelerate でインストール。

以上の手順で、上のスクリプトが走りました。
(こんな警告がでていますが、"The attention mask and the pad token id were not set. As a consequence, you may observe unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results.
Setting `pad_token_id` to `eos_token_id`:151645 for open-end generation.")

ただ走っても何も出力表示されないので、気がついたら print(response)を指定してませんでした💦

出力結果は以下でした。

A large language model is a type of artificial intelligence system that can generate human-like text based on input data. These models typically consist of complex neural networks that have been trained on vast amounts of text data, such as books, articles, and the internet.
One of the key benefits of large language models is their ability to understand and generate natural language text with high accuracy and fluency. This makes them useful for a wide range of applications, including chatbots, language translation, content creation, and more.
However, large language models also raise concerns about privacy and bias, particularly when it comes to training data and the potential for unintended consequences. As a result, there is ongoing research into how to develop large language models in an ethical and responsible manner.


#AI #AIとやってみた #やってみた #Huggingface #LLM #ローカルLLM #大規模言語モデル #Macbookpro #cuda #mps #Qwen

この記事が参加している募集

やってみた

AIとやってみた

この記事を最後までご覧いただき、ありがとうございます!もしも私の活動を応援していただけるなら、大変嬉しく思います。