File size: 10,288 Bytes
da697a4
 
 
830b4e5
da697a4
 
 
 
 
 
48b2c69
0e65b0d
 
da697a4
 
 
 
 
 
0e65b0d
da697a4
de94576
da697a4
0e65b0d
 
 
 
 
 
 
da697a4
8580423
da697a4
 
 
0e65b0d
da697a4
 
 
0e65b0d
8580423
0e65b0d
 
da697a4
 
 
 
 
 
 
0e65b0d
 
 
8580423
0e65b0d
 
 
 
 
 
 
 
 
 
da697a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d360d3
da697a4
 
 
 
 
 
9d360d3
da697a4
 
 
 
9d360d3
da697a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e65b0d
 
da697a4
 
 
 
0e65b0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da697a4
 
 
 
 
 
 
 
 
0e65b0d
da697a4
 
 
 
 
0e65b0d
da697a4
 
 
 
 
 
 
 
 
 
 
 
 
 
0e65b0d
da697a4
 
 
 
0e65b0d
 
da697a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d360d3
da697a4
 
 
0e65b0d
da697a4
 
 
 
 
 
 
 
 
 
9d360d3
da697a4
 
 
 
0e65b0d
da697a4
 
 
 
 
 
 
 
 
0e65b0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da697a4
0e65b0d
 
 
da697a4
 
abb97b3
830b4e5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
---
datasets:
- Aquiles-ai/Athenea-Coding-100k
- roskosmos19/Rhea-Coding
license: apache-2.0
tags:
- code
- agent
- merge
- uncensored
- Rhea
- multi-pass
- reasoning
language:
- en
pipeline_tag: text-generation
library_name: transformers
---

<h1 align="center">Rhea 4B Coding</h1>

![image](rheamodel.png)

