API reference
aisteer360
AI Steerability 360 toolkit.
The AI Steerability 360 toolkit (AISteer360) enables systematic control over language model behavior through four model control surfaces: input, structural, state, and output. Methods can be composed into composite model operations (via steering pipelines). Benchmarks enable comparison of steering pipelines on common use cases.
algorithms
Contains all steering logic and control implementations across input, structural, state, and output control methods.
core
Core functionality for steering pipelines, steering utilities, and argument parsing.
base_args
Base argument validation for steering method configuration.
T = TypeVar('T', bound='BaseArgs')
module-attribute
steering_pipeline
Core steering pipeline for composing and applying multiple LLM control methods.
SteeringPipeline
dataclass
Main steering pipeline for applying various control methods to Hugging Face causal language models.
Enables application of structural, state, input, and output controls in a coordinated manner. Controls are applied in a fixed bottom-up order during steering, then used together during generation.
Workflow:
- Instantiate with a base model checkpoint and/or control objects
- Call
steer()
once to apply all controls in order (structural → state → input → output) - Use
generate()
orgenerate_text()
for inference with steering applied
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_name_or_path
|
str or Path
|
HuggingFace model hub name or local directory.
Required when |
None
|
controls
|
Sequence[StructuralControl | StateControl | InputControl | OutputControl]
|
Controls for the steering pipeline, max one control per category. Omitted categories fall back to no-op controls (see control base classes). |
()
|
tokenizer_name_or_path
|
str
|
Tokenizer location. Defaults to |
None
|
device_map
|
str or dict[str, int]
|
Device map (passed to
|
'auto'
|
device
|
(device, str)
|
Device (passed to model's |
None
|
hf_model_kwargs
|
dict
|
Extra keyword arguments passed to
|
dict()
|
lazy_init
|
bool
|
If |
False
|
Raises:
Type | Description |
---|---|
RuntimeError
|
If |
ValueError
|
If multiple controls provided for same category or required arguments missing |
Note:
- Maximum one control per category; omitted categories use no-op defaults
- Controls with a
tokenizer
attribute will have it auto-injected if not already set
Source code in aisteer360/algorithms/core/steering_pipeline.py
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 |
|
controls = ()
class-attribute
instance-attribute
device = None
class-attribute
instance-attribute
device_map = 'auto'
class-attribute
instance-attribute
hf_model_kwargs = field(default_factory=dict)
class-attribute
instance-attribute
input_control = field(init=False)
class-attribute
instance-attribute
lazy_init = False
class-attribute
instance-attribute
model = field(init=False, default=None)
class-attribute
instance-attribute
model_name_or_path = None
class-attribute
instance-attribute
output_control = field(init=False)
class-attribute
instance-attribute
state_control = field(init=False)
class-attribute
instance-attribute
structural_control = field(init=False)
class-attribute
instance-attribute
tokenizer = field(init=False, default=None)
class-attribute
instance-attribute
tokenizer_name_or_path = None
class-attribute
instance-attribute
generate(input_ids, attention_mask=None, runtime_kwargs=None, **gen_kwargs)
Generate text with all steering controls applied.
Applies controls in sequence during generation:
- Input control adapts the prompt
- State control registers hooks for state control (e.g., activation steering)
- Output control handles the actual generation
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_ids
|
list[int] | LongTensor
|
Token IDs as list or tensor (shape: [seq_len] or [batch, seq_len]) |
required |
attention_mask
|
Tensor | None
|
Optional attention mask matching input_ids shape |
None
|
runtime_kwargs
|
dict | None
|
Per-generation parameters for controls (e.g., {"substrings": [...]}) |
None
|
**gen_kwargs
|
Generation parameters passed to |
{}
|
Returns:
Type | Description |
---|---|
Tensor
|
Generated token IDs (shape: [batch, generated_len]) |
Raises:
Type | Description |
---|---|
RuntimeError
|
If steer() has not yet been called |
Source code in aisteer360/algorithms/core/steering_pipeline.py
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 |
|
generate_text(*args, **kwargs)
Generate text and decode to string(s).
Convenience wrapper that calls generate() and decodes the output tokens.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*args
|
Arguments passed to generate() |
()
|
|
**kwargs
|
Keyword arguments passed to generate() |
{}
|
Returns:
Type | Description |
---|---|
str | list[str]
|
Decoded text string (single prompt) or list of strings (batch) |
Source code in aisteer360/algorithms/core/steering_pipeline.py
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 |
|
steer(**steer_kwargs)
Apply all steering controls to the model in place.
Executes each control's steer() method in a fixed bottom-up order: structural -> state -> input -> output. This ensures that higher-level controls always see the final configured model from lower levels.
If any control's steer() method returns a PreTrainedModel instance, it replaces the current model for subsequent controls.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
**steer_kwargs
|
Keyword arguments passed to all control steer() methods |
{}
|
Raises:
Type | Description |
---|---|
RuntimeError
|
If called more than once or no model available after steering |
Source code in aisteer360/algorithms/core/steering_pipeline.py
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 |
|
steering_utils
Helper functions for steering.
ensure_pad_token(tokenizer)
Set pad token to eos token if not already defined.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tokenizer
|
PreTrainedTokenizerBase
|
HuggingFace tokenizer instance |
required |
Returns:
Type | Description |
---|---|
PreTrainedTokenizerBase
|
The same tokenizer with pad_token configured |
Source code in aisteer360/algorithms/core/steering_utils.py
72 73 74 75 76 77 78 79 80 81 82 83 84 |
|
merge_controls(supplied)
Sort supplied controls by category and ensure at most one per category.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
supplied
|
Iterable[StructuralControl | StateControl | InputControl | OutputControl]
|
List of control instances to organize |
required |
Returns:
Type | Description |
---|---|
dict[str, object]
|
Dict mapping field names to control instances (with default no-ops for unspecified categories) |
Raises:
Type | Description |
---|---|
ValueError
|
If multiple controls of the same category are supplied |
TypeError
|
If an unrecognized control type is supplied |
Source code in aisteer360/algorithms/core/steering_utils.py
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 |
|
input_control
base
Input control base classes.
This module provides the abstract base class for methods that modify prompts before they reach the model.
Two base classes are provided:
InputControl
: Base class for all input control methods.NoInputControl
: Identity (null) control; used when no input control is defined in steering pipeline.
Input controls implement steering through prompt transformation σ(x), enabling behavior modification without altering model parameters or architecture. These methods transform inputs before they reach the model, resulting in generations following y ~ p_θ(σ(x)).
Examples of input controls:
- Few-shot learning (prepending examples)
- Prompt templates and formatting
- Soft prompts and prompt tuning
- Chain-of-thought prompting
- Iterative prompt refinement
See Also:
aisteer360.algorithms.input_control
: Implementations of input control methodsaisteer360.core.steering_pipeline
: Integration with steering pipeline
InputControl
Bases: ABC
Abstract base class for input control steering methods.
Transforms prompts before model processing through a prompt adapter function that modifies input token sequences.
Methods:
Name | Description |
---|---|
get_prompt_adapter |
Return transformation function (required) |
steer |
One-time preparation (optional) |
Source code in aisteer360/algorithms/input_control/base.py
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 |
|
args = self.Args.validate(*args, **kwargs)
instance-attribute
enabled = True
class-attribute
instance-attribute
get_prompt_adapter(runtime_kwargs=None)
abstractmethod
Receives (input_ids, runtime_kwargs) and returns modified input_ids..
Source code in aisteer360/algorithms/input_control/base.py
63 64 65 66 67 68 69 |
|
steer(model=None, tokenizer=None, **kwargs)
Optional steering/preparation.
Source code in aisteer360/algorithms/input_control/base.py
71 72 73 74 75 76 |
|
NoInputControl
Bases: InputControl
Identity input control.
Used as the default when no input control is needed. Returns input_ids.
Source code in aisteer360/algorithms/input_control/base.py
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 |
|
args = self.Args.validate(*args, **kwargs)
instance-attribute
enabled = False
class-attribute
instance-attribute
tokenizer = None
class-attribute
instance-attribute
get_prompt_adapter(runtime_kwargs=None)
Null adapter operation; returns identity map.
Source code in aisteer360/algorithms/input_control/base.py
87 88 89 90 91 92 93 94 95 96 97 98 |
|
steer(model=None, tokenizer=None, **kwargs)
Null steer operation; attaches tokenizer.
Source code in aisteer360/algorithms/input_control/base.py
100 101 102 103 104 105 106 107 |
|
few_shot
args
control
Few-shot learning control for prompt adaptation.
FewShot
Bases: InputControl
Implementation of few-shot learning control for prompt adaptation.
FewShot enables selective behavioral steering by prepending specific examples to user prompts, guiding model responses through demonstration.
The method operates in two modes:
-
Pool-based sampling: Maintains pools of positive and negative examples from which k examples are dynamically selected using configurable sampling strategies (random, semantic similarity, etc.).
-
Runtime injection: Accepts examples directly at inference time through runtime_kwargs, enabling context-specific demonstrations without predefined pools. Useful for dynamic or user-provided examples.
The selected examples are formatted into a system prompt with clear positive/negative labels and prepended to the user query using the model's chat template, allowing the model to learn the desired behavior pattern from the demonstrations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
directive
|
str
|
Instruction text that precedes the examples, explaining the task or desired behavior. Defaults to None. |
required |
positive_example_pool
|
Sequence[dict]
|
Pool of positive examples demonstrating desired behavior. Each dict can contain multiple key-value pairs. Defaults to None. |
required |
negative_example_pool
|
Sequence[dict]
|
Pool of negative examples showing undesired behavior to avoid. Each dict can contain multiple key-value pairs. Defaults to None. |
required |
k_positive
|
int
|
Number of positive examples to sample from the pool per query. Defaults to None. |
required |
k_negative
|
int
|
Number of negative examples to sample from the pool per query. Defaults to None. |
required |
selector_name
|
str
|
Name of the selection strategy ('random', 'semantic', etc.). Determines how examples are chosen from pools. Defaults to 'random'. |
required |
template
|
str
|
Custom template for formatting the system prompt. Should contain {directive} and {example_blocks} placeholders. Defaults to built-in template. |
required |
Runtime keyword arguments:
positive_examples
(list[dict]
,optional
): Positive examples to use for this specific query (overrides pool-based selection).negative_examples
(list[dict]
,optional
): Negative examples to use for this specific query (overrides pool-based selection).
Notes:
- Requires a tokenizer with chat_template support for optimal formatting
- Examples are automatically labeled as "### Positive example" or "### Negative example"
- When both pools and runtime examples are available, runtime examples take precedence
- If no examples are provided, the original input is returned unchanged
Source code in aisteer360/algorithms/input_control/few_shot/control.py
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 |
|
args = self.Args.validate(*args, **kwargs)
instance-attribute
directive = None
class-attribute
instance-attribute
enabled = True
class-attribute
instance-attribute
k_negative = None
class-attribute
instance-attribute
k_positive = None
class-attribute
instance-attribute
negative_example_pool = None
class-attribute
instance-attribute
positive_example_pool = None
class-attribute
instance-attribute
selector = None
class-attribute
instance-attribute
selector_name = None
class-attribute
instance-attribute
tokenizer = None
class-attribute
instance-attribute
get_prompt_adapter()
Return a prompt adapter function that adds few-shot examples to the model's system prompt. Creates and returns a closure that modifies input token sequences by prepending few-shot examples.
The returned adapter function performs the following steps:
- Determines operational mode (runtime examples take precedence over pools)
- Decodes input tokens to retrieve the original user message
- Selects or retrieves appropriate examples based on mode
- Formats examples with positive/negative labels
- Constructs a system prompt containing the examples
- Applies the model's chat template (if available) to combine system prompt and user message
- Re-encodes the adapted text to tokens
Returns:
Type | Description |
---|---|
Callable[[list[int] | Tensor, dict[str, Any]], list[int] | Tensor]
|
A prompt adapter function. |
Raises:
Type | Description |
---|---|
RuntimeError
|
If tokenizer is not set (requires calling |
Warns:
Type | Description |
---|---|
UserWarning
|
Issued when:
|
Source code in aisteer360/algorithms/input_control/few_shot/control.py
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 |
|
steer(model=None, tokenizer=None, **kwargs)
Optional steering/preparation.
Source code in aisteer360/algorithms/input_control/few_shot/control.py
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
|
selectors
Example selectors for few-shot learning prompt adaptation.
This module provides different strategies for selecting examples from pools during few-shot prompting. Selectors determine which examples are passed as demonstrations to the model.
Available selectors:
RandomSelector
: Randomly samples examples from the pool
SELECTOR_REGISTRY = {'random': RandomSelector}
module-attribute
base
Base interface for few-shot example selection strategies.
Selector
Bases: ABC
Base class for example selector.
Source code in aisteer360/algorithms/input_control/few_shot/selectors/base.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
sample(pool, k, **kwargs)
abstractmethod
Return k items chosen from pool.
Source code in aisteer360/algorithms/input_control/few_shot/selectors/base.py
13 14 15 16 17 18 19 20 21 |
|
random_selector
RandomSelector
Bases: Selector
Selects examples uniformly at random from a pool for few-shot prompting.
Source code in aisteer360/algorithms/input_control/few_shot/selectors/random_selector.py
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
sample(pool, k, **_)
Select k examples uniformly at random from the pool.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pool
|
Sequence[dict]
|
Available examples to select from |
required |
k
|
int
|
Number of examples to select |
required |
**_
|
Ignored (for compatibility with other selectors) |
{}
|
Returns:
Type | Description |
---|---|
list[dict]
|
List of randomly selected examples (up to min(k, len(pool))) |
Source code in aisteer360/algorithms/input_control/few_shot/selectors/random_selector.py
10 11 12 13 14 15 16 17 18 19 20 21 |
|
output_control
base
Output control base classes.
This module provides the abstract base classes for methods that intervene during text generation (e.g., via modifying logits, constraining the output space, or implementing alternative decoding strategies).
Two base classes are provided:
OutputControl
: Base class for all output control methods.NoOutputControl
: Identity (null) control; used when no output control is defined in steering pipeline.
Output controls implement steering through decoding algorithms and constraints, modifying the sampling process to produce generations y ~ᵈ p_θ(x), where ~ᵈ indicates the modified generation process.
Examples of output controls:
- Constrained beam search
- Reward-augmented decoding
- Grammar-constrained generation
- Token filtering and masking
- Classifier-guided generation
- Best-of-N sampling
See Also:
aisteer360.algorithms.output_control
: Implementations of output control methodsaisteer360.core.steering_pipeline
: Integration with steering pipeline
NoOutputControl
Bases: OutputControl
Identity output control.
Used as the default when no output control is needed. Calls (unsteered) model's generate.
Source code in aisteer360/algorithms/output_control/base.py
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
|
args = self.Args.validate(*args, **kwargs)
instance-attribute
enabled = False
class-attribute
instance-attribute
generate(input_ids, attention_mask, runtime_kwargs, model, **gen_kwargs)
Null generate operation; applies model's generate.
Source code in aisteer360/algorithms/output_control/base.py
91 92 93 94 95 96 97 98 99 100 |
|
steer(model, tokenizer=None, **kwargs)
Optional steering/preparation.
Source code in aisteer360/algorithms/output_control/base.py
76 77 78 79 80 81 |
|
OutputControl
Bases: ABC
Abstract base class for output control steering methods.
Overrides the generation process with custom logic.
Methods:
Name | Description |
---|---|
generate |
Custom generation (required) |
steer |
One-time preparation (optional) |
Source code in aisteer360/algorithms/output_control/base.py
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 |
|
args = self.Args.validate(*args, **kwargs)
instance-attribute
enabled = True
class-attribute
instance-attribute
generate(input_ids, attention_mask, runtime_kwargs, model, **gen_kwargs)
abstractmethod
Custom generation logic.
Source code in aisteer360/algorithms/output_control/base.py
64 65 66 67 68 69 70 71 72 73 74 |
|
steer(model, tokenizer=None, **kwargs)
Optional steering/preparation.
Source code in aisteer360/algorithms/output_control/base.py
76 77 78 79 80 81 |
|
deal
args
control
DeAL
Bases: OutputControl
Implementation of DeAL (Decoding-time Alignment) from Deng et al., 2024.
DeAL performs controlled text generation through iterative lookahead search and reward-guided beam selection. Unlike training-time alignment methods, DeAL operates purely at inference time to steer language model outputs toward desired behaviors.
The algorithm works in three phases:
-
Lookahead Generation: Generate multiple candidate continuations using beam search from the current context.
-
Reward-based Scoring: Evaluate each candidate continuation using a provided reward function that measures alignment with the desired objective (e.g., helpfulness, safety).
-
Iterative Refinement: Select the top-k highest-scoring beams and repeat the process until termination conditions are met (EOS token, max length, or max iterations reached).
This approach allows for flexible alignment with various objectives without requiring model retraining or fine-tuning.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
reward_func
|
Callable
|
Function that scores generated continuations. Should accept (prompt: str, continuations: list[str], reward_params: dict) and return list[float]. |
required |
lookahead
|
int
|
Number of tokens to generate in each lookahead step. Defaults to 4. |
required |
init_beams
|
int
|
Number of initial beams to generate at each iteration. Defaults to 8. |
required |
topk
|
int
|
Number of top-scoring beams to retain for the next iteration. Defaults to 4. |
required |
max_iterations
|
int
|
Maximum number of search iterations before termination. Defaults to 10. |
required |
Reference:
- "DeAL: Decoding-time Alignment for Large Language Models" James Y. Huang, Sailik Sengupta, Daniele Bonadiman, Yi-an Lai, Arshit Gupta, Nikolaos Pappas, Saab Mansour, Katrin Kirchhoff, Dan Roth https://arxiv.org/abs/2402.06147
Source code in aisteer360/algorithms/output_control/deal/control.py
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 |
|
args = self.Args.validate(*args, **kwargs)
instance-attribute
base_generate = None
class-attribute
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 guided generation with iterative lookahead search and reward-based selection. Returns the highest-scoring generation.
The generation process is as follows:
- Generate
init_beams
candidate continuations oflookahead
tokens each - Score all candidates using the provided reward function
- Select top-k highest scoring beams
- Check termination conditions (EOS, max length, max iterations)
- If not terminated, continue from the selected beams
- Return the highest-scoring complete generation
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_ids
|
Tensor
|
Input token IDs of shape [1, seq_len]. Currently only supports single prompts (batch size must be 1). |
required |
attention_mask
|
Tensor
|
Attention mask matching input_ids shape. Automatically recomputed during iteration based on padding tokens. |
required |
runtime_kwargs
|
dict | None
|
Runtime parameters including:
|
required |
model
|
PreTrainedModel
|
The language model used for generation. Must match the model provided during steer(). |
required |
**gen_kwargs
|
Generation parameters passed to the underlying model.generate().
Note: |
{}
|
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor: Generated token IDs of shape [1, output_len] or [output_len]. Contains the highest-scoring complete generation found during search. |
Raises:
Type | Description |
---|---|
ValueError
|
If base_generate is not callable |
NotImplementedError
|
If input has batch size > 1 (multiple prompts not supported) |
RuntimeError
|
If reward function returns incorrect number of scores |
Source code in aisteer360/algorithms/output_control/deal/control.py
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 |
|
steer(model, tokenizer=None, **_)
Lightweight preparation; attaches model, tokenizer, and generate to instance.
Source code in aisteer360/algorithms/output_control/deal/control.py
57 58 59 60 61 62 63 64 65 66 67 |
|
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 |
|
sasa
args
control
SASA
Bases: OutputControl
Implementation of SASA (Self-disciplined autoregressive sampling) from Ko et al., 2024.
SASA works in two phases:
-
Subspace learning: From a labelled toxic / non-toxic corpus, it fits a linear classifier in the model’s own sentence-embedding space; the weight vector defines a toxicity subspace.
-
Controlled decoding: At every decoding step the candidate-token logits are shifted by beta * margin, where margin is the classifier distance of the updated context from the toxic side of the subspace. Sampling from the soft-max of these adjusted logits (optionally with nucleus sampling) nudges generation away from toxic regions while staying close to the original distribution.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
beta
|
float
|
Scaling coefficient for value redistribution. Defaults to 0.0. |
required |
wv_path
|
str
|
Path to a saved steering-vector tensor. Defaults to None. |
required |
gen_wv_data_path
|
str
|
Path to the value dataset, e.g. sentences with labeled toxicity. Defaults to "Jigsaw_data/". |
required |
gen_wv_length
|
int
|
The maximum number of samples used for preparing SASA steering if wv_path does not exist. Defaults to -1 (use all). |
required |
gen_wv_batch_size
|
int
|
The batch size used for preparing SASA steering if wv_path does not exist. Defaults to 4. |
required |
Reference:
- "Large Language Models can Become Strong Self-Detoxifiers" Ching-Yun Ko, Pin-Yu Chen, Payel Das, Youssef Mroueh, Soham Dan, Georgios Kollias, Subhajit Chaudhury, Tejaswini Pedapati, Luca Daniel https://arxiv.org/abs/2410.03818
Source code in aisteer360/algorithms/output_control/sasa/control.py
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 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 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 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 |
|
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
wv
instance-attribute
generate(input_ids, attention_mask, runtime_kwargs, model, **gen_kwargs)
Execute SASA-guided generation with margin-based logit adjustment.
Performs controlled generation by computing the distance from toxic subspace at each decoding step and adjusting token logits based on this margin. Returns text steered away from toxic regions while maintaining coherence.
At each decoding step:
- Generate embeddings for all valid candidate tokens
- Compute margin (distance from toxic subspace) for each candidate
- Adjust logits by beta * softmax(margins)
- 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 (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 internals:
|
{}
|
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor: Generated token IDs including the input prompt. |
Note:
- Computes full forward passes for all valid candidate tokens at each step
- Uses custom KV cache manipulation for efficient candidate evaluation
- Margins computed relative to learned toxic/non-toxic boundary
- SASA is memory intensive; scales with vocabulary size at each generation step
Source code in aisteer360/algorithms/output_control/sasa/control.py
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 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 |
|
repeat_kv_cache(cache, repeats)
staticmethod
Repeat KV cache entries for parallel candidate evaluation.
Duplicates cache entries to enable efficient parallel processing of multiple candidate tokens without recomputing shared context.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cache
|
KV cache in various formats (DynamicCache, tuple, or custom). |
required | |
repeats
|
int
|
Number of times to repeat each cache entry. |
required |
Returns:
Type | Description |
---|---|
Repeated cache in same format as input. |
Raises:
Type | Description |
---|---|
TypeError
|
If cache type is not supported. |
Source code in aisteer360/algorithms/output_control/sasa/control.py
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 |
|
select_kv_cache(cache, select_idx)
staticmethod
Select specific entries from KV cache based on indices.
Extracts cache entries corresponding to selected beam paths, used after evaluating multiple candidates to continue with the chosen token.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cache
|
KV cache in various formats. |
required | |
select_idx
|
Tensor
|
1D tensor of indices to select. |
required |
Returns:
Type | Description |
---|---|
Selected cache entries in same format as input. |
Raises:
Type | Description |
---|---|
ValueError
|
If select_idx is not 1D. |
TypeError
|
If cache type is not supported. |
Source code in aisteer360/algorithms/output_control/sasa/control.py
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 336 337 338 339 340 341 342 |
|
steer(model, tokenizer=None, **__)
Initialize SASA by loading or generating the toxicity steering vector.
Sets up the linear classifier in the model's embedding space that defines the toxicity subspace. Either loads a pre-computed steering vector or generates one from labeled data.
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). |
Raises:
Type | Description |
---|---|
FileNotFoundError
|
If gen_wv_data_path doesn't contain required Jigsaw dataset |
Note:
- If wv_path is provided, loads pre-computed steering vector
- Otherwise generates steering vector from Jigsaw toxicity dataset
- Steering vector generation uses closed-form Bayes optimal classifier
- Saves generated steering vector to 'steer_wv.pt' for future use
Source code in aisteer360/algorithms/output_control/sasa/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 |
|
thinking_intervention
args
control
ThinkingIntervention
Bases: OutputControl
Implementation of Thinking Intervention from Wu et al., 2025.
ThinkingIntervention
enables controlled text generation by injecting structured thinking processes into the model's
reasoning chain. The method modifies the input prompt to include explicit thinking steps enclosed in special tags,
allowing the model to engage in guided reasoning before producing the final output.
The algorithm works in three phases:
-
Prompt Modification: Transform the original prompt by applying an intervention function that injects thinking instructions, reasoning templates, or structured prompts to guide the model's internal reasoning process.
-
Guided Generation: Generate text using the modified prompt, where the model first produces thinking content within special tags (e.g.,
... ) before generating the actual response. -
Output Extraction: Parse the generated text to extract only the content after the thinking tags.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
intervention
|
Callable[[str, dict], str]
|
Function that modifies the input prompt to include thinking instructions. Takes the original prompt string and parameter dict, returns the modified prompt string. |
required |
Reference
"Effectively Controlling Reasoning Models through Thinking Intervention" Tong Wu, Chong Xiang, Jiachen T. Wang, G. Edward Suh, Prateek Mittal https://arxiv.org/abs/2503.24370
Source code in aisteer360/algorithms/output_control/thinking_intervention/control.py
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 |
|
args = self.Args.validate(*args, **kwargs)
instance-attribute
base_generate = None
class-attribute
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)
Custom generation logic.
Source code in aisteer360/algorithms/output_control/thinking_intervention/control.py
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 |
|
steer(model, tokenizer=None, **_)
Optional steering/preparation.
Source code in aisteer360/algorithms/output_control/thinking_intervention/control.py
48 49 50 51 52 53 54 55 56 57 |
|
state_control
base
State control base classes.
This module provides the abstract base class for methods that register hooks into the model (e.g., to modify intermediate representations during inference); does not change model weights.
Two base classes are provided:
StateControl
: Base class for all state control methods.NoStateControl
: Identity (null) control; used when no state control is defined in steering pipeline.
State controls implement steering through runtime intervention in the model's forward pass, modifying internal states (activations, attention patterns) to produce generations following y ~ p_θᵃ(x), where "p_θᵃ" is the model with state controls.
Examples of state controls:
- Activation steering (e.g., adding direction vectors)
- Attention head manipulation and pruning
- Layer-wise activation editing
- Dynamic routing between components
- Representation engineering techniques
The base class provides automatic hook management through context managers (ensures cleanup and avoids memory leaks).
See Also:
aisteer360.algorithms.state_control
: Implementations of state control methodsaisteer360.core.steering_pipeline
: Integration with steering pipeline
BackwardHook = Callable[[nn.Module, tuple, tuple], tuple]
module-attribute
ForwardHook = Callable[[nn.Module, tuple, torch.Tensor], torch.Tensor]
module-attribute
HookSpec = dict[str, str | PreHook | ForwardHook | BackwardHook]
module-attribute
PreHook = Callable[[nn.Module, tuple], tuple | torch.Tensor]
module-attribute
NoStateControl
Bases: StateControl
Identity state control.
Used as the default when no state control is needed. Returns empty hook dictionaries and skips registration.
Source code in aisteer360/algorithms/state_control/base.py
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 |
|
args = self.Args.validate(*args, **kwargs)
instance-attribute
enabled = False
class-attribute
instance-attribute
hooks = {'pre': [], 'forward': [], 'backward': []}
instance-attribute
registered = []
instance-attribute
get_hooks(*_, **__)
Return empty hooks.
Source code in aisteer360/algorithms/state_control/base.py
152 153 154 |
|
register_hooks(*_)
Null registration operation.
Source code in aisteer360/algorithms/state_control/base.py
163 164 165 |
|
remove_hooks(*_)
Null removal operation.
Source code in aisteer360/algorithms/state_control/base.py
167 168 169 |
|
reset()
Null reset operation.
Source code in aisteer360/algorithms/state_control/base.py
175 176 177 |
|
set_hooks(hooks)
Null set operation.
Source code in aisteer360/algorithms/state_control/base.py
171 172 173 |
|
steer(model, tokenizer=None, **kwargs)
Null steering operation.
Source code in aisteer360/algorithms/state_control/base.py
156 157 158 159 160 161 |
|
StateControl
Bases: ABC
Abstract base class for state control steering methods.
Modifies internal model states during forward passes via hooks.
Methods:
Name | Description |
---|---|
get_hooks |
Create hook specs (required) |
steer |
One-time preparation (optional) |
reset |
Reset logic (optional) |
register_hooks |
Attach hooks to model (provided) |
remove_hooks |
Remove all registered hooks (provided) |
Source code in aisteer360/algorithms/state_control/base.py
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 |
|
args = self.Args.validate(*args, **kwargs)
instance-attribute
enabled = True
class-attribute
instance-attribute
hooks = {'pre': [], 'forward': [], 'backward': []}
instance-attribute
registered = []
instance-attribute
get_hooks(input_ids, runtime_kwargs, **kwargs)
abstractmethod
Create hook specifications for the current generation.
Source code in aisteer360/algorithms/state_control/base.py
79 80 81 82 83 84 85 86 87 |
|
register_hooks(model)
Attach hooks to model.
Source code in aisteer360/algorithms/state_control/base.py
96 97 98 99 100 101 102 103 104 105 106 107 |
|
remove_hooks()
Remove all registered hooks from the model.
Source code in aisteer360/algorithms/state_control/base.py
109 110 111 112 113 |
|
reset()
Optional reset call for state control
Source code in aisteer360/algorithms/state_control/base.py
140 141 142 |
|
set_hooks(hooks)
Update the hook specifications to be registered.
Source code in aisteer360/algorithms/state_control/base.py
115 116 117 |
|
steer(model, tokenizer=None, **kwargs)
Optional steering/preparation.
Source code in aisteer360/algorithms/state_control/base.py
89 90 91 92 93 94 |
|
cast
args
control
CAST
Bases: StateControl
Implementation of CAST (Conditional Activation Steering) from Lee et al., 2024.
CAST enables selective control of LLM behavior by conditionally applying activation steering based on input context, allowing fine-grained control without affecting responses to non-targeted content.
The method operates in two phases:
-
Condition Detection: Analyzes hidden state activation patterns at specified layers during inference to detect if the input matches target conditions. This is done by projecting hidden states onto a condition subspace and computing similarity scores against a threshold.
-
Conditional Behavior Modification: When conditions are met, applies steering vectors to hidden states at designated behavior layers. This selectively modifies the model's internal representations to produce desired behavioral changes while preserving normal functionality for non-matching inputs.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
condition_vector
|
SteeringVector
|
Steering vector defining the condition subspace for detecting target input patterns. Defaults to None. |
required |
behavior_vector
|
SteeringVector
|
Steering vector applied to modify behavior when conditions are met. Defaults to None. |
required |
condition_layer_ids
|
list[int]
|
Layer indices where condition detection occurs. Defaults to None. |
required |
behavior_layer_ids
|
list[int]
|
Layer indices where behavior modification is applied. Defaults to None. |
required |
condition_vector_threshold
|
float
|
Similarity threshold for condition detection. Higher values require stronger pattern matches. Defaults to 0.5. |
required |
behavior_vector_strength
|
float
|
Scaling factor for the behavior steering vector. Controls the intensity of behavioral modification. Defaults to 1.0. |
required |
condition_comparator_threshold_is
|
str
|
Comparison mode for threshold ('larger' or 'smaller'). Determines if condition is met when similarity is above or below threshold. Defaults to 'larger'. |
required |
condition_threshold_comparison_mode
|
str
|
How to aggregate hidden states for comparison ('mean' or 'last'). Defaults to 'mean'. |
required |
apply_behavior_on_first_call
|
bool
|
Whether to apply behavior steering on the first forward pass. Defaults to True. |
required |
use_ooi_preventive_normalization
|
bool
|
Apply out-of-distribution preventive normalization to maintain hidden state magnitudes. Defaults to False. |
required |
use_explained_variance
|
bool
|
Scale steering vectors by their explained variance for adaptive layer-wise control. Defaults to False. |
required |
Reference:
- "Programming Refusal with Conditional Activation Steering" Bruce W. Lee, Inkit Padhi, Karthikeyan Natesan Ramamurthy, Erik Miehling, Pierre Dognin, Manish Nagireddy, Amit Dhurandhar https://arxiv.org/abs/2409.05907
Source code in aisteer360/algorithms/state_control/cast/control.py
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 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 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 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 |
|
args = self.Args.validate(*args, **kwargs)
instance-attribute
device = None
class-attribute
instance-attribute
enabled = True
class-attribute
instance-attribute
hooks = {'pre': [], 'forward': [], 'backward': []}
instance-attribute
model = None
class-attribute
instance-attribute
registered = []
instance-attribute
tokenizer = None
class-attribute
instance-attribute
get_hooks(input_ids, runtime_kwargs, **__)
Create pre-forward hooks for conditional activation steering.
Generates hook specifications for all model layers that will conditionally detect patterns and apply behavior modifications during the forward pass.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_ids
|
Tensor
|
Input token IDs (unused but required by interface). |
required |
runtime_kwargs
|
dict | None
|
Runtime parameters (currently unused). |
required |
**__
|
Additional arguments (unused). |
{}
|
Returns:
Type | Description |
---|---|
dict[str, list]
|
dict[str, list]: Hook specifications with "pre", "forward", "backward" keys. Only "pre" hooks are populated with CAST steering logic. |
Source code in aisteer360/algorithms/state_control/cast/control.py
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 |
|
get_model_layer_list(model)
Extract the list of transformer layers from the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
PreTrainedModel
|
Model to extract layers from. |
required |
Returns:
List of layers for given model
List of layers module name prefix for given model
Source code in aisteer360/algorithms/state_control/cast/control.py
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 |
|
register_hooks(model)
Attach hooks to model.
Source code in aisteer360/algorithms/state_control/base.py
96 97 98 99 100 101 102 103 104 105 106 107 |
|
remove_hooks()
Remove all registered hooks from the model.
Source code in aisteer360/algorithms/state_control/base.py
109 110 111 112 113 |
|
reset()
Reset internal state tracking between generation calls.
Clears condition detection flags, forward call counters, and similarity scores.
Source code in aisteer360/algorithms/state_control/cast/control.py
91 92 93 94 95 96 97 98 |
|
set_hooks(hooks)
Update the hook specifications to be registered.
Source code in aisteer360/algorithms/state_control/base.py
115 116 117 |
|
steer(model, tokenizer=None, **__)
Initialization by configuring condition detection and behavior modification layers.
Sets up steering vectors, condition projectors, and layer-specific parameters for conditional activation steering. Pre-computes projection matrices and behavior vectors.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
PreTrainedModel
|
The base language model to be steered. |
required |
tokenizer
|
PreTrainedTokenizer | None
|
Tokenizer (currently unused but maintained for API consistency). If None, attempts to retrieve from model attributes. |
None
|
**__
|
Additional arguments (unused). |
{}
|
Returns:
Name | Type | Description |
---|---|---|
PreTrainedModel |
PreTrainedModel
|
The input model, unchanged. |
Source code in aisteer360/algorithms/state_control/cast/control.py
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 |
|
pasta
args
control
PASTA
Bases: StateControl
Implementation of PASTA (Post-hoc Attention STeering Approach) from Zhang et al., 2023.
PASTA performs controlled text generation by dynamically modifying attention patterns during inference to amplify or suppress the influence of specific text spans. This allows for fine-grained steering of model behavior without requiring model retraining or parameter updates.
The algorithm works by:
-
Substring Identification: Locate target substrings within the input prompt using tokenizer offset mapping to determine precise token ranges.
-
Attention Modification: Inject scaling factors into the attention mask of specified layers and heads to increase or decrease attention weights for the identified token ranges.
-
Dynamic Steering: Apply different scaling strategies (include, exclude, or generation-focused) to control how the model attends to relevant spans during text generation.
This approach enables real-time control over model focus and can be used for tasks like concept amplification, bias mitigation, or content filtering without architectural changes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
alpha
|
float
|
Scaling factor for attention modification. Positive values increase attention, negative values decrease attention. Defaults to 1.0. |
required |
head_config
|
dict | list
|
Configuration specifying which layers/heads to modify. If dict, maps layer indices to lists of head indices. If list, applies to all heads in specified layers. |
required |
scale_position
|
str
|
Strategy for applying attention scaling. Options:
Defaults to "include". |
required |
Reference: - "PASTA: Tell Your Model Where to Attend: Post-hoc Attention Steering for LLMs" Qingru Zhang, Chandan Singh, Liyuan Liu, Xiaodong Liu, Bin Yu, Jianfeng Gao, Tuo Zhao https://arxiv.org/abs/2311.02262
Source code in aisteer360/algorithms/state_control/pasta/control.py
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 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 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 |
|
args = self.Args.validate(*args, **kwargs)
instance-attribute
device = None
class-attribute
instance-attribute
enabled = True
class-attribute
instance-attribute
hooks = {'pre': [], 'forward': [], 'backward': []}
instance-attribute
model = None
class-attribute
instance-attribute
registered = []
instance-attribute
tokenizer = None
class-attribute
instance-attribute
get_hooks(input_ids, runtime_kwargs, **__)
Create attention modification hooks for specified substrings.
Identifies token ranges corresponding to target substrings and prepares hooks that will modify attention weights during the forward pass.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_ids
|
Tensor
|
Input token IDs of shape [batch_size, seq_len]. |
required |
runtime_kwargs
|
dict | None
|
Must contain "substrings" key with target text spans:
|
required |
**__
|
Additional arguments (unused). |
{}
|
Returns:
Type | Description |
---|---|
dict[str, list]
|
dict[str, list]: Hook specifications with "pre", "forward", "backward" keys. Only "pre" hooks are populated for attention modification. |
Raises:
Type | Description |
---|---|
ValueError
|
If "substrings" not in runtime_kwargs or batch size mismatch. |
Source code in aisteer360/algorithms/state_control/pasta/control.py
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 |
|
register_hooks(model)
Attach hooks to model.
Source code in aisteer360/algorithms/state_control/base.py
96 97 98 99 100 101 102 103 104 105 106 107 |
|
remove_hooks()
Remove all registered hooks from the model.
Source code in aisteer360/algorithms/state_control/base.py
109 110 111 112 113 |
|
reset()
Optional reset call for state control
Source code in aisteer360/algorithms/state_control/base.py
140 141 142 |
|
set_hooks(hooks)
Update the hook specifications to be registered.
Source code in aisteer360/algorithms/state_control/base.py
115 116 117 |
|
steer(model, tokenizer=None, **__)
Initialize PASTA by configuring attention head mappings and model references.
Sets up the layer and head configurations that will be modified during generation. Validates head configurations against model architecture.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
PreTrainedModel
|
The base language model to be steered. |
required |
tokenizer
|
PreTrainedTokenizer | None
|
Tokenizer for substring identification. If None, attempts to retrieve from model attributes. |
None
|
**__
|
Additional arguments (unused). |
{}
|
Returns:
Name | Type | Description |
---|---|---|
PreTrainedModel |
PreTrainedModel
|
The input model (unchanged). |
Source code in aisteer360/algorithms/state_control/pasta/control.py
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
|
structural_control
base
Structural control base classes.
This module provides the abstract base class for methods that create persistent changes to the model, either through weight updates or architectural changes.
Two base classes are provided:
StructuralControl
: Base class for all structural control methods.NoStructuralControl
: Identity (null) control; used when no structural control is defined in steering pipeline.
Structural controls implement steering through model weight or architecture modifications, transforming base parameters θ to θ', resulting in generations following y ~ p_θ'(x).
Examples of structural controls:
- Fine-tuning (full or parameter-efficient like LoRA)
- Model merging (e.g., via MergeKit)
- Direct Preference Optimization (DPO)
- Adapter layers and modules
- Weight interpolation and averaging
See Also:
aisteer360.algorithms.structural_control
: Implementations of structural control methodsaisteer360.core.steering_pipeline
: Integration with steering pipeline
NoStructuralControl
Bases: StructuralControl
Identity structural control.
Used as the default when no structural control is needed. Passes the model through unchanged.
Source code in aisteer360/algorithms/structural_control/base.py
72 73 74 75 76 77 78 79 80 81 |
|
args = self.Args.validate(*args, **kwargs)
instance-attribute
enabled = False
class-attribute
instance-attribute
steer(model, **__)
Null steer operation; returns model.
Source code in aisteer360/algorithms/structural_control/base.py
79 80 81 |
|
StructuralControl
Bases: ABC
Abstract base class for structural control steering methods.
Modifies model parameters or architecture persistently, returning a new model instance with transformed weights.
Methods:
Name | Description |
---|---|
steer |
Training logic (required) |
Source code in aisteer360/algorithms/structural_control/base.py
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 |
|
args = self.Args.validate(*args, **kwargs)
instance-attribute
enabled = True
class-attribute
instance-attribute
steer(model, tokenizer=None, **kwargs)
abstractmethod
Required steering/preparation.
Source code in aisteer360/algorithms/structural_control/base.py
61 62 63 64 65 66 67 68 69 |
|
wrappers
mergekit
args
control
MergeKit
Bases: StructuralControl
Wrapper for merging models via MergeKit https://github.com/arcee-ai/mergekit.
MergeKit combines multiple language models using various merge strategies like linear interpolation, SLERP, and TIES. This wrapper integrates MergeKit's functionality to enable structural control through model composition.
The process involves loading a merge configuration (from YAML or dict), executing the merge operation, and optionally loading the resulting merged model. Supports caching to avoid redundant operations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
config_path
|
str
|
Path to YAML merge configuration file. Defaults to None. |
required |
config_dict
|
dict
|
Dictionary merge configuration. Defaults to None. |
required |
out_path
|
str
|
Output directory for merged model. |
required |
load_merged
|
bool
|
Whether to load merged model after merging. Defaults to True. |
required |
force_remerge
|
bool
|
Force remerge even if output exists. Defaults to False. |
required |
allow_cuda
|
bool
|
Use CUDA acceleration if available. Defaults to True. |
required |
device_map
|
str | dict
|
Device mapping for model loading. Defaults to None. |
required |
trust_remote_code
|
bool
|
Trust remote code when loading. Defaults to False. |
required |
dtype
|
str
|
PyTorch dtype for loading. Defaults to "float16". |
required |
Reference:
- "Arcee's MergeKit: A Toolkit for Merging Large Language Models" Charles Goddard, Shamane Siriwardhana, Malikeh Ehghaghi, Luke Meyers, Vladimir Karpukhin, Brian Benedict, Mark McQuade, Jacob Solawetz https://aclanthology.org/2024.emnlp-industry.36
Source code in aisteer360/algorithms/structural_control/wrappers/mergekit/control.py
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 |
|
args = self.Args.validate(*args, **kwargs)
instance-attribute
enabled = True
class-attribute
instance-attribute
steer(model, tokenizer=None, **_)
Execute model merging via MergeKit and optionally return the merged model.
Performs structural steering by merging multiple models according to a configuration file or dictionary. Supports caching to avoid redundant merge operations and can either return the merged model or the original model based on configuration.
The method follows this logic:
- Load merge configuration from YAML file or dictionary
- Check if merged model already exists (skip if
force_remerge=False
) - Execute merge if needed using MergeKit
- Optionally load and return the merged model
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
PreTrainedModel
|
The base model (potentially unused depending on the method). |
required |
tokenizer
|
PreTrainedTokenizer
|
Base tokenizer (currently unused). |
None
|
**_
|
Additional arguments (ignored). |
{}
|
Returns:
Name | Type | Description |
---|---|---|
PreTrainedModel |
Either the merged model (if |
|
merged model, attempts to attach a new tokenizer if one was created during merging. |
Note:
- If out_path exists and
force_remerge=False
, skips merging and loads cached result - Merged model saved to
out_path
directory with full weights and config - If
load_merged=False
, performs merge but returns original model
Source code in aisteer360/algorithms/structural_control/wrappers/mergekit/control.py
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 |
|
trl
The TRL wrapper implements a variety of methods from Hugging Face's TRL library.
The current functionality spans the following methods:
- SFT (Supervised Fine-Tuning): Standard supervised learning to fine-tune language models on demonstration data
- DPO (Direct Preference Optimization): Trains models directly on preference data without requiring a separate reward model
- APO (Anchored Preference Optimization): A variant of DPO that uses an anchor model to improve training stability and performance
- SPPO (Self-Play Preference Optimization): Iterative preference optimization using self-generated synthetic data to reduce dependency on external preference datasets
For documentation information, please refer to the TRL page and the SPPO repository.
apotrainer
args
control
APO
Bases: DPOTrainerMixin
Source code in aisteer360/algorithms/structural_control/wrappers/trl/apotrainer/control.py
9 10 11 12 13 |
|
Config
instance-attribute
args = self.Args.validate(*args, **kwargs)
instance-attribute
enabled = True
class-attribute
instance-attribute
eval_dataset = None
class-attribute
instance-attribute
lora_kwargs = None
class-attribute
instance-attribute
model = None
class-attribute
instance-attribute
peft_type = None
class-attribute
instance-attribute
ref_model = None
class-attribute
instance-attribute
tokenizer = None
class-attribute
instance-attribute
train_dataset = None
class-attribute
instance-attribute
training_args = None
class-attribute
instance-attribute
use_peft = False
class-attribute
instance-attribute
steer(model, tokenizer=None, ref_model=None, **_)
Required steering/preparation.
Source code in aisteer360/algorithms/structural_control/wrappers/trl/dpotrainer/base_mixin.py
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 |
|
args
base_mixin
TRLMixin
Bases: StructuralControl
Source code in aisteer360/algorithms/structural_control/wrappers/trl/base_mixin.py
4 5 6 7 8 9 |
|
args = self.Args.validate(*args, **kwargs)
instance-attribute
enabled = True
class-attribute
instance-attribute
steer(model, tokenizer=None, **kwargs)
abstractmethod
Required steering/preparation.
Source code in aisteer360/algorithms/structural_control/base.py
61 62 63 64 65 66 67 68 69 |
|
dpotrainer
args
base_mixin
DPOTrainerMixin
Bases: StructuralControl
Source code in aisteer360/algorithms/structural_control/wrappers/trl/dpotrainer/base_mixin.py
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 |
|
Config
instance-attribute
args = self.Args.validate(*args, **kwargs)
instance-attribute
enabled = True
class-attribute
instance-attribute
eval_dataset = None
class-attribute
instance-attribute
lora_kwargs = None
class-attribute
instance-attribute
model = None
class-attribute
instance-attribute
peft_type = None
class-attribute
instance-attribute
ref_model = None
class-attribute
instance-attribute
tokenizer = None
class-attribute
instance-attribute
train_dataset = None
class-attribute
instance-attribute
training_args = None
class-attribute
instance-attribute
use_peft = False
class-attribute
instance-attribute
steer(model, tokenizer=None, ref_model=None, **_)
Required steering/preparation.
Source code in aisteer360/algorithms/structural_control/wrappers/trl/dpotrainer/base_mixin.py
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 |
|
control
DPO
Bases: DPOTrainerMixin
Source code in aisteer360/algorithms/structural_control/wrappers/trl/dpotrainer/control.py
9 10 11 12 13 |
|
Config
instance-attribute
args = self.Args.validate(*args, **kwargs)
instance-attribute
enabled = True
class-attribute
instance-attribute
eval_dataset = None
class-attribute
instance-attribute
lora_kwargs = None
class-attribute
instance-attribute
model = None
class-attribute
instance-attribute
peft_type = None
class-attribute
instance-attribute
ref_model = None
class-attribute
instance-attribute
tokenizer = None
class-attribute
instance-attribute
train_dataset = None
class-attribute
instance-attribute
training_args = None
class-attribute
instance-attribute
use_peft = False
class-attribute
instance-attribute
steer(model, tokenizer=None, ref_model=None, **_)
Required steering/preparation.
Source code in aisteer360/algorithms/structural_control/wrappers/trl/dpotrainer/base_mixin.py
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 |
|
sfttrainer
args
base_mixin
SFTTrainerMixin
Bases: StructuralControl
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sfttrainer/base_mixin.py
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 |
|
Config
instance-attribute
args = self.Args.validate(*args, **kwargs)
instance-attribute
data_collator = None
class-attribute
instance-attribute
enabled = True
class-attribute
instance-attribute
eval_dataset = None
class-attribute
instance-attribute
lora_kwargs = None
class-attribute
instance-attribute
model = None
class-attribute
instance-attribute
peft_type = None
class-attribute
instance-attribute
tokenizer = None
class-attribute
instance-attribute
train_dataset = None
class-attribute
instance-attribute
training_args = None
class-attribute
instance-attribute
use_peft = False
class-attribute
instance-attribute
steer(model, tokenizer=None, **_)
Required steering/preparation.
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sfttrainer/base_mixin.py
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 |
|
control
SFT
Bases: SFTTrainerMixin
Structural control that applies a LoRA adapter.
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sfttrainer/control.py
9 10 11 12 13 |
|
Config
instance-attribute
args = self.Args.validate(*args, **kwargs)
instance-attribute
data_collator = None
class-attribute
instance-attribute
enabled = True
class-attribute
instance-attribute
eval_dataset = None
class-attribute
instance-attribute
lora_kwargs = None
class-attribute
instance-attribute
model = None
class-attribute
instance-attribute
peft_type = None
class-attribute
instance-attribute
tokenizer = None
class-attribute
instance-attribute
train_dataset = None
class-attribute
instance-attribute
training_args = None
class-attribute
instance-attribute
use_peft = False
class-attribute
instance-attribute
steer(model, tokenizer=None, **_)
Required steering/preparation.
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sfttrainer/base_mixin.py
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 |
|
sppotrainer
args
base_mixin
SPPOTrainerMixin
Bases: StructuralControl
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/base_mixin.py
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 |
|
Config
instance-attribute
args = self.Args.validate(*args, **kwargs)
instance-attribute
enabled = True
class-attribute
instance-attribute
eval_dataset = None
class-attribute
instance-attribute
lora_kwargs = None
class-attribute
instance-attribute
model = None
class-attribute
instance-attribute
peft_type = None
class-attribute
instance-attribute
refModel = None
class-attribute
instance-attribute
tokenizer = None
class-attribute
instance-attribute
train_dataset = None
class-attribute
instance-attribute
training_args = None
class-attribute
instance-attribute
use_peft = False
class-attribute
instance-attribute
steer(model, tokenizer=None, refModel=None, maxlen=2048, num_prompts=5, start_iter_num=1, end_iter_num=1, additional_train_datasets=None, sppo_temp_dir='sppo_temp_dir', **_)
Required steering/preparation.
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/base_mixin.py
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 |
|
control
SPPO
Bases: SPPOTrainerMixin
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/control.py
9 10 11 12 13 |
|
Config
instance-attribute
args = self.Args.validate(*args, **kwargs)
instance-attribute
enabled = True
class-attribute
instance-attribute
eval_dataset = None
class-attribute
instance-attribute
lora_kwargs = None
class-attribute
instance-attribute
model = None
class-attribute
instance-attribute
peft_type = None
class-attribute
instance-attribute
refModel = None
class-attribute
instance-attribute
tokenizer = None
class-attribute
instance-attribute
train_dataset = None
class-attribute
instance-attribute
training_args = None
class-attribute
instance-attribute
use_peft = False
class-attribute
instance-attribute
steer(model, tokenizer=None, refModel=None, maxlen=2048, num_prompts=5, start_iter_num=1, end_iter_num=1, additional_train_datasets=None, sppo_temp_dir='sppo_temp_dir', **_)
Required steering/preparation.
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/base_mixin.py
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 |
|
trainer
SPPOTrainer
Bases: Trainer
Initialize SPPOTrainer.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
`transformers.PreTrainedModel`
|
The model to train, preferably an |
None
|
ref_model
|
`PreTrainedModelWrapper`
|
Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation and loss. If no reference model is provided, the trainer will create a reference model with the same architecture as the model to be optimized. |
None
|
beta
|
`float`, defaults to 0.1
|
The beta factor in DPO loss. In SPPO, eta=1/beta. Higher beta means less divergence from the initial policy. For the IPO loss, beta is the regularization parameter denoted by tau in the paper. |
0.1
|
label_smoothing
|
`float`, defaults to 0
|
The robust DPO label smoothing parameter from the cDPO report that should be between 0 and 0.5. |
0
|
loss_type
|
`str`, defaults to `"sigmoid"`
|
'sigmoid'
|
|
args
|
`transformers.TrainingArguments`
|
The arguments to use for training. |
None
|
data_collator
|
`transformers.DataCollator`
|
The data collator to use for training. If None is specified, the default data collator ( |
None
|
label_pad_token_id
|
`int`, defaults to `-100`
|
The label pad token id. This argument is required if you want to use the default data collator. |
-100
|
padding_value
|
`int`, defaults to `0`
|
The padding value if it is different to the tokenizer's pad_token_id. |
0
|
truncation_mode
|
`str`, defaults to `keep_end`
|
The truncation mode to use, either |
'keep_end'
|
train_dataset
|
`datasets.Dataset`
|
The dataset to use for training. |
None
|
eval_dataset
|
`datasets.Dataset`
|
The dataset to use for evaluation. |
None
|
processing_class
|
`transformers.PreTrainedTokenizerBase`
|
The tokenizer to use for training. This argument is required if you want to use the default data collator. |
None
|
model_init
|
`Callable[[], transformers.PreTrainedModel]`
|
The model initializer to use for training. If None is specified, the default model initializer will be used. |
None
|
callbacks
|
`List[transformers.TrainerCallback]`
|
The callbacks to use for training. |
None
|
optimizers
|
`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`
|
The optimizer and scheduler to use for training. |
(None, None)
|
preprocess_logits_for_metrics
|
`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`
|
The function to use to preprocess the logits before computing the metrics. |
None
|
max_length
|
`int`, defaults to `None`
|
The maximum length of the sequences in the batch. This argument is required if you want to use the default data collator. |
None
|
max_prompt_length
|
`int`, defaults to `None`
|
The maximum length of the prompt. This argument is required if you want to use the default data collator. |
None
|
max_target_length
|
`int`, defaults to `None`
|
The maximum length of the target. This argument is required if you want to use the default data collator and your model is an encoder-decoder. |
None
|
peft_config
|
`Dict`, defaults to `None`
|
The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model. |
None
|
is_encoder_decoder
|
`Optional[bool]`, `optional`, defaults to `None`
|
If no model is provided, we need to know if the model_init returns an encoder-decoder. |
None
|
disable_dropout
|
`bool`, defaults to `True`
|
Whether or not to disable dropouts in |
True
|
generate_during_eval
|
`bool`, defaults to `False`
|
Whether to sample and log generations during evaluation step. |
False
|
compute_metrics
|
`Callable[[EvalPrediction], Dict]`, *optional*
|
The function to use to compute the metrics. Must take a |
None
|
precompute_ref_log_probs
|
`bool`, defaults to `False`
|
Flag to precompute reference model log probabilities and evaluation datasets. This is useful if you want to train without the reference model and reduce the total GPU memory needed. |
False
|
model_init_kwargs
|
Optional[Dict]
|
( |
None
|
ref_model_init_kwargs
|
Optional[Dict]
|
( |
None
|
model_adapter_name
|
`str`, defaults to `None`
|
Name of the train target PEFT adapter, when using LoRA with multiple adapters. |
None
|
ref_adapter_name
|
`str`, defaults to `None`
|
Name of the reference PEFT adapter, when using LoRA with multiple adapters. |
None
|
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/trainer.py
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 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 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 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 |
|
beta = beta
instance-attribute
generate_during_eval = generate_during_eval
instance-attribute
is_encoder_decoder = model.config.is_encoder_decoder
instance-attribute
is_peft_model = is_peft_available() and isinstance(model, PeftModel)
instance-attribute
label_pad_token_id = label_pad_token_id
instance-attribute
label_smoothing = label_smoothing
instance-attribute
loss_type = loss_type
instance-attribute
max_length = max_length
instance-attribute
max_prompt_length = max_prompt_length
instance-attribute
max_target_length = max_target_length
instance-attribute
model_adapter_name = model_adapter_name
instance-attribute
padding_value = padding_value if padding_value is not None else processing_class.pad_token_id
instance-attribute
precompute_ref_log_probs = precompute_ref_log_probs
instance-attribute
processing_class = processing_class
instance-attribute
ref_adapter_name = ref_adapter_name
instance-attribute
ref_model = ref_model
instance-attribute
truncation_mode = truncation_mode
instance-attribute
use_dpo_data_collator = True
instance-attribute
build_tokenized_answer(prompt, answer)
Llama tokenizer does satisfy enc(a + b) = enc(a) + enc(b)
.
It does ensure enc(a + b) = enc(a) + enc(a + b)[len(enc(a)):]
.
Reference:
https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/trainer.py
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 |
|
compute_loss(model, inputs, return_outputs=False, num_items_in_batch=None)
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/trainer.py
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 |
|
compute_reference_log_probs(padded_batch)
Computes log probabilities of the reference model for a single padded batch of a DPO specific dataset.
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/trainer.py
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 |
|
concatenated_forward(model, batch)
Run the given model on the given batch of inputs, concatenating the chosen and rejected inputs together.
We do this to avoid doing two forward passes, because it's faster for FSDP.
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/trainer.py
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 |
|
concatenated_inputs(batch, is_encoder_decoder=False, label_pad_token_id=-100, padding_value=0, device=None)
staticmethod
Concatenate the chosen and rejected inputs into a single tensor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch
|
Dict[str, Union[List, LongTensor]]
|
A batch of data. Must contain the keys 'chosen_input_ids' and 'rejected_input_ids', which are tensors of shape (batch_size, sequence_length). |
required |
is_encoder_decoder
|
bool
|
Whether the model is an encoder-decoder model. |
False
|
label_pad_token_id
|
int
|
The label pad token id. |
-100
|
padding_value
|
int
|
The padding value to use for the concatenated inputs_ids. |
0
|
device
|
Optional[device]
|
The device for the concatenated inputs. |
None
|
Returns:
Type | Description |
---|---|
Dict[str, LongTensor]
|
A dictionary containing the concatenated inputs under the key 'concatenated_input_ids'. |
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/trainer.py
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 |
|
evaluation_loop(dataloader, description, prediction_loss_only=None, ignore_keys=None, metric_key_prefix='eval')
Overriding built-in evaluation loop to store metrics for each batch.
Prediction/evaluation loop, shared by Trainer.evaluate()
and Trainer.predict()
.
Works both with or without labels.
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/trainer.py
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 |
|
generate_from_model(model, batch)
Generate samples from the model and reference model for the given batch of inputs.
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/trainer.py
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 |
|
get_batch_logps(logits, labels, average_log_prob=False, label_pad_token_id=-100, is_encoder_decoder=False)
staticmethod
Compute the log probabilities of the given labels under the given logits.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
logits
|
FloatTensor
|
Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size) |
required |
labels
|
LongTensor
|
Labels for which to compute the log probabilities. Label tokens with a value of label_pad_token_id are ignored. Shape: (batch_size, sequence_length) |
required |
average_log_prob
|
bool
|
If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the log probabilities of the (non-masked) tokens. |
False
|
label_pad_token_id
|
int
|
The label pad token id. |
-100
|
is_encoder_decoder
|
bool
|
Whether the model is an encoder-decoder model. |
False
|
Returns:
Type | Description |
---|---|
FloatTensor
|
A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the given logits. |
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/trainer.py
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 |
|
get_batch_loss_metrics(model, batch, train_eval='train')
Compute the SPPO loss and other metrics for the given batch of inputs for train or test.
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/trainer.py
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 |
|
get_eval_dataloader(eval_dataset=None)
Returns the evaluation [~torch.utils.data.DataLoader
].
Subclass of transformers.src.transformers.trainer.get_eval_dataloader to precompute ref_log_probs
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
eval_dataset
|
`torch.utils.data.Dataset`, *optional*
|
If provided, will override |
None
|
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/trainer.py
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 |
|
get_train_dataloader()
Returns the training [~torch.utils.data.DataLoader
].
Subclass of transformers.src.transformers.trainer.get_train_dataloader to precompute ref_log_probs
.
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/trainer.py
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 |
|
log(logs, start_time=None)
Log logs
on the various objects watching training, including stored metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
logs
|
`Dict[str, float]`
|
The values to log. |
required |
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/trainer.py
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 |
|
null_ref_context()
Context manager for handling null reference model (that is, peft adapter manipulation).
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/trainer.py
727 728 729 730 731 732 733 734 735 736 737 |
|
prediction_step(model, inputs, prediction_loss_only, ignore_keys=None)
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/trainer.py
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 |
|
sppo_loss(policy_chosen_logps, policy_rejected_logps, reference_chosen_logps, reference_rejected_logps, chosen_probs=None, chosen_probs_win=None, chosen_probs_lose=None, reference_free=False)
Compute the SPPO loss for a batch of policy and reference model log probabilities.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
policy_chosen_logps
|
FloatTensor
|
Log probabilities of the policy model for the chosen responses. Shape: (batch_size,) |
required |
policy_rejected_logps
|
FloatTensor
|
Log probabilities of the policy model for the rejected responses. Shape: (batch_size,) |
required |
reference_chosen_logps
|
FloatTensor
|
Log probabilities of the reference model for the chosen responses. Shape: (batch_size,) |
required |
reference_rejected_logps
|
FloatTensor
|
Log probabilities of the reference model for the rejected responses. Shape: (batch_size,) |
required |
reference_free
|
bool
|
If True, we ignore the provided reference model and implicitly use a reference model that assigns equal probability to all responses. |
False
|
Returns:
Type | Description |
---|---|
FloatTensor
|
A tuple of three tensors: (losses, chosen_rewards, rejected_rewards). |
FloatTensor
|
The losses tensor contains the SPPO loss for each example in the batch. |
FloatTensor
|
The chosen_rewards and rejected_rewards tensors contain the rewards for the chosen and rejected responses, respectively. |
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/trainer.py
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 |
|
store_metrics(metrics, train_eval='train')
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/trainer.py
1181 1182 1183 |
|
tokenize_row(feature, model=None)
Tokenize a single row from a SPPO specific dataset.
At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation in case the prompt + chosen or prompt + rejected responses is/are too long. First we truncate the prompt; if we're still too long, we truncate the chosen/rejected.
We also create the labels for the chosen/rejected responses, which are of length equal to the sum of the length of the prompt and the chosen/rejected response, with label_pad_token_id for the prompt tokens.
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/trainer.py
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 |
|
utils
apply_chat_template(example, tokenizer, skip_system_message)
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/utils.py
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 |
|
apply_template(text, tokenizer)
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/utils.py
19 20 21 22 23 |
|
from_ranks(data, pairs, sppo_temp_dir, iter_num)
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/utils.py
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 |
|
prepare_dataset_from_prompts(llm, tokenizer, data, sppo_temp_dir, iter_num=1, maxlen=2048, num_prompts=5)
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/utils.py
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 |
|
prepare_score(pairs, sppo_temp_dir, iter_num)
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/utils.py
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 |
|
process_dataset(raw_dataset, tokenizer)
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/utils.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 |
|
ranking(sppo_temp_dir, iter_num, prompts, candidates)
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/utils.py
30 31 32 33 34 |
|
set_seed(seed=5775709)
Source code in aisteer360/algorithms/structural_control/wrappers/trl/sppotrainer/utils.py
13 14 15 16 17 |
|
evaluation
benchmark
Benchmark
Benchmark framework for comparing steering pipelines on specific use cases.
Provides a standardized way to compare different steering control configurations against a baseline model on a given evaluation task. Handles the complete benchmark workflow: model loading, generation, and evaluation.
The benchmark runs each control pipeline configuration independently, allowing for fair comparison of controls on a common task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
use_case
|
UseCase
|
The evaluation task defining prompts, generation logic, and metrics.
Must implement |
required |
base_model_name_or_path
|
str | Path
|
HuggingFace model identifier or local path to the base model. Used for all pipeline configurations and baseline. |
required |
steering_pipelines
|
dict[str, list[Any]]
|
Named configurations of steering pipelines. Keys are configuration names (e.g., "baseline", "with_activation_steering"). Values are pipelines, e.g., lists of controls (StructuralControl, StateControl, etc.). Empty list or None creates a baseline configuration without steering. |
required |
runtime_overrides
|
dict[str, dict[str, Any]]
|
Runtime parameters for specific pipeline
configurations. Outer keys match |
None
|
hf_model_kwargs
|
dict
|
Additional arguments passed to |
None
|
gen_kwargs
|
dict
|
Generation parameters passed to model.generate(). Defaults to {}. |
None
|
device_map
|
str
|
Device placement strategy for model loading. Defaults to "auto". |
'auto'
|
Source code in aisteer360/evaluation/benchmark.py
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 |
|
base_model_name_or_path = base_model_name_or_path
instance-attribute
device_map = device_map
instance-attribute
gen_kwargs = gen_kwargs or {}
instance-attribute
hf_model_kwargs = hf_model_kwargs or {}
instance-attribute
runtime_overrides = runtime_overrides
instance-attribute
steering_pipelines = steering_pipelines
instance-attribute
use_case = use_case
instance-attribute
export(profiles, save_dir)
Export benchmark results to disk.
Saves the benchmark profiles to the specified directory. Creates the directory if it doesn't exist. Delegates the actual export logic to the use case's export method, which handles format-specific serialization.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
profiles
|
dict[str, Any]
|
Benchmark results from |
required |
save_dir
|
str
|
Directory path where results will be saved. Will be created if it doesn't exist. |
required |
Source code in aisteer360/evaluation/benchmark.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 |
|
run()
Run benchmark on all configured steering pipelines.
Executes the benchmark by iterating through each pipeline configuration defined in control_pipelines
. For each
configuration, calls _run_pipeline()
to handle model setup, generation, and evaluation. Results from all
pipelines are collected for comparison.
Returns:
Type | Description |
---|---|
dict[str, Any]
|
Benchmark profiles for all pipeline configurations. Keys are pipeline names from
|
Source code in aisteer360/evaluation/benchmark.py
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 |
|
metrics
Base classes for evaluation metrics.
Contains two classes:
Metric
: Base class for all evaluation metrics.LLMJudgeMetric
: Base class for LLM-as-a-judge metrics (subclassesMetric
)
Factuality
Bases: LLMJudgeMetric
Judge factual correctness of a response to a prompt.
Source code in aisteer360/evaluation/metrics/generic/factuality.py
19 20 21 22 23 24 25 26 27 28 29 30 |
|
base_prompt_template = prompt_template.strip()
instance-attribute
batch_size = batch_size
instance-attribute
device = device or ('cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu')
instance-attribute
extras = extras
instance-attribute
format_instructions = self.output_parser.get_format_instructions()
instance-attribute
max_retries = max_retries
instance-attribute
model = AutoModelForCausalLM.from_pretrained(model_or_id)
instance-attribute
name = self.__class__.__name__
instance-attribute
num_return_sequences = int(gen_kwargs.pop('num_return_sequences', 1))
instance-attribute
pipeline = TextGenerationPipeline(model=(self.model), tokenizer=(self.tokenizer))
instance-attribute
scale = scale
instance-attribute
tokenizer = tokenizer or AutoTokenizer.from_pretrained(model_or_id)
instance-attribute
use_chat = hasattr(self.tokenizer, 'apply_chat_template') and self.tokenizer.chat_template is not None
instance-attribute
compute(responses, prompts=None, **kwargs)
Compute LLM judge scores for a list of responses.
Evaluates each response using the configured judge model and prompt template. Scores are averaged when multiple
samples are generated per response (via num_return_sequences
).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
responses
|
list[str]
|
List of text responses to evaluate. |
required |
prompts
|
list[str] | None
|
Optional list of prompts corresponding to each response. If provided, must be the same length as responses. These prompts can be referenced in the prompt_template using the {prompt} placeholder. |
None
|
**kwargs
|
Any
|
Additional keyword arguments (currently unused). |
{}
|
Returns:
Type | Description |
---|---|
dict[str, float | list[float]]
|
Score statistics containing:
|
Raises:
Type | Description |
---|---|
AssertionError
|
If prompts is provided but has different length than responses. |
Source code in aisteer360/evaluation/metrics/base_judge.py
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 |
|
LLMJudgeMetric
Bases: Metric
Base class for LLM-as-a-judge evaluation metrics.
Leverages a language model to evaluate the quality of generated text responses according to customized (natural language) criteria. The judge model evaluates each response (optionally with respect to an associated prompt and context) and returns numerical scores within a specified range. When multiple samples are generated per prompt (via num_return_sequences), scores are averaged to improve reliability.
Subclasses should define their specific evaluation criteria by providing a prompt_template
that instructs the
judge model how to score responses. The template should use placeholders {response}, {lower_bound}, and
{upper_bound} (and optionally {prompt} and {context}). Subclasses typically override __init__()
to set their
specific prompt template and scoring scale (e.g., see metrics.generic.relevance
).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_or_id
|
str | PreTrainedModel
|
HuggingFace model ID or loaded model instance to use as the judge. If string, the model will be loaded automatically. |
required |
prompt_template
|
str
|
Template string for evaluation prompts. Should contain placeholders for {response}, {lower_bound}, {upper_bound}, and optionally {prompt}, {context}. The formatted prompt will be passed to the judge model. |
required |
tokenizer
|
Any | None
|
Tokenizer for the judge model. If None, will be loaded from the model ID. Required if passing a PreTrainedModel instance. |
None
|
device
|
str | None
|
Device for model inference ('cuda', 'mps', 'cpu'). Defaults to GPU if available, otherwise CPU. |
None
|
scale
|
tuple[float, float]
|
Score range as (min, max) tuple. Scores outside this range will be clamped. Defaults to (1, 5). |
(1, 5)
|
batch_size
|
int
|
Number of prompts to process simultaneously. Defaults to 8. |
8
|
max_retries
|
int
|
Maximum retry attempts when score parsing fails. Defaults to 5. |
5
|
gen_kwargs
|
dict[str, Any] | None
|
Generation parameters passed to the model. |
None
|
Source code in aisteer360/evaluation/metrics/base_judge.py
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 |
|
base_prompt_template = prompt_template.strip()
instance-attribute
batch_size = batch_size
instance-attribute
device = device or ('cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu')
instance-attribute
extras = extras
instance-attribute
format_instructions = self.output_parser.get_format_instructions()
instance-attribute
max_retries = max_retries
instance-attribute
model = AutoModelForCausalLM.from_pretrained(model_or_id)
instance-attribute
name = self.__class__.__name__
instance-attribute
num_return_sequences = int(gen_kwargs.pop('num_return_sequences', 1))
instance-attribute
pipeline = TextGenerationPipeline(model=(self.model), tokenizer=(self.tokenizer))
instance-attribute
scale = scale
instance-attribute
tokenizer = tokenizer or AutoTokenizer.from_pretrained(model_or_id)
instance-attribute
use_chat = hasattr(self.tokenizer, 'apply_chat_template') and self.tokenizer.chat_template is not None
instance-attribute
compute(responses, prompts=None, **kwargs)
Compute LLM judge scores for a list of responses.
Evaluates each response using the configured judge model and prompt template. Scores are averaged when multiple
samples are generated per response (via num_return_sequences
).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
responses
|
list[str]
|
List of text responses to evaluate. |
required |
prompts
|
list[str] | None
|
Optional list of prompts corresponding to each response. If provided, must be the same length as responses. These prompts can be referenced in the prompt_template using the {prompt} placeholder. |
None
|
**kwargs
|
Any
|
Additional keyword arguments (currently unused). |
{}
|
Returns:
Type | Description |
---|---|
dict[str, float | list[float]]
|
Score statistics containing:
|
Raises:
Type | Description |
---|---|
AssertionError
|
If prompts is provided but has different length than responses. |
Source code in aisteer360/evaluation/metrics/base_judge.py
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 |
|
Metric
Bases: ABC
Base-class for evaluation metrics.
Provides a standardized interface for computing evaluation scores on model-generated responses. Subclasses should
define their specific scoring logic in compute()
and can accept additional configuration through constructor
arguments stored in extras
.
Source code in aisteer360/evaluation/metrics/base.py
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 |
|
extras = extras
instance-attribute
name = self.__class__.__name__
instance-attribute
compute(responses, prompts=None, **kwargs)
abstractmethod
Base compute method.
Source code in aisteer360/evaluation/metrics/base.py
21 22 23 24 25 26 27 28 29 |
|
Perplexity
Bases: Metric
Compute token-level perplexity for a batch of sentences.
Perplexity is the exponentiated mean cross-entropy between the language model’s predicted distribution and the true next token. Lower is better.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_or_id
|
str | Module
|
Hugging Face model ID or an already-instantiated causal language model. |
required |
tokenizer
|
PreTrainedTokenizer | None
|
Tokenizer to use. Leave |
None
|
batch_size
|
int
|
Number of sentences per forward pass. Higher is faster until GPU memory becomes the
bottleneck. Defaults to |
16
|
add_bos
|
bool
|
Whether to prepend the tokenizer’s BOS token so the first word in each sentence is
also scored. Ignored if the tokenizer has no BOS token. Defaults to |
True
|
max_length
|
int | None
|
If set, truncate inputs to this length so they fit the model’s context
window. |
None
|
device
|
str | None
|
|
None
|
Attributes:
Name | Type | Description |
---|---|---|
add_bos |
bool
|
Whether a BOS token is prepended before scoring. |
batch_size |
int
|
Number of sentences processed per forward pass. |
device |
str
|
The device actually selected for computation ( |
max_length |
int | None
|
Truncation length for inputs, or |
model |
PreTrainedModel
|
The loaded causal language model used to score tokens. |
tokenizer |
PreTrainedTokenizer
|
Tokenizer used for encoding, padding, and BOS handling. |
Source code in aisteer360/evaluation/metrics/generic/perplexity.py
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 |
|
add_bos = add_bos and self.tokenizer.bos_token_id is not None
instance-attribute
batch_size = batch_size
instance-attribute
device = device or ('cuda' if torch.cuda.is_available() else 'cpu')
instance-attribute
extras = extras
instance-attribute
max_length = max_length
instance-attribute
model = AutoModelForCausalLM.from_pretrained(model_or_id)
instance-attribute
name = self.__class__.__name__
instance-attribute
tokenizer = tokenizer or AutoTokenizer.from_pretrained(model_or_id)
instance-attribute
compute(responses, prompts=None)
Compute perplexity for each response (and the mean across the batch).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
responses
|
list[str]
|
Text sequences to score. |
required |
prompts
|
list[str] | None
|
Unused here; present for a uniform metric API. |
None
|
Returns:
Type | Description |
---|---|
dict[str, float]
|
dict[str, float]: A dict with keys:
|
Source code in aisteer360/evaluation/metrics/generic/perplexity.py
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 |
|
Relevance
Bases: LLMJudgeMetric
Judge relevance of a response to a prompt.
Source code in aisteer360/evaluation/metrics/generic/relevance.py
19 20 21 22 23 24 25 26 27 28 29 30 |
|
base_prompt_template = prompt_template.strip()
instance-attribute
batch_size = batch_size
instance-attribute
device = device or ('cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu')
instance-attribute
extras = extras
instance-attribute
format_instructions = self.output_parser.get_format_instructions()
instance-attribute
max_retries = max_retries
instance-attribute
model = AutoModelForCausalLM.from_pretrained(model_or_id)
instance-attribute
name = self.__class__.__name__
instance-attribute
num_return_sequences = int(gen_kwargs.pop('num_return_sequences', 1))
instance-attribute
pipeline = TextGenerationPipeline(model=(self.model), tokenizer=(self.tokenizer))
instance-attribute
scale = scale
instance-attribute
tokenizer = tokenizer or AutoTokenizer.from_pretrained(model_or_id)
instance-attribute
use_chat = hasattr(self.tokenizer, 'apply_chat_template') and self.tokenizer.chat_template is not None
instance-attribute
compute(responses, prompts=None, **kwargs)
Compute LLM judge scores for a list of responses.
Evaluates each response using the configured judge model and prompt template. Scores are averaged when multiple
samples are generated per response (via num_return_sequences
).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
responses
|
list[str]
|
List of text responses to evaluate. |
required |
prompts
|
list[str] | None
|
Optional list of prompts corresponding to each response. If provided, must be the same length as responses. These prompts can be referenced in the prompt_template using the {prompt} placeholder. |
None
|
**kwargs
|
Any
|
Additional keyword arguments (currently unused). |
{}
|
Returns:
Type | Description |
---|---|
dict[str, float | list[float]]
|
Score statistics containing:
|
Raises:
Type | Description |
---|---|
AssertionError
|
If prompts is provided but has different length than responses. |
Source code in aisteer360/evaluation/metrics/base_judge.py
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 |
|
base
Metric
Bases: ABC
Base-class for evaluation metrics.
Provides a standardized interface for computing evaluation scores on model-generated responses. Subclasses should
define their specific scoring logic in compute()
and can accept additional configuration through constructor
arguments stored in extras
.
Source code in aisteer360/evaluation/metrics/base.py
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 |
|
extras = extras
instance-attribute
name = self.__class__.__name__
instance-attribute
compute(responses, prompts=None, **kwargs)
abstractmethod
Base compute method.
Source code in aisteer360/evaluation/metrics/base.py
21 22 23 24 25 26 27 28 29 |
|
base_judge
LLMJudgeMetric
Bases: Metric
Base class for LLM-as-a-judge evaluation metrics.
Leverages a language model to evaluate the quality of generated text responses according to customized (natural language) criteria. The judge model evaluates each response (optionally with respect to an associated prompt and context) and returns numerical scores within a specified range. When multiple samples are generated per prompt (via num_return_sequences), scores are averaged to improve reliability.
Subclasses should define their specific evaluation criteria by providing a prompt_template
that instructs the
judge model how to score responses. The template should use placeholders {response}, {lower_bound}, and
{upper_bound} (and optionally {prompt} and {context}). Subclasses typically override __init__()
to set their
specific prompt template and scoring scale (e.g., see metrics.generic.relevance
).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_or_id
|
str | PreTrainedModel
|
HuggingFace model ID or loaded model instance to use as the judge. If string, the model will be loaded automatically. |
required |
prompt_template
|
str
|
Template string for evaluation prompts. Should contain placeholders for {response}, {lower_bound}, {upper_bound}, and optionally {prompt}, {context}. The formatted prompt will be passed to the judge model. |
required |
tokenizer
|
Any | None
|
Tokenizer for the judge model. If None, will be loaded from the model ID. Required if passing a PreTrainedModel instance. |
None
|
device
|
str | None
|
Device for model inference ('cuda', 'mps', 'cpu'). Defaults to GPU if available, otherwise CPU. |
None
|
scale
|
tuple[float, float]
|
Score range as (min, max) tuple. Scores outside this range will be clamped. Defaults to (1, 5). |
(1, 5)
|
batch_size
|
int
|
Number of prompts to process simultaneously. Defaults to 8. |
8
|
max_retries
|
int
|
Maximum retry attempts when score parsing fails. Defaults to 5. |
5
|
gen_kwargs
|
dict[str, Any] | None
|
Generation parameters passed to the model. |
None
|
Source code in aisteer360/evaluation/metrics/base_judge.py
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 |
|
base_prompt_template = prompt_template.strip()
instance-attribute
batch_size = batch_size
instance-attribute
device = device or ('cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu')
instance-attribute
extras = extras
instance-attribute
format_instructions = self.output_parser.get_format_instructions()
instance-attribute
max_retries = max_retries
instance-attribute
model = AutoModelForCausalLM.from_pretrained(model_or_id)
instance-attribute
name = self.__class__.__name__
instance-attribute
num_return_sequences = int(gen_kwargs.pop('num_return_sequences', 1))
instance-attribute
pipeline = TextGenerationPipeline(model=(self.model), tokenizer=(self.tokenizer))
instance-attribute
scale = scale
instance-attribute
tokenizer = tokenizer or AutoTokenizer.from_pretrained(model_or_id)
instance-attribute
use_chat = hasattr(self.tokenizer, 'apply_chat_template') and self.tokenizer.chat_template is not None
instance-attribute
compute(responses, prompts=None, **kwargs)
Compute LLM judge scores for a list of responses.
Evaluates each response using the configured judge model and prompt template. Scores are averaged when multiple
samples are generated per response (via num_return_sequences
).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
responses
|
list[str]
|
List of text responses to evaluate. |
required |
prompts
|
list[str] | None
|
Optional list of prompts corresponding to each response. If provided, must be the same length as responses. These prompts can be referenced in the prompt_template using the {prompt} placeholder. |
None
|
**kwargs
|
Any
|
Additional keyword arguments (currently unused). |
{}
|
Returns:
Type | Description |
---|---|
dict[str, float | list[float]]
|
Score statistics containing:
|
Raises:
Type | Description |
---|---|
AssertionError
|
If prompts is provided but has different length than responses. |
Source code in aisteer360/evaluation/metrics/base_judge.py
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 |
|
build_structured_parser(scale)
Build a StructuredOutputParser and parsing function for rating predictions.
Constructs a StructuredOutputParser
configured with a single ResponseSchema
that expects a float score within
the specified scale range. It also returns a parsing function that extracts and validates the score from text,
ensuring the result is clamped between the provided bounds.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scale
|
tuple[float, float]
|
A |
required |
Source code in aisteer360/evaluation/metrics/base_judge.py
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 |
|
custom
Custom metrics for specific evaluation use cases.
This module contains metrics tailored to particular use cases, organized by subdirectory. Unlike generic metrics that work across any use case, custom metrics are designed with specific evaluation contexts in mind (e.g., question answering, instruction following, etc.).
commonsense_mcqa
Evaluation metrics for the CommonsenseMCQA
use case.
mcqa_accuracy
MCQAAccuracy
Bases: Metric
Exact-match accuracy for multiple-choice QA.
Source code in aisteer360/evaluation/metrics/custom/commonsense_mcqa/mcqa_accuracy.py
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 |
|
extras = extras
instance-attribute
name = self.__class__.__name__
instance-attribute
compute(responses, prompts=None, reference_answers=None, question_ids=None, **kwargs)
Computes trial-level and question-level accuracy metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
responses
|
list[str]
|
List of predicted answer choices (e.g., 'A', 'B', 'C', 'D'). |
required |
prompts
|
list[str] | None
|
List of question prompts (unused, for interface compatibility). |
None
|
reference_answers
|
list[str] | None
|
List of correct answer choices. |
None
|
question_ids
|
list[str] | None
|
Optional question IDs for grouping responses by question. |
None
|
**kwargs
|
Additional arguments (unused). |
{}
|
Returns:
Type | Description |
---|---|
dict[str, float]
|
Dictionary of accuracy score statistics with values:
|
Raises:
Type | Description |
---|---|
ValueError
|
If reference_answers is None or length mismatches occur. |
Source code in aisteer360/evaluation/metrics/custom/commonsense_mcqa/mcqa_accuracy.py
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 |
|
mcqa_calibration
MCQACalibration
Bases: Metric
Calibration metrics for multiple-choice QA.
Measures how well model confidence scores align with actual performance using Expected Calibration Error (ECE) and related metrics.
Source code in aisteer360/evaluation/metrics/custom/commonsense_mcqa/mcqa_calibration.py
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 |
|
extras = extras
instance-attribute
n_bins = n_bins
instance-attribute
name = self.__class__.__name__
instance-attribute
compute(responses, reference_answers=None, confidence_scores=None, question_ids=None, **kwargs)
Computes calibration metrics for model predictions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
responses
|
list[str]
|
List of predicted answer choices (e.g., 'A', 'B', 'C', 'D'). |
required |
reference_answers
|
list[str]
|
List of correct answer choices. |
None
|
confidence_scores
|
list[float]
|
List of model confidence scores (0.0 to 1.0). |
None
|
question_ids
|
list[str] | None
|
Optional question IDs (unused, for interface compatibility). |
None
|
**kwargs
|
Additional arguments (unused). |
{}
|
Returns:
Type | Description |
---|---|
dict[str, float]
|
Dictionary of calibration metrics with values:
|
Raises:
Type | Description |
---|---|
ValueError
|
If reference_answers or confidence_scores is None. |
Source code in aisteer360/evaluation/metrics/custom/commonsense_mcqa/mcqa_calibration.py
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 |
|
mcqa_positional_bias
MCQAPositionalBias
Bases: Metric
Positional bias metrics for multiple-choice QA.
Measures whether the model exhibits bias toward selecting certain answer positions.
Source code in aisteer360/evaluation/metrics/custom/commonsense_mcqa/mcqa_positional_bias.py
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 |
|
extras = extras
instance-attribute
name = self.__class__.__name__
instance-attribute
compute(responses, prompts=None, question_ids=None, **kwargs)
Computes positional bias metrics for model predictions.
Calculates how much the model's choice frequencies deviate from uniform distribution across answer positions. For K answer choices, each position should ideally be selected 1/K of the time.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
responses
|
list[str]
|
List of predicted answer choices (e.g., 'A', 'B', 'C', 'D'). |
required |
prompts
|
list[str] | None
|
List of question prompts (unused, for interface compatibility). |
None
|
question_ids
|
list[str] | None
|
Optional question IDs for computing per-question bias variance. |
None
|
**kwargs
|
Additional arguments (unused). |
{}
|
Returns:
Type | Description |
---|---|
dict[str, float]
|
Dictionary of positional bias metrics with values:
|
Note:
- If question_ids is None, per-question analysis is skipped and std will be 0.0.
Source code in aisteer360/evaluation/metrics/custom/commonsense_mcqa/mcqa_positional_bias.py
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 |
|
instruction_following
Evaluation metrics for the InstructionFollowing
use case.
helpers
We have omitted the documentation details on the IFEval functions (located in helpers/
) from our API reference. For details please see the
IFEval repo: https://github.com/google-research/google-research/tree/master/instruction_following_eval.
evaluation_main
Binary of evaluating instruction following. See README.md.
InputExample
dataclass
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/evaluation_main.py
46 47 48 49 50 51 |
|
instruction_id_list
instance-attribute
key
instance-attribute
kwargs
instance-attribute
prompt
instance-attribute
OutputExample
dataclass
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/evaluation_main.py
54 55 56 57 58 59 60 |
|
follow_all_instructions
instance-attribute
follow_instruction_list
instance-attribute
instruction_id_list
instance-attribute
prompt
instance-attribute
response
instance-attribute
main(argv)
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/evaluation_main.py
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 |
|
print_report(outputs)
Prints a report on accuracy scores.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/evaluation_main.py
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 |
|
read_prompt_list(input_jsonl)
Read inputs from jsonl.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/evaluation_main.py
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 |
|
read_prompt_to_response_dict(input_jsonl)
Creates dictionary matching prompt and response.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/evaluation_main.py
194 195 196 197 198 199 200 201 202 203 204 205 206 207 |
|
test_instruction_following_loose(inp, prompt_to_response)
Tests response for an upper bound for following instructions.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/evaluation_main.py
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 |
|
test_instruction_following_strict(inp, prompt_to_response)
Tests response to see if instrutions are followed.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/evaluation_main.py
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 |
|
write_outputs(output_jsonl_filename, outputs)
Writes outputs to jsonl.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/evaluation_main.py
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
|
instructions
Library of instructions.
BulletListChecker
Bases: Instruction
Checks the bullet list in the prompt.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
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 |
|
id = instruction_id
instance-attribute
build_description(*, num_bullets=None)
Build the instruction description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
num_bullets
|
An integer specifying the exact number of bullet lists that is required to appear in the response. |
None
|
Returns:
Type | Description |
---|---|
A string representing the instruction description. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 |
|
check_following(value)
Check if the number of bullet lists meets the requirement.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
A string representing the response. The response is expected to
contain some bullet lists that start with |
required |
Returns:
Type | Description |
---|---|
True if the actual number of bullet lists in the response meets the |
|
requirement. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 |
|
get_instruction_args()
Returns the keyward args of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
305 306 307 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
309 310 311 |
|
CapitalLettersEnglishChecker
Bases: Instruction
Checks that the response is in english and is in all capital letters.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 |
|
id = instruction_id
instance-attribute
build_description()
Build the instruction description.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1398 1399 1400 1401 1402 1403 |
|
check_following(value)
Checks that the response is in English and in all capital letters.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 |
|
get_instruction_args()
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1405 1406 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1408 1409 1410 |
|
CapitalWordFrequencyChecker
Bases: Instruction
Checks frequency of words with all capital letters.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 |
|
id = instruction_id
instance-attribute
build_description(capital_frequency=None, capital_relation=None)
Build the instruction description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
capital_frequency
|
An integer that represents the number of words that should be in all capital letters. |
None
|
|
capital_relation
|
A string that is 'at least' or 'at most' that refers to the frequency. |
None
|
Returns:
Type | Description |
---|---|
A string representing the instruction description. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 |
|
check_following(value)
Checks the frequency of words with all capital letters.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 |
|
get_instruction_args()
Returns the keyword args of build description.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1521 1522 1523 1524 1525 1526 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1528 1529 1530 |
|
CommaChecker
Bases: Instruction
Checks the response for no commas.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 |
|
id = instruction_id
instance-attribute
build_description()
Build the instruction description.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1461 1462 1463 1464 1465 1466 |
|
check_following(value)
Checks that the response does not contain commas.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1475 1476 1477 |
|
get_instruction_args()
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1468 1469 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1471 1472 1473 |
|
ConstrainedResponseChecker
Bases: Instruction
Checks the constrained response.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
330 331 332 333 334 335 336 337 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 |
|
id = instruction_id
instance-attribute
build_description()
Build the instruction description.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
333 334 335 336 337 338 339 340 |
|
check_following(value)
Checks if the response matches the constrained options.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
A string representing the response. |
required |
Returns:
Type | Description |
---|---|
True if the actual response contains one of the options in the constrained |
|
responses; otherwise False. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 |
|
get_instruction_args()
Returns the keyward args of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
342 343 344 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
346 347 348 |
|
ConstrainedStartChecker
Bases: Instruction
Checks the response start.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
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 397 398 399 400 401 402 403 404 405 406 407 408 409 |
|
id = instruction_id
instance-attribute
build_description(*, starter=None)
Build the instruction description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
starter
|
A string representing the keyward that the response should start with. |
None
|
Returns:
Type | Description |
---|---|
A string representing the instruction description. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 |
|
check_following(value)
Checks if the response starts with the constrained keyword or phrase.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
A string representing the response. |
required |
Returns:
Type | Description |
---|---|
True if the response starts with the given phrase or keyword that is |
|
contained in |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
396 397 398 399 400 401 402 403 404 405 406 407 408 409 |
|
get_instruction_args()
Returns the keyward args of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
388 389 390 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
392 393 394 |
|
EndChecker
Bases: Instruction
Checks that the prompt ends with a given phrase.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 |
|
id = instruction_id
instance-attribute
build_description(*, end_phrase=None)
Build the instruction description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
end_phrase
|
A string representing the phrase the response should end with. |
None
|
Returns:
Type | Description |
---|---|
A string representing the instruction description. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 |
|
check_following(value)
Checks if the response ends with the expected phrase.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1280 1281 1282 1283 1284 |
|
get_instruction_args()
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1273 1274 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1276 1277 1278 |
|
ForbiddenWords
Bases: Instruction
Checks that specified words are not used in response.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 |
|
id = instruction_id
instance-attribute
build_description(forbidden_words=None)
Build the instruction description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
forbidden_words
|
A sequences of strings respresenting words that are not allowed in the response. |
None
|
Returns:
Type | Description |
---|---|
A string representing the instruction description. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 |
|
check_following(value)
Check if the response does not contain the expected keywords.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1108 1109 1110 1111 1112 1113 |
|
get_instruction_args()
Returns the keyward args of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1100 1101 1102 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1104 1105 1106 |
|
HighlightSectionChecker
Bases: Instruction
Checks the highlighted section.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 |
|
id = instruction_id
instance-attribute
build_description(*, num_highlights=None)
Build the instruction description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
num_highlights
|
An integer specifying the minimum number of highlighted sections. |
None
|
Returns:
Type | Description |
---|---|
A string representing the instruction description. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 |
|
check_following(value)
Checks if the number of highlighted sections meets the requirement.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
a string repesenting the response. The response is expected to contain highlighted sections in the format of highlighted. |
required |
Returns:
Type | Description |
---|---|
True if the actual number of highlighted sections in the format of |
|
highlighed sections meets the minimum requirement; otherwise False. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 |
|
get_instruction_args()
Returns the keyward args of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
435 436 437 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
439 440 441 |
|
Instruction
An instruction template.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
|
id = instruction_id
instance-attribute
build_description(**kwargs)
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
101 102 |
|
check_following(value)
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
110 111 |
|
get_instruction_args()
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
104 105 |
|
get_instruction_args_keys()
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
107 108 |
|
JsonFormat
Bases: Instruction
Check the Json format.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 |
|
id = instruction_id
instance-attribute
build_description()
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
877 878 879 880 881 882 |
|
check_following(value)
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 |
|
get_instruction_args()
Returns the keyward args of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
884 885 886 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
888 889 890 |
|
KeySentenceChecker
Bases: Instruction
Check the existence of certain key sentences.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 |
|
id = instruction_id
instance-attribute
build_description(key_sentences=None, num_sentences=None)
Build the instruction description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key_sentences
|
A sequences of strings representing the key sentences that are expected in the response. |
None
|
|
num_sentences
|
The number of key sentences that are expected to be seen in the response. |
None
|
Returns:
Type | Description |
---|---|
A string representing the instruction description. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 |
|
check_following(value)
Checks if the response contains the expected key sentences.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1060 1061 1062 1063 1064 1065 1066 1067 1068 |
|
get_instruction_args()
Returns the keyward args of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1051 1052 1053 1054 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1056 1057 1058 |
|
KeywordChecker
Bases: Instruction
Check the exisitence of certain keywords.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 |
|
id = instruction_id
instance-attribute
build_description(*, keywords=None)
Build the instruction description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
keywords
|
A sequence of strings representing the keywords that are expected in the response. |
None
|
Returns:
Type | Description |
---|---|
A string representing the instruction description. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 |
|
check_following(value)
Check if the response contain the expected keywords.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
738 739 740 741 742 743 |
|
get_instruction_args()
Returns the keyward args of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
730 731 732 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
734 735 736 |
|
KeywordFrequencyChecker
Bases: Instruction
Check the keyword frequency.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 |
|
id = instruction_id
instance-attribute
build_description(*, keyword=None, frequency=None, relation=None)
Build the instruction description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
keyword
|
A string representing a keyword that is expected in the response. |
None
|
|
frequency
|
An integer specifying the number of times |
None
|
|
relation
|
A string in ( |
None
|
Returns:
Type | Description |
---|---|
A string representing the instruction description. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 |
|
check_following(value)
Checks if the response contain the keyword with required frequency.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
803 804 805 806 807 808 809 810 811 |
|
get_instruction_args()
Returns the keyward args of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
793 794 795 796 797 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
799 800 801 |
|
LetterFrequencyChecker
Bases: Instruction
Checks letter frequency.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 |
|
id = instruction_id
instance-attribute
build_description(*, letter=None, let_frequency=None, let_relation=None)
Build the instruction description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
letter
|
A string representing a letter that is expected in the response. |
None
|
|
let_frequency
|
An integer specifying the number of times |
None
|
|
let_relation
|
A string in ( |
None
|
Returns:
Type | Description |
---|---|
A string representing the instruction description. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 |
|
check_following(value)
Checks that the response contains the letter at the right frequency.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1384 1385 1386 1387 1388 1389 1390 1391 1392 |
|
get_instruction_args()
Returns the keyword args of build description.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1374 1375 1376 1377 1378 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1380 1381 1382 |
|
LowercaseLettersEnglishChecker
Bases: Instruction
Checks that the response is in english and is in all lowercase letters.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 |
|
id = instruction_id
instance-attribute
build_description()
Build the instruction description.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1429 1430 1431 1432 1433 1434 1435 |
|
check_following(value)
Checks that the response is in English and in all lowercase letters.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 |
|
get_instruction_args()
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1437 1438 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1440 1441 1442 |
|
NumberOfSentences
Bases: Instruction
Check the number of sentences.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
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 |
|
id = instruction_id
instance-attribute
build_description(*, num_sentences=None, relation=None)
Build the instruction description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
num_sentences
|
An integer specifying the number of sentences as a threshold. |
None
|
|
relation
|
A string in ( |
None
|
Returns:
Type | Description |
---|---|
A string representing the instruction description. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
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 |
|
check_following(value)
Check if the number of sentences follows the instruction.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
A string representing the response. |
required |
Returns:
Type | Description |
---|---|
True if the response follows the instruction. |
Raise
ValueError if the string in instruction_args
is not in
[less_than
, at_least
].
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
|
get_instruction_args()
Returns the keyward args of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
207 208 209 210 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
212 213 214 |
|
NumberOfWords
Bases: Instruction
Checks the number of words.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 |
|
id = instruction_id
instance-attribute
build_description(*, num_words=None, relation=None)
Build the instruction description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
num_words
|
An integer specifying the number of words contained in the response. |
None
|
|
relation
|
A string in ( |
None
|
Returns:
Type | Description |
---|---|
A string representing the instruction description. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 |
|
check_following(value)
Checks if the response contains the expected number of words.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
864 865 866 867 868 869 870 871 |
|
get_instruction_args()
Returns the keyward args of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
855 856 857 858 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
860 861 862 |
|
ParagraphChecker
Bases: Instruction
Checks the paragraphs.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 |
|
id = instruction_id
instance-attribute
build_description(*, num_paragraphs=None)
Build the instruction description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
num_paragraphs
|
An integer specifying the number of paragraphs. |
None
|
Returns:
Type | Description |
---|---|
A string representing the instruction description. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 |
|
check_following(value)
Checks the response contains required number of paragraphs.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
A string representing the response. The response may contain
paragraphs that are separated by the markdown divider: |
required |
Returns:
Type | Description |
---|---|
True if the actual number of paragraphs is the same as required; |
|
otherwise, False. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 |
|
get_instruction_args()
Returns the keyward args of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
553 554 555 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
557 558 559 |
|
ParagraphFirstWordCheck
Bases: Instruction
Check the paragraph and the first word of the nth paragraph.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 |
|
id = instruction_id
instance-attribute
build_description(num_paragraphs=None, nth_paragraph=None, first_word=None)
Build the instruction description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
num_paragraphs
|
An integer indicating the number of paragraphs expected in the response. A paragraph is a subset of the string that is expected to be separated by '\n\n'. |
None
|
|
nth_paragraph
|
An integer indicating the paragraph number that we look at. Note that n starts from 1. |
None
|
|
first_word
|
A string that represent the first word of the bth paragraph. |
None
|
Returns:
Type | Description |
---|---|
A string representing the instruction description. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 |
|
check_following(value)
Checks for required number of paragraphs and correct first word.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
a string representing the response. The response may contain paragraphs that are separated by two new lines and the first word of the nth paragraph will have to match a specified word. |
required |
Returns:
Type | Description |
---|---|
True if the number of paragraphs is the same as required and the first |
|
word of the specified paragraph is the same as required. Otherwise, false. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 |
|
get_instruction_args()
Returns the keyward args of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
956 957 958 959 960 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
962 963 964 |
|
PlaceholderChecker
Bases: Instruction
Check the placeholders in template writing.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
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 |
|
id = instruction_id
instance-attribute
build_description(*, num_placeholders=None)
Build the instruction description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
num_placeholders
|
An integer denoting the minimum number of placeholders required in the response. |
None
|
Returns:
Type | Description |
---|---|
A string representing the instruction description. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 |
|
check_following(value)
Check if the number of placeholders follows the instruction.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
A string representing the response. |
required |
Returns:
Type | Description |
---|---|
True if the actual number of placeholders in the response is greater than |
|
or equal to |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
266 267 268 269 270 271 272 273 274 275 276 277 278 |
|
get_instruction_args()
Returns the keyward args of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
258 259 260 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
262 263 264 |
|
PostscriptChecker
Bases: Instruction
Checks the postscript.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 |
|
id = instruction_id
instance-attribute
build_description(*, postscript_marker=None)
Build the instruction description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
postscript_marker
|
A string containing the keyword that marks the start of the postscript section. |
None
|
Returns:
Type | Description |
---|---|
A string representing the instruction description. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 |
|
check_following(value)
Checks if the response follows the postscript format.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
a string representing the response. The response is expected to contain a postscript section. |
required |
Returns:
Type | Description |
---|---|
True if the response contains a postscript section starting with |
|
the keyword containing in the |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 |
|
get_instruction_args()
Returns the keyward args of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
610 611 612 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
614 615 616 |
|
QuotationChecker
Bases: Instruction
Checks response is wrapped with double quotation marks.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 |
|
id = instruction_id
instance-attribute
build_description()
Build the instruction description.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1549 1550 1551 1552 1553 1554 |
|
check_following(value)
Checks if the response is wrapped with double quotation marks.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1564 1565 1566 1567 |
|
get_instruction_args()
Returns the keyword args of build description.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1556 1557 1558 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1560 1561 1562 |
|
RepeatPromptThenAnswer
Bases: Instruction
Checks that Prompt is first repeated then answered.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 |
|
id = instruction_id
instance-attribute
build_description(*, prompt_to_repeat=None)
Build the instruction description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prompt_to_repeat
|
The prompt that is meant to be repeated. |
None
|
Returns:
Type | Description |
---|---|
A string representing the instruction description. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 |
|
check_following(value)
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1245 1246 1247 1248 |
|
get_instruction_args()
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1238 1239 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1241 1242 1243 |
|
RephraseChecker
Bases: Instruction
Checks the repharse.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 |
|
id = instruction_id
instance-attribute
build_description(*, original_message)
Build the instruction description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
original_message
|
A string representing the original message. The rephrased response should only change its words/sentences in between its two asterisks, for example, change me. Both original and rephrased messages should contain the changes in the form of change me. |
required |
Returns:
Type | Description |
---|---|
A string representing the instruction description. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 |
|
check_following(value)
Checks if the rephrasing follows the instruction.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
A string representing the response, which is expected to rephras
the string of |
required |
Returns:
Type | Description |
---|---|
True if |
|
in between two asterisks such as change me; otherwise, False. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 |
|
get_instruction_args()
Returns the keyward args of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
665 666 667 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
669 670 671 |
|
is_change(response)
Check if there is change in the response in the form of change me.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
695 696 697 |
|
strip_changes(response)
Strips off the changes.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
699 700 701 |
|
RephraseParagraph
Bases: Instruction
Checks that the paragraph is rephrased.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 |
|
id = instruction_id
instance-attribute
build_description(*, original_paragraph, low, high)
Builds the instruction description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
original_paragraph
|
A string presenting the original paragraph. The rephrases response should have betweeb low-high words in generic. |
required | |
low
|
An integer presenting the lower bound of similar words. |
required | |
high
|
An integer representing the upper bound of similar words. |
required |
Returns:
Type | Description |
---|---|
A string representing the instruction description. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 |
|
check_following(value)
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 |
|
get_instruction_args()
Returns the keyward args of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1148 1149 1150 1151 1152 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1154 1155 1156 |
|
ResponseLanguageChecker
Bases: Instruction
Check the language of the entire response.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
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 |
|
id = instruction_id
instance-attribute
build_description(*, language=None)
Build the instruction description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
language
|
A string representing the expected language of the response. The
language has to comply to the 97 types defined in
|
None
|
Returns:
Type | Description |
---|---|
A string representing the instruction description. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 |
|
check_following(value)
Check if the language of the entire response follows the instruction.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
A string representing the response. |
required |
Returns:
Type | Description |
---|---|
True if the language of |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 |
|
get_instruction_args()
Returns the keyward args of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
139 140 141 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
143 144 145 |
|
SectionChecker
Bases: Instruction
Checks the sections.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 |
|
id = instruction_id
instance-attribute
build_description(*, section_spliter=None, num_sections=None)
Build the instruction description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
section_spliter
|
A string represents the section spliter keyword that
marks a new section, i.e., |
None
|
|
num_sections
|
An integer specifying the number of sections. |
None
|
Returns:
Type | Description |
---|---|
A string representing the instruction description. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 |
|
check_following(value)
Checks the response contains multiple sections.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
A string representing the response. The response is expected
to contain multiple sections (number of sections is greater than 1).
A new section starts with |
required |
Returns:
Type | Description |
---|---|
True if the number of sections in the response is greater than or equal to |
|
the minimum number of sections; otherwise, False. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 |
|
get_instruction_args()
Returns the keyward args of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
503 504 505 506 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
508 509 510 |
|
TitleChecker
Bases: Instruction
Checks the response for a title.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 |
|
id = instruction_id
instance-attribute
build_description()
Build the instruction description.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1290 1291 1292 1293 1294 1295 1296 |
|
check_following(value)
Checks if the response contains a title.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 |
|
get_instruction_args()
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1298 1299 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1301 1302 1303 |
|
TwoResponsesChecker
Bases: Instruction
Check that two responses were given.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 |
|
id = instruction_id
instance-attribute
build_description()
Build the instruction description.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1175 1176 1177 1178 1179 1180 1181 |
|
check_following(value)
Checks if the response has two different answers.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
A string representing the response. |
required |
Returns:
Type | Description |
---|---|
True if two responses are detected and false otherwise. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 |
|
get_instruction_args()
Returns the keyward args of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1183 1184 1185 |
|
get_instruction_args_keys()
Returns the args keys of build_description
.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions.py
1187 1188 1189 |
|
instructions_registry
Registry of all instructions.
INSTRUCTION_CONFLICTS = {_KEYWORD + 'existence': {_KEYWORD + 'existence'}, _KEYWORD + 'frequency': {_KEYWORD + 'frequency'}, _KEYWORD + 'forbidden_words': {_KEYWORD + 'forbidden_words'}, _KEYWORD + 'letter_frequency': {_KEYWORD + 'letter_frequency'}, _LANGUAGE + 'response_language': {_LANGUAGE + 'response_language', _FORMAT + 'multiple_sections', _KEYWORD + 'existence', _KEYWORD + 'frequency', _KEYWORD + 'forbidden_words', _STARTEND + 'end_checker', _CHANGE_CASES + 'english_capital', _CHANGE_CASES + 'english_lowercase'}, _LENGTH + 'number_sentences': {_LENGTH + 'number_sentences'}, _LENGTH + 'number_paragraphs': {_LENGTH + 'number_paragraphs', _LENGTH + 'nth_paragraph_first_word', _LENGTH + 'number_sentences', _LENGTH + 'nth_paragraph_first_word'}, _LENGTH + 'number_words': {_LENGTH + 'number_words'}, _LENGTH + 'nth_paragraph_first_word': {_LENGTH + 'nth_paragraph_first_word', _LENGTH + 'number_paragraphs'}, _CONTENT + 'number_placeholders': {_CONTENT + 'number_placeholders'}, _CONTENT + 'postscript': {_CONTENT + 'postscript'}, _FORMAT + 'number_bullet_lists': {_FORMAT + 'number_bullet_lists'}, _FORMAT + 'constrained_response': set(INSTRUCTION_DICT.keys()), _FORMAT + 'number_highlighted_sections': {_FORMAT + 'number_highlighted_sections'}, _FORMAT + 'multiple_sections': {_FORMAT + 'multiple_sections', _LANGUAGE + 'response_language', _FORMAT + 'number_highlighted_sections'}, _FORMAT + 'json_format': set(INSTRUCTION_DICT.keys()).difference({_KEYWORD + 'forbidden_words', _KEYWORD + 'existence'}), _FORMAT + 'title': {_FORMAT + 'title'}, _COMBINATION + 'two_responses': set(INSTRUCTION_DICT.keys()).difference({_KEYWORD + 'forbidden_words', _KEYWORD + 'existence', _LANGUAGE + 'response_language', _FORMAT + 'title', _PUNCTUATION + 'no_comma'}), _COMBINATION + 'repeat_prompt': set(INSTRUCTION_DICT.keys()).difference({_KEYWORD + 'existence', _FORMAT + 'title', _PUNCTUATION + 'no_comma'}), _STARTEND + 'end_checker': {_STARTEND + 'end_checker'}, _CHANGE_CASES + 'capital_word_frequency': {_CHANGE_CASES + 'capital_word_frequency', _CHANGE_CASES + 'english_lowercase', _CHANGE_CASES + 'english_capital'}, _CHANGE_CASES + 'english_capital': {_CHANGE_CASES + 'english_capital'}, _CHANGE_CASES + 'english_lowercase': {_CHANGE_CASES + 'english_lowercase', _CHANGE_CASES + 'english_capital'}, _PUNCTUATION + 'no_comma': {_PUNCTUATION + 'no_comma'}, _STARTEND + 'quotation': {_STARTEND + 'quotation', _FORMAT + 'title'}}
module-attribute
INSTRUCTION_DICT = {_KEYWORD + 'existence': instructions.KeywordChecker, _KEYWORD + 'frequency': instructions.KeywordFrequencyChecker, _KEYWORD + 'forbidden_words': instructions.ForbiddenWords, _KEYWORD + 'letter_frequency': instructions.LetterFrequencyChecker, _LANGUAGE + 'response_language': instructions.ResponseLanguageChecker, _LENGTH + 'number_sentences': instructions.NumberOfSentences, _LENGTH + 'number_paragraphs': instructions.ParagraphChecker, _LENGTH + 'number_words': instructions.NumberOfWords, _LENGTH + 'nth_paragraph_first_word': instructions.ParagraphFirstWordCheck, _CONTENT + 'number_placeholders': instructions.PlaceholderChecker, _CONTENT + 'postscript': instructions.PostscriptChecker, _FORMAT + 'number_bullet_lists': instructions.BulletListChecker, _FORMAT + 'constrained_response': instructions.ConstrainedResponseChecker, _FORMAT + 'number_highlighted_sections': instructions.HighlightSectionChecker, _FORMAT + 'multiple_sections': instructions.SectionChecker, _FORMAT + 'json_format': instructions.JsonFormat, _FORMAT + 'title': instructions.TitleChecker, _COMBINATION + 'two_responses': instructions.TwoResponsesChecker, _COMBINATION + 'repeat_prompt': instructions.RepeatPromptThenAnswer, _STARTEND + 'end_checker': instructions.EndChecker, _CHANGE_CASES + 'capital_word_frequency': instructions.CapitalWordFrequencyChecker, _CHANGE_CASES + 'english_capital': instructions.CapitalLettersEnglishChecker, _CHANGE_CASES + 'english_lowercase': instructions.LowercaseLettersEnglishChecker, _PUNCTUATION + 'no_comma': instructions.CommaChecker, _STARTEND + 'quotation': instructions.QuotationChecker}
module-attribute
conflict_make(conflicts)
Makes sure if A conflicts with B, B will conflict with A.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
conflicts
|
Dictionary of potential conflicts where key is instruction id and value is set of instruction ids that it conflicts with. |
required |
Returns:
Type | Description |
---|---|
Revised version of the dictionary. All instructions conflict with |
|
themselves. If A conflicts with B, B will conflict with A. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_registry.py
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 |
|
instructions_test
Tests for instructions.py.
InstructionsTest
Bases: TestCase
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
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 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 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 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 |
|
BULLET_TEST_MESSAGE_1 = '\n A Markdown bullet point is a way of formatting text to create a list. To\n create a bullet point, start each line with an asterisk (*). For example:\n * This is a bullet point.\n *(no space required)Another bullet point.\n * (no newline ending required)Another bullet point.\n markdown bullet points are often used to create to-do lists or to list items\n in a step-by-step guide.'
class-attribute
instance-attribute
BULLET_TEST_MESSAGE_2 = '\n Check that inline asterisk (*), *, will not be counted. Only * that starts a\n bullet list will be counted:\n * This is a bullet point.\n * Another bullet point.\n . dot is not counted'
class-attribute
instance-attribute
BULLET_TEST_MESSAGE_3 = '\n Here are three bullets starting with asterisk:\n * I am a large language model, also known as a conversational AI.\n * I am trained on a massive amount of text data, and I am able to communicate.\n * I am still under development, but I am learning new things every day.'
class-attribute
instance-attribute
BULLET_TEST_MESSAGE_4 = '\n Here are three markdown bullets:\n - I am a large language model, also known as a conversational AI.\n - I am trained on a massive amount of text data, and I am able to communicate.\n -I am still under development, but I am learning new things every day.'
class-attribute
instance-attribute
BULLET_TEST_MESSAGE_5 = '\n Paragraph 1\n ***\n Paragraph 2\n ***\n Paragraph 3\n * only one bullet point\n '
class-attribute
instance-attribute
CONSTRAINED_RESPONSE_TEST_RESPONSE_1 = '\n My answer is no.\n'
class-attribute
instance-attribute
CONSTRAINED_RESPONSE_TEST_RESPONSE_2 = 'My answer is no. '
class-attribute
instance-attribute
CONSTRAINED_RESPONSE_TEST_RESPONSE_3 = '\n My answer is no. I am still under development and I am always learning and\n improving. I am not the best chatbot in the world, but I am striving to be\n the best that I can be.'
class-attribute
instance-attribute
CONSTRAINED_START_TEST_MESSAGE_1 = '\n My response is: ASIC is a specialized chip for specific tasks in electronic\n devices, offering advantages in efficiency and processing speed.'
class-attribute
instance-attribute
CONSTRAINED_START_TEST_MESSAGE_2 = '\n My response is: ASIC is a specialized chip for specific tasks in\n electronic\n devices, offering advantages in efficiency and processing speed.'
class-attribute
instance-attribute
CONSTRAINED_START_TEST_MESSAGE_3 = '\n An ASIC, or Application-Specific Integrated Circuit, is a type of specialized\n chip that, my response is, is designed to perform specific tasks in electronic\n devices.'
class-attribute
instance-attribute
END_PHRASE_1 = '\n Any more questions?\n '
class-attribute
instance-attribute
END_PHRASE_2 = '\n This is the end.\n '
class-attribute
instance-attribute
END_PHRASE_3 = '\n This will fail.\n '
class-attribute
instance-attribute
FORBIDDEN_WORDS_1 = ('HOUSE', 'POWER', 'BECOME')
class-attribute
instance-attribute
FORBIDDEN_WORDS_2 = ('GOOGLE', 'TEXT')
class-attribute
instance-attribute
FORBIDDEN_WORDS_3 = ('GENE', 'TRANSFORM')
class-attribute
instance-attribute
HIGHLIGHTED_TEST_MESSAGE_1 = '\n To highlight text with Markdown, you can use the * character before and after\n the text you want to highlight. For example, if you want to highlight the\n word `hello`, you would type:*hello*, You can also use the ** character to\n create bold text. For example, if you want to bold the word `hello`, you\n would type: **hello** '
class-attribute
instance-attribute
HIGHLIGHTED_TEST_MESSAGE_2 = '\n Sure, here are the numerical methods for solving partial differential\n equations highlighted with Markdown:\n *Finite difference methods\n *Finite element methods*\n *Boundary element methods\n *Monte Carlo methods\n I hope this helps!'
class-attribute
instance-attribute
HIGHLIGHTED_TEST_MESSAGE_3 = '\n There is allowed to be *two different* highlighted *sections in the same*\n line. **This is also true** for **double markdown highlights.**\n '
class-attribute
instance-attribute
INSTRUCTION_DICT = {'language:response_language': instructions.ResponseLanguageChecker, 'length_constraints:number_sentences': instructions.NumberOfSentences, 'length_constraints:number_paragraphs': instructions.ParagraphChecker, 'length_constraints:number_words': instructions.NumberOfWords, 'detectable_content:number_placeholders': instructions.PlaceholderChecker, 'detectable_content:postscript': instructions.PostscriptChecker, 'detectable_format:number_bullet_lists': instructions.BulletListChecker, 'detectable_format:constrained_response': instructions.ConstrainedResponseChecker, 'detectable_format:number_highlighted_sections': instructions.HighlightSectionChecker, 'detectable_format:multiple_sections': instructions.SectionChecker, 'detectable_format:json_format': instructions.JsonFormat}
class-attribute
instance-attribute
KEYWORDS = ('romantic', 'river', 'Mona Lisa')
class-attribute
instance-attribute
PARAGRAPH_FIRST_WORD_TEST_1 = '\n paragraph 1\n\n I paragraph 2\n\n paragraph 3'
class-attribute
instance-attribute
PARAGRAPH_FIRST_WORD_TEST_2 = '\n paragraph 1\n\n I paragraph 2'
class-attribute
instance-attribute
PARAGRAPH_FIRST_WORD_TEST_3 = '\n paragraph 1\n\n fail paragraph 2\n\n paragraph 3'
class-attribute
instance-attribute
PARAGRAPH_FIRST_WORD_TEST_4 = "\n Wow this is a very long response.\n\n I can't believe there is more than three paragraphs.\n\n Really more than three? No way!\n\n I can't believe it but I guess I am living proof.\n\n Haha, you go that right."
class-attribute
instance-attribute
PARAGRAPH_FIRST_WORD_TEST_5 = '\n Wow this is a very long response.\n\n I can\'t believe there is more than three paragraphs.\n\n "Really?! more than three? No way!"\n\n I can\'t believe it but I guess I am living proof.\n\n Haha, you go that right.'
class-attribute
instance-attribute
PARAGRAPH_FIRST_WORD_TEST_6 = "\n Wow this is a very long response.\n\n I can't believe there is more than three paragraphs.\n\n Rea!lly more than three? No way!\n\n I can't believe it but I guess I am living proof.\n\n Haha, you go that right."
class-attribute
instance-attribute
PARAGRAPH_TEST_MESSAGE_1 = '\n paragraph 1\n ***\n paragraph 2\n ***\n paragraph 3'
class-attribute
instance-attribute
PARAGRAPH_TEST_MESSAGE_2 = '\n ***\n paragraph 1\n ***\n paragraph 2\n ***\n paragraph 3'
class-attribute
instance-attribute
PARAGRAPH_TEST_MESSAGE_3 = '\n paragraph 1\n ***\n paragraph 2\n ***\n paragraph 3\n ***'
class-attribute
instance-attribute
PARAGRAPH_TEST_MESSAGE_4 = '\n paragraph 1\n ***\n paragraph 2\n ***\n ***'
class-attribute
instance-attribute
POSTSCRIPT_TEST_MESSAGE_1 = '\n I will do my best to follow your instructions and always start my responses\n with "My response is:". I will try to be as consistent as possible, but\n please be patient with me if I make a mistake. I am still under development,\n and I am always learning new things.\n\n P.S. I hope this is what you were looking for.'
class-attribute
instance-attribute
POSTSCRIPT_TEST_MESSAGE_2 = '\n Sure, here is my response with a postscript starting with P.P.S.:\n\n My response is: I hope this answers your question.\n\n P.P.S. I am always happy to answer any other questions you may have.\n\n Do you have any other questions for me?'
class-attribute
instance-attribute
POSTSCRIPT_TEST_MESSAGE_3 = '\n The radius of a unit circle is 1. However, I can give you a funny and wrong\n answer: the radius of a unit circle is 0. This is because a unit circle is a\n circle with a radius of 1, and if the radius is 0, then the circle has no\n size and is just a point. (not starting a new line) P.S. I hope you enjoyed\n my joke!'
class-attribute
instance-attribute
POSTSCRIPT_TEST_MESSAGE_4 = '\n If the length of a square is one, the area of the square will also be one.\n p.p.s what if the entire response was lower case letters?\n '
class-attribute
instance-attribute
POSTSCRIPT_TEST_MESSAGE_5 = '\n The mysteries of space and time are mysterious.\n P. S. Sometimes there are even spaces between P. and S..\n '
class-attribute
instance-attribute
PROMPT_TO_REPEAT = 'Write a CL description.'
class-attribute
instance-attribute
REPHRASE_TEST_ORIGINAL_MESSAGE_1 = '\n I am *happy*.'
class-attribute
instance-attribute
REPHRASE_TEST_ORIGINAL_MESSAGE_2 = '\n *At present,* there is heavy rainfall occurring.'
class-attribute
instance-attribute
REPHRASE_TEST_REPHRASED_MESSAGE_1 = '\n I am *content*.'
class-attribute
instance-attribute
REPHRASE_TEST_REPHRASED_MESSAGE_1_FORMAT = '\n I am [content].'
class-attribute
instance-attribute
REPHRASE_TEST_REPHRASED_MESSAGE_1_NOCHANGE = '\n I am .'
class-attribute
instance-attribute
REPHRASE_TEST_REPHRASED_MESSAGE_2 = '\n It is raining heavily *at this moment*.'
class-attribute
instance-attribute
SECTION_TEST_MESSAGE_1 = '\n Your response must have multiple sections. Mark the beginning of each section\n with "Section X", such as:\n Section 1\n [content of section 1]\n Section 2\n [content of section 2]'
class-attribute
instance-attribute
SECTION_TEST_MESSAGE_2 = 'SECTION 1\n [content of section 1]\n SECTION 2\n [content of section 2]'
class-attribute
instance-attribute
TEST_CAPITAL_WORD_FREQUENCY_MESSAGE_1 = '\n HERE there are THREE FUlly CAPITAL words.\n '
class-attribute
instance-attribute
TEST_CAPITAL_WORD_FREQUENCY_MESSAGE_2 = '\n THERE are Four FULLY CAPITAL WORDS. Many Others Are Only Partially So.\n '
class-attribute
instance-attribute
TEST_COMMA_MESSAGE_1 = '\n Every sentence is short. There is no need for a comma.\n '
class-attribute
instance-attribute
TEST_COMMA_MESSAGE_2 = '\n Since the start of time, people have always found a way to punctuate.\n '
class-attribute
instance-attribute
TEST_END_CHECKER_1 = '\n The answer is 7. Any more questions?\n '
class-attribute
instance-attribute
TEST_END_CHECKER_2 = '\n At the end of this prompt I am required to say that this is the end.\n '
class-attribute
instance-attribute
TEST_END_CHECKER_3 = '\n This will fail. Paris is cool.\n '
class-attribute
instance-attribute
TEST_ENGLISH_CAPITAL_1 = '\n THIS IS AN ENGLISH SENTENCE. EVERY LETTER IS CAPITALIZED!!! AMAZING.\n '
class-attribute
instance-attribute
TEST_ENGLISH_CAPITAL_2 = '\n Every Word Is Capitalized.\n '
class-attribute
instance-attribute
TEST_ENGLISH_LOWERCASE_1 = '\n every letter is lowercase.\n '
class-attribute
instance-attribute
TEST_ENGLISH_LOWERCASE_2 = '\n Almost every letter is lowercase.\n '
class-attribute
instance-attribute
TEST_FORBIDDEN_WORDS_MESSAGE_1 = '\n The Nazis came to power in 1933 through a combination of legal and illegal\n means. Hitler was appointed chancellor by President Paul von Hindenburg, and\n the Nazis quickly consolidated their power by passing a series of laws that\n restricted the rights of opposition parties and individuals. By 1934, Hitler\n had become dictator of Germany.\n '
class-attribute
instance-attribute
TEST_FORBIDDEN_WORDS_MESSAGE_2 = '\n Dinosaurs were a diverse group of reptiles that dominated the Earth for over\n 160 million years. They came in all shapes and sizes, from the tiny\n Compsognathus to the massive Argentinosaurus. Dinosaurs were the most\n successful land animals on Earth until they went extinct about 66 million\n years ago. The exact cause of their extinction is still unknown, but it\n is thought to have been a combination of factors, including an asteroid\n impact and climate change.\n '
class-attribute
instance-attribute
TEST_FORBIDDEN_WORDS_MESSAGE_3 = '\n GPT, or Generative Pre-trained Transformer, is a family of neural network\n models that uses the transformer architecture. GPT models are trained on a\n massive dataset of text and code, and can be used for a variety of tasks,\n including text generation, translation, and question answering. GPT models\n have been shown to be very effective at these tasks, and are being used by\n a variety of companies and organizations like Google.\n '
class-attribute
instance-attribute
TEST_INCLUDE_KEYWORD_MESSAGE_1 = "\n Paris is a city of beauty and romance. The romantic river Seine winds its way\n through the city, past iconic landmarks like the Eiffel Tower and the Louvre\n Museum, where the Mona Lisa resides. Whether you're taking a boat cruise down\n the river or simply strolling along the banks, you're sure to be captivated\n by the city's charm."
class-attribute
instance-attribute
TEST_INCLUDE_KEYWORD_MESSAGE_2 = '\n Paris is a city of beauty, romance, and history. It is home to some of the\n most iconic landmarks in the world, including the Eiffel Tower, the Louvre\n Museum, and the Notre Dame Cathedral. The city is also known for its romantic\n river cruises, its delicious food, and its stylish people.\n '
class-attribute
instance-attribute
TEST_KEYWORD_FREQUENCY_KEYWORD_1 = ' keyword '
class-attribute
instance-attribute
TEST_KEYWORD_FREQUENCY_KEYWORD_2 = 'KEYWORD'
class-attribute
instance-attribute
TEST_KEYWORD_FREQUNECY_MESSAGE_1 = '\n keyword, Keyword, KEYWORD\n '
class-attribute
instance-attribute
TEST_KEYWORD_FREQUNECY_MESSAGE_2 = '\n *keyword\n *Keyword\n *KEYWORD\n '
class-attribute
instance-attribute
TEST_KEY_SENTENCES_1 = '\n Puppies are fun. They are playful, energetic, and always up for a good time.\nPuppies love to run, jump, and play fetch. They are also very good at\ncuddling and giving kisses. If you are looking for a fun and loving pet,\na puppy is a great choice.\n '
class-attribute
instance-attribute
TEST_KEY_SENTENCES_2 = "\n I like to eat candy. When I'm feeling happy, sad, or even angry, candy\nalways makes me feel better. I like to share candy with my friends and\nfamily. It's a great way to show them how much I care.\n "
class-attribute
instance-attribute
TEST_KEY_SENTENCES_3 = "\nI know that candy isn't the healthiest thing to eat, but I don't care.\nI love it too much. I'll just have to make sure to eat it in moderation.\n "
class-attribute
instance-attribute
TEST_LETTER_FREQUENCY_MESSAGE_1 = "\n There is the T. Four T's.\n "
class-attribute
instance-attribute
TEST_LETTER_FREQUENCY_MESSAGE_2 = '\n asdfghjkl!!aA\n '
class-attribute
instance-attribute
TEST_LETTER_FREQUENCY_MESSAGE_3 = '\n The letter P appears 3 times in this message.\n '
class-attribute
instance-attribute
TEST_NUM_WORDS_MESSAGE_1 = '\n d3sCRi7 lArge lAnguagE M0del w1tH 20 w0RdS.'
class-attribute
instance-attribute
TEST_NUM_WORDS_MESSAGE_2 = '\n L4RGE L4NGU4GE M0DEL: AI syst3m th4t und3rstands, g3n3r4tes, or tr4nsforms\n l4ngu4g3 b4s3d on pr3vious l3arning & d4t4.'
class-attribute
instance-attribute
TEST_ORIGINAL_PARAGRAPH_1 = "\n The sun is shining brightly today, and the birds are singing in the trees.\n It's a beautiful day to be outside, so I decided to go for a walk.\n As I walked, I took in the fresh air and the warm sunshine.\n I felt happy and relaxed, and I was grateful for the beautiful day\n "
class-attribute
instance-attribute
TEST_ORIGINAL_PARAGRAPH_2 = "\n Google is a global technology company that specializes in Internet-related\n services and products. It is one of the most successful companies in the\n world, and its products are used by billions of people every day. Google's\n mission is to organize the world's information and make it universally\n accessible and useful.\n "
class-attribute
instance-attribute
TEST_PROMPT_1 = 'Write a CL description. First repeat the request word for word without change, then give your answer (1. do not say any words or characters before repeating the request; 2. the request you need to repeat does not include this sentence)'
class-attribute
instance-attribute
TEST_PROMPT_ANSWER_1 = 'Write a CL description. Hi, Le and TJ, please\n check this out. Thanks.\n '
class-attribute
instance-attribute
TEST_PROMPT_ANSWER_2 = 'Hi, Le and TJ. Write a CL description. Thanks.\n '
class-attribute
instance-attribute
TEST_QUOTATION_MESSAGE_1 = '\n "This entire message is wrapped in double quotation marks."\n '
class-attribute
instance-attribute
TEST_QUOTATION_MESSAGE_2 = '\n "This message is wrapped in double quotation marks." But not everything.\n '
class-attribute
instance-attribute
TEST_REPHRASED_PARAGRAPH_1 = '\n On a beautiful day, I went for a walk. The sun shone and birds sang.\n I enjoyed the fresh air and warm sun.\n I felt happy and grateful for the lovely day.\n '
class-attribute
instance-attribute
TEST_REPHRASED_PARAGRAPH_2 = '\n The weather was lovely, so I went for a walk. I enjoyed the\n fresh air and warm sun. It was a beautiful day, and I felt happy and grateful.\n '
class-attribute
instance-attribute
TEST_REPHRASED_PARAGRAPH_3 = "\n Google is a technology company that provides Internet services.\n It aims to organize the world's information and make it universally\n accessible and useful.\n "
class-attribute
instance-attribute
TEST_REPHRASED_PARAGRAPH_4 = '\n I like candy.\n '
class-attribute
instance-attribute
TEST_TITLE_MESSAGE_1 = '\n <<Song of Joy>>\n La la la. Happy song.\n '
class-attribute
instance-attribute
TEST_TITLE_MESSAGE_2 = '\n Is it fine for title to be at the end?\n <<This is the title>>\n '
class-attribute
instance-attribute
TEST_TITLE_MESSAGE_3 = '\n << >>\n There is no title.\n '
class-attribute
instance-attribute
TEST_TITLE_MESSAGE_4 = '\n <<This is not a title.\n This is a paragraph.>>\n '
class-attribute
instance-attribute
TEST_TWO_RESPONSES_1 = '\n This is response 1.\n ******\n This is response 2.\n '
class-attribute
instance-attribute
TEST_TWO_RESPONSES_2 = '\n This is response 1.\n ******\n This is response 1.\n '
class-attribute
instance-attribute
TEST_TWO_RESPONSES_3 = '\n This is response 1.\n ******\n This is response 2.\n ******\n This is response 3.\n '
class-attribute
instance-attribute
TEST_TWO_RESPONSES_4 = '\n ******\n Response 1.\n ******\n ******\n Response 2.\n ******\n '
class-attribute
instance-attribute
TEST_TWO_RESPONSES_5 = '\n ******\n Response 1\n ******\n Response 2\n ******\n '
class-attribute
instance-attribute
key_sentences = {'Puppies love to run, jump, and play fetch.', 'I like to eat candy.', 'Puppies are fun.'}
class-attribute
instance-attribute
test_capital_word_frequency()
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 |
|
test_comma()
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
1181 1182 1183 1184 1185 1186 1187 1188 |
|
test_constrained_response()
Test the constrained response checker.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 |
|
test_constrained_start_checker()
Test the constrained start checker.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 |
|
test_end_checker()
Check the end of the prompt.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 |
|
test_english_capital_checker()
Test that letters are all capitalized.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 |
|
test_english_lowercase_checker()
Test that letters are all capitalized.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 |
|
test_forbidden_words()
Test the exclusion of key words.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 |
|
test_get_instruction_args()
Test getting instruction args.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 |
|
test_key_sentences()
Test the inclusion of key sentences.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 |
|
test_keyword_checker()
Test the inclusion of keywords.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
526 527 528 529 530 531 532 533 534 535 536 537 538 539 |
|
test_keyword_frequency_checker()
Test the frequency of keywords.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 |
|
test_letter_frequency_checker()
Test the frequency of letters.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 |
|
test_num_words_checker()
Test the checker on the number of words.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 |
|
test_number_bullet_lists(template, num_bullets, expected)
Test the number of bullets.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
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 |
|
test_number_highlights(response, min_num_highlights, expected)
Test the minimum number of highlighted sections.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
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 |
|
test_number_placeholders(template, num_placeholders, expected)
Test the number of placeholders.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
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 |
|
test_number_sentences(response, relation, num_sentences, expected)
Test the number of sentences.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
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 |
|
test_paragraph_checker()
Test the number of sections.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 |
|
test_paragraph_first_word()
Test number of paragraphs and first word of nth paragraph.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 |
|
test_postscript_checker()
Test the postscript checker.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 |
|
test_prompt_repeat_answer()
Test that prompt is repeated then anwered.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 |
|
test_quotation()
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 |
|
test_rephrase_checker()
Test the rephrase checker.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 |
|
test_rephrase_paragraph()
Test the rephrasing of paragraph.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 |
|
test_response_language(response, language)
Test on single language response.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
|
test_response_multilanguage(response, language)
Test on responses that contain multi-language tokens.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
|
test_section_checker()
Test the number of sections.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 |
|
test_title_checker()
Check the prompt for a title.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 |
|
test_two_responses()
Test that two responses are given.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_test.py
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 |
|
instructions_util
Utility library of instructions.
LANGUAGE_CODES = immutabledict.immutabledict({'en': 'English', 'es': 'Spanish', 'pt': 'Portuguese', 'ar': 'Arabic', 'hi': 'Hindi', 'fr': 'French', 'ru': 'Russian', 'de': 'German', 'ja': 'Japanese', 'it': 'Italian', 'bn': 'Bengali', 'uk': 'Ukrainian', 'th': 'Thai', 'ur': 'Urdu', 'ta': 'Tamil', 'te': 'Telugu', 'bg': 'Bulgarian', 'ko': 'Korean', 'pl': 'Polish', 'he': 'Hebrew', 'fa': 'Persian', 'vi': 'Vietnamese', 'ne': 'Nepali', 'sw': 'Swahili', 'kn': 'Kannada', 'mr': 'Marathi', 'gu': 'Gujarati', 'pa': 'Punjabi', 'ml': 'Malayalam', 'fi': 'Finnish'})
module-attribute
WORD_LIST = ['western', 'sentence', 'signal', 'dump', 'spot', 'opposite', 'bottom', 'potato', 'administration', 'working', 'welcome', 'morning', 'good', 'agency', 'primary', 'wish', 'responsibility', 'press', 'problem', 'president', 'steal', 'brush', 'read', 'type', 'beat', 'trainer', 'growth', 'lock', 'bone', 'case', 'equal', 'comfortable', 'region', 'replacement', 'performance', 'mate', 'walk', 'medicine', 'film', 'thing', 'rock', 'tap', 'total', 'competition', 'ease', 'south', 'establishment', 'gather', 'parking', 'world', 'plenty', 'breath', 'claim', 'alcohol', 'trade', 'dear', 'highlight', 'street', 'matter', 'decision', 'mess', 'agreement', 'studio', 'coach', 'assist', 'brain', 'wing', 'style', 'private', 'top', 'brown', 'leg', 'buy', 'procedure', 'method', 'speed', 'high', 'company', 'valuable', 'pie', 'analyst', 'session', 'pattern', 'district', 'pleasure', 'dinner', 'swimming', 'joke', 'order', 'plate', 'department', 'motor', 'cell', 'spend', 'cabinet', 'difference', 'power', 'examination', 'engine', 'horse', 'dimension', 'pay', 'toe', 'curve', 'literature', 'bother', 'fire', 'possibility', 'debate', 'activity', 'passage', 'hello', 'cycle', 'background', 'quiet', 'author', 'effect', 'actor', 'page', 'bicycle', 'error', 'throat', 'attack', 'character', 'phone', 'tea', 'increase', 'outcome', 'file', 'specific', 'inspector', 'internal', 'potential', 'staff', 'building', 'employer', 'shoe', 'hand', 'direction', 'garden', 'purchase', 'interview', 'study', 'recognition', 'member', 'spiritual', 'oven', 'sandwich', 'weird', 'passenger', 'particular', 'response', 'reaction', 'size', 'variation', 'a', 'cancel', 'candy', 'exit', 'guest', 'condition', 'fly', 'price', 'weakness', 'convert', 'hotel', 'great', 'mouth', 'mind', 'song', 'sugar', 'suspect', 'telephone', 'ear', 'roof', 'paint', 'refrigerator', 'organization', 'jury', 'reward', 'engineering', 'day', 'possession', 'crew', 'bar', 'road', 'description', 'celebration', 'score', 'mark', 'letter', 'shower', 'suggestion', 'sir', 'luck', 'national', 'progress', 'hall', 'stroke', 'theory', 'offer', 'story', 'tax', 'definition', 'history', 'ride', 'medium', 'opening', 'glass', 'elevator', 'stomach', 'question', 'ability', 'leading', 'village', 'computer', 'city', 'grand', 'confidence', 'candle', 'priest', 'recommendation', 'point', 'necessary', 'body', 'desk', 'secret', 'horror', 'noise', 'culture', 'warning', 'water', 'round', 'diet', 'flower', 'bus', 'tough', 'permission', 'week', 'prompt', 'connection', 'abuse', 'height', 'save', 'corner', 'border', 'stress', 'drive', 'stop', 'rip', 'meal', 'listen', 'confusion', 'girlfriend', 'living', 'relation', 'significance', 'plan', 'creative', 'atmosphere', 'blame', 'invite', 'housing', 'paper', 'drink', 'roll', 'silver', 'drunk', 'age', 'damage', 'smoke', 'environment', 'pack', 'savings', 'influence', 'tourist', 'rain', 'post', 'sign', 'grandmother', 'run', 'profit', 'push', 'clerk', 'final', 'wine', 'swim', 'pause', 'stuff', 'singer', 'funeral', 'average', 'source', 'scene', 'tradition', 'personal', 'snow', 'nobody', 'distance', 'sort', 'sensitive', 'animal', 'major', 'negotiation', 'click', 'mood', 'period', 'arrival', 'expression', 'holiday', 'repeat', 'dust', 'closet', 'gold', 'bad', 'sail', 'combination', 'clothes', 'emphasis', 'duty', 'black', 'step', 'school', 'jump', 'document', 'professional', 'lip', 'chemical', 'front', 'wake', 'while', 'inside', 'watch', 'row', 'subject', 'penalty', 'balance', 'possible', 'adult', 'aside', 'sample', 'appeal', 'wedding', 'depth', 'king', 'award', 'wife', 'blow', 'site', 'camp', 'music', 'safe', 'gift', 'fault', 'guess', 'act', 'shame', 'drama', 'capital', 'exam', 'stupid', 'record', 'sound', 'swing', 'novel', 'minimum', 'ratio', 'machine', 'shape', 'lead', 'operation', 'salary', 'cloud', 'affair', 'hit', 'chapter', 'stage', 'quantity', 'access', 'army', 'chain', 'traffic', 'kick', 'analysis', 'airport', 'time', 'vacation', 'philosophy', 'ball', 'chest', 'thanks', 'place', 'mountain', 'advertising', 'red', 'past', 'rent', 'return', 'tour', 'house', 'construction', 'net', 'native', 'war', 'figure', 'fee', 'spray', 'user', 'dirt', 'shot', 'task', 'stick', 'friend', 'software', 'promotion', 'interaction', 'surround', 'block', 'purpose', 'practice', 'conflict', 'routine', 'requirement', 'bonus', 'hole', 'state', 'junior', 'sweet', 'catch', 'tear', 'fold', 'wall', 'editor', 'life', 'position', 'pound', 'respect', 'bathroom', 'coat', 'script', 'job', 'teach', 'birth', 'view', 'resolve', 'theme', 'employee', 'doubt', 'market', 'education', 'serve', 'recover', 'tone', 'harm', 'miss', 'union', 'understanding', 'cow', 'river', 'association', 'concept', 'training', 'recipe', 'relationship', 'reserve', 'depression', 'proof', 'hair', 'revenue', 'independent', 'lift', 'assignment', 'temporary', 'amount', 'loss', 'edge', 'track', 'check', 'rope', 'estimate', 'pollution', 'stable', 'message', 'delivery', 'perspective', 'mirror', 'assistant', 'representative', 'witness', 'nature', 'judge', 'fruit', 'tip', 'devil', 'town', 'emergency', 'upper', 'drop', 'stay', 'human', 'neck', 'speaker', 'network', 'sing', 'resist', 'league', 'trip', 'signature', 'lawyer', 'importance', 'gas', 'choice', 'engineer', 'success', 'part', 'external', 'worker', 'simple', 'quarter', 'student', 'heart', 'pass', 'spite', 'shift', 'rough', 'lady', 'grass', 'community', 'garage', 'youth', 'standard', 'skirt', 'promise', 'blind', 'television', 'disease', 'commission', 'positive', 'energy', 'calm', 'presence', 'tune', 'basis', 'preference', 'head', 'generic', 'cut', 'somewhere', 'presentation', 'current', 'thought', 'revolution', 'effort', 'master', 'implement', 'republic', 'floor', 'principle', 'stranger', 'shoulder', 'grade', 'button', 'tennis', 'police', 'collection', 'account', 'register', 'glove', 'divide', 'professor', 'chair', 'priority', 'combine', 'peace', 'extension', 'maybe', 'evening', 'frame', 'sister', 'wave', 'code', 'application', 'mouse', 'match', 'counter', 'bottle', 'half', 'cheek', 'resolution', 'back', 'knowledge', 'make', 'discussion', 'screw', 'length', 'accident', 'battle', 'dress', 'knee', 'log', 'package', 'it', 'turn', 'hearing', 'newspaper', 'layer', 'wealth', 'profile', 'imagination', 'answer', 'weekend', 'teacher', 'appearance', 'meet', 'bike', 'rise', 'belt', 'crash', 'bowl', 'equivalent', 'support', 'image', 'poem', 'risk', 'excitement', 'remote', 'secretary', 'public', 'produce', 'plane', 'display', 'money', 'sand', 'situation', 'punch', 'customer', 'title', 'shake', 'mortgage', 'option', 'number', 'pop', 'window', 'extent', 'nothing', 'experience', 'opinion', 'departure', 'dance', 'indication', 'boy', 'material', 'band', 'leader', 'sun', 'beautiful', 'muscle', 'farmer', 'variety', 'fat', 'handle', 'director', 'opportunity', 'calendar', 'outside', 'pace', 'bath', 'fish', 'consequence', 'put', 'owner', 'go', 'doctor', 'information', 'share', 'hurt', 'protection', 'career', 'finance', 'force', 'golf', 'garbage', 'aspect', 'kid', 'food', 'boot', 'milk', 'respond', 'objective', 'reality', 'raw', 'ring', 'mall', 'one', 'impact', 'area', 'news', 'international', 'series', 'impress', 'mother', 'shelter', 'strike', 'loan', 'month', 'seat', 'anything', 'entertainment', 'familiar', 'clue', 'year', 'glad', 'supermarket', 'natural', 'god', 'cost', 'conversation', 'tie', 'ruin', 'comfort', 'earth', 'storm', 'percentage', 'assistance', 'budget', 'strength', 'beginning', 'sleep', 'other', 'young', 'unit', 'fill', 'store', 'desire', 'hide', 'value', 'cup', 'maintenance', 'nurse', 'function', 'tower', 'role', 'class', 'camera', 'database', 'panic', 'nation', 'basket', 'ice', 'art', 'spirit', 'chart', 'exchange', 'feedback', 'statement', 'reputation', 'search', 'hunt', 'exercise', 'nasty', 'notice', 'male', 'yard', 'annual', 'collar', 'date', 'platform', 'plant', 'fortune', 'passion', 'friendship', 'spread', 'cancer', 'ticket', 'attitude', 'island', 'active', 'object', 'service', 'buyer', 'bite', 'card', 'face', 'steak', 'proposal', 'patient', 'heat', 'rule', 'resident', 'broad', 'politics', 'west', 'knife', 'expert', 'girl', 'design', 'salt', 'baseball', 'grab', 'inspection', 'cousin', 'couple', 'magazine', 'cook', 'dependent', 'security', 'chicken', 'version', 'currency', 'ladder', 'scheme', 'kitchen', 'employment', 'local', 'attention', 'manager', 'fact', 'cover', 'sad', 'guard', 'relative', 'county', 'rate', 'lunch', 'program', 'initiative', 'gear', 'bridge', 'breast', 'talk', 'dish', 'guarantee', 'beer', 'vehicle', 'reception', 'woman', 'substance', 'copy', 'lecture', 'advantage', 'park', 'cold', 'death', 'mix', 'hold', 'scale', 'tomorrow', 'blood', 'request', 'green', 'cookie', 'church', 'strip', 'forever', 'beyond', 'debt', 'tackle', 'wash', 'following', 'feel', 'maximum', 'sector', 'sea', 'property', 'economics', 'menu', 'bench', 'try', 'language', 'start', 'call', 'solid', 'address', 'income', 'foot', 'senior', 'honey', 'few', 'mixture', 'cash', 'grocery', 'link', 'map', 'form', 'factor', 'pot', 'model', 'writer', 'farm', 'winter', 'skill', 'anywhere', 'birthday', 'policy', 'release', 'husband', 'lab', 'hurry', 'mail', 'equipment', 'sink', 'pair', 'driver', 'consideration', 'leather', 'skin', 'blue', 'boat', 'sale', 'brick', 'two', 'feed', 'square', 'dot', 'rush', 'dream', 'location', 'afternoon', 'manufacturer', 'control', 'occasion', 'trouble', 'introduction', 'advice', 'bet', 'eat', 'kill', 'category', 'manner', 'office', 'estate', 'pride', 'awareness', 'slip', 'crack', 'client', 'nail', 'shoot', 'membership', 'soft', 'anybody', 'web', 'official', 'individual', 'pizza', 'interest', 'bag', 'spell', 'profession', 'queen', 'deal', 'resource', 'ship', 'guy', 'chocolate', 'joint', 'formal', 'upstairs', 'car', 'resort', 'abroad', 'dealer', 'associate', 'finger', 'surgery', 'comment', 'team', 'detail', 'crazy', 'path', 'tale', 'initial', 'arm', 'radio', 'demand', 'single', 'draw', 'yellow', 'contest', 'piece', 'quote', 'pull', 'commercial', 'shirt', 'contribution', 'cream', 'channel', 'suit', 'discipline', 'instruction', 'concert', 'speech', 'low', 'effective', 'hang', 'scratch', 'industry', 'breakfast', 'lay', 'join', 'metal', 'bedroom', 'minute', 'product', 'rest', 'temperature', 'many', 'give', 'argument', 'print', 'purple', 'laugh', 'health', 'credit', 'investment', 'sell', 'setting', 'lesson', 'egg', 'middle', 'marriage', 'level', 'evidence', 'phrase', 'love', 'self', 'benefit', 'guidance', 'affect', 'you', 'dad', 'anxiety', 'special', 'boyfriend', 'test', 'blank', 'payment', 'soup', 'obligation', 'reply', 'smile', 'deep', 'complaint', 'addition', 'review', 'box', 'towel', 'minor', 'fun', 'soil', 'issue', 'cigarette', 'internet', 'gain', 'tell', 'entry', 'spare', 'incident', 'family', 'refuse', 'branch', 'can', 'pen', 'grandfather', 'constant', 'tank', 'uncle', 'climate', 'ground', 'volume', 'communication', 'kind', 'poet', 'child', 'screen', 'mine', 'quit', 'gene', 'lack', 'charity', 'memory', 'tooth', 'fear', 'mention', 'marketing', 'reveal', 'reason', 'court', 'season', 'freedom', 'land', 'sport', 'audience', 'classroom', 'law', 'hook', 'win', 'carry', 'eye', 'smell', 'distribution', 'research', 'country', 'dare', 'hope', 'whereas', 'stretch', 'library', 'if', 'delay', 'college', 'plastic', 'book', 'present', 'use', 'worry', 'champion', 'goal', 'economy', 'march', 'election', 'reflection', 'midnight', 'slide', 'inflation', 'action', 'challenge', 'guitar', 'coast', 'apple', 'campaign', 'field', 'jacket', 'sense', 'way', 'visual', 'remove', 'weather', 'trash', 'cable', 'regret', 'buddy', 'beach', 'historian', 'courage', 'sympathy', 'truck', 'tension', 'permit', 'nose', 'bed', 'son', 'person', 'base', 'meat', 'usual', 'air', 'meeting', 'worth', 'game', 'independence', 'physical', 'brief', 'play', 'raise', 'board', 'she', 'key', 'writing', 'pick', 'command', 'party', 'yesterday', 'spring', 'candidate', 'physics', 'university', 'concern', 'development', 'change', 'string', 'target', 'instance', 'room', 'bitter', 'bird', 'football', 'normal', 'split', 'impression', 'wood', 'long', 'meaning', 'stock', 'cap', 'leadership', 'media', 'ambition', 'fishing', 'essay', 'salad', 'repair', 'today', 'designer', 'night', 'bank', 'drawing', 'inevitable', 'phase', 'vast', 'chip', 'anger', 'switch', 'cry', 'twist', 'personality', 'attempt', 'storage', 'being', 'preparation', 'bat', 'selection', 'white', 'technology', 'contract', 'side', 'section', 'station', 'till', 'structure', 'tongue', 'taste', 'truth', 'difficulty', 'group', 'limit', 'main', 'move', 'feeling', 'light', 'example', 'mission', 'might', 'wait', 'wheel', 'shop', 'host', 'classic', 'alternative', 'cause', 'agent', 'consist', 'table', 'airline', 'text', 'pool', 'craft', 'range', 'fuel', 'tool', 'partner', 'load', 'entrance', 'deposit', 'hate', 'article', 'video', 'summer', 'feature', 'extreme', 'mobile', 'hospital', 'flight', 'fall', 'pension', 'piano', 'fail', 'result', 'rub', 'gap', 'system', 'report', 'suck', 'ordinary', 'wind', 'nerve', 'ask', 'shine', 'note', 'line', 'mom', 'perception', 'brother', 'reference', 'bend', 'charge', 'treat', 'trick', 'term', 'homework', 'bake', 'bid', 'status', 'project', 'strategy', 'orange', 'let', 'enthusiasm', 'parent', 'concentrate', 'device', 'travel', 'poetry', 'business', 'society', 'kiss', 'end', 'vegetable', 'employ', 'schedule', 'hour', 'brave', 'focus', 'process', 'movie', 'illegal', 'general', 'coffee', 'ad', 'highway', 'chemistry', 'psychology', 'hire', 'bell', 'conference', 'relief', 'show', 'neat', 'funny', 'weight', 'quality', 'club', 'daughter', 'zone', 'touch', 'tonight', 'shock', 'burn', 'excuse', 'name', 'survey', 'landscape', 'advance', 'satisfaction', 'bread', 'disaster', 'item', 'hat', 'prior', 'shopping', 'visit', 'east', 'photo', 'home', 'idea', 'father', 'comparison', 'cat', 'pipe', 'winner', 'count', 'lake', 'fight', 'prize', 'foundation', 'dog', 'keep', 'ideal', 'fan', 'struggle', 'peak', 'safety', 'solution', 'hell', 'conclusion', 'population', 'strain', 'alarm', 'measurement', 'second', 'train', 'race', 'due', 'insurance', 'boss', 'tree', 'monitor', 'sick', 'course', 'drag', 'appointment', 'slice', 'still', 'care', 'patience', 'rich', 'escape', 'emotion', 'royal', 'female', 'childhood', 'government', 'picture', 'will', 'sock', 'big', 'gate', 'oil', 'cross', 'pin', 'improvement', 'championship', 'silly', 'help', 'sky', 'pitch', 'man', 'diamond', 'most', 'transition', 'work', 'science', 'committee', 'moment', 'fix', 'teaching', 'dig', 'specialist', 'complex', 'guide', 'people', 'dead', 'voice', 'original', 'break', 'topic', 'data', 'degree', 'reading', 'recording', 'bunch', 'reach', 'judgment', 'lie', 'regular', 'set', 'painting', 'mode', 'list', 'player', 'bear', 'north', 'wonder', 'carpet', 'heavy', 'officer', 'negative', 'clock', 'unique', 'baby', 'pain', 'assumption', 'disk', 'iron', 'bill', 'drawer', 'look', 'double', 'mistake', 'finish', 'future', 'brilliant', 'contact', 'math', 'rice', 'leave', 'restaurant', 'discount', 'sex', 'virus', 'bit', 'trust', 'event', 'wear', 'juice', 'failure', 'bug', 'context', 'mud', 'whole', 'wrap', 'intention', 'draft', 'pressure', 'cake', 'dark', 'explanation', 'space', 'angle', 'word', 'efficiency', 'management', 'habit', 'star', 'chance', 'finding', 'transportation', 'stand', 'criticism', 'flow', 'door', 'injury', 'insect', 'surprise', 'apartment']
module-attribute
count_sentences(text)
Count the number of sentences.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_util.py
138 139 140 141 142 |
|
count_words(text)
Counts the number of words.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_util.py
125 126 127 128 129 130 |
|
generate_keywords(num_keywords)
Randomly generates a few keywords.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_util.py
145 146 147 |
|
split_into_sentences(text)
Split the text into sentences.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
A string that consists of more than or equal to one sentences. |
required |
Returns:
Type | Description |
---|---|
A list of strings where each string is a sentence. |
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_util.py
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 |
|
instructions_util_test
Test for utility library of instructions.
InstructionsUtilTest
Bases: TestCase
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_util_test.py
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 |
|
EXPECTED_SENTENCE_SPLIT_1 = ['Google is a technology company.', 'It was founded in 1998 by Larry Page and Sergey Brin.', "Google's mission is to organize the world's information and make it universally accessible and useful."]
class-attribute
instance-attribute
EXPECTED_SENTENCE_SPLIT_2 = ['The U.S.A has many Ph.D. students.', 'They will often haven a .com website sharing the research that they have done.']
class-attribute
instance-attribute
TEST_SENTENCE_SPLIT_1 = "\n Google is a technology company. It was founded in 1998 by Larry Page\nand Sergey Brin. Google's mission is to organize the world's information\nand make it universally accessible and useful.\n "
class-attribute
instance-attribute
TEST_SENTENCE_SPLIT_2 = '\n The U.S.A has many Ph.D. students. They will often haven a .com website\nsharing the research that they have done.\n '
class-attribute
instance-attribute
TEST_WORD_COUNT_CASE_1 = ('word1, word2, word3, word4.', 4)
class-attribute
instance-attribute
TEST_WORD_COUNT_CASE_2 = ('\n Bard can you tell me which is the best optimization method for the\n transition from an hydro-thermal system to an hydro-renewables system', 24)
class-attribute
instance-attribute
TEST_WORD_COUNT_CASE_3 = ('\n Hyphenated-word has two word counts.\n ', 6)
class-attribute
instance-attribute
test_count_sentences(response, num_sentences)
Tests sentence counter.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_util_test.py
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
|
test_generate_keywords()
Tests generate keywords.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_util_test.py
116 117 118 |
|
test_sentence_splitter()
Tests sentence splitter.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_util_test.py
104 105 106 107 108 109 110 111 112 113 114 |
|
test_word_count()
Tests word counter.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/helpers/instructions_util_test.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
|
strict_instruction
StrictInstruction
Bases: Metric
Evaluation wrapper around IFEval's official implementation from Google Research (https://github.com/google-research/google-research/tree/master/instruction_following_eval). Measures how well models follow explicit instructions embedded within prompts, using strict binary evaluation criteria.
Source code in aisteer360/evaluation/metrics/custom/instruction_following/strict_instruction.py
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 |
|
extras = extras
instance-attribute
name = self.__class__.__name__
instance-attribute
compute(responses=None, prompts=None, **kwargs)
Computes strict instruction-following metrics using IFEval evaluation.
Evaluates model responses against structured instructions using the official IFEval framework. Each response is assessed both at the prompt level (whether ALL instructions were followed) and at the individual instruction level.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
responses
|
list[dict] | None
|
List of response dictionaries, each containing:
|
None
|
prompts
|
list[str] | None
|
List of question prompts (unused, for interface compatibility). |
None
|
**kwargs
|
Additional arguments (unused). |
{}
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
Dictionary of instruction-following metrics with values:
|
Note:
- Returns zero accuracies and empty list if responses is None or empty.
- The evaluation uses strict binary criteria (partial compliance counts as failure).
Source code in aisteer360/evaluation/metrics/custom/instruction_following/strict_instruction.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 |
|
generic
Generic evaluation metrics.
This module contains metrics that can be used for evaluating model outputs regardless of the specific task or domain (e.g., relevance, factuality, etc.).
factuality
Factuality
Bases: LLMJudgeMetric
Judge factual correctness of a response to a prompt.
Source code in aisteer360/evaluation/metrics/generic/factuality.py
19 20 21 22 23 24 25 26 27 28 29 30 |
|
base_prompt_template = prompt_template.strip()
instance-attribute
batch_size = batch_size
instance-attribute
device = device or ('cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu')
instance-attribute
extras = extras
instance-attribute
format_instructions = self.output_parser.get_format_instructions()
instance-attribute
max_retries = max_retries
instance-attribute
model = AutoModelForCausalLM.from_pretrained(model_or_id)
instance-attribute
name = self.__class__.__name__
instance-attribute
num_return_sequences = int(gen_kwargs.pop('num_return_sequences', 1))
instance-attribute
pipeline = TextGenerationPipeline(model=(self.model), tokenizer=(self.tokenizer))
instance-attribute
scale = scale
instance-attribute
tokenizer = tokenizer or AutoTokenizer.from_pretrained(model_or_id)
instance-attribute
use_chat = hasattr(self.tokenizer, 'apply_chat_template') and self.tokenizer.chat_template is not None
instance-attribute
compute(responses, prompts=None, **kwargs)
Compute LLM judge scores for a list of responses.
Evaluates each response using the configured judge model and prompt template. Scores are averaged when multiple
samples are generated per response (via num_return_sequences
).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
responses
|
list[str]
|
List of text responses to evaluate. |
required |
prompts
|
list[str] | None
|
Optional list of prompts corresponding to each response. If provided, must be the same length as responses. These prompts can be referenced in the prompt_template using the {prompt} placeholder. |
None
|
**kwargs
|
Any
|
Additional keyword arguments (currently unused). |
{}
|
Returns:
Type | Description |
---|---|
dict[str, float | list[float]]
|
Score statistics containing:
|
Raises:
Type | Description |
---|---|
AssertionError
|
If prompts is provided but has different length than responses. |
Source code in aisteer360/evaluation/metrics/base_judge.py
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 |
|
perplexity
Perplexity
Bases: Metric
Compute token-level perplexity for a batch of sentences.
Perplexity is the exponentiated mean cross-entropy between the language model’s predicted distribution and the true next token. Lower is better.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_or_id
|
str | Module
|
Hugging Face model ID or an already-instantiated causal language model. |
required |
tokenizer
|
PreTrainedTokenizer | None
|
Tokenizer to use. Leave |
None
|
batch_size
|
int
|
Number of sentences per forward pass. Higher is faster until GPU memory becomes the
bottleneck. Defaults to |
16
|
add_bos
|
bool
|
Whether to prepend the tokenizer’s BOS token so the first word in each sentence is
also scored. Ignored if the tokenizer has no BOS token. Defaults to |
True
|
max_length
|
int | None
|
If set, truncate inputs to this length so they fit the model’s context
window. |
None
|
device
|
str | None
|
|
None
|
Attributes:
Name | Type | Description |
---|---|---|
add_bos |
bool
|
Whether a BOS token is prepended before scoring. |
batch_size |
int
|
Number of sentences processed per forward pass. |
device |
str
|
The device actually selected for computation ( |
max_length |
int | None
|
Truncation length for inputs, or |
model |
PreTrainedModel
|
The loaded causal language model used to score tokens. |
tokenizer |
PreTrainedTokenizer
|
Tokenizer used for encoding, padding, and BOS handling. |
Source code in aisteer360/evaluation/metrics/generic/perplexity.py
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 |
|
add_bos = add_bos and self.tokenizer.bos_token_id is not None
instance-attribute
batch_size = batch_size
instance-attribute
device = device or ('cuda' if torch.cuda.is_available() else 'cpu')
instance-attribute
extras = extras
instance-attribute
max_length = max_length
instance-attribute
model = AutoModelForCausalLM.from_pretrained(model_or_id)
instance-attribute
name = self.__class__.__name__
instance-attribute
tokenizer = tokenizer or AutoTokenizer.from_pretrained(model_or_id)
instance-attribute
compute(responses, prompts=None)
Compute perplexity for each response (and the mean across the batch).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
responses
|
list[str]
|
Text sequences to score. |
required |
prompts
|
list[str] | None
|
Unused here; present for a uniform metric API. |
None
|
Returns:
Type | Description |
---|---|
dict[str, float]
|
dict[str, float]: A dict with keys:
|
Source code in aisteer360/evaluation/metrics/generic/perplexity.py
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 |
|
relevance
Relevance
Bases: LLMJudgeMetric
Judge relevance of a response to a prompt.
Source code in aisteer360/evaluation/metrics/generic/relevance.py
19 20 21 22 23 24 25 26 27 28 29 30 |
|
base_prompt_template = prompt_template.strip()
instance-attribute
batch_size = batch_size
instance-attribute
device = device or ('cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu')
instance-attribute
extras = extras
instance-attribute
format_instructions = self.output_parser.get_format_instructions()
instance-attribute
max_retries = max_retries
instance-attribute
model = AutoModelForCausalLM.from_pretrained(model_or_id)
instance-attribute
name = self.__class__.__name__
instance-attribute
num_return_sequences = int(gen_kwargs.pop('num_return_sequences', 1))
instance-attribute
pipeline = TextGenerationPipeline(model=(self.model), tokenizer=(self.tokenizer))
instance-attribute
scale = scale
instance-attribute
tokenizer = tokenizer or AutoTokenizer.from_pretrained(model_or_id)
instance-attribute
use_chat = hasattr(self.tokenizer, 'apply_chat_template') and self.tokenizer.chat_template is not None
instance-attribute
compute(responses, prompts=None, **kwargs)
Compute LLM judge scores for a list of responses.
Evaluates each response using the configured judge model and prompt template. Scores are averaged when multiple
samples are generated per response (via num_return_sequences
).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
responses
|
list[str]
|
List of text responses to evaluate. |
required |
prompts
|
list[str] | None
|
Optional list of prompts corresponding to each response. If provided, must be the same length as responses. These prompts can be referenced in the prompt_template using the {prompt} placeholder. |
None
|
**kwargs
|
Any
|
Additional keyword arguments (currently unused). |
{}
|
Returns:
Type | Description |
---|---|
dict[str, float | list[float]]
|
Score statistics containing:
|
Raises:
Type | Description |
---|---|
AssertionError
|
If prompts is provided but has different length than responses. |
Source code in aisteer360/evaluation/metrics/base_judge.py
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 |
|
use_cases
base
Base class for all use cases. Provides a framework for loading evaluation data, applying metrics, and running
standardized evaluations across different types of tasks. Subclasses must implement the generate()
and evaluate()
methods to define task-specific evaluation logic.
UseCase
Bases: ABC
Base use case class.
Source code in aisteer360/evaluation/use_cases/base.py
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 |
|
evaluation_data = [(json.loads(line)) for line in f] if path.suffix == '.jsonl' else json.load(f)
instance-attribute
evaluation_metrics = evaluation_metrics
instance-attribute
evaluate(generations)
abstractmethod
Required evaluation logic for model's generations via evaluation_metrics
.
Source code in aisteer360/evaluation/use_cases/base.py
68 69 70 71 72 73 74 75 76 |
|
export(profiles, save_dir)
Optional formatting and export of evaluation profiles.
Source code in aisteer360/evaluation/use_cases/base.py
78 79 80 81 82 83 84 85 |
|
generate(model_or_pipeline, tokenizer, gen_kwargs=None, runtime_overrides=None)
abstractmethod
Required generation logic for the current use case.
Source code in aisteer360/evaluation/use_cases/base.py
55 56 57 58 59 60 61 62 63 64 65 66 |
|
validate_evaluation_data(evaluation_data)
Optional validation of the evaluation dataset.
Source code in aisteer360/evaluation/use_cases/base.py
90 91 92 93 94 |
|
commonsense_mcqa
Use case class for the commonsense multiple-choice question answering (MCQA) task.
use_case
CommonsenseMCQA
Bases: UseCase
Commonsense MCQA evaluation use case.
Evaluates model's ability to answer commonsense questions via accuracy on the CommonsenseMCQA dataset (https://huggingface.co/datasets/tau/commonsense_qa). Supports answer choice shuffling across multiple runs to reduce position bias and improve evaluation robustness.
The evaluation data should contain questions with multiple choice options where models are asked to respond with only the letter (A, B, C, etc.) corresponding to their chosen answer.
Attributes:
Name | Type | Description |
---|---|---|
num_shuffling_runs |
int
|
Number of times to shuffle answer choices for each question to mitigate position bias effects. |
Source code in aisteer360/evaluation/use_cases/commonsense_mcqa/use_case.py
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 |
|
evaluation_data = [(json.loads(line)) for line in f] if path.suffix == '.jsonl' else json.load(f)
instance-attribute
evaluation_metrics = evaluation_metrics
instance-attribute
num_shuffling_runs
instance-attribute
evaluate(generations)
Evaluates generated responses against reference answers using configured metrics.
Extracts responses and reference answers from generations and computes scores using all evaluation metrics specified during initialization.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
generations
|
list[dict[str, Any]]
|
List of generation dictionaries returned by the |
required |
Returns:
Type | Description |
---|---|
dict[str, dict[str, Any]]
|
Dictionary of scores keyed by |
Source code in aisteer360/evaluation/use_cases/commonsense_mcqa/use_case.py
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 |
|
export(profiles, save_dir)
Exports evaluation profiles to (tabbed) JSON format.
Source code in aisteer360/evaluation/use_cases/commonsense_mcqa/use_case.py
176 177 178 179 180 |
|
generate(model_or_pipeline, tokenizer, gen_kwargs=None, runtime_overrides=None)
Generates model responses for multiple-choice questions with shuffled answer orders.
Creates prompts for each question with shuffled answer choices, generates model responses, and parses the outputs to extract letter choices. Repeats the process multiple times with different answer orderings to reduce positional bias.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_or_pipeline
|
Either a HuggingFace model or SteeringPipeline instance to use for generation. |
required | |
tokenizer
|
Tokenizer for encoding/decoding text. |
required | |
gen_kwargs
|
dict | None
|
Optional generation parameters. |
None
|
runtime_overrides
|
dict[tuple[str, str], str] | None
|
Optional runtime parameter overrides for steering controls, structured as {(pipeline_name, param_name): value}. |
None
|
Returns:
Type | Description |
---|---|
list[dict[str, Any]]
|
List of generation dictionaries, each containing:
|
Note:
- The number of returned generations will be
len(evaluation_data)
*num_shuffling_runs
due to answer choice shuffling.
Source code in aisteer360/evaluation/use_cases/commonsense_mcqa/use_case.py
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 |
|
validate_evaluation_data(evaluation_data)
Validates that evaluation data contains required fields for MCQA evaluation.
Ensures each data instance has the necessary keys and non-null values for the evaluation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
evaluation_data
|
dict[str, Any]
|
Dictionary containing a single evaluation instance with question, answer choices, and correct answer information. |
required |
Raises:
Type | Description |
---|---|
ValueError
|
If required keys ('id', 'question', 'answer', 'choices') are missing or if any required fields contain null/NaN values. |
Source code in aisteer360/evaluation/use_cases/commonsense_mcqa/use_case.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
|
instruction_following
Use case class for the instruction following task.
use_case
InstructionFollowing
Bases: UseCase
Instruction following use case using the IFEval dataset.
Evaluates model ability to follow specific instructions by testing adherence to various formatting, content, and structural constraints. Uses the IFEval dataset which contains prompts with explicit instructions that models must follow precisely.
The evaluation focuses on whether models can follow instructions like:
- Formatting requirements (e.g., "respond in exactly 3 sentences")
- Content constraints (e.g., "include the word 'fantastic' twice")
- Structural requirements (e.g., "use bullet points", "write in JSON format")
Expected evaluation data format should include fields like 'prompt', 'instructions', 'instruction_id_list', and 'kwargs' for comprehensive instruction following assessment.
Source code in aisteer360/evaluation/use_cases/instruction_following/use_case.py
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 |
|
evaluation_data = [(json.loads(line)) for line in f] if path.suffix == '.jsonl' else json.load(f)
instance-attribute
evaluation_metrics = evaluation_metrics
instance-attribute
evaluate(generations)
Required evaluation logic for model's generations via evaluation_metrics
.
Source code in aisteer360/evaluation/use_cases/instruction_following/use_case.py
91 92 93 94 95 |
|
export(profiles, save_dir)
Exports instruction following evaluation results to structured JSON files.
Creates two output files:
responses.json
: Contains model responses for each steering methodscores.json
: Contains strict metric scores for each steering method
Parameters:
Name | Type | Description | Default |
---|---|---|---|
profiles
|
dict[str, Any]
|
Dictionary containing evaluation results from all tested pipelines. |
required |
save_dir
|
str
|
Directory path where results should be saved. |
required |
Source code in aisteer360/evaluation/use_cases/instruction_following/use_case.py
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 |
|
generate(model_or_pipeline, tokenizer, gen_kwargs=None, runtime_overrides=None)
Generates model responses for instruction following prompts.
Processes evaluation data to create chat-formatted prompts and generates model responses.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_or_pipeline
|
Either a HuggingFace model or SteeringPipeline instance to use for generation. |
required | |
tokenizer
|
Tokenizer for encoding/decoding text. |
required | |
gen_kwargs
|
dict | None
|
Optional generation parameters passed to the model's generate method. |
None
|
runtime_overrides
|
dict[tuple[str, str], str] | None
|
Optional runtime parameter overrides for steering controls, structured as {(pipeline_name, param_name): value}. |
None
|
Returns:
Type | Description |
---|---|
list[dict[str, Any]]
|
List of generation dictionaries, each containing:
|
Source code in aisteer360/evaluation/use_cases/instruction_following/use_case.py
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 |
|
validate_evaluation_data(evaluation_data)
Optional validation of the evaluation dataset.
Source code in aisteer360/evaluation/use_cases/instruction_following/use_case.py
29 30 |
|
utils
generation_utils
BATCH_SIZE = 64
module-attribute
apply_chat_template(tokenizer, batch, **kwargs)
Constructs template prompts for each batch element based on following cases: 1. If the model's tokenizer does not support chat_template, return the string as is. 2. If it supports chat_template: Check each instance of the batch to construct chat messages if needed. Cases: - Plain string -> convert as 'content' of 'user' - List of dictionaries with 'role' and 'content'. Continue Then apply chat template and return
Source code in aisteer360/evaluation/utils/generation_utils.py
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 |
|
batch_retry_generate(prompt_data, model_or_pipeline, tokenizer, gen_kwargs=None, runtime_overrides=None, evaluation_data=None, parse_fn=None, max_retries=2, return_raw=False)
Generate chat completions with optional parsing/retry logic.
Function keeps retrying only the prompts whose outputs fail parse_fn (up to max_retries); return value is a list of parsed objects (or None if parsing doesn't succeed).
If return_raw is True the function instead returns a tuple (parsed_list, raw_list).
Source code in aisteer360/evaluation/utils/generation_utils.py
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 |
|
chat_generate_model(batch, model, tokenizer, device, gen_kwargs=None)
Batch generate on model with chunking to prevent OOM. Each instance of the batch must have a 'prompt' which could be: - A plain string , in which case we apply the chat template - Dict with the chat template already applied ('role' and 'content' keys)
Source code in aisteer360/evaluation/utils/generation_utils.py
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 |
|
chat_generate_pipeline(batch, pipeline, tokenizer, device, gen_kwargs=None, runtime_overrides=None, evaluation_data=None)
Generate on pipeline.
Source code in aisteer360/evaluation/utils/generation_utils.py
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 |
|
metric_utils
to_1d_array(result, n_examples)
Normalize a metric's result into a 1d numpy array of length n_examples.
Source code in aisteer360/evaluation/utils/metric_utils.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
utils
model_utils
find_project_root(current_path)
Finds root dir by looking for pyproject.toml
Source code in aisteer360/utils/model_utils.py
4 5 6 7 8 9 10 |
|
is_valid_model(config, model_id, service)
Source code in aisteer360/utils/model_utils.py
13 14 15 16 17 18 |
|