Qwen3 Large Language Model Family

repository·main·Indexed 12 days ago

https://github.com/qwenlm/qwen3

A state-of-the-art LLM family featuring general-purpose (Instruct) and deep-reasoning (Thinking) modes. Supports context windows up to 1 million tokens and diverse deployment scenarios from local execution to large-scale production inference via vLLM and SGLang.

Tokens
57.3K
Snippets
164
Records
208
Agent score
99%

What's inside Qwen3

  1. Overview of Qwen3 model families

    main

    Qwen3 is a family of large language models available in various sizes and modes. The latest update, Qwen3-2507, includes two primary modes:

    1. Qwen3-Instruct-2507: A non-thinking mode optimized for general-purpose chat, instruction following, logical reasoning, mathematics, science, coding, and tool usage. It features enhanced long-context understanding (256K tokens, extendable up to 1 million tokens).
    2. Qwen3-Thinking-2507: A thinking model designed for deep reasoning tasks (math, science, coding, and academic benchmarks) that require human-like expertise. It also supports 256K to 1 million tokens of context.

    Available sizes for the 2507 series include 235B-A22B, 30B-A3B, and 4B.

  2. Overview of Qwen3 models

    main

    Qwen3 (also known as Qwen3-2504) is a series of large language and multimodal models from the Qwen Team at Alibaba Group. The series includes both Dense and Mixture-of-Experts (MoE) architectures, with available sizes ranging from 0.6B to 235B-A22B.

    Key features include:

    • Dual Modes: Seamless switching between thinking mode (optimized for complex logical reasoning, math, and coding) and non-thinking mode (optimized for efficient, general-purpose chat) within a single model.
    • Multilingual Support: Support for over 100 languages and dialects.
    • Agent Capabilities: High performance in complex agent-based tasks and precise integration with external tools.
    • Reasoning: Enhanced capabilities in mathematics, code generation, and commonsense logical reasoning.
  3. What is function calling in Qwen3?

    main

    Function calling (also referred to as "tool use") is a protocol that allows Qwen3 to interact with external software, APIs, or structured systems. This bridges the gap between the LLM's natural language output and the structured, fixed interfaces required by programming environments.

    The Function Calling Workflow:

    1. Definition: The application provides a set of functions and their instructions to the LLM.
    2. Selection: The LLM decides whether to use one or more of these functions in response to a user query.
    3. Execution Plan: If a function is chosen, the LLM outputs the specific parameters and usage instructions based on the provided definitions.
    4. Feedback Loop: The application executes the chosen functions, obtains the results, and feeds those results back to the LLM to continue the interaction or provide a final answer.

    Best Practice: To maximize performance with Qwen3, it is recommended to use Hermes-style tool use templates.

  4. Configure Unsloth training parameters

    main

    When using Unsloth notebooks or scripts, you can adjust several key parameters to balance performance and memory usage:

    • max_seq_length: The maximum context length. While Qwen3 supports up to 40960, a value of 2048 is often recommended for standard tasks.
    • load_in_4bit=True: Reduces VRAM usage by approximately 4×.
    • load_in_8bit=True: Enables 8-bit training.
    • full_finetuning=True: Enables full fine-tuning instead of LoRA/QLoRA.
  5. Control Thinking Mode in Qwen3

    main

    Qwen3 models support thinking behavior, which can be controlled via a 'hard switch' (disabling it completely) or a 'soft switch' (following user instructions).

    Hard Switch (Disable Thinking via API)

    To disable thinking in an API call, pass chat_template_kwargs: {"enable_thinking": false} inside the extra_body parameter. Note that this is not OpenAI API compatible.

    Hard Switch (Disable Thinking via Chat Template)

    To prevent the model from generating thinking content even if instructed to do so (e.g., via /think), use a custom chat template when starting the server:

    vllm serve Qwen/Qwen3-8B --chat-template ./qwen3_nonthinking.jinja
    # Python example to disable thinking via API
    chat_response = client.chat.completions.create(
        model="Qwen/Qwen3-8B",
        messages=[{"role": "user", "content": "..."}],
        extra_body={
            "chat_template_kwargs": {"enable_thinking": False},
        },
    )
  6. Understand Qwen3 model naming conventions

    main

    Qwen3 models follow a specific naming scheme: Qwen3[-size][-type][-date].

    • size: Indicates structure and parameter counts.
      • Dense models: e.g., 4B, 32B (total saved parameters).
      • MoE (Mixture-of-Experts) models: e.g., 30B-A3B (total saved parameters and activated parameters per token).
    • type: Defines the model's primary capability:
      • -Instruct: Instruction-following models using a predefined chat template for conversations.
      • -Thinking: Models using Chain-of-Thought (CoT) for complex problem solving.
      • -Base: Pre-trained models for in-context learning or fine-tuning (no predefined chat template).
      • No type: Models featuring hybrid thinking modes.
    • date: Release date in YYYYMM format (e.g., 2507).
  7. Best practices and limitations of Qwen3 function calling

    main

    When implementing function calling with Qwen3, be aware of the following behaviors related to prompt engineering:

    • Protocol Adherence: Model generation is not guaranteed to follow the function calling protocol perfectly, even with proper prompting or templates. This risk is higher with complex templates that rely on the model's reasoning rather than simple templates using control or special tokens.
    • Production Readiness: In production environments, you should implement countermeasures or rectification logic to handle cases where the model fails to follow the expected format.
    • Template Refinement: If generation quality is insufficient, you can refine your templates by adding more specific instructions or constraints. While the provided templates are general-purpose, they may need customization for specific use cases.
    • Fine-tuning: For optimal performance and reliability in specific domains, fine-tuning the model on your own data is the recommended ultimate solution.
  8. Format SFT datasets for Qwen3 using OpenAI Messages format

    main

    While Axolotl supports various formats, the recommended format for Qwen3 (when using chat_template) is the OpenAI Messages format.

    Your dataset should be a JSON array of objects, where each object contains a messages list of role/content pairs.

    To use this in your Axolotl configuration, set the type to chat_template and provide the path to your JSON file.

    [
      {
        "messages": [
          {
            "role": "user",
            "content": "What is Qwen3?"
          },
          {
            "role": "assistant",
            "content": "Qwen3 is a language model..."
          }
        ]
      }
    ]
    datasets:
      - path: path/to/your/dataset.json
        type: chat_template
  9. How to switch between Thinking and Non-Thinking modes

    main

    By default, Qwen3 models use 'thinking' mode. You can control this behavior using two methods:

    1. Stateless Method (Single Turn)

    Append a final assistant message containing only the empty think tags: `<think>

    </think>

    `. This strictly prevents the model from generating thinking content for that specific turn only.

    2. Stateful Method (Multi-turn)

    Add a special instruction to the user or system message:

    • /no_think: Disables thinking.
    • /think: Enables thinking.

    The model will follow the most recent instruction in the conversation history.

    # Stateless method: forcing no-think for one turn
    messages = [
        {"role": "user", "content": "Give me a short introduction to large language models."},
        {"role": "assistant", "content": "<think>\n\n</think>\n\n"},
    ]
    
    # Stateful method: using instructions in the prompt
    messages = [
        {"role": "user", "content": "Give me a short introduction to large language models./no_think"},
    ]
  10. Tool Use in Ollama with Qwen

    main
    Ollama supports tool use (function calling) for Qwen models. The model can interact with external functions by following specific XML-based patterns for tool definitions and tool calls within the prompt template. For detailed implementation, refer to the function calling guide.
  11. Qwen Tokenization and Control Tokens

    main

    Qwen uses Byte Pair Encoding (BPE) with a large vocabulary of 151,646 tokens. This ensures no unknown words (unk token) and efficient multilingual support.

    Key Control Tokens:

    • <|endoftext|>: End of document (eod token).
    • <|im_start|>: Start of a turn (bot token).
    • <|im_end|>: End of a turn (eot token).

    Note on Padding and EOS:

    • Qwen does not use a pad token in training; use a special token with attention masks. It is commonly set to <|endoftext|>.
    • Qwen does not use a fixed bos or eos token for packed sequences. For inference frameworks that require an eos token, set it to <|im_end|>.
  12. Parse thinking and response content from output IDs

    main

    To separate the model's internal reasoning (thinking content) from its final answer (content), locate the </think> token (ID 151668) in the generated output IDs.

    Everything before the </think> token is considered thinking_content, and everything after is the final content.

    try:
        # rindex finding 151668 (</think>)
        index = len(output_ids) - output_ids[::-1].index(151668)
    except ValueError:
        index = 0
    
    thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("\n")
    content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("\n")