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 d6213a398a
commit 71ef67be46
13 changed files with 2972 additions and 271 deletions

View File

@ -35,7 +35,7 @@ jobs:
shell: bash
run: |
export PATH="$HOME/.local/bin:$PATH"
pip install --upgrade pip
python -m pip install --upgrade pip
pip install uv
uv venv --python=python3.11
source .venv/Scripts/activate

View File

@ -24,12 +24,12 @@ jobs:
run: |
curl -LsSf https://astral.sh/uv/install.sh | sh
uv sync --dev
uv add pytest-ruff pytest-check-links
uv add pytest-check-links
- name: Check links
run: |
source .venv/bin/activate
pytest --ruff --check-links ./ \
pytest --check-links ./ \
--check-links-ignore "https://platform.openai.com/*" \
--check-links-ignore "https://openai.com/*" \
--check-links-ignore "https://arena.lmsys.org" \

View File

@ -158,7 +158,7 @@ Several folders contain optional materials as a bonus for interested readers:
- [Building a User Interface to Interact With the Pretrained LLM](ch05/06_user_interface)
- [Converting GPT to Llama](ch05/07_gpt_to_llama)
- [Llama 3.2 From Scratch](ch05/07_gpt_to_llama/standalone-llama32.ipynb)
- [Qwen3 From Scratch](ch05/11_qwen3/standalone-qwen3.ipynb)
- [Qwen3 Dense and Mixture-of-Experts (MoE) From Scratch](ch05/11_qwen3/)
- [Memory-efficient Model Weight Loading](ch05/08_memory_efficient_weight_loading/memory-efficient-state-dict.ipynb)
- [Extending the Tiktoken BPE Tokenizer with New Tokens](ch05/09_extending-tokenizers/extend-tiktoken.ipynb)
- [PyTorch Performance Tips for Faster LLM Training](ch05/10_llm-training-speed)

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

View File

