Skip to main content

Qwen3

Introduction​

This codebase includes the Qwen3 family of models and currently supports the model variants:

Set environment variables​

# at $TT_METAL_HOME
source env_set.sh qwen3

How to Run​

For a single user example:​

HF_MODEL=<model_name> pytest models/bos_model/qwen3/demo/demo.py -k 'performance and batch-one and full'
  • <model_name> is the HuggingFace model repo string, e.g.
    • Qwen/Qwen3-4B
    • Qwen/Qwen3-8B
  • -k is the pytest filter to run a specific test. Please use -k <test_name>
    • You can use batch-one for single user (latency) to batch-20 for 20-user (throughput).
      • Currently batch sizes only support 1, 2, 4, 8, 16, 20
    • There are two execution modes
      • performance: use BFP8-major weight datatype casting for improved inference speed (BF4, BFP8, BF16). Average 1 byte per element; e.g. 8B = 8GB
      • accuracy: use adjusted weight datatype for accurate output (BF8 and BF16). Average 1.5 byte per element; e.g. 8B = 12GB
      • For details, please refer to the generated model cache model_cache/{model_name}/{arch}/tensor_cache_instruct_{dtype}
    • There are two cache execution modes:
      • full: use the complete KV cache for stable inference (default).
      • streaming: use StreamingLLM to maintain only a subset of the KV cache for resource-efficient execution.

Tracy report:​

HF_MODEL=<model_name> python -m tracy --op-support-count 10000 -m -r -p -v "pytest models/bos_model/qwen3/demo/demo.py -k 'performance and profiler and full'"
  • profiler is a special test case for tracy recording or ttnn-visualizer. We've fixed profiling environment for stable device time analysis, so please use this test case for profiling.
    • max_batch_size = 1, repeat_batches = 1, max_seq_len = 4096, max_generated_tokens = 3, stop_at_eos = False
    • This produces one prefill token and two decode tokens. Decode TPS excludes the prefill token and compile overhead; the second decode provides the steady-state timing sample.
    • The default Tracy command keeps decode trace capture enabled. Profiler prefill runs op-by-op so its LM-head buffers are not allocated while a cached prefill trace is live; this also exposes the prefill operations directly in the device report.
    • --op-support-count 10000 reserves enough device-profiler DRAM space between the profiler reads performed at safe demo/generator boundaries.
  • Tracy's output is saved in generated/profiler/reports. For how to view the reports, please refer to tt-perf-report.

Run for ttnn-visualizer Profiler​

  • Install ttnn-visualizer in the active Python environment:

    python3 -m pip install ttnn-visualizer
  • First, export ENV using script file

    source models/bos_model/export_l1_vis.sh <EXPERIMENT_NAME>
    • <EXPERIMENT_NAME>: set the experiment name as you like (for example, qwen)
  • Second, run model

    HF_MODEL=<model_name> pytest models/bos_model/qwen3/demo/demo.py -k 'performance and profiler and full' --timeout 10000
    • --timeout is required because per-op graph logging makes trace-disabled execution substantially slower than normal execution.
    • The environment exported above enables TTNN logging and graph reporting, so the demo automatically disables model trace capture for this visualizer run.
    • If the model has finished running successfully, the result report will be generated in the following path (generated/ttnn/reports/<EXPERIMENT_NAME>_MMDD_hhmm/)
  • Third, run ttnn-visualizer

    ttnn-visualizer --profiler-path <REPORT_PATH>
    • <REPORT_PATH>: It is the path mentioned in the previous step
    • visit http://localhost:8000/ using your web-browser
  • If the experiment has finished, please run the following command to clear the environment variables

    source models/bos_model/unset_l1_vis.sh

Details​

  • model_cache: On the first execution of each model, TTNN will create weight cache files for that model, to speed up future runs. These cache files only need to be created once for each model and each weight (i.e. new finetuned weights will need to be cached) and will be stored accordingly to the machine you are running the models.
  • Unable to access HuggingFace: If HF model weights are already stored in the local .cache/huggingface/hub but HF fails to access online, try HF_HUB_OFFLINE=1.

