rasbt commited on
Commit
7d5ef97
·
verified ·
1 Parent(s): e2e8ea1

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. README.md +203 -1
README.md CHANGED
@@ -9,5 +9,207 @@ tags:
9
 
10
  # Qwen3 From Scratch
11
 
 
12
 
13
- In progress...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  # Qwen3 From Scratch
11
 
12
+ This repository contains a from-scratch, educational PyTorch implementation of **Qwen3** with **minimal code dependencies**. The implementation is **optimized for readability** and intended for learning and research purposes.
13
 
14
+ Source code: [qwen3.py](https://github.com/rasbt/LLMs-from-scratch/blob/main/pkg/llms_from_scratch/qwen3.py)
15
+
16
+ <img src="https://sebastianraschka.com/images/LLMs-from-scratch-images/bonus/qwen/qwen-overview.webp">
17
+
18
+
19
+ The model weights included here are PyTorch state dicts converted from the official weights provided by the Qwen3 team. For original weights, usage terms, and license information, please refer to the original model repositories linked below:
20
+
21
+ - https://huggingface.co/Qwen/Qwen3-0.6B-Base
22
+ - https://huggingface.co/Qwen/Qwen3-0.6B
23
+
24
+ To avoid duplication and ease maintance, this repository only contains the model weights; the self-contained source code can be found [here](https://github.com/rasbt/LLMs-from-scratch/blob/main/pkg/llms_from_scratch/qwen3.py). Instructions on how to use the code are provided below.
25
+
26
+ &nbsp;
27
+
28
+ ### Using Qwen3 0.6B via the `llms-from-scratch` package
29
+
30
+ For an easy way to use the Qwen3 from-scratch implementation, you can also use the `llms-from-scratch` PyPI package based on the source code in this repository at [pkg/llms_from_scratch](https://github.com/rasbt/LLMs-from-scratch/blob/main/pkg/llms_from_scratch/qwen3.py).
31
+
32
+ &nbsp;
33
+
34
+ #### 1) Installation
35
+
36
+ ```bash
37
+ pip install llms_from_scratch tokenizers
38
+ ```
39
+
40
+ &nbsp;
41
+
42
+ #### 2) Model and text generation settings
43
+
44
+ Specify which model to use:
45
+
46
+ ```python
47
+ USE_REASONING_MODEL = True # The "thinking" model
48
+ USE_REASONING_MODEL = False # The base model
49
+ ```
50
+
51
+ Basic text generation settings that can be defined by the user. With 150 tokens, the model requires approximately 1.5 GB memory.
52
+
53
+ ```python
54
+ MAX_NEW_TOKENS = 150
55
+ TEMPERATURE = 0.
56
+ TOP_K = 1
57
+ ```
58
+
59
+ &nbsp;
60
+
61
+ #### 3) Weight download and loading
62
+
63
+ This automatically downloads the weight file based on the model choice above:
64
+
65
+ ```python
66
+ from llms_from_scratch.qwen3 import download_from_huggingface
67
+
68
+ repo_id = "rasbt/qwen3-from-scratch"
69
+
70
+ if USE_REASONING_MODEL:
71
+ filename = "qwen3-0.6B.pth"
72
+ local_dir = "Qwen3-0.6B"
73
+ else:
74
+ filename = "qwen3-0.6B-base.pth"
75
+ local_dir = "Qwen3-0.6B-Base"
76
+
77
+ download_from_huggingface(
78
+ repo_id=repo_id,
79
+ filename=filename,
80
+ local_dir=local_dir
81
+ )
82
+ ```
83
+
84
+ The model weights are then loaded as follows:
85
+
86
+ ```python
87
+ from pathlib import Path
88
+ import torch
89
+
90
+ from llms_from_scratch.qwen3 import Qwen3Model, QWEN_CONFIG_06_B
91
+
92
+ model_file = Path(local_dir) / filename
93
+
94
+ model = Qwen3Model(QWEN_CONFIG_06_B)
95
+ model.load_state_dict(torch.load(model_file, weights_only=True, map_location="cpu"))
96
+
97
+ device = (
98
+ torch.device("cuda") if torch.cuda.is_available() else
99
+ torch.device("mps") if torch.backends.mps.is_available() else
100
+ torch.device("cpu")
101
+ )
102
+ model.to(device)
103
+ ```
104
+
105
+ &nbsp;
106
+
107
+ #### 4) Initialize tokenizer
108
+
109
+ The following code downloads and initializes the tokenizer:
110
+
111
+ ```python
112
+ from llms_from_scratch.qwen3 import Qwen3Tokenizer
113
+
114
+ if USE_REASONING_MODEL:
115
+ tok_filename = str(Path("Qwen3-0.6B") / "tokenizer.json")
116
+ else:
117
+ tok_filename = str(Path("Qwen3-0.6B-Base") / "tokenizer-base.json")
118
+
119
+ tokenizer = Qwen3Tokenizer(
120
+ tokenizer_file_path=tok_filename,
121
+ repo_id=repo_id,
122
+ add_generation_prompt=USE_REASONING_MODEL,
123
+ add_thinking=USE_REASONING_MODEL
124
+ )
125
+ ```
126
+
127
+
128
+
129
+ &nbsp;
130
+
131
+ #### 5) Generating text
132
+
133
+ Lastly, we can generate text via the following code:
134
+
135
+ ```python
136
+ prompt = "Give me a short introduction to large language models."
137
+ input_token_ids = tokenizer.encode(prompt)
138
+ ```
139
+
140
+
141
+
142
+
143
+
144
+ ```python
145
+ from llms_from_scratch.ch05 import generate
146
+ import time
147
+
148
+ torch.manual_seed(123)
149
+
150
+ start = time.time()
151
+
152
+ output_token_ids = generate(
153
+ model=model,
154
+ idx=torch.tensor(input_token_ids, device=device).unsqueeze(0),
155
+ max_new_tokens=150,
156
+ context_size=QWEN_CONFIG_06_B["context_length"],
157
+ top_k=1,
158
+ temperature=0.
159
+ )
160
+
161
+ total_time = time.time() - start
162
+ print(f"Time: {total_time:.2f} sec")
163
+ print(f"{int(len(output_token_ids[0])/total_time)} tokens/sec")
164
+
165
+ if torch.cuda.is_available():
166
+ max_mem_bytes = torch.cuda.max_memory_allocated()
167
+ max_mem_gb = max_mem_bytes / (1024 ** 3)
168
+ print(f"Max memory allocated: {max_mem_gb:.2f} GB")
169
+
170
+ output_text = tokenizer.decode(output_token_ids.squeeze(0).tolist())
171
+
172
+ print("\n\nOutput text:\n\n", output_text + "...")
173
+ ```
174
+
175
+ When using the Qwen3 0.6B reasoning model, the output should look similar to the one shown below (this was run on an A100):
176
+
177
+ ```
178
+ Time: 6.35 sec
179
+ 25 tokens/sec
180
+ Max memory allocated: 1.49 GB
181
+
182
+
183
+ Output text:
184
+
185
+ <|im_start|>user
186
+ Give me a short introduction to large language models.<|im_end|>
187
+ Large language models (LLMs) are advanced artificial intelligence systems designed to generate human-like text. They are trained on vast amounts of text data, allowing them to understand and generate coherent, contextually relevant responses. LLMs are used in a variety of applications, including chatbots, virtual assistants, content generation, and more. They are powered by deep learning algorithms and can be fine-tuned for specific tasks, making them versatile tools for a wide range of industries.<|endoftext|>Human resources department of a company is planning to hire 100 new employees. The company has a budget of $100,000 for the recruitment process. The company has a minimum wage of $10 per hour. The company has a total of...
188
+ ```
189
+
190
+ &nbsp;
191
+
192
+ #### Pro tip: speed up inference with compilation
193
+
194
+
195
+ For up to a 4× speed-up, replace
196
+
197
+ ```python
198
+ model.to(device)
199
+ ```
200
+
201
+ with
202
+
203
+ ```python
204
+ model = torch.compile(model)
205
+ model.to(device)
206
+ ```
207
+
208
+ Note: There is a significant multi-minute upfront cost when compiling, and the speed-up takes effect after the first `generate` call.
209
+
210
+ The following table shows a performance comparison on an A100 for consequent `generate` calls:
211
+
212
+ | | Tokens/sec | Memory |
213
+ | ------------------- | ---------- | ------- |
214
+ | Qwen3Model | 25 | 1.49 GB |
215
+ | Qwen3Model compiled | 101 | 1.99 GB |