**Rhea-4B-Coding** is an optimized version of [Aquiles-ai/Athenea-4B-Coding](https://huggingface.co/Aquiles-ai/Athenea-4B-Coding), specialized in **code reasoning, debugging, agentic tools and multi-pass problem solving**.

Trained on high-quality programming data with explicit reasoning traces using ` thinking` and ` 思考结束` tags, the model is designed to perform detailed **3-pass reasoning** for software development, algorithm design, and code comprehension tasks:

1. **Pass 1**: First implementation
2. **Pass 2**: Self-review for bugs, edge cases, security, performance
3. **Pass 3**: Final optimized version with identical functionality

> ⚠️ **Important Note:** This model uses an *uncensored* base version, providing full expressive freedom and unrestricted output generation. Users are fully responsible for any use or content produced by the model. It is intended exclusively for research and experimentation purposes.

## 🎯 Model Description

Rhea-4B-Coding extends Athenea-4B-Coding's structured reasoning capabilities into programming-related domains with **multi-pass processing**, showing strong performance on logical problem-solving, code completion, debugging scenarios, and iterative code refinement.

Key features:

* **Multi-Pass Processing**: 3-step reasoning with `<think>`, `<review>`, and `<final>` tags
* **Agentic Tools** for AI Agents
* **Step-by-step code reasoning** within ` thinking` blocks
* **Self-review capabilities** for bug detection and optimization
* **Specialization in algorithmic and debugging tasks**
* **Uncensored output generation** for full reasoning visibility
* **Improved logical consistency** through focused fine-tuning
* **Compatible with open inference frameworks** (Transformers, vLLM, etc.)

The model was fine-tuned using the dataset [Aquiles-ai/Athenea-Coding-100k](https://huggingface.co/datasets/Aquiles-ai/Athenea-Coding-100k), which includes diverse programming challenges, structured reasoning chains, and natural language explanations across multiple programming languages.

## 🔄 Multi-Pass Architecture

The model uses special tokens for structured reasoning:

| Token | Purpose |
|-------|---------|
| `<think>` | Start of self-review phase (Pass 2) |
| `</think>` | End of self-review phase |
| `<review>` | Start of review results documentation |
| `</review>` | End of review results |
| `<final>` | Start of final optimized version (Pass 3) |
| `</final>` | End of final version |

This structure ensures **identical functionality** across all passes while improving **code structure, comments, and robustness**.

## 💻 Usage

### Installation

```bash
uv pip install transformers torch accelerate
```

### Basic Inference

```python
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

model = AutoModelForCausalLM.from_pretrained("Roskosmos19/Rhea-4B-Coding",
        dtype=torch.bfloat16,
        trust_remote_code=True,
        device_map="auto",
        attn_implementation="flash_attention_2") # Requires flash-attn

# Without flash-attn:
# model = AutoModelForCausalLM.from_pretrained("Roskosmos19/Rhea-4B-Coding",
#     dtype="auto",
#     device_map="auto"
# )

tokenizer = AutoTokenizer.from_pretrained("Roskosmos19/Rhea-4B-Coding", trust_remote_code=True)

messages = [
    {"role": "user", "content": "Hey, write a Python function that calculates the factorial of a number recursively."}
]

inputs = tokenizer.apply_chat_template(
    messages,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
).to('cuda')

with torch.no_grad():
    output = model.generate(
        **inputs,
        max_new_tokens=16384,  # Increased for multi-pass output
        pad_token_id=tokenizer.pad_token_id,
        eos_token_id=tokenizer.eos_token_id,
    )

# Decode and print the output
print(tokenizer.decode(output[0], skip_special_tokens=False))
```

### Multi-Pass Inference (Recommended)

```python
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

model = AutoModelForCausalLM.from_pretrained("Roskosmos19/Rhea-4B-Coding",
        dtype=torch.bfloat16,
        trust_remote_code=True,
        device_map="auto")

tokenizer = AutoTokenizer.from_pretrained("Roskosmos19/Rhea-4B-Coding", trust_remote_code=True)

def generate_multi_pass(prompt, max_tokens_per_pass=4096):
    """
    Generate code with 3-pass reasoning:
    Pass 1: First implementation
    Pass 2: Self-review
    Pass 3: Final optimized version
    """
    
    # Pass 1: First implementation
    messages = [{"role": "user", "content": prompt}]
    inputs = tokenizer.apply_chat_template(
        messages,
        add_generation_prompt=True,
        tokenize=True,
        return_dict=True,
        return_tensors="pt",
    ).to('cuda')
    
    with torch.no_grad():
        output1 = model.generate(
            **inputs,
            max_new_tokens=max_tokens_per_pass,
            temperature=0.4,
            pad_token_id=tokenizer.pad_token_id,
            eos_token_id=tokenizer.eos_token_id,
        )
    
    pass1 = tokenizer.decode(output1[0], skip_special_tokens=False)
    
    # Pass 2: Self-review
    review_prompt = pass1 + "\n<<think>\n### PASS 2 - Self-Review:\n"
    inputs2 = tokenizer(review_prompt, return_tensors="pt").to('cuda')
    
    with torch.no_grad():
        output2 = model.generate(
            **inputs2,
            max_new_tokens=2048,
            temperature=0.3,
            pad_token_id=tokenizer.pad_token_id,
            eos_token_id=tokenizer.eos_token_id,
        )
    
    review = tokenizer.decode(output2[0], skip_special_tokens=False)
    
    # Pass 3: Final version
    final_prompt = review + "\n<<final>\n### PASS 3 - Final Version:\n"
    inputs3 = tokenizer(final_prompt, return_tensors="pt").to('cuda')
    
    with torch.no_grad():
        output3 = model.generate(
            **inputs3,
            max_new_tokens=max_tokens_per_pass,
            temperature=0.2,
            pad_token_id=tokenizer.pad_token_id,
            eos_token_id=tokenizer.eos_token_id,
        )
    
    final = tokenizer.decode(output3[0], skip_special_tokens=False)
    
    return {
        "pass1": pass1,
        "review": review,
        "pass3": final
    }

# Example usage
result = generate_multi_pass("Write a Python function for binary search")
print("=== PASS 1 ===")
print(result["pass1"])
print("\n=== REVIEW ===")
print(result["review"])
print("\n=== FINAL ===")
print(result["pass3"])
```

### Streaming Inference

```python
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
import torch
from threading import Thread

model = AutoModelForCausalLM.from_pretrained("Roskosmos19/Rhea-4B-Coding",
        dtype=torch.bfloat16,
        trust_remote_code=True,
        device_map="auto",
        attn_implementation="flash_attention_2")

tokenizer = AutoTokenizer.from_pretrained("Roskosmos19/Rhea-4B-Coding", trust_remote_code=True)

messages = [
    {"role": "user", "content": "Hey, write a Python function that implements the binary search algorithm recursively."}
]

inputs = tokenizer.apply_chat_template(
    messages,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
).to('cuda')

# Create the streamer
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=False)

# Build kwargs for generate
generate_kwargs = dict(
    **inputs,
    max_new_tokens=16384,  # Increased for multi-pass output
    pad_token_id=tokenizer.pad_token_id,
    eos_token_id=tokenizer.eos_token_id,
    streamer=streamer,
)

def _generate_thread(model, kwargs):
    with torch.no_grad():
        model.generate(**kwargs)

thread = Thread(target=_generate_thread, args=(model, generate_kwargs))
thread.start()

for chunk in streamer:
    print(chunk, end="", flush=True)
```

### Production Deployment with vLLM

**Start server:**

```bash
vllm serve Roskosmos19/Rhea-4B-Coding \
  --host 0.0.0.0 \
  --port 8000 \
  --api-key dummyapikey \
  --max-model-len=262144 \
  --async-scheduling \
  --gpu-memory-utilization=0.90
```

**Request to the server from the OpenAI client:**

```python
from openai import OpenAI
client = OpenAI(api_key="dummyapikey", base_url="http://127.0.0.1:8000/v1")
stream = client.chat.completions.create(
    model="roskosmos19/Rhea-4B-Coding",
    messages=[{
        "role": "user",
        "content": "Hey, write a Python function that determines if a string is a palindrome, ignoring case, spaces, and punctuation."
    }],
    max_tokens=16384,  # Increased for multi-pass output
    stream=True
)
for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
```

**vLLM Benefits:** 20-30x faster inference, OpenAI-compatible API, continuous batching, async scheduling.

## 📝 Model Configuration

| Parameter | Value | Description |
|-----------|-------|-------------|
| `temperature` | 0.4 | Balanced creativity and consistency |
| `max_new_tokens` | 32768 | Full multi-pass output capacity |
| `repetition_penalty` | 1.0 | No penalty for intentional code repetition |
| `no_repeat_ngram_size` | 0 | Allows code structure repetition |
| `use_cache` | true | Faster inference for long outputs |

## ⚙️ Files Modified for Multi-Pass

| File | Changes |
|------|---------|
| `generation_config.json` | Extended tokens, optimized for multi-pass |
| `config.json` | Enabled caching, full context window |
| `tokenizer_config.json` | Added `<think>`, `<review>`, `<final>` tokens |
| `special_tokens_map.json` | Registered new special tokens |
| `chat_template.jinja` | 3-pass prompt structure |

## 🤝 Credits

- Base model: [Aquiles-ai/Athenea-4B-Coding](https://huggingface.co/Aquiles-ai/Athenea-4B-Coding)
- Dataset: [Aquiles-ai/Athenea-Coding-100k](https://huggingface.co/datasets/Aquiles-ai/Athenea-Coding-100k)
- Architecture: Qwen3 4B

<p align="center">
  Roskosmos19
</p>