Spaces:
Sleeping
Sleeping
Merge feature/fast-inference-docs
Browse files- README.md +11 -0
- docs/README.en.md +23 -17
- sandbox/Unsloth_inference_llama3-2.md +158 -0
- sandbox/Unsloth_inference_llm_jp.md +120 -0
README.md
CHANGED
@@ -81,6 +81,17 @@ license: mit
|
|
81 |
- → [マークダウン形式からノートブック形式への変換はこちらを使用してください](https://huggingface.co/spaces/MakiAi/JupytextWebUI)
|
82 |
- [📒ノートブックはこちら](https://colab.research.google.com/drive/1AjtWF2vOEwzIoCMmlQfSTYCVgy4Y78Wi?usp=sharing)
|
83 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
84 |
### OllamaとLiteLLMを使用した効率的なモデル運用
|
85 |
- Google Colabでのセットアップと運用ガイド
|
86 |
- → 詳細は [`efficient-ollama-colab-setup-with-litellm-guide.md`](sandbox/efficient-ollama-colab-setup-with-litellm-guide.md) をご参照ください。
|
|
|
81 |
- → [マークダウン形式からノートブック形式への変換はこちらを使用してください](https://huggingface.co/spaces/MakiAi/JupytextWebUI)
|
82 |
- [📒ノートブックはこちら](https://colab.research.google.com/drive/1AjtWF2vOEwzIoCMmlQfSTYCVgy4Y78Wi?usp=sharing)
|
83 |
|
84 |
+
### Unslothを使用した高速推論
|
85 |
+
- Llama-3.2モデルの高速推論実装
|
86 |
+
- → 詳細は [`Unsloth_inference_llama3-2.md`](sandbox/Unsloth_inference_llama3-2.md) をご参照ください。
|
87 |
+
- → Unslothを使用したLlama-3.2モデルの効率的な推論処理の実装
|
88 |
+
- [📒ノートブックはこちら](https://colab.research.google.com/drive/1FkAYiX2fbGPTRUopYw39Qt5UE2tWJRpa?usp=sharing)
|
89 |
+
|
90 |
+
- LLM-JPモデルの高速推論実装
|
91 |
+
- → 詳細は [`Unsloth_inference_llm_jp.md`](sandbox/Unsloth_inference_llm_jp.md) をご参照ください。
|
92 |
+
- → 日本語LLMの高速推論処理の実装とパフォーマンス最適化
|
93 |
+
- [📒ノートブックはこちら](https://colab.research.google.com/drive/1lbMKv7NzXQ1ynCg7DGQ6PcCFPK-zlSEG?usp=sharing)
|
94 |
+
|
95 |
### OllamaとLiteLLMを使用した効率的なモデル運用
|
96 |
- Google Colabでのセットアップと運用ガイド
|
97 |
- → 詳細は [`efficient-ollama-colab-setup-with-litellm-guide.md`](sandbox/efficient-ollama-colab-setup-with-litellm-guide.md) をご参照ください。
|
docs/README.en.md
CHANGED
@@ -31,7 +31,7 @@ license: mit
|
|
31 |
</p>
|
32 |
|
33 |
<h2 align="center">
|
34 |
-
Llama Model Fine-tuning
|
35 |
</h2>
|
36 |
|
37 |
<p align="center">
|
@@ -44,7 +44,7 @@ license: mit
|
|
44 |
|
45 |
## 🚀 Project Overview
|
46 |
|
47 |
-
**Llama-finetune-sandbox** provides an experimental environment for learning and verifying
|
48 |
|
49 |
|
50 |
## ✨ Key Features
|
@@ -58,16 +58,16 @@ license: mit
|
|
58 |
- Various quantization options
|
59 |
- Multiple attention mechanisms
|
60 |
|
61 |
-
3. **
|
62 |
-
-
|
63 |
- Visualization of experimental results
|
64 |
|
65 |
4. **Context-Aware Reflexive QA Generation System:**
|
66 |
- Generates high-quality Q&A datasets from Wikipedia data.
|
67 |
- Uses LLMs to automatically generate context-aware questions and answers, evaluate quality, and iteratively improve them.
|
68 |
-
- Employs a reflexive approach
|
69 |
- Provides comprehensive code and explanations covering environment setup, model selection, data preprocessing, Q&A pair generation, quality evaluation, and the improvement process.
|
70 |
-
-
|
71 |
- Generated Q&A pairs are saved in JSON format and can be easily uploaded to the Hugging Face Hub.
|
72 |
|
73 |
|
@@ -82,25 +82,33 @@ This repository includes the following examples:
|
|
82 |
- [📒Notebook here](https://colab.research.google.com/drive/1AjtWF2vOEwzIoCMmlQfSTYCVgy4Y78Wi?usp=sharing)
|
83 |
|
84 |
### Efficient Model Deployment using Ollama and LiteLLM
|
85 |
-
- Setup and
|
86 |
- → See [`efficient-ollama-colab-setup-with-litellm-guide.md`](sandbox/efficient-ollama-colab-setup-with-litellm-guide.md) for details.
|
87 |
- [📒Notebook here](https://colab.research.google.com/drive/1buTPds1Go1NbZOLlpG94VG22GyK-F4GW?usp=sharing)
|
88 |
|
89 |
### Q&A Dataset Generation from Wikipedia Data (Sentence Pool QA Method)
|
90 |
- High-quality Q&A dataset generation using the sentence pool QA method.
|
91 |
-
- → A new dataset creation method that generates Q&A pairs while preserving context by pooling
|
92 |
-
- → Chunk size is flexibly adjustable (default 200 characters)
|
93 |
- → See [`wikipedia-qa-dataset-generator.md`](sandbox/wikipedia-qa-dataset-generator.md) for details.
|
94 |
- [📒Notebook here](https://colab.research.google.com/drive/1mmK5vxUzjk3lI6OnEPrQqyjSzqsEoXpk?usp=sharing)
|
95 |
|
96 |
### Context-Aware Reflexive QA Generation System
|
97 |
- Q&A dataset generation with reflexive quality improvement.
|
98 |
-
- →
|
99 |
- → Quantifies factuality, question quality, and answer completeness for evaluation.
|
100 |
-
- →
|
101 |
- → See [`context_aware_Reflexive_qa_generator_V2.md`](sandbox/context_aware_Reflexive_qa_generator_V2.md) for details.
|
102 |
- [📒Notebook here](https://colab.research.google.com/drive/1OYdgAuXHbl-0LUJgkLl_VqknaAEmAm0S?usp=sharing)
|
103 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
|
105 |
## 🛠️ Setup
|
106 |
|
@@ -113,11 +121,10 @@ cd Llama-finetune-sandbox
|
|
113 |
## 📝 Adding Examples
|
114 |
|
115 |
1. Add new implementations to the `sandbox/` directory.
|
116 |
-
2. Add necessary
|
117 |
-
3. Update documentation and tests (
|
118 |
4. Create a pull request.
|
119 |
|
120 |
-
|
121 |
## 🤝 Contributions
|
122 |
|
123 |
- Implementation of new fine-tuning methods
|
@@ -127,15 +134,14 @@ cd Llama-finetune-sandbox
|
|
127 |
|
128 |
## 📚 References
|
129 |
|
130 |
-
- [HuggingFace PEFT
|
131 |
- [About Llama models](https://github.com/facebookresearch/llama)
|
132 |
-
- [Fine-tuning best practices](https://github.com/Sunwood-ai-labs/Llama-finetune-sandbox/wiki) (
|
133 |
|
134 |
## 📄 License
|
135 |
|
136 |
This project is licensed under the MIT License.
|
137 |
|
138 |
-
|
139 |
## v0.5.0 Updates
|
140 |
|
141 |
**🆕 What's New:**
|
|
|
31 |
</p>
|
32 |
|
33 |
<h2 align="center">
|
34 |
+
Llama Model Fine-tuning Experimentation Environment
|
35 |
</h2>
|
36 |
|
37 |
<p align="center">
|
|
|
44 |
|
45 |
## 🚀 Project Overview
|
46 |
|
47 |
+
**Llama-finetune-sandbox** provides an experimental environment for learning and verifying the fine-tuning of Llama models. You can try various fine-tuning methods, customize models, and evaluate performance. It caters to a wide range of users, from beginners to researchers. Version 0.5.0 includes updated documentation and the addition of a context-aware reflexive QA generation system. This system generates high-quality Q&A datasets from Wikipedia data, leveraging LLMs to iteratively improve the quality of questions and answers, resulting in a more accurate dataset.
|
48 |
|
49 |
|
50 |
## ✨ Key Features
|
|
|
58 |
- Various quantization options
|
59 |
- Multiple attention mechanisms
|
60 |
|
61 |
+
3. **Well-equipped Experimentation Environment:**
|
62 |
+
- Optimized memory usage
|
63 |
- Visualization of experimental results
|
64 |
|
65 |
4. **Context-Aware Reflexive QA Generation System:**
|
66 |
- Generates high-quality Q&A datasets from Wikipedia data.
|
67 |
- Uses LLMs to automatically generate context-aware questions and answers, evaluate quality, and iteratively improve them.
|
68 |
+
- Employs a reflexive approach, quantifying factuality, question quality, and answer completeness for iterative improvement.
|
69 |
- Provides comprehensive code and explanations covering environment setup, model selection, data preprocessing, Q&A pair generation, quality evaluation, and the improvement process.
|
70 |
+
- Utilizes libraries such as `litellm`, `wikipedia`, and `transformers`.
|
71 |
- Generated Q&A pairs are saved in JSON format and can be easily uploaded to the Hugging Face Hub.
|
72 |
|
73 |
|
|
|
82 |
- [📒Notebook here](https://colab.research.google.com/drive/1AjtWF2vOEwzIoCMmlQfSTYCVgy4Y78Wi?usp=sharing)
|
83 |
|
84 |
### Efficient Model Deployment using Ollama and LiteLLM
|
85 |
+
- Setup and deployment guide on Google Colab.
|
86 |
- → See [`efficient-ollama-colab-setup-with-litellm-guide.md`](sandbox/efficient-ollama-colab-setup-with-litellm-guide.md) for details.
|
87 |
- [📒Notebook here](https://colab.research.google.com/drive/1buTPds1Go1NbZOLlpG94VG22GyK-F4GW?usp=sharing)
|
88 |
|
89 |
### Q&A Dataset Generation from Wikipedia Data (Sentence Pool QA Method)
|
90 |
- High-quality Q&A dataset generation using the sentence pool QA method.
|
91 |
+
- → A new dataset creation method that generates Q&A pairs while preserving context by pooling sentence segments delimited by punctuation.
|
92 |
+
- → Chunk size is flexibly adjustable (default 200 characters) to generate Q&A pairs with an optimal context range depending on the application.
|
93 |
- → See [`wikipedia-qa-dataset-generator.md`](sandbox/wikipedia-qa-dataset-generator.md) for details.
|
94 |
- [📒Notebook here](https://colab.research.google.com/drive/1mmK5vxUzjk3lI6OnEPrQqyjSzqsEoXpk?usp=sharing)
|
95 |
|
96 |
### Context-Aware Reflexive QA Generation System
|
97 |
- Q&A dataset generation with reflexive quality improvement.
|
98 |
+
- → Automatically evaluates the quality of generated Q&A pairs and iteratively improves them.
|
99 |
- → Quantifies factuality, question quality, and answer completeness for evaluation.
|
100 |
+
- → Generates high-precision questions and performs consistency checks on answers using contextual information.
|
101 |
- → See [`context_aware_Reflexive_qa_generator_V2.md`](sandbox/context_aware_Reflexive_qa_generator_V2.md) for details.
|
102 |
- [📒Notebook here](https://colab.research.google.com/drive/1OYdgAuXHbl-0LUJgkLl_VqknaAEmAm0S?usp=sharing)
|
103 |
|
104 |
+
### LLM Evaluation System (LLMs as a Judge)
|
105 |
+
- Advanced quality evaluation system using LLMs as evaluators.
|
106 |
+
- → Automatically evaluates questions, model answers, and LLM responses on a four-level scale.
|
107 |
+
- → Robust design with error handling and retry functions.
|
108 |
+
- → Generates detailed evaluation reports in CSV and HTML formats.
|
109 |
+
- → See [`LLMs_as_a_Judge_TOHO_V2.md`](sandbox/LLMs_as_a_Judge_TOHO_V2.md) for details.
|
110 |
+
- [📒Notebook here](https://colab.research.google.com/drive/1Zjw3sOMa2v5RFD8dFfxMZ4NDGFoQOL7s?usp=sharing)
|
111 |
+
|
112 |
|
113 |
## 🛠️ Setup
|
114 |
|
|
|
121 |
## 📝 Adding Examples
|
122 |
|
123 |
1. Add new implementations to the `sandbox/` directory.
|
124 |
+
2. Add necessary settings and utilities to `utils/` (This section was removed as `utils/` directory appears not to exist).
|
125 |
+
3. Update documentation and tests (This section was removed as there's no mention of existing tests).
|
126 |
4. Create a pull request.
|
127 |
|
|
|
128 |
## 🤝 Contributions
|
129 |
|
130 |
- Implementation of new fine-tuning methods
|
|
|
134 |
|
135 |
## 📚 References
|
136 |
|
137 |
+
- [HuggingFace PEFT documentation](https://huggingface.co/docs/peft)
|
138 |
- [About Llama models](https://github.com/facebookresearch/llama)
|
139 |
+
- [Fine-tuning best practices](https://github.com/Sunwood-ai-labs/Llama-finetune-sandbox/wiki) (This section was removed as the wiki page appears not to exist).
|
140 |
|
141 |
## 📄 License
|
142 |
|
143 |
This project is licensed under the MIT License.
|
144 |
|
|
|
145 |
## v0.5.0 Updates
|
146 |
|
147 |
**🆕 What's New:**
|
sandbox/Unsloth_inference_llama3-2.md
ADDED
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 🦙 Unslothで作成したLLaMA 3.2ベースのファインチューニングモデルを使った高速推論ガイド
|
2 |
+
|
3 |
+
## 📦 必要なライブラリのインストール
|
4 |
+
|
5 |
+
```python
|
6 |
+
%%capture
|
7 |
+
!pip install unsloth
|
8 |
+
# 最新のUnslothナイトリービルドを取得
|
9 |
+
!pip uninstall unsloth -y && pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
|
10 |
+
```
|
11 |
+
|
12 |
+
**解説**:
|
13 |
+
Unslothライブラリをインストールします。このライブラリを使用することで、LLaMAモデルのファインチューニングと推論を大幅に高速化できます。ナイトリービルドを使用することで、最新の機能と改善が利用可能です。
|
14 |
+
|
15 |
+
## 🔧 ライブラリのインポートと基本設定
|
16 |
+
|
17 |
+
```python
|
18 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
19 |
+
from unsloth import FastLanguageModel
|
20 |
+
from unsloth.chat_templates import get_chat_template
|
21 |
+
import torch
|
22 |
+
|
23 |
+
# モデルの基本設定
|
24 |
+
max_seq_length = 512
|
25 |
+
dtype = None
|
26 |
+
load_in_4bit = True
|
27 |
+
model_id = "MakiAi/Llama-3-2-3B-Instruct-bnb-4bit-10epochs-adapter" # ファインチューニング済みのモデルパス
|
28 |
+
```
|
29 |
+
|
30 |
+
**解説**:
|
31 |
+
- 必要なライブラリをインポート
|
32 |
+
- モデルは4ビット量子化を使用して、メモリ効率を改善
|
33 |
+
- `model_id`には、Unslothでファインチューニングしたモデルのパスを指定
|
34 |
+
|
35 |
+
## 🚀 モデルとトークナイザーの初期化
|
36 |
+
|
37 |
+
```python
|
38 |
+
# モデルとトークナイザーのロード
|
39 |
+
model, tokenizer = FastLanguageModel.from_pretrained(
|
40 |
+
model_name=model_id,
|
41 |
+
dtype=dtype,
|
42 |
+
load_in_4bit=load_in_4bit,
|
43 |
+
trust_remote_code=True,
|
44 |
+
)
|
45 |
+
|
46 |
+
# LLaMA 3.1のチャットテンプレートを使用
|
47 |
+
tokenizer = get_chat_template(
|
48 |
+
tokenizer,
|
49 |
+
chat_template="llama-3.1", # LLaMA 3.1のテンプレートで問題なし
|
50 |
+
)
|
51 |
+
|
52 |
+
# 高速推論モードを有効化
|
53 |
+
FastLanguageModel.for_inference(model) # 通常の2倍の速度
|
54 |
+
```
|
55 |
+
|
56 |
+
**解説**:
|
57 |
+
1. ファインチューニング済みのモデルをロード
|
58 |
+
2. LLaMA 3.1のチャットテンプレートを適用(3.2でも互換性あり)
|
59 |
+
3. Unslothの高速推論モードを有効化
|
60 |
+
|
61 |
+
## 💬 データセットを使用した推論の実装
|
62 |
+
|
63 |
+
```python
|
64 |
+
def generate_response(dataset_entry):
|
65 |
+
"""
|
66 |
+
データセットのエントリーに対して応答を生成する関数
|
67 |
+
"""
|
68 |
+
# メッセージの作成
|
69 |
+
messages = [
|
70 |
+
{"role": "user", "content": dataset_entry["conversations"][0]['content']},
|
71 |
+
]
|
72 |
+
|
73 |
+
# チャットテンプレートの適用
|
74 |
+
inputs = tokenizer.apply_chat_template(
|
75 |
+
messages,
|
76 |
+
tokenize=True,
|
77 |
+
add_generation_prompt=True, # 生成プロンプトの追加
|
78 |
+
return_tensors="pt",
|
79 |
+
).to(model.device)
|
80 |
+
|
81 |
+
# 応答の生成
|
82 |
+
outputs = model.generate(
|
83 |
+
input_ids=inputs,
|
84 |
+
max_new_tokens=64, # 生成するトークン数
|
85 |
+
use_cache=True, # キャッシュを使用して高速化
|
86 |
+
temperature=1.5, # より創造的な応答を生成
|
87 |
+
min_p=0.1 # 出力の多様性を確保
|
88 |
+
)
|
89 |
+
|
90 |
+
return tokenizer.batch_decode(outputs)
|
91 |
+
```
|
92 |
+
|
93 |
+
**解説**:
|
94 |
+
この関数は:
|
95 |
+
1. データセットのエントリーからユーザーの入力を抽出
|
96 |
+
2. LLaMA 3.1形式のチャットテンプレートを適用
|
97 |
+
3. 以下のパラメータで応答を生成:
|
98 |
+
- `max_new_tokens`: 64(短めの応答を生成)
|
99 |
+
- `temperature`: 1.5(創造性を高める)
|
100 |
+
- `min_p`: 0.1(多様な応答を確保)
|
101 |
+
|
102 |
+
## ✅ 実行例
|
103 |
+
|
104 |
+
```python
|
105 |
+
if __name__ == "__main__":
|
106 |
+
# テストデータセット
|
107 |
+
dataset = [
|
108 |
+
{"conversations": [{"content": "火焔猫燐について教えてください。"}]},
|
109 |
+
{"conversations": [{"content": "水橋パルスィの本質は何ですか?"}]},
|
110 |
+
{"conversations": [{"content": "プログラミング初心者へのアドバイスをお願いします。"}]}
|
111 |
+
]
|
112 |
+
|
113 |
+
# 2番目のデータセットエントリーで試してみる
|
114 |
+
response = generate_response(dataset[0])
|
115 |
+
|
116 |
+
print("入力:", dataset[0]["conversations"][0]['content'])
|
117 |
+
print("応答:", response)
|
118 |
+
```
|
119 |
+
|
120 |
+
```python
|
121 |
+
if __name__ == "__main__":
|
122 |
+
# テストデータセット
|
123 |
+
dataset = [
|
124 |
+
{"conversations": [{"content": "火焔猫燐について教えてください。"}]},
|
125 |
+
{"conversations": [{"content": "水橋パルスィの本質は何ですか?"}]},
|
126 |
+
{"conversations": [{"content": "プログラミング初心者へのアドバイスをお願いします。"}]}
|
127 |
+
]
|
128 |
+
|
129 |
+
# 2番目のデータセットエントリーで試してみる
|
130 |
+
response = generate_response(dataset[1])
|
131 |
+
|
132 |
+
print("入力:", dataset[1]["conversations"][0]['content'])
|
133 |
+
print("応答:", response)
|
134 |
+
```
|
135 |
+
|
136 |
+
```python
|
137 |
+
if __name__ == "__main__":
|
138 |
+
# テストデータセット
|
139 |
+
dataset = [
|
140 |
+
{"conversations": [{"content": "火焔猫燐について教えてください。"}]},
|
141 |
+
{"conversations": [{"content": "水橋パルスィの本質は何ですか?"}]},
|
142 |
+
{"conversations": [{"content": "プログラミング初心者へのアドバイスをお願いします。"}]}
|
143 |
+
]
|
144 |
+
|
145 |
+
# 2番目のデータセットエントリーで試してみる
|
146 |
+
response = generate_response(dataset[2])
|
147 |
+
|
148 |
+
print("入力:", dataset[2]["conversations"][0]['content'])
|
149 |
+
print("応答:", response)
|
150 |
+
```
|
151 |
+
|
152 |
+
**解説**:
|
153 |
+
サンプルの実行方法を示しています:
|
154 |
+
- テスト用のデータセットを定義
|
155 |
+
- 選択したエントリーで応答を生成
|
156 |
+
- 入力と生成された応答を表示
|
157 |
+
|
158 |
+
このコードを使用することで、UnslothでファインチューニングしたカスタムのデータセットでトレーニングしたLLaMA 3.2モデルを、高速に推論できます。LLaMA 3.1のトークナイザーを使用することで、新しいモデルでも安定した出力が得られます。必要に応じて生成パラメータを調整することで、モデルの応答特性をカスタマイズできます。
|
sandbox/Unsloth_inference_llm_jp.md
ADDED
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 🤖 UnslothによるLLM-JPモデルの高速推論実装ガイド(Google Colab📒ノートブック付)
|
2 |
+
|
3 |
+
## 📦 必要なライブラリのインストール
|
4 |
+
|
5 |
+
```python
|
6 |
+
%%capture
|
7 |
+
!pip install unsloth
|
8 |
+
# 最新のUnslothナイトリービルドを取得
|
9 |
+
!pip uninstall unsloth -y && pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
|
10 |
+
```
|
11 |
+
|
12 |
+
**解説**:
|
13 |
+
このセルではUnslothライブラリをインストールしています。Unslothは大規模言語モデル(LLM)の推論を高速化するためのライブラリです。`%%capture`を使用することで、インストール時の出力を非表示にしています。
|
14 |
+
|
15 |
+
## 🔧 必要なライブラリのインポートと基本設定
|
16 |
+
|
17 |
+
```python
|
18 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
19 |
+
from unsloth import FastLanguageModel
|
20 |
+
import torch
|
21 |
+
|
22 |
+
# モデルの基本設定
|
23 |
+
max_seq_length = 512
|
24 |
+
dtype = None
|
25 |
+
load_in_4bit = True
|
26 |
+
model_id = "llm-jp/llm-jp-3-13b" # または自分でファインチューニングしたモデルID
|
27 |
+
```
|
28 |
+
|
29 |
+
**解説**:
|
30 |
+
- `transformers`: Hugging Faceの変換器ライブラリ
|
31 |
+
- `unsloth`: 高速化ライブラリ
|
32 |
+
- `torch`: PyTorchフレームワーク
|
33 |
+
- モデルの設定では:
|
34 |
+
- 最大シーケンス長: 512トークン
|
35 |
+
- 4ビット量子化を有効化
|
36 |
+
- LLM-JP 13Bモデルを使用
|
37 |
+
|
38 |
+
## 🚀 モデルとトークナイザーの初期化
|
39 |
+
|
40 |
+
```python
|
41 |
+
# モデルとトークナイザーのロード
|
42 |
+
model, tokenizer = FastLanguageModel.from_pretrained(
|
43 |
+
model_name=model_id,
|
44 |
+
dtype=dtype,
|
45 |
+
load_in_4bit=load_in_4bit,
|
46 |
+
trust_remote_code=True,
|
47 |
+
)
|
48 |
+
|
49 |
+
# 推論モードに設定
|
50 |
+
FastLanguageModel.for_inference(model)
|
51 |
+
```
|
52 |
+
|
53 |
+
**解説**:
|
54 |
+
このセルでは:
|
55 |
+
1. モデルとトークナイザーを同時にロード
|
56 |
+
2. 4ビット量子化を適用し、メモリ使用量を削減
|
57 |
+
3. モデルを推論モードに設定して最適化
|
58 |
+
|
59 |
+
## 💬 応答生成関数の実装
|
60 |
+
|
61 |
+
```python
|
62 |
+
def generate_response(input_text):
|
63 |
+
"""
|
64 |
+
入力テキストに対して応答を生成する関数
|
65 |
+
"""
|
66 |
+
# プロンプトの作成
|
67 |
+
prompt = f"""### 指示\n{input_text}\n### 回答\n"""
|
68 |
+
|
69 |
+
# 入力のトークナイズ
|
70 |
+
inputs = tokenizer([prompt], return_tensors="pt").to(model.device)
|
71 |
+
|
72 |
+
# 応答の生成
|
73 |
+
outputs = model.generate(
|
74 |
+
**inputs,
|
75 |
+
max_new_tokens=512,
|
76 |
+
use_cache=True,
|
77 |
+
do_sample=False,
|
78 |
+
repetition_penalty=1.2
|
79 |
+
)
|
80 |
+
|
81 |
+
# デコードして回答部分を抽出
|
82 |
+
prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
|
83 |
+
|
84 |
+
return prediction
|
85 |
+
```
|
86 |
+
|
87 |
+
**解説**:
|
88 |
+
この関数は以下の処理を行います:
|
89 |
+
1. 入力テキストを指示形式のプロンプトに変換
|
90 |
+
2. トークナイズしてモデルに入力可能な形式に変換
|
91 |
+
3. 以下のパラメータで応答を生成:
|
92 |
+
- `max_new_tokens`: 最大512トークンまで生成
|
93 |
+
- `use_cache`: キャッシュを使用して高速化
|
94 |
+
- `do_sample`: 決定的な出力を生成
|
95 |
+
- `repetition_penalty`: 繰り返しを抑制(1.2)
|
96 |
+
4. 生成された出力から回答部分のみを抽出
|
97 |
+
|
98 |
+
## ✅ 使用例
|
99 |
+
|
100 |
+
```python
|
101 |
+
if __name__ == "__main__":
|
102 |
+
# 入力例
|
103 |
+
sample_input = "今日の天気について教えてください。"
|
104 |
+
|
105 |
+
# 応答の生成
|
106 |
+
response = generate_response(sample_input)
|
107 |
+
|
108 |
+
print("入力:", sample_input)
|
109 |
+
print("応答:", response)
|
110 |
+
```
|
111 |
+
|
112 |
+
**解説**:
|
113 |
+
このセルは実際の使用例を示しています:
|
114 |
+
- サンプル入力を設定
|
115 |
+
- `generate_response`関数を呼び出して応答を生成
|
116 |
+
- 入力と応答を表示
|
117 |
+
|
118 |
+
このコードを実行することで、LLM-JPモデルを使用して日本語の質問に対する応答を生成できます。Unslothによる最適化により、標準的な実装と比較して高速な推論が可能です。
|
119 |
+
|
120 |
+
|