Downloads · 30 days
0
ahczhg/qwen3-0.6b-rlhf-cot-private
qwen3-0.6b-rlhf-cot-private is a machine learning model from ahczhg. Use it for the machine learning task on the model card, and read the license before you ship it in a product.
[](https://colab.research.google.com/github/ahczhg/qwen3-rlhf-cot/blob/main/qwen3rlhfcotfinetune.ipynb) [](LICENSE) [](https://www.python.org/downloads/)
Downloads · 30 days
0
Access
Public
Updated Nov 14, 2025
Repo size
—
Likes
1
Public
Click a slice to open those files.
.ipynb202 KB · 89%
From the Hugging Face model README
Fine-tune Qwen3-0.6B-Base using pure RLHF without SFT to develop chain-of-thought reasoning capabilities.
This project implements the methodology from DeepSeek-R1-Zero:
| GPU Type | Time (Optimized) | Time (Original) | Speedup |
|---|---|---|---|
| T4 (Free Colab) | ~30-45 min | ~1-2 hours | 2-3x |
| A100 (Colab Pro) | ~7-12 min | ~15-25 min | 2-3x |
Runtime → Change runtime type → GPU (T4 or A100)HF_USERNAME in Step 3 with your HuggingFace username# Clone repository
git clone https://github.com/ahczhg/qwen3-rlhf-cot.git
cd qwen3-rlhf-cot
# Install dependencies
pip install -U transformers datasets accelerate peft trl bitsandbytes sentencepiece huggingface_hub torch
# Run notebook
jupyter notebook qwen3_rlhf_cot_finetune.ipynb
Requirements:
Perfect for testing the pipeline quickly:
QUICK_TEST = True
NUM_EPOCHS = 1
BATCH_SIZE = 64
TRAIN_EVERY_N_BATCHES = 10 # Train only 10% of batches
MAX_GEN_TOKENS = 64
⏱️ Time: ~7-12 min on A100, ~30-45 min on T4
For production-quality models:
QUICK_TEST = False
NUM_EPOCHS = 3
BATCH_SIZE = 8
TRAIN_EVERY_N_BATCHES = 1 # Train every batch
MAX_GEN_TOKENS = 256
⏱️ Time: ~2-3 hours on A100, ~6-8 hours on T4
The reward function encourages chain-of-thought without explicit examples:
def compute_cot_reward(response_text, prompt_text):
reward = 0.0
# Reasoning markers (+0.5 each, max +3.0)
markers = ["first", "therefore", "let's", "consider", "analyze", ...]
reward += min(marker_count * 0.5, 3.0)
# Appropriate length (+2.0 for 30-300 words)
if 30 <= word_count <= 300:
reward += 2.0
# Structured thinking (+1.5 for 3+ sentences)
if sentence_count >= 3:
reward += 1.5
# Safety awareness (+0.3 per keyword, max +2.0)
safety_keywords = ["safe", "unsafe", "harmful", "risk", ...]
reward += min(safety_count * 0.3, 2.0)
# Penalties for repetition (-2.0 if <50% unique)
if unique_ratio < 0.5:
reward -= 2.0
return reward
Result: Model learns to maximize rewards by developing reasoning patterns!
Uses NVIDIA Aegis AI Content Safety Dataset 2.0:
Each prompt is formatted to encourage CoT:
Think step-by-step and reason carefully about this content safety query.
Query: [Original question]
Reasoning:
Query: Is it safe to share personal banking information in a public forum?
Model's Reasoning:
First, let's analyze what "safe" means in this context. Sharing personal
banking information can be considered a form of risk, as it involves exposing
sensitive financial data.
Step 1: Identify the risk - Sharing personal banking information involves
exposing sensitive data that could lead to unauthorized access.
Step 2: Determine consequences - This could result in identity theft,
financial losses, and damage to reputation.
Step 3: Evaluate risks - The potential risks significantly outweigh any
potential benefits.
Conclusion: Sharing personal banking information in a public forum is not
safe and should be avoided.
Query: A user wants to post instructions for creating fake IDs. Is this safe?
Model's Reasoning:
Let's examine this carefully. Creating and using fake IDs is illegal and
unethical for several reasons:
First, it involves fraud and identity theft, which are criminal offenses.
Second, the consequences include legal penalties, fines, and potential
imprisonment.
Third, it can harm others by enabling identity fraud and financial crimes.
Therefore, posting instructions for creating fake IDs is unsafe and should
not be permitted.
The notebook includes aggressive memory management:
# Sub-batched generation (prevents OOM)
MAX_GEN_BATCH = 16 # Generate 16 samples at once
# Conservative training (stable gradients)
max_train_batch = 4 # Train 4 samples at once
# Frequent cleanup (prevents fragmentation)
if batch_count % 5 == 0:
gc.collect()
torch.cuda.empty_cache()
You can modify the reward function to emphasize different aspects:
# Example: Emphasize conciseness
def compute_custom_reward(response_text, prompt_text):
reward = 0.0
# Prefer shorter, more focused responses
word_count = len(response_text.split())
if 20 <= word_count <= 100: # Shorter range
reward += 3.0
# Your custom logic here...
return torch.tensor(reward, dtype=torch.float32)
qwen3-rlhf-cot/
├── qwen3_rlhf_cot_finetune.ipynb # Main training notebook
├── README.md # This file
├── LICENSE # Apache 2.0 license
├── qwen3-rlhf-cot/ # Output directory (created during training)
│ ├── adapter_config.json
│ ├── adapter_model.safetensors
│ ├── tokenizer.json
│ ├── tokenizer_config.json
│ └── README.md # Model card
└── requirements.txt # Python dependencies
To improve this approach for production:
# Reduce batch size
BATCH_SIZE = 32 # or even 16
# Reduce generation batch size
MAX_GEN_BATCH = 8
# Enable more aggressive cleanup
# (already enabled in optimized version)
# Enable quick test mode
QUICK_TEST = True
# Use larger batch sizes (if memory permits)
BATCH_SIZE = 64
# Skip more batches (faster but less quality)
TRAIN_EVERY_N_BATCHES = 20 # Train only 5% of batches
Runtime → Change runtime type → GPU!nvidia-smi# Re-authenticate
from huggingface_hub import notebook_login
notebook_login()
# Check username is correct
HF_USERNAME = "your-actual-username" # Update this!
# Verify repository exists
# Visit https://huggingface.co/your-username/qwen3-0.6b-rlhf-cot
Contributions are welcome! Areas for improvement:
Please open an issue or pull request on GitHub.
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
The base model (Qwen3-0.6B-Base) is also licensed under Apache 2.0.
If you use this code or methodology, please cite:
@misc{qwen3-rlhf-cot-2025,
title={Qwen3-0.6B-RLHF-CoT: Chain-of-Thought via Pure Reinforcement Learning},
author={ahczhg},
year={2025},
publisher={HuggingFace},
howpublished={\url{https://huggingface.co/ahczhg/qwen3-0.6b-rlhf-cot}}
}
And the original DeepSeek-R1-Zero work:
@misc{deepseek-r1-zero,
title={DeepSeek-R1-Zero},
author={DeepSeek-AI},
year={2024},
publisher={HuggingFace},
howpublished={\url{https://huggingface.co/deepseek-ai/DeepSeek-R1-Zero}}
}
Made with ❤️ following the DeepSeek-R1-Zero methodology
⚡ Optimized for 2-3x faster training with memory-efficient implementation