RAD
aisteer360.algorithms.output_control.rad
args
control
GPT2RewardModel
Bases: Module
GPT-2 based reward model for scoring text toxicity or other attributes.
Modified GPT-2 architecture where the language modeling head is replaced with a classification head. Used to score text sequences for desired attributes during RAD-guided generation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
reward_model_name
|
str
|
Base GPT-2 model variant to use. Defaults to "gpt2". |
'gpt2'
|
out_features
|
int
|
Number of output classes/attributes. Defaults to 1. |
1
|
Source code in aisteer360/algorithms/output_control/rad/control.py
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 |
|
model = model
instance-attribute
out_features = out_features
instance-attribute
pad_token_id = model.config.eos_token_id
instance-attribute
forward(input_ids=None, past_key_values=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None)
Forward pass through reward model.
Processes input through GPT-2 backbone and returns scores from the classification head at the last valid token position for each sequence.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_ids
|
Optional[Tensor]
|
Token IDs of shape [batch_size, seq_len]. |
None
|
past_key_values
|
Optional[Tuple[FloatTensor]]
|
Cached key-value pairs for efficient generation. |
None
|
attention_mask
|
Optional[Tensor]
|
Attention mask for padding. |
None
|
token_type_ids
|
Optional[Tensor]
|
Token type IDs (unused for GPT-2). |
None
|
position_ids
|
Optional[Tensor]
|
Position embeddings. |
None
|
head_mask
|
Optional[Tensor]
|
Attention head mask. |
None
|
Returns:
Type | Description |
---|---|
torch.Tensor: Classification scores of shape [batch_size, out_features]. Extracted from the last non-padding position of each sequence. |
Source code in aisteer360/algorithms/output_control/rad/control.py
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 |
|
RAD
Bases: OutputControl
Implementation of RAD (Reward-Augmented Decoding) from Deng and Raffel, 2023. Integrated from the official implementation of RAD (https://github.com/r-three/RAD?tab=readme-ov-file).
RAD works in two phases:
-
Reward model training: Train a reward model with a lebeled dataset containing texts and labels. For detials about this step, please see https://github.com/r-three/RAD?tab=readme-ov-file. We skip this step in this implementation and re-use the open-source toxicity reward model trained by the authors via gdown https://storage.googleapis.com/rad_release/saved_models.zip
-
Controlled decoding: At every decoding step the candidate-token logits are shifted by beta * reward, where the reward is given by a trained reward model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
beta
|
float
|
Steering intensity. Defaults to 0.0. |
required |
reward_path
|
str
|
Path to the trained reward model. See https://github.com/r-three/RAD for details. Defaults to None. |
required |
Reference:
- "Reward-Augmented Decoding: Efficient Controlled Text Generation With a Unidirectional Reward Model" Haikang Deng, Colin Raffel https://arxiv.org/abs/2310.09520
Source code in aisteer360/algorithms/output_control/rad/control.py
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 |
|
args = self.Args.validate(*args, **kwargs)
instance-attribute
base_generate = None
class-attribute
instance-attribute
beta
instance-attribute
enabled = True
class-attribute
instance-attribute
model = None
class-attribute
instance-attribute
tokenizer = None
class-attribute
instance-attribute
generate(input_ids, attention_mask, runtime_kwargs, model, **gen_kwargs)
Execute RAD-guided generation with reward-augmented logits processing.
Performs controlled generation by shifting token logits at each decoding step based on reward model scores. Returns generated text steered toward desired behavior.
At each decoding step:
- Generate top-k candidate next tokens
- Score each candidate continuation with the reward model
- Adjust logits by beta * reward_score
- Sample from adjusted distribution
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_ids
|
Tensor
|
Input token IDs of shape [batch_size, seq_len]. |
required |
attention_mask
|
Tensor
|
Attention mask matching input_ids shape. |
required |
runtime_kwargs
|
dict | None
|
Runtime parameters (currently unused). |
required |
model
|
PreTrainedModel
|
The language model used for generation. Must match the model provided during steer(). |
required |
**gen_kwargs
|
Generation parameters passed to model.generate():
|
{}
|
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor: Generated token IDs with same batch dimension as input. |
Note:
- Requires reward model to be loaded during steer() phase
- When both top_k and top_p are specified, top_k takes precedence for RAD processing
- Reward scores are clamped to [0, 1] and inverted (1 - score) for toxicity reduction
- Non-top-k tokens are set to -inf to ensure selection from reward-adjusted candidates
Source code in aisteer360/algorithms/output_control/rad/control.py
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 |
|
steer(model, tokenizer=None, **__)
Initialize RAD by loading and configuring the reward model.
Sets up the toxicity reward model used for steering during generation. Automatically downloads the model from the RAD repository if not found locally.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
PreTrainedModel
|
The base language model to be steered. |
required |
tokenizer
|
PreTrainedTokenizer | None
|
Tokenizer for the base model. If None, attempts to retrieve from model attributes. |
None
|
**__
|
Additional arguments (unused). |
{}
|
Returns:
Name | Type | Description |
---|---|---|
PreTrainedModel |
PreTrainedModel
|
The input model, unchanged. |
Note:
- Downloads ~500MB reward model on first use if not cached
- Reward model is GPT2-based with 7 toxicity classification heads
- Model weights are loaded onto the same device as the base model
Source code in aisteer360/algorithms/output_control/rad/control.py
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 |
|
RewardAugmentedLogitsProcessorNoPkv
Bases: LogitsProcessor
Logits processor that adjusts token probabilities based on reward model scores.
Implements the core RAD algorithm by evaluating candidate tokens with a reward model and shifting their logits
proportionally to the reward scores. Designed to work with transformers' generate() method as part of a
LogitsProcessorList
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
lm_tokenizer
|
Tokenizer for the language model being steered. |
required | |
rm_tokenizer
|
Tokenizer for the reward model (typically GPT-2). |
required | |
reward_model
|
Trained reward model that scores text for desired attributes. |
required | |
topk
|
int
|
Number of candidate tokens to evaluate. Defaults to 20. |
20
|
topp
|
float
|
Nucleus sampling threshold if using top-p instead of top-k. Defaults to 1. |
1
|
method
|
str
|
Reward application method. Currently only "linear" supported. Defaults to "linear". |
'linear'
|
beta
|
float
|
Scaling factor for reward scores. Higher values = stronger steering. Defaults to 30. |
30
|
inverse
|
bool
|
Whether to invert reward scores (1 - score). Used for toxicity reduction. Defaults to False. |
False
|
Source code in aisteer360/algorithms/output_control/rad/control.py
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 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 |
|
apply_function(original_score, reward_score)
Apply reward adjustment to original logits.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
original_score
|
Original logit values for candidate tokens. |
required | |
reward_score
|
Reward model scores for candidates. |
required |
Returns:
Type | Description |
---|---|
torch.Tensor: Adjusted logits computed as original + (beta * reward). |
Raises:
Type | Description |
---|---|
ValueError
|
If method is not "linear". |
Note:
- Reward scores are clamped to [0, 1] before application.
Source code in aisteer360/algorithms/output_control/rad/control.py
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 |
|
get_reward(candidate_texts)
Score candidate text sequences with the reward model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
candidate_texts
|
List of text strings to evaluate. |
required |
Returns:
Type | Description |
---|---|
torch.Tensor: Reward scores for each candidate, extracted from first output head. |
Source code in aisteer360/algorithms/output_control/rad/control.py
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 |
|