Model Runner (For SQA)​

Sequence length requirements​

  • max_seq_len is the total context budget for both the input prompt and generated tokens.
  • The Model Runner argument max_gen_len (CLI: --max_gen_len) reserves the maximum number of generated tokens.
  • max_seq_len must be strictly greater than max_gen_len. The available input-prompt budget is max_seq_len - max_gen_len tokens.

CLI

HF_MODEL=Qwen/Qwen3-8B python models/bos_model/qwen3/run_qwen3.py
  • Please check --help for other option info

Python REPL

  • Execute Python with HF_MODEL set
    HF_MODEL=Qwen/Qwen3-8B python
  • Run the model
    >>> from models.bos_model.qwen3.run_qwen3 import get_mesh_device, close_mesh_device, qwen3_runner
    >>> mesh_device = get_mesh_device()
    >>> result = qwen3_runner(device=mesh_device, batch_size=1, num_iters=1)
    >>> close_mesh_device(mesh_device)
  • Test with custom query
    >>> mesh_device = get_mesh_device()
    >>> result2 = qwen3_runner(device=mesh_device, batch_size=1, num_iters=1, queries=["please count 1 to 50"])
    >>> result3 = qwen3_runner(device=mesh_device, batch_size=2, num_iters=1, queries=["please count 1 to 50", "what is the capital of France?"])
    >>> close_mesh_device(mesh_device)

Streaming-LLM​

  • StreamingLLM-style decode can be enabled with:

    HF_MODEL=Qwen/Qwen3-8B python models/bos_model/qwen3/run_qwen3.py --enable_streaming_llm

    This keeps the first sink blocks and the latest recent blocks visible through the paged KV page_table. We refer to the paper and streaming-llm github.

  • This streaming LLM implementation is supported only when page attention is enabled.

  • Differences from the original implementation:

    • Block-granular sink/recent window: TT paged attention addresses KV cache by page blocks, so requested sink/recent sizes are rounded to page_block_size. For example, sink_token=4 with page_block_size=32 keeps one full sink block, i.e. 32 tokens.
    • No re-shifting RoPE for key cache: The original implementation applies RoPE differently to Q and K, using normal position_ids for Q and cache-local key_position_ids for K. In this TT path, KV cache stores K after RoPE has already been applied, so cached keys cannot be re-rotated by only changing page_table. Instead, compact decode positions keep absolute RoPE behavior by adjusting rope_delta.
    • Decode-stage only: The original implementation overrides the attention forward, so the same StreamingLLM behavior is used through the model forward path. In TT, prefill and decode use separate paths, so this implementation applies StreamingLLM only to the decode-stage view for now. Prefill still uses the normal TT prefill path.

Prefix Cache​

  • Prefix cache can be enabled with --prefix_cache_len. Since this flag separately processes prefill corresponding to the prefix length of the given prompt, the input prompt must be sufficiently longer than prefix_cache_len.
  • The model performs prefill for the first prefix_cache_len tokens during compilation run and updates the KV cache. After then, only the remaining suffix prompts are prefilled using the cached KV state, and the reported TTFT includes only this suffix prefill.
  • Prefix cache requires paged attention. Therefore, prefix_cache_len is internally rounded to a multiple of 32. For best performance, using a multiple of 64 is recommended.
  • If prefix_cache_len is also a multiple of the chunked prefill size (4096), the execution uses exactly the same kernels and execution flow as the standard prefill path, producing identical results. Otherwise, minor numerical differences may be observed.
HF_MODEL=Qwen/Qwen3-8B \
pytest models/bos_model/qwen3/demo/demo.py \
-k "performance and batch-one and full" \
--input_prompts models/bos_model/qwen3/sample_prompts/prompt_10k.json \
--prefix_cache_len 9024 \
--max_seq_len 10100 \
--max_generated_tokens 100
  • For throughput-only benchmarking, models/bos_model/lm_benchmark/run_throughput.py also exposes the same flow with --prefix-cache-len. See models/bos_model/lm_benchmark/README.md for detailed benchmark commands.