Views
No views yet

pip install rewardanything1import rewardanything
2
3# Load model locally (similar to HuggingFace)
4reward_model = rewardanything.from_pretrained(
5 "zhuohaoyu/RewardAnything-8B-v1", # Model path/name
6 device="cuda", # Device placement
7 torch_dtype="auto" # Automatic dtype selection
8)
9
10# Define your evaluation principle
11principle = "I prefer clear, concise and helpful responses over long and detailed ones."
12
13# Your evaluation data
14prompt = "How do I learn Python programming effectively?"
15responses = {
16 "response_a": "Start with Python.org's tutorial, practice daily with small projects, and join r/learnpython for help. Focus on fundamentals first.",
17 "response_b": "Here's a comprehensive approach: 1) Start with Python basics including variables, data types, operators, control structures like if-statements, for-loops, while-loops, and functions, 2) Practice with small projects like calculators, text games, and data manipulation scripts, 3) Use interactive platforms like Codecademy, Python.org's official tutorial, edX courses, Coursera specializations, and YouTube channels, 4) Join communities like r/learnpython, Stack Overflow, Python Discord servers, and local meetups for support and networking, 5) Build progressively complex projects including web scrapers, APIs, data analysis tools, and web applications, 6) Read books like 'Automate the Boring Stuff', 'Python Crash Course', and 'Effective Python', 7) Dedicate 1-2 hours daily for consistent progress and track your learning journey.",
18 "response_c": "Learn Python by coding."
19}
20
21# Get comprehensive evaluation
22result = reward_model.judge(
23 principle=principle,
24 prompt=prompt,
25 responses=responses
26)
27
28print(f"Scores: {result.scores}")
29print(f"Best to worst: {result.ranking}")
30print(f"Reasoning: {result.reasoning}")1# Install vLLM
2pip install vllm
3
4# Start vLLM server with RewardAnything model
5vllm serve zhuohaoyu/RewardAnything-8B-v1 \
6 --host 0.0.0.0 \
7 --port 8000 \
8 --max-model-len 8192 \
9 --tensor-parallel-size 1config.json:1{
2 "api_key": ["dummy-key-for-vllm"],
3 "api_model": "zhuohaoyu/RewardAnything-8B-v1",
4 "api_base": ["http://localhost:8000/v1"],
5 "api_timeout": 120.0,
6 "generation_config": {
7 "temperature": 0.0,
8 "max_tokens": 4096
9 },
10 "num_workers": 8,
11 "request_limit": 500,
12 "request_limit_period": 60
13}1# Start the RewardAnything API server
2rewardanything serve -c config.json --port 80011import rewardanything
2
3# Connect to the RewardAnything server
4client = rewardanything.Client("http://localhost:8001")
5
6# Process batch requests efficiently
7requests = [
8 {
9 "principle": "Prefer clear, concise and helpful responses over long and detailed ones.",
10 "prompt": "How to learn programming?",
11 "responses": {
12 "assistant_a": "Start with Python, practice daily, build projects.",
13 "assistant_b": "Read books and hope for the best.",
14 "assistant_c": "Start with Python.org's tutorial, practice daily with small projects, and join r/learnpython for help. Focus on fundamentals first."
15 }
16 },
17 # ... more requests
18]
19
20results = client.judge_batch(requests)
21for result in results:
22 print(f"Winner: {result.ranking[0]}")1from transformers import AutoTokenizer, AutoModelForCausalLM
2from rewardanything.processing import prepare_chat_messages, parse_rewardanything_output
3
4# Load model and tokenizer directly
5model = AutoModelForCausalLM.from_pretrained(
6 "zhuohaoyu/RewardAnything-8B-v1",
7 torch_dtype="auto",
8 device_map="auto"
9)
10tokenizer = AutoTokenizer.from_pretrained("zhuohaoyu/RewardAnything-8B-v1")
11
12# Prepare evaluation data
13principle = "Judge responses based on helpfulness and accuracy"
14prompt = "What is the capital of France?"
15responses = {
16 "model_a": "Paris is the capital of France.",
17 "model_b": "I think it might be Lyon or Paris."
18}
19
20# Prepare chat messages (handles masking automatically)
21messages, masked2real = prepare_chat_messages(principle, prompt, responses)
22
23# Format with chat template
24formatted_input = tokenizer.apply_chat_template(
25 messages, tokenize=False, add_generation_prompt=True
26)
27
28# Generate response
29inputs = tokenizer(formatted_input, return_tensors="pt").to(model.device)
30with torch.no_grad():
31 outputs = model.generate(
32 **inputs,
33 max_new_tokens=4096,
34 temperature=0.1,
35 do_sample=True,
36 pad_token_id=tokenizer.eos_token_id
37 )
38
39# Decode output
40generated_tokens = outputs[0][inputs.input_ids.shape[1]:]
41output_text = tokenizer.decode(generated_tokens, skip_special_tokens=True)
42
43# Parse structured results (handles JSON parsing robustly)
44result = parse_rewardanything_output(output_text, masked2real)
45
46print(f"Raw output: {output_text}")
47print(f"Parsed scores: {result.scores}")
48print(f"Ranking: {result.ranking}")
49print(f"Reasoning: {result.reasoning}")| Use Case | Method | Why |
|---|---|---|
| Quick testing | Local Inference | Simplest setup |
| Research & development | Local Inference | Full control, easy debugging |
| RLHF training | vLLM Deployment | High throughput, optimized for batches |
| Production evaluation | vLLM Deployment | Scalable, reliable |
| Large-scale evaluation | vLLM Deployment | Best performance |
| Custom integration | Direct HuggingFace | Maximum flexibility |
1complex_principle = """
2Evaluate responses using these criteria:
31. **Technical Accuracy** (40%): Factual correctness and up-to-date information
42. **Clarity** (30%): Clear explanations and logical structure
53. **Practical Value** (20%): Actionable advice and real-world applicability
64. **Safety** (10%): No harmful content, appropriate disclaimers
7
8For conflicting criteria, prioritize: safety > accuracy > clarity > practical value.
9"""
10
11result = reward_model.judge(complex_principle, prompt, responses)1# Example: Use in PPO training loop
2def reward_function(principle, prompt, response):
3 result = reward_model.judge(
4 principle=principle,
5 prompt=prompt,
6 responses={"generated": response, "reference": "baseline response"}
7 )
8 return result.scores["generated"]
9
10# Use in your RLHF training
11rewards = [reward_function(principle, prompt, resp) for resp in generated_responses]1result = reward_model.judge(
2 principle="Judge based on helpfulness",
3 prompt="How to cook pasta?",
4 responses={
5 "gpt4": "Boil water, add pasta...",
6 "claude": "Start by bringing water to boil..."
7 },
8 mask_responses=True # Default: True, model sees "model-1", "model-2"
9)1@article{yu2025rewardanything,
2 title={RewardAnything: Generalizable Principle-Following Reward Models},
3 author={Yu, Zhuohao and Zeng, Jiali and Gu, Weizheng and Wang, Yidong and Wang, Jindong and Meng, Fandong and Zhou, Jie and Zhang, Yue and Zhang, Shikun and Ye, Wei},
4 journal={arXiv preprint arXiv:2506.03637},
5 year={2025}
6}