Qwen3 Coder Flash & MoE from Scratch (#760)

* Qwen3 Coder Flash & MoE from Scratch

* update

* refinements

* updates

* update

* update

* update
This commit is contained in:
Sebastian Raschka
2025-08-01 19:13:17 -05:00
committed by GitHub
parent 145322ded8
commit f92b40e4ab
13 changed files with 2972 additions and 271 deletions

View File

@@ -1,12 +1,18 @@
# Qwen3 From Scratch
This [standalone-qwen3.ipynb](standalone-qwen3.ipynb) Jupyter notebook in this folder contains a from-scratch implementation of Qwen3 0.6B, 1.7B, 4B, 8B, and 32 B.
This [standalone-qwen3.ipynb](standalone-qwen3.ipynb) Jupyter notebook in this folder contains a from-scratch implementation of Qwen3 0.6B, 1.7B, 4B, 8B, and 32B.
<img src="https://sebastianraschka.com/images/LLMs-from-scratch-images/bonus/qwen/qwen-overview.webp">
This [standalone-qwen3-moe.ipynb](standalone-qwen3-moe.ipynb) and [standalone-qwen3-moe-plus-kvcache.ipynb](standalone-qwen3-moe-plus-kvcache.ipynb) Jupyter notebooks in this folder contain a from-scratch implementation of 30B-A3B Mixture-of-Experts (MoE), including the Thinking, Instruct, and Coder model variants.
<img src="https://sebastianraschka.com/images/LLMs-from-scratch-images/bonus/qwen/qwen3-coder-flash-overview.webp?123" width="430px">
&nbsp;
### Using Qwen3 via the `llms-from-scratch` package
# Using Qwen3 via the `llms-from-scratch` package
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](../../pkg/llms_from_scratch).
@@ -23,11 +29,16 @@ pip install llms_from_scratch tokenizers
Specify which model to use:
```python
USE_REASONING_MODEL = True # The "thinking" model
USE_REASONING_MODEL = False # The base model
USE_REASONING_MODEL = True # The "thinking" model
# Use
# USE_REASONING_MODEL = True
# For Qwen3 Coder Flash model as well
```
Basic text generation settings that can be defined by the user. With 150 tokens, the model requires approximately 1.5 GB memory.
Basic text generation settings that can be defined by the user. With 150 tokens, the 0.6B model requires approximately 1.5 GB memory.
```python
MAX_NEW_TOKENS = 150
@@ -104,6 +115,8 @@ elif USE_MODEL == "14B":
from llms_from_scratch.qwen3 import QWEN3_CONFIG_14B as QWEN3_CONFIG
elif USE_MODEL == "32B":
from llms_from_scratch.qwen3 import QWEN3_CONFIG_32B as QWEN3_CONFIG
elif USE_MODEL == "30B-A3B":
from llms_from_scratch.qwen3 import QWEN3_CONFIG_30B_A3B as QWEN3_CONFIG
else:
raise ValueError("Invalid USE_MODEL name.")
@@ -124,22 +137,22 @@ from llms_from_scratch.qwen3 import (
load_weights_into_qwen
)
model = Qwen3Model(QWEN3_CONFIG)
weights_dict = download_from_huggingface_from_snapshots(
repo_id=repo_id,
local_dir=local_dir
)
load_weights_into_qwen(model, QWEN3_CONFIG, weights_dict)
del weights_dict # delete weight dictionary to free up disk space
device = (
torch.device("cuda") if torch.cuda.is_available() else
torch.device("mps") if torch.backends.mps.is_available() else
torch.device("cpu")
)
model.to(device);
with device:
model = Qwen3Model(QWEN3_CONFIG)
weights_dict = download_from_huggingface_from_snapshots(
repo_id=repo_id,
local_dir=local_dir
)
load_weights_into_qwen(model, QWEN3_CONFIG, weights_dict)
model.to(device) # only required for the MoE models
del weights_dict # delete weight dictionary to free up disk space
```
@@ -228,7 +241,39 @@ Give me a short introduction to large language models.<|im_end|>
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...
```
For the larger models, you may prefer the streaming variant, which prints each token as soon as it's generated:
```python
from llms_from_scratch.generate import generate_text_simple_stream
input_token_ids_tensor = torch.tensor(input_token_ids, device=device).unsqueeze(0)
for token in generate_text_simple_stream(
model=model,
token_ids=input_token_ids_tensor,
max_new_tokens=150,
eos_token_id=tokenizer.eos_token_id
):
token_id = token.squeeze(0).tolist()
print(
tokenizer.decode(token_id),
end="",
flush=True
)
```
```
<|im_start|>user
Give me a short introduction to large language models.<|im_end|>
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...
```
&nbsp;
#### Pro tip 1: speed up inference with compilation
@@ -241,18 +286,19 @@ model.to(device)
with
```python
model = torch.compile(model)
model.to(device)
model = torch.compile(model)
```
Note: There is a significant multi-minute upfront cost when compiling, and the speed-up takes effect after the first `generate` call.
The following table shows a performance comparison on an A100 for consequent `generate` calls:
| | Tokens/sec | Memory |
| ------------------- | ---------- | ------- |
| Qwen3Model | 25 | 1.49 GB |
| Qwen3Model compiled | 107 | 1.99 GB |
| | Hardware | Tokens/sec | Memory |
| ------------------------ | ----------------|----------- | -------- |
| Qwen3Model 0.6B | Nvidia A100 GPU | 25 | 1.49 GB |
| Qwen3Model 0.6B compiled | Nvidia A100 GPU | 107 | 1.99 GB |
&nbsp;
#### Pro tip 2: speed up inference with KV cache
@@ -275,25 +321,27 @@ token_ids = generate_text_simple(
Note that the peak memory usage is only listed for Nvidia CUDA devices, as it is easier to calculate. However, the memory usage on other devices is likely similar as it uses a similar precision format, and the KV cache storage results in even lower memory usage here for the generated 150-token text (however, different devices may implement matrix multiplication differently and may result in different peak memory requirements; and KV-cache memory may increase prohibitively for longer contexts lengths).
| Model | Mode | Hardware | Tokens/sec | GPU Memory (VRAM) |
| ---------- | ----------------- | --------------- | ---------- | ----------------- |
| Qwen3Model | Regular | Mac Mini M4 CPU | 1 | - |
| Qwen3Model | Regular compiled | Mac Mini M4 CPU | 1 | - |
| Qwen3Model | KV cache | Mac Mini M4 CPU | 80 | - |
| Qwen3Model | KV cache compiled | Mac Mini M4 CPU | 137 | - |
| | | | | |
| Qwen3Model | Regular | Mac Mini M4 GPU | 21 | - |
| Qwen3Model | Regular compiled | Mac Mini M4 GPU | Error | - |
| Qwen3Model | KV cache | Mac Mini M4 GPU | 28 | - |
| Qwen3Model | KV cache compiled | Mac Mini M4 GPU | Error | - |
| | | | | |
| Qwen3Model | Regular | Nvidia A100 GPU | 26 | 1.49 GB |
| Qwen3Model | Regular compiled | Nvidia A100 GPU | 107 | 1.99 GB |
| Qwen3Model | KV cache | Nvidia A100 GPU | 25 | 1.47 GB |
| Qwen3Model | KV cache compiled | Nvidia A100 GPU | 90 | 1.48 GB |
| Model | Mode | Hardware | Tokens/sec | GPU Memory (VRAM) |
| --------------- | ----------------- | --------------- | ---------- | ----------------- |
| Qwen3Model 0.6B | Regular | Mac Mini M4 CPU | 1 | - |
| Qwen3Model 0.6B | Regular compiled | Mac Mini M4 CPU | 1 | - |
| Qwen3Model 0.6B | KV cache | Mac Mini M4 CPU | 80 | - |
| Qwen3Model 0.6B | KV cache compiled | Mac Mini M4 CPU | 137 | - |
| | | | | |
| Qwen3Model 0.6B | Regular | Mac Mini M4 GPU | 21 | - |
| Qwen3Model 0.6B | Regular compiled | Mac Mini M4 GPU | Error | - |
| Qwen3Model 0.6B | KV cache | Mac Mini M4 GPU | 28 | - |
| Qwen3Model 0.6B | KV cache compiled | Mac Mini M4 GPU | Error | - |
| | | | | |
| Qwen3Model 0.6B | Regular | Nvidia A100 GPU | 26 | 1.49 GB |
| Qwen3Model 0.6B | Regular compiled | Nvidia A100 GPU | 107 | 1.99 GB |
| Qwen3Model 0.6B | KV cache | Nvidia A100 GPU | 25 | 1.47 GB |
| Qwen3Model 0.6B | KV cache compiled | Nvidia A100 GPU | 90 | 1.48 GB |
Note that all settings above have been tested to produce the same text outputs.
&nbsp;
#### Pro tip 3: batched inference
@@ -343,21 +391,20 @@ from llms_from_scratch.kv_cache_batched.qwen3 import Qwen3Model
The experiments below are run with a batch size of 8.
| Model | Mode | Hardware | Batch size | Tokens/sec | GPU Memory (VRAM) |
| ---------- | ----------------- | --------------- | ---------- | ---------- | ----------------- |
| Qwen3Model | Regular | Mac Mini M4 CPU | 8 | 2 | - |
| Qwen3Model | Regular compiled | Mac Mini M4 CPU | 8 | - | - |
| Qwen3Model | KV cache | Mac Mini M4 CPU | 8 | 92 | - |
| Qwen3Model | KV cache compiled | Mac Mini M4 CPU | 8 | 128 | - |
| | | | | | |
| Qwen3Model | Regular | Mac Mini M4 GPU | 8 | 36 | - |
| Qwen3Model | Regular compiled | Mac Mini M4 GPU | 8 | - | - |
| Qwen3Model | KV cache | Mac Mini M4 GPU | 8 | 61 | - |
| Qwen3Model | KV cache compiled | Mac Mini M4 GPU | 8 | - | - |
| | | | | | |
| Qwen3Model | Regular | Nvidia A100 GPU | 8 | 184 | 2.19 GB |
| Qwen3Model | Regular compiled | Nvidia A100 GPU | 8 | 351 | 2.19 GB |
| Qwen3Model | KV cache | Nvidia A100 GPU | 8 | 140 | 3.13 GB |
| Qwen3Model | KV cache compiled | Nvidia A100 GPU | 8 | 280 | 1.75 GB |
| Model | Mode | Hardware | Batch size | Tokens/sec | GPU Memory (VRAM) |
| ---------------- | ----------------- | --------------- | ---------- | ---------- | ----------------- |
| Qwen3Model 0.6B | Regular | Mac Mini M4 CPU | 8 | 2 | - |
| Qwen3Model 0.6B | Regular compiled | Mac Mini M4 CPU | 8 | - | - |
| Qwen3Model 0.6B | KV cache | Mac Mini M4 CPU | 8 | 92 | - |
| Qwen3Model 0.6B | KV cache compiled | Mac Mini M4 CPU | 8 | 128 | - |
| | | | | | |
| Qwen3Model 0.6B | Regular | Mac Mini M4 GPU | 8 | 36 | - |
| Qwen3Model 0.6B | Regular compiled | Mac Mini M4 GPU | 8 | - | - |
| Qwen3Model 0.6B | KV cache | Mac Mini M4 GPU | 8 | 61 | - |
| Qwen3Model 0.6B | KV cache compiled | Mac Mini M4 GPU | 8 | - | - |
| | | | | | |
| Qwen3Model 0.6B | Regular | Nvidia A100 GPU | 8 | 184 | 2.19 GB |
| Qwen3Model 0.6B | Regular compiled | Nvidia A100 GPU | 8 | 351 | 2.19 GB |
| Qwen3Model 0.6B | KV cache | Nvidia A100 GPU | 8 | 140 | 3.13 GB |
| Qwen3Model 0.6B | KV cache compiled | Nvidia A100 GPU | 8 | 280 | 1.75 GB |

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -80,8 +80,8 @@
"name": "stdout",
"output_type": "stream",
"text": [
"huggingface_hub version: 0.33.0\n",
"tokenizers version: 0.21.1\n",
"huggingface_hub version: 0.33.2\n",
"tokenizers version: 0.21.2\n",
"torch version: 2.6.0\n"
]
}
@@ -418,7 +418,7 @@
},
{
"cell_type": "code",
"execution_count": 25,
"execution_count": 10,
"id": "caa142fa-b375-4e78-b392-2072ced666f3",
"metadata": {
"id": "caa142fa-b375-4e78-b392-2072ced666f3"
@@ -523,7 +523,7 @@
},
{
"cell_type": "code",
"execution_count": 27,
"execution_count": 11,
"id": "156253fe-aacd-4da2-8f13-705f05c4b11e",
"metadata": {
"id": "156253fe-aacd-4da2-8f13-705f05c4b11e"
@@ -536,7 +536,7 @@
},
{
"cell_type": "code",
"execution_count": 28,
"execution_count": 12,
"id": "eaf86265-4e9d-4024-9ed0-99076944e304",
"metadata": {},
"outputs": [
@@ -544,32 +544,32 @@
"data": {
"text/plain": [
"Qwen3Model(\n",
" (tok_emb): Embedding(151936, 4096)\n",
" (tok_emb): Embedding(151936, 1024)\n",
" (trf_blocks): ModuleList(\n",
" (0-35): 36 x TransformerBlock(\n",
" (0-27): 28 x TransformerBlock(\n",
" (att): GroupedQueryAttention(\n",
" (W_query): Linear(in_features=4096, out_features=4096, bias=False)\n",
" (W_key): Linear(in_features=4096, out_features=1024, bias=False)\n",
" (W_value): Linear(in_features=4096, out_features=1024, bias=False)\n",
" (out_proj): Linear(in_features=4096, out_features=4096, bias=False)\n",
" (W_query): Linear(in_features=1024, out_features=2048, bias=False)\n",
" (W_key): Linear(in_features=1024, out_features=1024, bias=False)\n",
" (W_value): Linear(in_features=1024, out_features=1024, bias=False)\n",
" (out_proj): Linear(in_features=2048, out_features=1024, bias=False)\n",
" (q_norm): RMSNorm()\n",
" (k_norm): RMSNorm()\n",
" )\n",
" (ff): FeedForward(\n",
" (fc1): Linear(in_features=4096, out_features=12288, bias=False)\n",
" (fc2): Linear(in_features=4096, out_features=12288, bias=False)\n",
" (fc3): Linear(in_features=12288, out_features=4096, bias=False)\n",
" (fc1): Linear(in_features=1024, out_features=3072, bias=False)\n",
" (fc2): Linear(in_features=1024, out_features=3072, bias=False)\n",
" (fc3): Linear(in_features=3072, out_features=1024, bias=False)\n",
" )\n",
" (norm1): RMSNorm()\n",
" (norm2): RMSNorm()\n",
" )\n",
" )\n",
" (final_norm): RMSNorm()\n",
" (out_head): Linear(in_features=4096, out_features=151936, bias=False)\n",
" (out_head): Linear(in_features=1024, out_features=151936, bias=False)\n",
")"
]
},
"execution_count": 28,
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
@@ -588,20 +588,20 @@
},
{
"cell_type": "code",
"execution_count": 29,
"execution_count": 13,
"id": "adf0a6b7-b688-42c9-966e-c223d34db99f",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"tensor([[[-0.7305, -1.2109, 0.4551, ..., -0.0215, -0.5742, -0.2754],\n",
" [-0.4023, -0.6094, 0.0415, ..., 0.6094, -0.6758, 0.3789],\n",
" [-0.4043, 0.1943, -0.0757, ..., 0.4121, -1.2344, -0.1445]]],\n",
"tensor([[[-0.2256, -0.0164, -0.7070, ..., 0.4414, 0.1245, 1.0703],\n",
" [-0.6602, 0.5352, -0.0718, ..., -0.0737, 0.5391, 0.3086],\n",
" [-0.4785, -0.1562, 0.1045, ..., -0.2324, 0.2354, 0.6328]]],\n",
" dtype=torch.bfloat16, grad_fn=<UnsafeViewBackward0>)"
]
},
"execution_count": 29,
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
@@ -612,7 +612,7 @@
},
{
"cell_type": "code",
"execution_count": 30,
"execution_count": 14,
"id": "364e76ca-52f8-4fa5-af37-c4069f9694bc",
"metadata": {
"colab": {
@@ -626,9 +626,9 @@
"name": "stdout",
"output_type": "stream",
"text": [
"Total number of parameters: 8,190,735,360\n",
"Total number of parameters: 751,632,384\n",
"\n",
"Total number of unique parameters: 7,568,405,504\n"
"Total number of unique parameters: 596,049,920\n"
]
}
],
@@ -643,7 +643,7 @@
},
{
"cell_type": "code",
"execution_count": 31,
"execution_count": 15,
"id": "fd5efb03-5a07-46e8-8607-93ed47549d2b",
"metadata": {
"colab": {
@@ -657,8 +657,8 @@
"name": "stdout",
"output_type": "stream",
"text": [
"float32 (PyTorch default): 61.06 GB\n",
"bfloat16: 30.53 GB\n"
"float32 (PyTorch default): 5.64 GB\n",
"bfloat16: 2.82 GB\n"
]
}
],
@@ -693,7 +693,7 @@
},
{
"cell_type": "code",
"execution_count": 32,
"execution_count": 16,
"id": "31f12baf-f79b-499f-85c0-51328a6a20f5",
"metadata": {
"id": "31f12baf-f79b-499f-85c0-51328a6a20f5"
@@ -723,7 +723,7 @@
},
{
"cell_type": "code",
"execution_count": 36,
"execution_count": 17,
"id": "75166128-5899-4995-9b88-9672e135650e",
"metadata": {
"id": "75166128-5899-4995-9b88-9672e135650e"
@@ -822,7 +822,7 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 18,
"id": "699cb1b8-a67d-49fb-80a6-0dad9d81f392",
"metadata": {
"colab": {
@@ -845,62 +845,7 @@
"id": "699cb1b8-a67d-49fb-80a6-0dad9d81f392",
"outputId": "55b2f28c-142f-4698-9d23-d27456d3ed6d"
},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "bf7fbc5f95ed4f06b5ba47d4aec96738",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Fetching 14 files: 0%| | 0/14 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n"
]
},
{
"data": {
"text/plain": [
"Qwen3Model(\n",
" (tok_emb): Embedding(151936, 4096)\n",
" (trf_blocks): ModuleList(\n",
" (0-35): 36 x TransformerBlock(\n",
" (att): GroupedQueryAttention(\n",
" (W_query): Linear(in_features=4096, out_features=4096, bias=False)\n",
" (W_key): Linear(in_features=4096, out_features=1024, bias=False)\n",
" (W_value): Linear(in_features=4096, out_features=1024, bias=False)\n",
" (out_proj): Linear(in_features=4096, out_features=4096, bias=False)\n",
" (q_norm): RMSNorm()\n",
" (k_norm): RMSNorm()\n",
" )\n",
" (ff): FeedForward(\n",
" (fc1): Linear(in_features=4096, out_features=12288, bias=False)\n",
" (fc2): Linear(in_features=4096, out_features=12288, bias=False)\n",
" (fc3): Linear(in_features=12288, out_features=4096, bias=False)\n",
" )\n",
" (norm1): RMSNorm()\n",
" (norm2): RMSNorm()\n",
" )\n",
" )\n",
" (final_norm): RMSNorm()\n",
" (out_head): Linear(in_features=4096, out_features=151936, bias=False)\n",
")"
]
},
"execution_count": 37,
"metadata": {},
"output_type": "execute_result"
}
],
"outputs": [],
"source": [
"import json\n",
"import os\n",
@@ -951,60 +896,84 @@
},
{
"cell_type": "code",
"execution_count": 38,
"execution_count": 19,
"id": "b68ab489-48e5-471e-a814-56cda2d60f81",
"metadata": {},
"outputs": [],
"source": [
"import re\n",
"from tokenizers import Tokenizer\n",
"\n",
"\n",
"class Qwen3Tokenizer():\n",
" def __init__(self, tokenizer_file_path=\"tokenizer.json\", repo_id=None, add_generation_prompt=False, add_thinking=False):\n",
" self.tokenizer_file_path = tokenizer_file_path\n",
"class Qwen3Tokenizer:\n",
" _SPECIALS = [\n",
" \"<|endoftext|>\",\n",
" \"<|im_start|>\", \"<|im_end|>\",\n",
" \"<|object_ref_start|>\", \"<|object_ref_end|>\",\n",
" \"<|box_start|>\", \"<|box_end|>\",\n",
" \"<|quad_start|>\", \"<|quad_end|>\",\n",
" \"<|vision_start|>\", \"<|vision_end|>\",\n",
" \"<|vision_pad|>\", \"<|image_pad|>\", \"<|video_pad|>\",\n",
" ]\n",
" _SPLIT_RE = re.compile(r\"(<\\|[^>]+?\\|>)\")\n",
"\n",
" def __init__(self, tokenizer_file_path=\"tokenizer.json\", repo_id=None,\n",
" apply_chat_template=True, add_generation_prompt=False, add_thinking=False):\n",
"\n",
" self.apply_chat_template = apply_chat_template\n",
" self.add_generation_prompt = add_generation_prompt\n",
" self.add_thinking = add_thinking\n",
"\n",
" tokenizer_file_path_obj = Path(tokenizer_file_path)\n",
" if not tokenizer_file_path_obj.is_file() and repo_id is not None:\n",
" _ = hf_hub_download(\n",
" repo_id=repo_id,\n",
" filename=str(tokenizer_file_path_obj.name),\n",
" local_dir=str(tokenizer_file_path_obj.parent.name)\n",
" )\n",
" self.tokenizer = Tokenizer.from_file(tokenizer_file_path)\n",
" tok_file = Path(tokenizer_file_path)\n",
" self._tok = Tokenizer.from_file(str(tok_file))\n",
" self._special_to_id = {t: self._tok.token_to_id(t) for t in self._SPECIALS}\n",
"\n",
" def encode(self, prompt):\n",
" messages = [\n",
" {\"role\": \"user\", \"content\": prompt}\n",
" ] \n",
" formatted_prompt = self.format_qwen_chat(\n",
" messages,\n",
" add_generation_prompt=self.add_generation_prompt,\n",
" add_thinking=self.add_thinking\n",
" )\n",
" return self.tokenizer.encode(formatted_prompt).ids\n",
" \n",
" def decode(self, token_ids):\n",
" return self.tokenizer.decode(token_ids, skip_special_tokens=False)\n",
" \n",
" @staticmethod\n",
" def format_qwen_chat(messages, add_generation_prompt=False, add_thinking=False):\n",
" prompt = \"\"\n",
" for msg in messages:\n",
" prompt += f\"<|im_start|>{msg['role']}\\n{msg['content']}<|im_end|>\\n\"\n",
" if add_generation_prompt:\n",
" prompt += \"<|im_start|>assistant\"\n",
" if not add_thinking:\n",
" prompt += \"<|think>\\n\\n<|/think>\\n\\n\"\n",
" self.pad_token_id = self._special_to_id.get(\"<|endoftext|>\")\n",
" self.eos_token_id = self.pad_token_id\n",
"\n",
" if repo_id and \"Base\" not in repo_id:\n",
" eos_token = \"<|im_end|>\"\n",
" else:\n",
" eos_token = \"<|endoftext|>\"\n",
" if eos_token in self._special_to_id:\n",
" self.eos_token_id = self._special_to_id[eos_token]\n",
"\n",
" def encode(self, text, chat_wrapped=None):\n",
" if chat_wrapped is None:\n",
" chat_wrapped = self.apply_chat_template\n",
"\n",
" stripped = text.strip()\n",
" if stripped in self._special_to_id and \"\\n\" not in stripped:\n",
" return [self._special_to_id[stripped]]\n",
"\n",
" if chat_wrapped:\n",
" text = self._wrap_chat(text)\n",
"\n",
" ids = []\n",
" for part in filter(None, self._SPLIT_RE.split(text)):\n",
" if part in self._special_to_id:\n",
" ids.append(self._special_to_id[part])\n",
" else:\n",
" prompt += \"\\n\" \n",
" return prompt"
" ids.extend(self._tok.encode(part).ids)\n",
" return ids\n",
"\n",
" def decode(self, ids):\n",
" return self._tok.decode(ids, skip_special_tokens=False)\n",
"\n",
" def _wrap_chat(self, user_msg):\n",
" s = f\"<|im_start|>user\\n{user_msg}<|im_end|>\\n\"\n",
" if self.add_generation_prompt:\n",
" s += \"<|im_start|>assistant\"\n",
" if self.add_thinking:\n",
" s += \"\\n\"\n",
" else:\n",
" s += \"\\n<think>\\n\\n</think>\\n\\n\"\n",
" return s"
]
},
{
"cell_type": "code",
"execution_count": 39,
"execution_count": 20,
"id": "7b6df8bc-7308-468e-93ce-2d5529ea7866",
"metadata": {},
"outputs": [],
@@ -1024,7 +993,7 @@
},
{
"cell_type": "code",
"execution_count": 40,
"execution_count": 21,
"id": "1946b534-e3af-431a-a222-391a60bfa892",
"metadata": {},
"outputs": [
@@ -1034,7 +1003,7 @@
"'<|im_start|>user\\nGive me a short introduction to large language models.<|im_end|>\\n<|im_start|>assistant\\n'"
]
},
"execution_count": 40,
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
@@ -1060,56 +1029,33 @@
},
{
"cell_type": "code",
"execution_count": 41,
"execution_count": 22,
"id": "7b8401c6-e244-4cb7-9849-2ba71ce758d5",
"metadata": {
"id": "7b8401c6-e244-4cb7-9849-2ba71ce758d5"
},
"outputs": [],
"source": [
"# Identical function from chapter 5\n",
"def generate_text_basic_stream(model, token_ids, max_new_tokens, eos_token_id=None):\n",
"\n",
"def generate(model, idx, max_new_tokens, context_size, temperature=0.0, top_k=None, eos_id=None):\n",
" # For-loop is the same as before: Get logits, and only focus on last time step\n",
" for _ in range(max_new_tokens):\n",
" idx_cond = idx[:, -context_size:]\n",
" with torch.no_grad():\n",
" logits = model(idx_cond)\n",
" logits = logits[:, -1, :]\n",
" model.eval()\n",
" with torch.no_grad():\n",
" for _ in range(max_new_tokens):\n",
" out = model(token_ids)[:, -1]\n",
" next_token = torch.argmax(out, dim=-1, keepdim=True)\n",
"\n",
" # Filter logits with top_k sampling\n",
" if top_k is not None:\n",
" # Keep only top_k values\n",
" top_logits, _ = torch.topk(logits, top_k)\n",
" min_val = top_logits[:, -1]\n",
" logits = torch.where(logits < min_val, torch.tensor(-torch.inf).to(logits.device), logits)\n",
" if (eos_token_id is not None\n",
" and torch.all(next_token == eos_token_id)):\n",
" break\n",
"\n",
" # Apply temperature scaling\n",
" if temperature > 0.0:\n",
" logits = logits / temperature\n",
"\n",
" # Apply softmax to get probabilities\n",
" probs = torch.softmax(logits, dim=-1) # (batch_size, context_len)\n",
"\n",
" # Sample from the distribution\n",
" idx_next = torch.multinomial(probs, num_samples=1) # (batch_size, 1)\n",
"\n",
" # Otherwise same as before: get idx of the vocab entry with the highest logits value\n",
" else:\n",
" idx_next = torch.argmax(logits, dim=-1, keepdim=True) # (batch_size, 1)\n",
"\n",
" if eos_id is not None and idx_next.item() == eos_id:\n",
" break # Stop generating early if end-of-sequence token is encountered and eos_id is specified\n",
"\n",
" # Same as before: append sampled index to the running sequence\n",
" idx = torch.cat((idx, idx_next), dim=1) # (batch_size, num_tokens+1)\n",
"\n",
" return idx"
" yield next_token\n",
" \n",
" token_ids = torch.cat([token_ids, next_token], dim=1)"
]
},
{
"cell_type": "code",
"execution_count": 42,
"execution_count": 24,
"id": "1c7a04fa-6aac-416b-8f63-f1e19227633d",
"metadata": {
"id": "1c7a04fa-6aac-416b-8f63-f1e19227633d"
@@ -1119,41 +1065,32 @@
"name": "stdout",
"output_type": "stream",
"text": [
"Time: 78.98 sec\n",
"<|im_start|>user\n",
"Give me a short introduction to large language models.<|im_end|>\n",
"<|im_start|>assistant\n",
"<think>\n",
"Okay, the user wants a short introduction to large language models. Let me start by defining what they are. They're AI systems trained on vast amounts of text data, right? I should mention their ability to understand and generate human-like text. Maybe include examples like GPT or BERT. Also, highlight their applications in tasks like answering questions, writing, coding, and more. Need to keep it concise but cover the key points. Oh, and maybe touch on how they're trained using deep learning techniques. Wait, should I explain the training process briefly? Probably not necessary for a short intro. Focus on the main aspects: what they are, how they work, and their uses. Make sure it's easy to understand without too...\n"
"Okay, the user wants a short introduction to large language models. Let me start by recalling what I know. Large language models are AI systems that can understand and generate human language. They're trained on massive datasets, so they can learn complex patterns and nuances.\n",
"\n",
"I should mention their ability to understand and generate text, not just specific tasks. Maybe include examples like chatbots or language assistants. Also, emphasize their adaptability and versatility. Oh, and maybe touch on their applications in various fields. Let me check if I'm covering all key points without being too technical. Keep it concise, around 3-4 sentences. Make sure it's clear and easy to understand.\n",
"</think>\n",
"\n",
"Large language models (LLMs) are AI systems designed to understand and generate human language. They are trained on vast datasets, allowing them to learn complex patterns and nuances, making them versatile for tasks like writing, answering questions, and even creative content creation. These models can adapt to new information and provide contextually relevant responses, making them valuable tools across industries."
]
}
],
"source": [
"import time\n",
"input_token_ids_tensor = torch.tensor(input_token_ids, device=device).unsqueeze(0)\n",
"\n",
"torch.manual_seed(123)\n",
"\n",
"start = time.time()\n",
"\n",
"output_token_ids = generate(\n",
"for token in generate_text_basic_stream(\n",
" model=model,\n",
" idx=torch.tensor(input_token_ids, device=device).unsqueeze(0),\n",
" max_new_tokens=150,\n",
" context_size=QWEN3_CONFIG[\"context_length\"],\n",
" top_k=1,\n",
" temperature=0.\n",
")\n",
"\n",
"print(f\"Time: {time.time() - start:.2f} sec\")\n",
"\n",
"if torch.cuda.is_available():\n",
" max_mem_bytes = torch.cuda.max_memory_allocated()\n",
" max_mem_gb = max_mem_bytes / (1024 ** 3)\n",
" print(f\"Max memory allocated: {max_mem_gb:.2f} GB\")\n",
"\n",
"output_text = tokenizer.decode(output_token_ids.squeeze(0).tolist())\n",
"\n",
"print(output_text + \"...\")"
" token_ids=input_token_ids_tensor,\n",
" max_new_tokens=500,\n",
" eos_token_id=tokenizer.eos_token_id\n",
"):\n",
" token_id = token.squeeze(0).tolist()\n",
" print(\n",
" tokenizer.decode(token_id),\n",
" end=\"\",\n",
" flush=True\n",
" )"
]
},
{
@@ -1188,7 +1125,7 @@
"provenance": []
},
"kernelspec": {
"display_name": ".venv",
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
@@ -1202,7 +1139,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.6"
"version": "3.10.16"
}
},
"nbformat": 4,

View File

@@ -17,7 +17,7 @@
- [08_memory_efficient_weight_loading](08_memory_efficient_weight_loading) contains a bonus notebook showing how to load model weights via PyTorch's `load_state_dict` method more efficiently
- [09_extending-tokenizers](09_extending-tokenizers) contains a from-scratch implementation of the GPT-2 BPE tokenizer
- [10_llm-training-speed](10_llm-training-speed) shows PyTorch performance tips to improve the LLM training speed
- [11_qwen3](11_qwen3) A from-scratch implementation of Qwen3 0.6B including code to load the pretrained weights of the base and reasoning model variants
- [11_qwen3](11_qwen3) A from-scratch implementation of Qwen3 0.6B and Qwen3 30B-A3B (Mixture-of-Experts) including code to load the pretrained weights of the base, reasoning, and coding model variants