@ -160,10 +160,16 @@ from llms_from_scratch.qwen3 import (
# KV cache drop-in replacements
from llms_from_scratch.kv_cache.qwen3 import Qwen3Model
from llms_from_scratch.kv_cache.generate import generate_text_simple
from llms_from_scratch.kv_cache.generate import (
generate_text_simple,
generate_text_simple_stream
)
# KV cache drop-in replacements with batched inference support
from llms_from_scratch.kv_cache_batched.generate import generate_text_simple
from llms_from_scratch.kv_cache_batched.generate import (
generate_text_simple,
generate_text_simple_stream
)
from llms_from_scratch.kv_cache_batched.qwen3 import Qwen3Model
```

View File

@ -28,3 +28,27 @@ def generate_text_simple(model, idx, max_new_tokens, context_size=None, use_cach
idx = torch.cat([idx, next_idx], dim=1)
return idx
def generate_text_simple_stream(model, token_ids, max_new_tokens, eos_token_id=None, context_size=None):
model.eval()
with torch.no_grad():
cache = KVCache(n_layers=model.cfg["n_layers"])
model.reset_kv_cache()
# Prime the cache with the initial context
logits = model(token_ids, cache=cache)
for _ in range(max_new_tokens):
next_token = torch.argmax(logits[:, -1], dim=-1, keepdim=True)
if eos_token_id is not None and torch.all(next_token == eos_token_id):
break
yield next_token
token_ids = torch.cat([token_ids, next_token], dim=1)
# Feed only the new token to the model; cache handles history
logits = model(next_token, cache=cache)

View File

@ -29,7 +29,7 @@ class Qwen3Model(nn.Module):
self.final_norm = RMSNorm(cfg["emb_dim"])
self.out_head = nn.Linear(cfg["emb_dim"], cfg["vocab_size"], bias=False, dtype=cfg["dtype"])
# Reusuable utilities
# Reusable utilities
if cfg["head_dim"] is None:
head_dim = cfg["emb_dim"] // cfg["n_heads"]
else:
@ -94,7 +94,10 @@ class TransformerBlock(nn.Module):
qk_norm=cfg["qk_norm"],
dtype=cfg["dtype"]
)
self.ff = FeedForward(cfg)
if "num_experts" in cfg and cfg["num_experts"] > 0:
self.ff = MoEFeedForward(cfg)
else:
self.ff = FeedForward(cfg)
self.norm1 = RMSNorm(cfg["emb_dim"], eps=1e-6)
self.norm2 = RMSNorm(cfg["emb_dim"], eps=1e-6)
@ -128,6 +131,46 @@ class FeedForward(nn.Module):
return self.fc3(x)
class MoEFeedForward(nn.Module):
def __init__(self, cfg):
super().__init__()
self.num_experts_per_tok = cfg["num_experts_per_tok"]
self.num_experts = cfg["num_experts"]
self.gate = nn.Linear(cfg["emb_dim"], cfg["num_experts"], bias=False, dtype=cfg["dtype"])
meta_device = torch.device("meta") # to reduce memory pressure and only load them when used (trades compute for memory)
self.fc1 = nn.ModuleList([nn.Linear(cfg["emb_dim"], cfg["moe_intermediate_size"], bias=False, dtype=cfg["dtype"], device=meta_device)
for _ in range(cfg["num_experts"])])
self.fc2 = nn.ModuleList([nn.Linear(cfg["emb_dim"], cfg["moe_intermediate_size"], bias=False, dtype=cfg["dtype"], device=meta_device)
for _ in range(cfg["num_experts"])])
self.fc3 = nn.ModuleList([nn.Linear(cfg["moe_intermediate_size"], cfg["emb_dim"], bias=False, dtype=cfg["dtype"], device=meta_device)
for _ in range(cfg["num_experts"])])
def forward(self, x):
scores = self.gate(x) # (b, seq_len, num_experts)
topk_scores, topk_indices = torch.topk(scores, self.num_experts_per_tok, dim=-1)
topk_probs = torch.softmax(topk_scores, dim=-1)
expert_outputs = []
for e in range(self.num_experts):
hidden = torch.nn.functional.silu(self.fc1[e](x)) * self.fc2[e](x)
out = self.fc3[e](hidden)
expert_outputs.append(out.unsqueeze(-2))
expert_outputs = torch.cat(expert_outputs, dim=-2) # (b, t, num_experts, emb_dim)
gating_probs = torch.zeros_like(scores)
for i in range(self.num_experts_per_tok):
indices = topk_indices[..., i:i+1]
prob = topk_probs[..., i:i+1]
gating_probs.scatter_(dim=-1, index=indices, src=prob)
gating_probs = gating_probs.unsqueeze(-1) # (b, t, num_experts, 1)
# Weighted sum over experts
y = (gating_probs * expert_outputs).sum(dim=-2)
return y
class GroupedQueryAttention(nn.Module):
def __init__(
self, d_in, num_heads, num_kv_groups, head_dim=None, qk_norm=False, dtype=None

View File

@ -102,6 +102,23 @@ QWEN3_CONFIG_32B = {
"dtype": torch.bfloat16,
}
# Mixture of Experts Model
QWEN3_CONFIG_30B_A3B = {
"vocab_size": 151_936,
"context_length": 262_144,
"emb_dim": 2048,
"n_heads": 32,
"n_layers": 48,
"head_dim": 128,
"qk_norm": True,
"n_kv_groups": 4,
"rope_base": 10_000_000.0,
"dtype": torch.bfloat16,
"num_experts": 128,
"num_experts_per_tok": 8,
"moe_intermediate_size": 768,
}
class Qwen3Model(nn.Module):
def __init__(self, cfg):
@ -156,7 +173,10 @@ class TransformerBlock(nn.Module):
qk_norm=cfg["qk_norm"],
dtype=cfg["dtype"]
)
self.ff = FeedForward(cfg)
if "num_experts" in cfg and cfg["num_experts"] > 0:
self.ff = MoEFeedForward(cfg)
else:
self.ff = FeedForward(cfg)
self.norm1 = RMSNorm(cfg["emb_dim"], eps=1e-6)
self.norm2 = RMSNorm(cfg["emb_dim"], eps=1e-6)
@ -190,6 +210,46 @@ class FeedForward(nn.Module):
return self.fc3(x)
class MoEFeedForward(nn.Module):
def __init__(self, cfg):
super().__init__()
self.num_experts_per_tok = cfg["num_experts_per_tok"]
self.num_experts = cfg["num_experts"]
self.gate = nn.Linear(cfg["emb_dim"], cfg["num_experts"], bias=False, dtype=cfg["dtype"])
meta_device = torch.device("meta") # to reduce memory pressure and only load them when used (trades compute for memory)
self.fc1 = nn.ModuleList([nn.Linear(cfg["emb_dim"], cfg["moe_intermediate_size"], bias=False, dtype=cfg["dtype"], device=meta_device)
for _ in range(cfg["num_experts"])])
self.fc2 = nn.ModuleList([nn.Linear(cfg["emb_dim"], cfg["moe_intermediate_size"], bias=False, dtype=cfg["dtype"], device=meta_device)
for _ in range(cfg["num_experts"])])
self.fc3 = nn.ModuleList([nn.Linear(cfg["moe_intermediate_size"], cfg["emb_dim"], bias=False, dtype=cfg["dtype"], device=meta_device)
for _ in range(cfg["num_experts"])])
def forward(self, x):
scores = self.gate(x) # (b, seq_len, num_experts)
topk_scores, topk_indices = torch.topk(scores, self.num_experts_per_tok, dim=-1)
topk_probs = torch.softmax(topk_scores, dim=-1)
expert_outputs = []
for e in range(self.num_experts):
hidden = torch.nn.functional.silu(self.fc1[e](x)) * self.fc2[e](x)
out = self.fc3[e](hidden)
expert_outputs.append(out.unsqueeze(-2))
expert_outputs = torch.cat(expert_outputs, dim=-2) # (b, t, num_experts, emb_dim)
gating_probs = torch.zeros_like(scores)
for i in range(self.num_experts_per_tok):
indices = topk_indices[..., i:i+1]
prob = topk_probs[..., i:i+1]
gating_probs.scatter_(dim=-1, index=indices, src=prob)
gating_probs = gating_probs.unsqueeze(-1) # (b, t, num_experts, 1)
# Weighted sum over experts
y = (gating_probs * expert_outputs).sum(dim=-2)
return y
class GroupedQueryAttention(nn.Module):
def __init__(
self, d_in, num_heads, num_kv_groups, head_dim=None, qk_norm=False, dtype=None
@ -381,21 +441,53 @@ def load_weights_into_qwen(model, param_config, params):
)
# Feedforward weights
block.ff.fc1.weight = assign(
block.ff.fc1.weight,
params[f"model.layers.{l}.mlp.gate_proj.weight"],
f"model.layers.{l}.mlp.gate_proj.weight"
)
block.ff.fc2.weight = assign(
block.ff.fc2.weight,
params[f"model.layers.{l}.mlp.up_proj.weight"],
f"model.layers.{l}.mlp.up_proj.weight"
)
block.ff.fc3.weight = assign(
block.ff.fc3.weight,
params[f"model.layers.{l}.mlp.down_proj.weight"],
f"model.layers.{l}.mlp.down_proj.weight"
)
if "num_experts" in param_config:
# Load router (gating) weights
block.ff.gate.weight = assign(
block.ff.gate.weight,
params[f"model.layers.{l}.mlp.gate.weight"],
f"model.layers.{l}.mlp.gate.weight"
)
# Load expert weights
for e in range(param_config["num_experts"]):
prefix = f"model.layers.{l}.mlp.experts.{e}"
block.ff.fc1[e].weight = assign(
block.ff.fc1[e].weight,
params[f"{prefix}.gate_proj.weight"],
f"{prefix}.gate_proj.weight"
)
block.ff.fc2[e].weight = assign(
block.ff.fc2[e].weight,
params[f"{prefix}.up_proj.weight"],
f"{prefix}.up_proj.weight"
)
block.ff.fc3[e].weight = assign(
block.ff.fc3[e].weight,
params[f"{prefix}.down_proj.weight"],
f"{prefix}.down_proj.weight"
)
# After assigning weights, move the expert layers from meta to CPU
block.ff.fc1[e] = block.ff.fc1[e].to("cpu")
block.ff.fc2[e] = block.ff.fc2[e].to("cpu")
block.ff.fc3[e] = block.ff.fc3[e].to("cpu")
else:
block.ff.fc1.weight = assign(
block.ff.fc1.weight,
params[f"model.layers.{l}.mlp.gate_proj.weight"],
f"model.layers.{l}.mlp.gate_proj.weight"
)
block.ff.fc2.weight = assign(
block.ff.fc2.weight,
params[f"model.layers.{l}.mlp.up_proj.weight"],
f"model.layers.{l}.mlp.up_proj.weight"
)
block.ff.fc3.weight = assign(
block.ff.fc3.weight,
params[f"model.layers.{l}.mlp.down_proj.weight"],
f"model.layers.{l}.mlp.down_proj.weight"
)
block.norm2.scale = assign(
block.norm2.scale,
params[f"model.layers.{l}.post_attention_layernorm.weight"],
@ -405,8 +497,12 @@ def load_weights_into_qwen(model, param_config, params):
# Final normalization and output head
model.final_norm.scale = assign(model.final_norm.scale, params["model.norm.weight"], "model.norm.weight")
# Model uses weight tying, hence we reuse the embedding layer weights here
model.out_head.weight = assign(model.out_head.weight, params["model.embed_tokens.weight"], "model.embed_tokens.weight")
if "lm_head.weight" in params:
model.out_head.weight = assign(model.out_head.weight, params["lm_head.weight"], "lm_head.weight")
else:
# Model uses weight tying, hence we reuse the embedding layer weights here
print("Model uses weight tying.")
model.out_head.weight = assign(model.out_head.weight, params["model.embed_tokens.weight"], "model.embed_tokens.weight")
class Qwen3Tokenizer:

View File

@ -13,12 +13,14 @@ from llms_from_scratch.qwen3 import (
Qwen3Tokenizer
)
from llms_from_scratch.kv_cache.qwen3 import Qwen3Model as Qwen3ModelKV
from llms_from_scratch.kv_cache.utils import KVCache
from llms_from_scratch.kv_cache.generate import generate_text_simple as generate_text_simple_cached
from llms_from_scratch.kv_cache_batched.qwen3 import Qwen3Model as Qwen3ModelKVBatched
from llms_from_scratch.kv_cache_batched.generate import generate_text_simple as generate_text_simple_batched
import importlib
import platform
import pytest
import torch
import torch.nn as nn
@ -50,6 +52,92 @@ class Qwen3RMSNorm(nn.Module):
transformers_installed = importlib.util.find_spec("transformers") is not None
@pytest.fixture
def dummy_input():
torch.manual_seed(123)
return torch.randint(0, 100, (1, 8)) # batch size 1, seq length 8
@pytest.fixture
def dummy_cfg_base():
return {
"vocab_size": 100,
"emb_dim": 32,
"hidden_dim": 64,
"n_layers": 2,
"n_heads": 4,
"head_dim": 8,
"n_kv_groups": 1,
"qk_norm": False,
"dtype": torch.float32,
"rope_base": 10000,
"context_length": 64,
"num_experts": 0,
}
@pytest.fixture
def dummy_cfg_moe(dummy_cfg_base):
cfg = dummy_cfg_base.copy()
cfg.update({
"num_experts": 4,
"num_experts_per_tok": 2,
"moe_intermediate_size": 64,
})
return cfg
def test_dummy_qwen3_forward(dummy_cfg_base, dummy_input):
torch.manual_seed(123)
model = Qwen3Model(dummy_cfg_base)
out = model(dummy_input)
assert out.shape == (1, dummy_input.size(1), dummy_cfg_base["vocab_size"]), \
f"Expected shape (1, seq_len, vocab_size), got {out.shape}"
def test_dummy_qwen3_moe_forward(dummy_cfg_moe, dummy_input):
torch.manual_seed(123)
model = Qwen3Model(dummy_cfg_moe)
out = model(dummy_input)
assert out.shape == (1, dummy_input.size(1), dummy_cfg_moe["vocab_size"]), \
f"Expected shape (1, seq_len, vocab_size), got {out.shape}"
assert any(hasattr(block.ff, 'gate') for block in model.trf_blocks), \
"Expected MoEFeedForward in at least one transformer block"
@pytest.mark.parametrize("cfg_name", ["dummy_cfg_base", "dummy_cfg_moe"])
def test_qwen3_kvcache_equivalence(cfg_name, request):
cfg = request.getfixturevalue(cfg_name)
if cfg["num_experts"] > 0 and platform.system() == "Linux":
pytest.skip("Skipping MoE KV equivalence test on Linux due to nondeterministic expert routing")
torch.manual_seed(123)
model_regular = Qwen3Model(cfg)
model_regular.eval()
model_kv = Qwen3ModelKV(cfg)
model_kv.eval()
model_kv.load_state_dict(model_regular.state_dict())
model_kv.reset_kv_cache()
cache = KVCache(n_layers=cfg["n_layers"])
torch.manual_seed(123)
input_ids = torch.randint(0, cfg["vocab_size"], (1, 6))
out_full = model_regular(input_ids)
logits_stepwise = []
for t in range(input_ids.size(1)):
input_token = input_ids[:, t:t + 1]
logits = model_kv(input_token, cache=cache)
logits_stepwise.append(logits)
out_kv = torch.cat(logits_stepwise, dim=1)
assert out_full.shape == out_kv.shape, f"Shape mismatch: {out_full.shape} vs {out_kv.shape}"
assert torch.allclose(out_full, out_kv, atol=1e-5, rtol=1e-3)
@pytest.mark.skipif(not transformers_installed, reason="transformers not installed")
def test_rope():