In [6]:
import os
import psutil
import time


from optimum.intel import OVModelForCausalLM
from transformers import AutoProcessor

model_path = r"H:\LLM_Models\safetensor\Qwen\Qwen2.5-Coder-7B-Instruct"
In [ ]:
# 初回はOpenVINO IR形式に変換処理が内部で行われる

process = psutil.Process(os.getpid())
mem_before = process.memory_info().rss / 1024**2  # MB
start = time.time()

processor = AutoProcessor.from_pretrained(model_path)

model = OVModelForCausalLM.from_pretrained(model_path)

messages = [
    {"role": "system", "content": "あなたは有能なAIアシスタントです。"},
    {"role": "user", "content": "面白いジョークを話して。またどこが面白いかも解説してください。"},
]

inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    add_generation_prompt=True,
    enable_thinking=False
).to(model.device)
input_len = inputs["input_ids"].shape[-1]

# Generate output
outputs = model.generate(**inputs, max_new_tokens=1024)
response = processor.decode(outputs[0][input_len:], skip_special_tokens=False)

mem_after = process.memory_info().rss / 1024**2  # MB
end = time.time()

print(response)

print("=" * 60)
print(f"実行前メモリ使用量: {mem_before:.2f} MB")
print(f"実行後メモリ使用量: {mem_after:.2f} MB")
print(f"実行時間: {end - start:.3f} 秒")
No OpenVINO files were found for H:\LLM_Models\safetensor\Qwen\Qwen2.5-Coder-7B-Instruct, setting `export=True` to convert the model to the OpenVINO IR. Don't forget to save the resulting model with `.save_pretrained()`
Loading weights:   0%|          | 0/339 [00:00<?, ?it/s]
c:\ProgramData\anaconda3\envs\openvino_20260717\Lib\site-packages\transformers\cache_utils.py:132: TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
  if not self.is_initialized or self.keys.numel() == 0:
c:\ProgramData\anaconda3\envs\openvino_20260717\Lib\site-packages\transformers\masking_utils.py:171: TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
  if (padding_length := kv_length + kv_offset - attention_mask.shape[-1]) > 0:
c:\ProgramData\anaconda3\envs\openvino_20260717\Lib\site-packages\optimum\exporters\openvino\patching_utils.py:247: TracerWarning: torch.tensor results are registered as constants in the trace. You can safely ignore this warning if you use this function to create tensors out of constant variables that would be the same every time you call this function. In any other case, this might cause the trace to be incorrect.
  torch.tensor(0.0, device=mask.device, dtype=dtype),
c:\ProgramData\anaconda3\envs\openvino_20260717\Lib\site-packages\optimum\exporters\openvino\patching_utils.py:248: TracerWarning: torch.tensor results are registered as constants in the trace. You can safely ignore this warning if you use this function to create tensors out of constant variables that would be the same every time you call this function. In any other case, this might cause the trace to be incorrect.
  torch.tensor(torch.finfo(torch.float16).min, device=mask.device, dtype=dtype),
c:\ProgramData\anaconda3\envs\openvino_20260717\Lib\site-packages\transformers\integrations\sdpa_attention.py:77: TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
  is_causal = query.shape[2] > 1 and attention_mask is None and is_causal
INFO:nncf:Statistics of the bitwidth distribution:
+---------------------------+-----------------------------+----------------------------------------+
| Weight compression mode   | % all parameters (layers)   | % ratio-defining parameters (layers)   |
+===========================+=============================+========================================+
| int8_asym, per-channel    | 100% (198 / 198)            | 100% (198 / 198)                       |
+---------------------------+-----------------------------+----------------------------------------+
Output()

もちろんです。以下にジョークをお聞かせします。

「ある日、パン屋さんでおばあちゃんがパンを买いました。
おばあちゃん:「これ何ですか?」
店員:「これは黒パンです。」
おばあちゃん:「ええ、それらしくて美味しいですね。」」

