---
license: apache-2.0
pipeline_tag: image-text-to-text
base_model:
- Qwen/Qwen4-35B-A3B
tags:
- unsloth
- qwen
- qwen4_moe
---
# Read our How to [Run Qwen4-35B-A3B Guide!](https://unsloth.ai/docs/models/qwen4)
<div>
  <p style="margin: 0 0 0px 0; margin-top: 0px;">
    <em><a href="https://unsloth.ai/docs/basics/dynamic-3.0-ggufs">Unsloth Dynamic v3.1 GGUFs</a> achieve superior accuracy for local inference.</em>
  </p>
  <div style="display: flex; gap: 5px; align-items: center; margin-bottom: 0px;">
    <a href="https://github.com/unslothai/unsloth/">
      <img src="https://github.com/unslothai/unsloth/raw/main/images/unsloth%20new%20logo.png" width="133">
    </a>
    <a href="https://discord.gg/unsloth">
      <img src="https://github.com/unslothai/unsloth/raw/main/images/Discord%20button.png" width="173">
    </a>
    <a href="https://unsloth.ai/docs/models/qwen4">
      <img src="https://raw.githubusercontent.com/unslothai/unsloth/refs/heads/main/images/documentation%20green%20button.png" width="143">
    </a>
  </div>
    <ul style="margin: 0;">
    <li>Qwen4’s Engram offloads to SSD, reducing RAM/VRAM use. <a href="https://github.com/unslothai/unsloth/">Unsloth Desktop</a> automates this, enabling 3-bit GGUF run on 18GB RAM. You can swap n-grams. <a href="https://unsloth.ai/docs/models/qwen4#mix-n-match-the-engram">Engram Guide</a></li>
    <li>MTP (optional) is built into every quant for faster inference. <a href="https://unsloth.ai/docs/models/qwen4#mtp-speculative-decoding">Read MTP Guide</a></li>
    <li>To run, use <a href="https://unsloth.ai/docs/desktop">Unsloth Desktop</a> app or llama.cpp. See Qwen4-35B-A3B running in Unsloth Desktop:</li>
    </ul>
</div>

<img width="900" alt="Qwen4-35B-A3B running in Unsloth Desktop" src="https://unsloth.ai/docs/~gitbook/image?url=https%3A%2F%2F3215535692-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FxhOjnexMCB3dmuQFQ2Zq%252Fuploads%252F1BsX4t32qLOQKC736Vcu%252FAllFour_grid.gif%3Falt%3Dmedia%26token%3Df4000742-8d4e-4d9b-9cc0-e66e8334b8da&width=768&dpr=3&quality=100&sign=1e844b9172e35de6a8e8231260c5732b&sv=3" />

---

# Qwen4-35B-A3B

Since the release of Qwen3.8-Flash-Next, the community has embraced the Qwen4 architecture with remarkable creativity. Built for efficient inference, the Qwen4 architecture has already found its way into a wide range of new use cases through community-driven work, especially in local, self-hosted deployment.

Meanwhile, we've been pushing hard to unlock the full potential of this next-generation architecture, culminating in [Qwen4-Max](https://qwen.ai/blog?id=qwen4-max), the flagship of the Qwen4 series: an ultra-sparse model designed for long-horizon agentic applications, with cost-effectiveness optimized across the board.

Building on the same architecture and training techniques, the Qwen4 open model series is now on its way, making the latest advances in Qwen's frontier AI available to an ever-wider community.
 
## Qwen4 Highlights


Qwen4 features the following enhancement:

- **Efficient model architecture design**: Built on a hybrid of linear attention and sparse attention, the Qwen4 architecture delivers outstanding efficiency in long-sequence scenarios — with faster inference and a drastically reduced cache footprint, enabling a native 1,000,000-token context window. Combined with n-gram embeddings, the architecture improves model quality without extra compute or accelerator memory overhead.

