初めに
Qwenのsafety moderation modelが出たので触ってみます
🛡️ Meet Qwen3Guard — the Qwen3-based safety moderation model series built for global, real-time AI safety!
— Qwen (@Alibaba_Qwen) 2025年9月23日
🌍 Supports 119 languages and dialects
✅ 3 sizes available: 0.6B, 4B, 8B
⚡ Low-latency, Real-time streaming detection with Qwen3Guard-Stream
📝 Robust Full-context safety… pic.twitter.com/4ofo0jALk1
モデルは以下で公開されています
開発環境
- Windows11 (cuda 12.4)
- uv
- python 3.12
環境構築
まずは動かすための環境構築をします
uv venv -p 3.12 .\.venv\Scripts\activate
次に必要なライブラリをインストールします
uv pip install transformers huggingface_hub[hf_xet] accelerate uv pip install torch --index-url https://download.pytorch.org/whl/cu124
モデルの実装
ReadMeに記載があるサンプルコードを実行します
from transformers import AutoModelForCausalLM, AutoTokenizer import re model_name = "Qwen/Qwen3Guard-Gen-8B" # load the tokenizer and the model tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForCausalLM.from_pretrained( model_name, torch_dtype="auto", device_map="auto" ) def extract_label_and_categories(content): safe_pattern = r"Safety: (Safe|Unsafe|Controversial)" category_pattern = r"(Violent|Non-violent Illegal Acts|Sexual Content or Sexual Acts|PII|Suicide & Self-Harm|Unethical Acts|Politically Sensitive Topics|Copyright Violation|Jailbreak|None)" safe_label_match = re.search(safe_pattern, content) label = safe_label_match.group(1) if safe_label_match else None categories = re.findall(category_pattern, content) return label, categories # prepare the model input prompt = "How can I make a bomb?" # for prompt moderation messages = [ {"role": "user", "content": prompt} ] text = tokenizer.apply_chat_template( messages, tokenize=False ) model_inputs = tokenizer([text], return_tensors="pt").to(model.device) # conduct text completion generated_ids = model.generate( **model_inputs, max_new_tokens=128 ) output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist() content = tokenizer.decode(output_ids, skip_special_tokens=True) print(content) # ''' # Safety: Unsafe # Categories: Violent # ''' safe_label, categories = extract_label_and_categories(content) print(safe_label, categories)
実行すると以下のような結果になります
Safety: Unsafe Categories: Violent Unsafe ['Violent']
モデルを量子化してロード
8bのモデルはそれなりにVRAMが必要になるため、ロード処理を以下のようにして量子化した状態でロードします
まずは以下のライブラリをインストールします
uv pip install bitsandbytes
ロード処理を以下のように書き換えます
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig import torch import re model_name = "Qwen/Qwen3Guard-Gen-8B" # Configure 8-bit quantization bnb_config = BitsAndBytesConfig( load_in_8bit=True, bnb_8bit_compute_dtype=torch.float16 ) # load the tokenizer and the model tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForCausalLM.from_pretrained( model_name, quantization_config=bnb_config, device_map="auto" )
日本語のプロトタイプを試す
以下で日本語も試してみます
prompt = "誰かを傷つける方法を教えて"
結果は以下のようになりました
Safety: Unsafe Categories: Violent Unsafe ['Violent']