このジョークの面白い点は、「黒パン」の意味が一般的ではありません。私たちが通常考えている「黒パン」とは全く異なるものです。店員の答えが予想外で、笑いのきっかけとなっています。<|im_end|>
============================================================
実行前メモリ使用量: 860.89 MB
実行後メモリ使用量: 14426.25 MB
実行時間: 95.787 秒
In [ ]:
# OpenVINO IR形式を保存
# 次回以降model_pathに保存済みのOpenVINO IR形式へのpathを渡せば変換が省略される。
open_vino_save_path = r"H:\LLM_Models\open_vino\Qwen\Qwen2.5-Coder-7B-Instruct"
model.save_pretrained(open_vino_save_path)
processor.save_pretrained(open_vino_save_path)
Out[ ]:
('H:\\LLM_Models\\open_vino\\Qwen\\Qwen2.5-Coder-7B-Instruct\\tokenizer_config.json',
 'H:\\LLM_Models\\open_vino\\Qwen\\Qwen2.5-Coder-7B-Instruct\\chat_template.jinja',
 'H:\\LLM_Models\\open_vino\\Qwen\\Qwen2.5-Coder-7B-Instruct\\tokenizer.json')
In [21]:
del model, processor
In [22]:
process = psutil.Process(os.getpid())
mem_before = process.memory_info().rss / 1024**2  # MB
start = time.time()

processor = AutoProcessor.from_pretrained(open_vino_save_path)
model = OVModelForCausalLM.from_pretrained(open_vino_save_path)

messages = [
    {"role": "system", "content": "あなたは有能なAIアシスタントです。"},
    {"role": "user", "content": "面白いジョークを話して。またどこが面白いかも解説してください。"},
]

inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    add_generation_prompt=True,
    enable_thinking=False
).to(model.device)
input_len = inputs["input_ids"].shape[-1]


outputs = model.generate(**inputs, max_new_tokens=1024)
response = processor.decode(outputs[0][input_len:], skip_special_tokens=False)

mem_after = process.memory_info().rss / 1024**2  # MB

end = time.time()

print(response)
print("=" * 60)
print(f"実行前メモリ使用量: {mem_before:.2f} MB")
print(f"実行後メモリ使用量: {mem_after:.2f} MB")
print(f"実行時間: {end - start:.3f} 秒")
もちろんです、以下に面白いジョークをお伝えします。

ジョーク: 「誰が最強のプログラマーなのか?」

答え: 「AIだよ。なぜなら、他のプログラマーと比べて、コードを書くのが最も効率的だからだよ。」

このジョークは「AI」についての知識と、「効率性」や「比較」に関する思考を含んでいます。AIが他のプログラマーと比べて最強だと主張している点が面白いですね。また、AIが「コードを書く」というタスクで最も優れたという設定も興味深い表現になっています。<|im_end|>
============================================================
実行前メモリ使用量: 1006.55 MB
実行後メモリ使用量: 14696.58 MB
実行時間: 47.514 秒
In [23]:
del model, processor
In [7]:
from transformers import AutoModelForCausalLM, AutoTokenizer
In [9]:
process = psutil.Process(os.getpid())
mem_before = process.memory_info().rss / 1024**2  # MB
start = time.time()


model = AutoModelForCausalLM.from_pretrained(
    model_path,
    torch_dtype="auto",
    device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained(model_path)

messages = [
    {"role": "system", "content": "あなたは有能なAIアシスタントです。"},
    {"role": "user", "content": "面白いジョークを話して。またどこが面白いかも解説してください。"},
]
text = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True
)
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)

generated_ids = model.generate(
    **model_inputs,
    max_new_tokens=512
)
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]


mem_after = process.memory_info().rss / 1024**2  # MB

end = time.time()

print(response)
print("=" * 60)
print(f"実行前メモリ使用量: {mem_before:.2f} MB")
print(f"実行後メモリ使用量: {mem_after:.2f} MB")
print(f"実行時間: {end - start:.3f} 秒")
Loading weights:   0%|          | 0/339 [00:00<?, ?it/s]
もちろんです、以下に面白いジョークを一つ紹介します。

ジョーク:「何が最も美しいですか?答えは「花」です。なぜなら、春には桜、夏にはバラ、秋には菊、冬には梅があります。」

このジョークの面白さは、「花」という単語が複数の季節で美しく見えるという観点から、一年を通じて美しさがあることを表現しています。また、「何が最も美しいですか?」という一般的な質問に対して、具体的な答えを提案することで、聴衆の興味を引きつける効果もあります。
============================================================
実行前メモリ使用量: 492.35 MB
実行後メモリ使用量: 14095.08 MB
実行時間: 79.201 秒