👏

DeepSeek-R1-Distill-Qwen-1.5BをColabで動かす

2025/01/26に公開

目的

備忘録です。deepseekで遊んでみようとしたら、Pythonコードのみで簡単に動かせる実装例がrepo内になかったため、書きました。

Repo

https://github.com/deepseek-ai/DeepSeek-R1

実装

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

model = AutoModelForCausalLM.from_pretrained(
    "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B",
    torch_dtype="auto",
    device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B")

prompt = "Give me a short introduction to large language model."
messages = [
    {"role": "user", "content": prompt}
]
text = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True
)
model_inputs = tokenizer([text], return_tensors="pt").to(device)

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

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

出力

<think>
Okay, so I need to give a short introduction to a Large Language Model (LLM). Hmm, where do I start? Well, I know that LLMs are a type of artificial intelligence, right? They're different from traditional computers because they can understand and generate human language. But I'm not entirely sure about all the details.

Let me think. I remember that LLMs are trained on vast amounts of data, which allows them to learn complex patterns. Unlike traditional models that are limited to a few hundred training examples, LLMs have millions or even billions of them. That must mean they can handle a

Colab

https://colab.research.google.com/drive/1P_1aFS_jcDnmIxbGFTEEDAwOC8VpP6f7?usp=sharing

利用時の推奨事項

repoに書かれている推奨事項を翻訳したもの。

  • 無限の繰り返しや一貫性のない出力を防ぐために、温度を 0.5 ~ 0.7 (0.6 が推奨) の範囲に設定します。
  • システム プロンプトを追加しないでください。すべての指示はユーザー プロンプト内に含める必要があります。 数学の問題の場合、プロンプトに「ステップごとに推論し、最終的な答えを \boxed{} 内に入力してください」などの指示を含めることをお勧めします。
  • モデルのパフォーマンスを評価するときは、複数のテストを実行して結果を平均化することをお勧めします。

Discussion