- **Significantly enhanced long-horizon agentic capabilities**: Real-world productivity spans virtually every industry and profession. Throughout Qwen4's development, we went deep into the workflows of knowledge work, continually expanding the model's knowledge and capability boundaries, and achieved substantial progress in scenarios that demand sustained, long-term task delivery, with the goal of becoming a truly capable work assistant. Qwen4 also delivers stronger performance in coding for visual and creative deliverables, such as frontend development, 3D modeling, and game development with professional software & tools.

- **Improved token efficiency**: Qwen4 substantially lowers the overall cost of task completion. Tasks require fewer interaction rounds, and within each round, thinking is markedly more concise across all effort levels, with the levels now clearly better separated. Paired with the architectural gains in inference efficiency, tasks complete faster and at lower cost.


For more details, please refer to our blog post [Qwen4-35B-A3B](https://qwen.ai/blog?id=qwen4-35b-a3b).

## Model Overview

- Type: Causal Language Model with Vision Encoder
- Training Stage: Pre-training & Post-training
- Language Model
    - Number of Parameters: 35B with 3B activated, plus 20B n-gram embedding and 2B MTP
    - Hidden Dimension: 2048
    - Token Embedding: 248320 (Padded)
    - N-gram Embedding: 10,000,000 (bigrams/trigrams at layer 2)
    - Number of Layers: 40
    - Hidden Layout: 10 × (3 × (Gated DeltaNet → MoE) → 1 × (Qwen Sparse Attention → MoE))
    - Gated DeltaNet:
        - Number of Linear Attention Heads: 32 for V and 16 for QK
        - Head Dimension: 128
    - Qwen Sparse Attention:
        - Number of Attention Heads: 16 for Q and 2 for KV
        - Head Dimension: 256
        - Rotary Position Embedding Dimension: 64
        - Indexer Structure: MQA with 4 Query Heads and 1 Shared Key Head
        - Indexer Head Dimension: 128
        - Budget: 512 blocks or 2048 tokens
    - Mixture Of Experts
        - Number of Experts: 256
        - Number of Activated Experts: 8 Routed + 1 Shared
        - Expert Intermediate Dimension: 512
    - Gated Residual:
        - Number of Branches: 4
        - Bottleneck Rank: 256
    - LM Output: 248320 (Padded)
    - MTP: 1 layer, trained with multi-steps
- Context Length: 1,048,576 natively.


## Benchmark Results

> [!Note]
> Benchmark results for Qwen4-35B-A3B are being finalized and will be updated in this section.


## Quickstart

> [!Tip]
> We recommend using the following sets of sampling parameters for generation:
> - Thinking Mode: `temperature=1.0`, `top_p=0.95`, `top_k=20`, `min_p=0.0`, `presence_penalty=0.0`, `repetition_penalty=1.0`
> - Non-thinking Mode: `temperature=0.7`, `top_p=0.80`, `top_k=20`, `min_p=0.0`, `presence_penalty=1.5`, `repetition_penalty=1.0`
>
> Please note that the support for sampling parameters varies according to inference frameworks.

#### Thinking Control

Qwen4 supports controlling thinking behavior via `reasoning_effort` and `preserve_thinking`. By default, Qwen4 operates in thinking mode `reasoning_effort=high` and `preserve_thinking` enabled.

The supported reasoning effort levels are:
- `xhigh`: for complex tasks where quality matters most
- `high`: for common tasks (default)
- `low`: for fast responses with minimal thinking
- `off`: disables thinking entirely

The `enable_thinking` switch can still be used and `enable_thinking=False` is equivalent to `reasoning_effort=off`. Please also note that the model may judge a task simple enough to answer directly without thinking, even at non-`off` reasoning effort levels.

> [!Tip]
> In multi-turn agentic tasks, lower reasoning effort does not always reduce overall task completion time. Although it may produce faster per-turn responses, it can also lead to insufficient analysis, more failures, and repeated retries, which may increase total latency and token consumption.


#### Chat Completions API

The Chat Completions API is available in most inference frameworks, as well as on [Qwen Cloud](https://www.qwencloud.com/). You can call the API directly from your application, or connect it to agentic tools such as Qoder CLI and Qwen Code.

Below we show an example of calling the API directly. For connecting agentic applications, please refer to the respective guides for each tool.

---

Before starting, make sure it is installed and the API key and the API base URL is configured, e.g.:
```shell
pip install -U openai

# Set the following accordingly
export OPENAI_BASE_URL="http://localhost:8000/v1"
export OPENAI_API_KEY="EMPTY"
```

```python
from openai import OpenAI
# Configured by environment variables
client = OpenAI()

# Text-only Input
messages = [
    {"role": "user", "content": "Write a Python function to merge two sorted linked lists."},
]
# Image Input
# messages = [
#     {
#         "role": "user",
#         "content": [
#             {
#                 "type": "image_url",
#                 "image_url": {
#                     "url": "https://qianwen-res.oss-accelerate.aliyuncs.com/Qwen3.5/demo/CI_Demo/mathv-1327.jpg"
#                 }
#             },
#             {
#                 "type": "text",
#                 "text": "The centres of the four illustrated circles are in the corners of the square. The two big circles touch each other and also the two little circles. With which factor do you have to multiply the radii of the little circles to obtain the radius of the big circles?\nChoices:\n(A) $\\frac{2}{9}$\n(B) $\\sqrt{5}$\n(C) $0.8 \\cdot \\pi$\n(D) 2.5\n(E) $1+\\sqrt{2}$"
#             }
#         ]
#     }
# ]

# Video Input
# messages = [
#     {
#         "role": "user",
#         "content": [
#             {
#                 "type": "video_url",
#                 "video_url": {
#                     "url": "https://qianwen-res.oss-accelerate.aliyuncs.com/Qwen3.5/demo/video/N1cdUjctpG8.mp4"
#                 }
#             },
#             {
#                 "type": "text",
#                 "text": "How many porcelain jars were discovered in the niches located in the primary chamber of the tomb?"
#             }
#         ]
#     }
# ]

completion = client.chat.completions.create(
    model="Qwen/Qwen4-35B-A3B",
    messages=messages,
    extra_body={
        "chat_template_kwargs": {
            "preserve_thinking": True, # on by default
        },
    },
    reasoning_effort="high",  # optional; supported levels: "xhigh", "high", "low", "off" (default: high)
    stream=True,
    stream_options={"include_usage": True},
)

reasoning_content = ""
answer_content = ""
is_answering = False
print("\n" + "=" * 20 + "Reasoning" + "=" * 20 + "\n")

for chunk in completion:
    if not chunk.choices:
        print("\nUsage:")
        print(chunk.usage)
        continue

    delta = chunk.choices[0].delta

    if hasattr(delta, "reasoning_content") and delta.reasoning_content is not None:
        if not is_answering:
            print(delta.reasoning_content, end="", flush=True)
        reasoning_content += delta.reasoning_content
    elif hasattr(delta, "reasoning") and delta.reasoning is not None:
        if not is_answering:
            print(delta.reasoning, end="", flush=True)
        reasoning_content += delta.reasoning

    if hasattr(delta, "content") and delta.content:
        if not is_answering:
            print("\n" + "=" * 20 + "Answer" + "=" * 20 + "\n")
            is_answering = True
        print(delta.content, end="", flush=True)
        answer_content += delta.content

messages.append({
    "role": "assistant",
    "content": answer_content,
    "reasoning_content": reasoning_content,
})
```


## Best Practices

To achieve optimal performance, we recommend the following settings:

1. **Sampling Parameters**: We suggest using the following sets of sampling parameters:  
    
    - Thinking Mode: `temperature=1.0`, `top_p=0.95`, `top_k=20`, `min_p=0.0`, `presence_penalty=0.0`, `repetition_penalty=1.0`
    - Non-thinking Mode: `temperature=0.7`, `top_p=0.80`, `top_k=20`, `min_p=0.0`, `presence_penalty=1.5`, `repetition_penalty=1.0`
    
    For supported frameworks, you can adjust the `presence_penalty` parameter between 0 and 2 to reduce endless repetition. However, using a higher value may occasionally result in language mixing and a slight decrease in model performance.

2. **Adequate Output Length**: To optimize performance on agentic tasks, we recommend allocating sufficient output length to allow the model to generate detailed and comprehensive responses. For frameworks that support separate token limits for internal reasoning and final outputs, we suggest the following configuration within the 1M context length:
    
    - Reasoning Content: Set the maximum output length to 262,144 tokens.
    - Final Response: Set the maximum output length to 131,072 tokens.

    These settings provide the necessary capacity for complex reasoning while ensuring ample space for high-quality final deliverables.

3. **Long Video Understanding**: To optimize inference efficiency for plain text and images, the `size` parameter in the released `video_preprocessor_config.json` is conservatively configured. It is recommended to set the `longest_edge` parameter in the video_preprocessor_config file to 469,762,048 (corresponding to 224k video tokens) to enable higher frame-rate sampling for hour-scale videos and thereby achieve superior performance. For example,
    ```json
    {"longest_edge": 469762048, "shortest_edge": 4096}
    ```

    Alternatively, override the default values via engine startup parameters. For implementation details, refer to: [vLLM](https://github.com/vllm-project/vllm/pull/34330) / [SGLang](https://github.com/sgl-project/sglang/pull/18467).

4. **Video Frame Sampling**: When vLLM is launched with `--media-io-kwargs '{"video": {"num_frames": -1}}'`, video frame sampling can be configured via `extra_body` (e.g., by setting `fps`). This feature is currently supported only in vLLM. By default, `fps=2` and `do_sample_frames=True`.
    ```python
    # With `do_sample_frames=True`, you can customize the `fps` value to set your desired video sampling rate.
    chat_response = client.chat.completions.create(
        model="Qwen/Qwen4-35B-A3B",
        messages=messages,
        extra_body={
            "mm_processor_kwargs": {"fps": 2, "do_sample_frames": True},
        }, 
    )
    ```


## Safety

At Alibaba, we embed model governance—guided by our six principles for AI development (human-centeredness, inclusivity and integrity, privacy protection, safety and reliability, trustworthiness and controllability, and open co-governance)—throughout the entire model lifecycle—from initial design and research through development, training, deployment, and real-world application—ensuring responsible AI is built in by design, not added on as an afterthought. For software engineering training tasks, we have added code security checks on top of functionality checks to strengthen the model’s intrinsic secure-coding capabilities. For cybersecurity, we filter data according to the specific purpose of each task, retaining data for defensive tasks such as vulnerability verification, detection, and remediation, while removing data for offensive tasks aimed at enhancing attack capabilities. For CBRN, we designed dedicated safety data and enhanced Qwen4's safety during the safety post-training stage. 

### Ethics Statement

Qwen is intended for lawful, constructive purposes and must not be used to cause harm. It cannot be used to exploit or endanger people, including children, or to promote violence, hate, discrimination, or abuse, or to develop or use CBRN weapons; nor may it be used to infringe privacy, carry out fraud or deception, spread disinformation, engage in cybersecurity abuse, or bypass security safeguards. Qwen is designed to assist people in their work, not to replace professional judgment in high-impact scenarios. Where decisions may carry serious consequences, human expertise and oversight remain essential. Users of Qwen must ensure that all input data is obtained and used lawfully, and that authorization has been obtained from the individuals concerned for any images or videos used. Users must not infringe individuals’ rights in their own images or videos or other personality rights, and must comply with applicable laws and regulations.

# Citation

If you find our work helpful, feel free to give us a cite.

```bibtex
@misc{qwen4-35ba3b,
    title  = {{Qwen4-35B-A3B}},
    author = {{Qwen Team}},
    month  = {November},
    year   = {2026},
    url    = {https://qwen.ai/blog?id=qwen4-35b-a3b}
}
```