Common library
steerability.algorithms.input_control.common
Reusable building blocks for input controls.
This package holds components whose interface is self-explanatory and shared across unrelated methods.
Method-specific procedures stay in each method's own utils/ directory.
__all__ = ['RolloutBudget', 'ParetoFrontier', 'generate_with_system_prompt']
module-attribute
ParetoFrontier
Pareto-frontier utility over a [n_candidates, n_instances] score matrix.
Maximizes scores by default; pass minimize=True for the opposite. Scores are handled internally as a
maximization problem.
Source code in steerability/algorithms/input_control/common/pareto.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 | |
_minimize = minimize
instance-attribute
_scores = -scores if minimize else scores
instance-attribute
illumination_set
property
Algorithm 2's pruned candidate set Ĉ with win-frequencies f[·].
Returns (candidate_index, coverage) for every candidate that (a) is a per-instance winner on
at least one instance and (b) is not strictly dominated by any other candidate. Equivalent to
[(k, self.coverage(k)) for k in self.non_dominated if self.coverage(k) >= 1].
Empty only in degenerate cases; callers should fall back to uniform sampling then.
non_dominated
property
Candidate indices that are not strictly dominated by any other candidate.
Candidate a is dominated by b iff b >= a on every instance and b > a on at least one.
per_instance_best
property
Per-instance maximum score across candidates. Shape [n_instances]. Returned in the original
sign convention (i.e. minimum, when minimize=True).
per_instance_winners
property
For each instance, the set of candidate indices that achieve the per-instance best.
Multiple candidates may tie.
__init__(scores, minimize=False)
Source code in steerability/algorithms/input_control/common/pareto.py
17 18 19 20 21 22 23 24 | |
coverage(candidate)
Number of instances on which candidate is a per-instance winner (ties count).
Source code in steerability/algorithms/input_control/common/pareto.py
63 64 65 66 | |
RolloutBudget
Counter for capping the number of rollouts an optimizer may consume.
Used by methods that bound offline search (GEPA, CPO).
Example
budget = RolloutBudget(1000) while budget: budget.charge(minibatch_size) ...
Source code in steerability/algorithms/input_control/common/budget.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 33 | |
max = max_rollouts
instance-attribute
remaining
property
spent = 0
instance-attribute
__bool__()
Source code in steerability/algorithms/input_control/common/budget.py
27 28 | |
__init__(max_rollouts)
Source code in steerability/algorithms/input_control/common/budget.py
17 18 19 20 21 | |
charge(n=1)
Source code in steerability/algorithms/input_control/common/budget.py
30 31 32 33 | |
generate_with_system_prompt(task_lm, tokenizer, system_prompt, queries, gen_kwargs=None)
Generate one continuation per query under a shared system prompt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_lm
|
PreTrainedModel
|
Causal language model. |
required |
tokenizer
|
PreTrainedTokenizerBase
|
Tokenizer paired with |
required |
system_prompt
|
str
|
System prompt prepended to every query. |
required |
queries
|
list[str]
|
User-facing query texts (one continuation generated per query). |
required |
gen_kwargs
|
dict | None
|
Forwarded to |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Decoded continuations, one per query, in order. |
Source code in steerability/algorithms/input_control/common/generation.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 | |
budget
Counter for capping the number of rollouts an optimizer may consume.
RolloutBudget
Counter for capping the number of rollouts an optimizer may consume.
Used by methods that bound offline search (GEPA, CPO).
Example
budget = RolloutBudget(1000) while budget: budget.charge(minibatch_size) ...
Source code in steerability/algorithms/input_control/common/budget.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 33 | |
max = max_rollouts
instance-attribute
remaining
property
spent = 0
instance-attribute
__bool__()
Source code in steerability/algorithms/input_control/common/budget.py
27 28 | |
__init__(max_rollouts)
Source code in steerability/algorithms/input_control/common/budget.py
17 18 19 20 21 | |
charge(n=1)
Source code in steerability/algorithms/input_control/common/budget.py
30 31 32 33 | |
formatters
Formatters render Memory content into adapted prompts (token-level or message-level).
__all__ = ['BaseFormatter', 'ChatTemplateSlotFormatter', 'FewShotBlockFormatter', 'PrependTextFormatter', 'SystemPromptFormatter']
module-attribute
BaseFormatter
Bases: ABC
Renders memory content into an adapted prompt.
Two entry points: token-level (apply_to_ids) and message-level (apply_to_messages). Subclasses
implement one or both; the default of the unused one raises NotImplementedError. Methods using
adapt_messages should prefer apply_to_messages since it operates before chat-template tokenization.
Source code in steerability/algorithms/input_control/common/formatters/base.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 | |
apply_to_ids(input_ids, memory, tokenizer, runtime_kwargs=None)
Source code in steerability/algorithms/input_control/common/formatters/base.py
20 21 22 23 24 25 26 27 28 29 | |
apply_to_messages(messages, memory, runtime_kwargs=None)
Source code in steerability/algorithms/input_control/common/formatters/base.py
31 32 33 34 35 36 37 38 39 | |
ChatTemplateSlotFormatter
Bases: BaseFormatter
Replaces {{slot}} placeholders inside message content with the corresponding memory slot.
Slot values may be str or list[str] (lists are joined as bullet points). Unmatched placeholders
are left as-is.
Source code in steerability/algorithms/input_control/common/formatters/chat_template_slot.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 | |
_PATTERN = re.compile('\\{\\{\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\}\\}')
class-attribute
instance-attribute
list_prefix = list_prefix
instance-attribute
list_separator = list_separator
instance-attribute
__init__(list_separator='\n- ', list_prefix='- ')
Source code in steerability/algorithms/input_control/common/formatters/chat_template_slot.py
19 20 21 | |
_render_value(value)
Source code in steerability/algorithms/input_control/common/formatters/chat_template_slot.py
23 24 25 26 | |
_substitute(content, memory)
Source code in steerability/algorithms/input_control/common/formatters/chat_template_slot.py
28 29 30 31 32 33 34 | |
apply_to_ids(input_ids, memory, tokenizer, runtime_kwargs=None)
Source code in steerability/algorithms/input_control/common/formatters/base.py
20 21 22 23 24 25 26 27 28 29 | |
apply_to_messages(messages, memory, runtime_kwargs=None)
Source code in steerability/algorithms/input_control/common/formatters/chat_template_slot.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | |
FewShotBlockFormatter
Bases: BaseFormatter
Renders memory['directive'] and memory['examples'] as a single system message.
Each example dict's non-private fields (those not prefixed with _) are emitted as
Title-Cased Key: value lines under a header determined by the example's _polarity.
The _polarity key is set internally by FewShot and is the only required field.
Source code in steerability/algorithms/input_control/common/formatters/few_shot_block.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 | |
DEFAULT_NEGATIVE_HEADER = '### Negative example (behavior to avoid)'
class-attribute
instance-attribute
DEFAULT_POSITIVE_HEADER = '### Positive example (behavior to follow)'
class-attribute
instance-attribute
negative_header = negative_header
instance-attribute
positive_header = positive_header
instance-attribute
__init__(positive_header=DEFAULT_POSITIVE_HEADER, negative_header=DEFAULT_NEGATIVE_HEADER)
Source code in steerability/algorithms/input_control/common/formatters/few_shot_block.py
22 23 24 25 26 27 28 | |
_render_block(memory)
Source code in steerability/algorithms/input_control/common/formatters/few_shot_block.py
42 43 44 45 46 47 48 49 | |
_render_example(example)
Source code in steerability/algorithms/input_control/common/formatters/few_shot_block.py
30 31 32 33 34 35 36 37 38 39 40 | |
apply_to_ids(input_ids, memory, tokenizer, runtime_kwargs=None)
Source code in steerability/algorithms/input_control/common/formatters/few_shot_block.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | |
apply_to_messages(messages, memory, runtime_kwargs=None)
Source code in steerability/algorithms/input_control/common/formatters/few_shot_block.py
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | |
PrependTextFormatter
Bases: BaseFormatter
Prepends memory["text"] to a user message or to the raw token ids.
When operating on messages, the prepended text is concatenated to the content of the user-role
message(s) selected by target, joined with separator. target is one of:
- `"first_user"`: the first user-role message.
- `"last_user"`: the last user-role message.
- `"all_user"`: every user-role message.
When a chat contains no user-role message, all targets append a new {"role": "user", "content": text}
turn. Message dicts are copied, so the caller's structures are not mutated. When operating on token ids,
the encoded text is prefixed to each sequence in the batch; token streams carry no turn structure, so
target does not apply on the apply_to_ids path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
separator
|
str
|
String inserted between the prepended text and the existing message content. |
'\n\n'
|
target
|
str
|
Which user-role message(s) to prepend to ( |
'first_user'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in steerability/algorithms/input_control/common/formatters/prepend_text.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 | |
separator = separator
instance-attribute
target = target
instance-attribute
__init__(separator='\n\n', target='first_user')
Source code in steerability/algorithms/input_control/common/formatters/prepend_text.py
36 37 38 39 40 41 42 | |
_resolve_text(memory)
Source code in steerability/algorithms/input_control/common/formatters/prepend_text.py
44 45 46 47 48 49 50 | |
_target_indices(chat)
Source code in steerability/algorithms/input_control/common/formatters/prepend_text.py
52 53 54 55 56 57 58 59 60 | |
apply_to_ids(input_ids, memory, tokenizer, runtime_kwargs=None)
Source code in steerability/algorithms/input_control/common/formatters/prepend_text.py
84 85 86 87 88 89 90 91 92 93 94 95 96 97 | |
apply_to_messages(messages, memory, runtime_kwargs=None)
Source code in steerability/algorithms/input_control/common/formatters/prepend_text.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | |
SystemPromptFormatter
Bases: BaseFormatter
Sets or merges the leading system message in each chat with memory["instruction"].
Only the leading system message (chat[0] when its role is "system") participates; system messages
elsewhere in the chat are left untouched. When a leading system message is present, mode controls how
the instruction combines with its content:
- `"replace"`: the instruction becomes the content.
- `"prepend"`: `instruction + separator + existing`.
- `"append"`: `existing + separator + instruction`.
When no leading system message is present, all three modes insert a single
{"role": "system", "content": instruction} at position 0, so separator has no effect. Message dicts are
copied, so the caller's structures are not mutated. Every input shape yields exactly one leading system
message.
The token path (apply_to_ids) decodes, re-templates, and re-encodes, so it cannot merge with a system
prompt that decoding has flattened into text; mode does not apply there, and every mode behaves as
"replace". Prefer message-level entry for chat input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
str
|
How the instruction combines with an existing leading system message ( |
'replace'
|
separator
|
str
|
String inserted between the instruction and the existing content for |
'\n\n'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in steerability/algorithms/input_control/common/formatters/system_prompt.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 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 | |
mode = mode
instance-attribute
separator = separator
instance-attribute
__init__(mode='replace', separator='\n\n')
Source code in steerability/algorithms/input_control/common/formatters/system_prompt.py
45 46 47 48 49 | |
_resolve_instruction(memory)
Source code in steerability/algorithms/input_control/common/formatters/system_prompt.py
51 52 53 54 55 56 57 | |
apply_to_ids(input_ids, memory, tokenizer, runtime_kwargs=None)
Source code in steerability/algorithms/input_control/common/formatters/system_prompt.py
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 | |
apply_to_messages(messages, memory, runtime_kwargs=None)
Source code in steerability/algorithms/input_control/common/formatters/system_prompt.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 | |
base
Token-level and message-level rendering of Memory content.
BaseFormatter
Bases: ABC
Renders memory content into an adapted prompt.
Two entry points: token-level (apply_to_ids) and message-level (apply_to_messages). Subclasses
implement one or both; the default of the unused one raises NotImplementedError. Methods using
adapt_messages should prefer apply_to_messages since it operates before chat-template tokenization.
Source code in steerability/algorithms/input_control/common/formatters/base.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 | |
apply_to_ids(input_ids, memory, tokenizer, runtime_kwargs=None)
Source code in steerability/algorithms/input_control/common/formatters/base.py
20 21 22 23 24 25 26 27 28 29 | |
apply_to_messages(messages, memory, runtime_kwargs=None)
Source code in steerability/algorithms/input_control/common/formatters/base.py
31 32 33 34 35 36 37 38 39 | |
chat_template_slot
Replace {{slot}} placeholders in messages with memory content.
ChatTemplateSlotFormatter
Bases: BaseFormatter
Replaces {{slot}} placeholders inside message content with the corresponding memory slot.
Slot values may be str or list[str] (lists are joined as bullet points). Unmatched placeholders
are left as-is.
Source code in steerability/algorithms/input_control/common/formatters/chat_template_slot.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 | |
_PATTERN = re.compile('\\{\\{\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\}\\}')
class-attribute
instance-attribute
list_prefix = list_prefix
instance-attribute
list_separator = list_separator
instance-attribute
__init__(list_separator='\n- ', list_prefix='- ')
Source code in steerability/algorithms/input_control/common/formatters/chat_template_slot.py
19 20 21 | |
_render_value(value)
Source code in steerability/algorithms/input_control/common/formatters/chat_template_slot.py
23 24 25 26 | |
_substitute(content, memory)
Source code in steerability/algorithms/input_control/common/formatters/chat_template_slot.py
28 29 30 31 32 33 34 | |
apply_to_ids(input_ids, memory, tokenizer, runtime_kwargs=None)
Source code in steerability/algorithms/input_control/common/formatters/base.py
20 21 22 23 24 25 26 27 28 29 | |
apply_to_messages(messages, memory, runtime_kwargs=None)
Source code in steerability/algorithms/input_control/common/formatters/chat_template_slot.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | |
few_shot_block
Render memory['examples'] as a labeled system-message block.
FewShotBlockFormatter
Bases: BaseFormatter
Renders memory['directive'] and memory['examples'] as a single system message.
Each example dict's non-private fields (those not prefixed with _) are emitted as
Title-Cased Key: value lines under a header determined by the example's _polarity.
The _polarity key is set internally by FewShot and is the only required field.
Source code in steerability/algorithms/input_control/common/formatters/few_shot_block.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 | |
DEFAULT_NEGATIVE_HEADER = '### Negative example (behavior to avoid)'
class-attribute
instance-attribute
DEFAULT_POSITIVE_HEADER = '### Positive example (behavior to follow)'
class-attribute
instance-attribute
negative_header = negative_header
instance-attribute
positive_header = positive_header
instance-attribute
__init__(positive_header=DEFAULT_POSITIVE_HEADER, negative_header=DEFAULT_NEGATIVE_HEADER)
Source code in steerability/algorithms/input_control/common/formatters/few_shot_block.py
22 23 24 25 26 27 28 | |
_render_block(memory)
Source code in steerability/algorithms/input_control/common/formatters/few_shot_block.py
42 43 44 45 46 47 48 49 | |
_render_example(example)
Source code in steerability/algorithms/input_control/common/formatters/few_shot_block.py
30 31 32 33 34 35 36 37 38 39 40 | |
apply_to_ids(input_ids, memory, tokenizer, runtime_kwargs=None)
Source code in steerability/algorithms/input_control/common/formatters/few_shot_block.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | |
apply_to_messages(messages, memory, runtime_kwargs=None)
Source code in steerability/algorithms/input_control/common/formatters/few_shot_block.py
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | |
prepend_text
Prepend a raw text block to a user turn or input_ids.
_TARGETS = frozenset({'first_user', 'last_user', 'all_user'})
module-attribute
PrependTextFormatter
Bases: BaseFormatter
Prepends memory["text"] to a user message or to the raw token ids.
When operating on messages, the prepended text is concatenated to the content of the user-role
message(s) selected by target, joined with separator. target is one of:
- `"first_user"`: the first user-role message.
- `"last_user"`: the last user-role message.
- `"all_user"`: every user-role message.
When a chat contains no user-role message, all targets append a new {"role": "user", "content": text}
turn. Message dicts are copied, so the caller's structures are not mutated. When operating on token ids,
the encoded text is prefixed to each sequence in the batch; token streams carry no turn structure, so
target does not apply on the apply_to_ids path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
separator
|
str
|
String inserted between the prepended text and the existing message content. |
'\n\n'
|
target
|
str
|
Which user-role message(s) to prepend to ( |
'first_user'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in steerability/algorithms/input_control/common/formatters/prepend_text.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 | |
separator = separator
instance-attribute
target = target
instance-attribute
__init__(separator='\n\n', target='first_user')
Source code in steerability/algorithms/input_control/common/formatters/prepend_text.py
36 37 38 39 40 41 42 | |
_resolve_text(memory)
Source code in steerability/algorithms/input_control/common/formatters/prepend_text.py
44 45 46 47 48 49 50 | |
_target_indices(chat)
Source code in steerability/algorithms/input_control/common/formatters/prepend_text.py
52 53 54 55 56 57 58 59 60 | |
apply_to_ids(input_ids, memory, tokenizer, runtime_kwargs=None)
Source code in steerability/algorithms/input_control/common/formatters/prepend_text.py
84 85 86 87 88 89 90 91 92 93 94 95 96 97 | |
apply_to_messages(messages, memory, runtime_kwargs=None)
Source code in steerability/algorithms/input_control/common/formatters/prepend_text.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | |
system_prompt
Set or merge the leading system message from memory["instruction"].
_MODES = frozenset({'replace', 'prepend', 'append'})
module-attribute
SystemPromptFormatter
Bases: BaseFormatter
Sets or merges the leading system message in each chat with memory["instruction"].
Only the leading system message (chat[0] when its role is "system") participates; system messages
elsewhere in the chat are left untouched. When a leading system message is present, mode controls how
the instruction combines with its content:
- `"replace"`: the instruction becomes the content.
- `"prepend"`: `instruction + separator + existing`.
- `"append"`: `existing + separator + instruction`.
When no leading system message is present, all three modes insert a single
{"role": "system", "content": instruction} at position 0, so separator has no effect. Message dicts are
copied, so the caller's structures are not mutated. Every input shape yields exactly one leading system
message.
The token path (apply_to_ids) decodes, re-templates, and re-encodes, so it cannot merge with a system
prompt that decoding has flattened into text; mode does not apply there, and every mode behaves as
"replace". Prefer message-level entry for chat input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
str
|
How the instruction combines with an existing leading system message ( |
'replace'
|
separator
|
str
|
String inserted between the instruction and the existing content for |
'\n\n'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in steerability/algorithms/input_control/common/formatters/system_prompt.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 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 | |
mode = mode
instance-attribute
separator = separator
instance-attribute
__init__(mode='replace', separator='\n\n')
Source code in steerability/algorithms/input_control/common/formatters/system_prompt.py
45 46 47 48 49 | |
_resolve_instruction(memory)
Source code in steerability/algorithms/input_control/common/formatters/system_prompt.py
51 52 53 54 55 56 57 | |
apply_to_ids(input_ids, memory, tokenizer, runtime_kwargs=None)
Source code in steerability/algorithms/input_control/common/formatters/system_prompt.py
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 | |
apply_to_messages(messages, memory, runtime_kwargs=None)
Source code in steerability/algorithms/input_control/common/formatters/system_prompt.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 | |
generation
Shared batched generation helper for single-system-prompt input controls.
generate_with_system_prompt runs the task LM over a batch of queries under one system prompt. It applies
the tokenizer's chat template when available (otherwise a plain system\n\nquery join), left-pads for the
causal-LM batch, restores the tokenizer's padding side, and decodes only the continuation.
generate_with_system_prompt(task_lm, tokenizer, system_prompt, queries, gen_kwargs=None)
Generate one continuation per query under a shared system prompt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_lm
|
PreTrainedModel
|
Causal language model. |
required |
tokenizer
|
PreTrainedTokenizerBase
|
Tokenizer paired with |
required |
system_prompt
|
str
|
System prompt prepended to every query. |
required |
queries
|
list[str]
|
User-facing query texts (one continuation generated per query). |
required |
gen_kwargs
|
dict | None
|
Forwarded to |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Decoded continuations, one per query, in order. |
Source code in steerability/algorithms/input_control/common/generation.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 | |
memory
Method-owned, serializable state for input controls.
__all__ = ['Memory', 'PoolMemory', 'TextMemory']
module-attribute
Memory
Bases: Protocol
Method-owned, serializable state.
Methods place their persistent state behind this Protocol so that the framework can save/load it without
knowing the concrete type. Subclass or define a new class that satisfies this Protocol; see TextMemory
for the primary usage.
Source code in steerability/algorithms/input_control/common/memory/base.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
load(path)
classmethod
Source code in steerability/algorithms/input_control/common/memory/base.py
20 21 22 | |
save(path)
Source code in steerability/algorithms/input_control/common/memory/base.py
17 18 | |
PoolMemory
dataclass
Bases: Generic[T]
Typed pool of items with optional parallel-indexed metadata.
items[i] has metadata[k][i] for each metadata key k. All metadata lists must have
len() == len(items). None is used as a placeholder for missing per-item metadata.
Stored as pickle by default (T may be arbitrary). For text-only pools, methods can implement their own JSON path.
Source code in steerability/algorithms/input_control/common/memory/pool.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 | |
items = field(default_factory=list)
class-attribute
instance-attribute
metadata = field(default_factory=dict)
class-attribute
instance-attribute
__init__(items=list(), metadata=dict())
__len__()
Source code in steerability/algorithms/input_control/common/memory/pool.py
25 26 | |
add(item, **per_item_meta)
Source code in steerability/algorithms/input_control/common/memory/pool.py
28 29 30 31 32 33 34 35 36 37 38 39 | |
load(path)
classmethod
Source code in steerability/algorithms/input_control/common/memory/pool.py
45 46 47 48 49 | |
save(path)
Source code in steerability/algorithms/input_control/common/memory/pool.py
41 42 43 | |
TextMemory
dataclass
Named text slots.
Slot values are str or list[str]; nested structures should use a custom Memory implementation instead.
Example
memory = TextMemory(slots={"instruction": "...", "examples": [...]})
Source code in steerability/algorithms/input_control/common/memory/text.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 | |
slots = field(default_factory=dict)
class-attribute
instance-attribute
__contains__(key)
Source code in steerability/algorithms/input_control/common/memory/text.py
27 28 | |
__getitem__(key)
Source code in steerability/algorithms/input_control/common/memory/text.py
21 22 | |
__init__(slots=dict())
__setitem__(key, value)
Source code in steerability/algorithms/input_control/common/memory/text.py
24 25 | |
get(key, default=None)
Source code in steerability/algorithms/input_control/common/memory/text.py
30 31 | |
load(path)
classmethod
Source code in steerability/algorithms/input_control/common/memory/text.py
36 37 38 | |
save(path)
Source code in steerability/algorithms/input_control/common/memory/text.py
33 34 | |
base
The structural contract for input-control state.
Memory
Bases: Protocol
Method-owned, serializable state.
Methods place their persistent state behind this Protocol so that the framework can save/load it without
knowing the concrete type. Subclass or define a new class that satisfies this Protocol; see TextMemory
for the primary usage.
Source code in steerability/algorithms/input_control/common/memory/base.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
load(path)
classmethod
Source code in steerability/algorithms/input_control/common/memory/base.py
20 21 22 | |
save(path)
Source code in steerability/algorithms/input_control/common/memory/base.py
17 18 | |
pool
Typed pool with parallel-indexed metadata.
T = TypeVar('T')
module-attribute
PoolMemory
dataclass
Bases: Generic[T]
Typed pool of items with optional parallel-indexed metadata.
items[i] has metadata[k][i] for each metadata key k. All metadata lists must have
len() == len(items). None is used as a placeholder for missing per-item metadata.
Stored as pickle by default (T may be arbitrary). For text-only pools, methods can implement their own JSON path.
Source code in steerability/algorithms/input_control/common/memory/pool.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 | |
items = field(default_factory=list)
class-attribute
instance-attribute
metadata = field(default_factory=dict)
class-attribute
instance-attribute
__init__(items=list(), metadata=dict())
__len__()
Source code in steerability/algorithms/input_control/common/memory/pool.py
25 26 | |
add(item, **per_item_meta)
Source code in steerability/algorithms/input_control/common/memory/pool.py
28 29 30 31 32 33 34 35 36 37 38 39 | |
load(path)
classmethod
Source code in steerability/algorithms/input_control/common/memory/pool.py
45 46 47 48 49 | |
save(path)
Source code in steerability/algorithms/input_control/common/memory/pool.py
41 42 43 | |
text
Named text slots, JSON-serializable.
TextMemory
dataclass
Named text slots.
Slot values are str or list[str]; nested structures should use a custom Memory implementation instead.
Example
memory = TextMemory(slots={"instruction": "...", "examples": [...]})
Source code in steerability/algorithms/input_control/common/memory/text.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 | |
slots = field(default_factory=dict)
class-attribute
instance-attribute
__contains__(key)
Source code in steerability/algorithms/input_control/common/memory/text.py
27 28 | |
__getitem__(key)
Source code in steerability/algorithms/input_control/common/memory/text.py
21 22 | |
__init__(slots=dict())
__setitem__(key, value)
Source code in steerability/algorithms/input_control/common/memory/text.py
24 25 | |
get(key, default=None)
Source code in steerability/algorithms/input_control/common/memory/text.py
30 31 | |
load(path)
classmethod
Source code in steerability/algorithms/input_control/common/memory/text.py
36 37 38 | |
save(path)
Source code in steerability/algorithms/input_control/common/memory/text.py
33 34 | |
pareto
Utility for Pareto analysis over a [n_candidates, n_instances] score matrix.
Used by methods that maintain instance-wise best-so-far records during search (GEPA).
ParetoFrontier
Pareto-frontier utility over a [n_candidates, n_instances] score matrix.
Maximizes scores by default; pass minimize=True for the opposite. Scores are handled internally as a
maximization problem.
Source code in steerability/algorithms/input_control/common/pareto.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 | |
_minimize = minimize
instance-attribute
_scores = -scores if minimize else scores
instance-attribute
illumination_set
property
Algorithm 2's pruned candidate set Ĉ with win-frequencies f[·].
Returns (candidate_index, coverage) for every candidate that (a) is a per-instance winner on
at least one instance and (b) is not strictly dominated by any other candidate. Equivalent to
[(k, self.coverage(k)) for k in self.non_dominated if self.coverage(k) >= 1].
Empty only in degenerate cases; callers should fall back to uniform sampling then.
non_dominated
property
Candidate indices that are not strictly dominated by any other candidate.
Candidate a is dominated by b iff b >= a on every instance and b > a on at least one.
per_instance_best
property
Per-instance maximum score across candidates. Shape [n_instances]. Returned in the original
sign convention (i.e. minimum, when minimize=True).
per_instance_winners
property
For each instance, the set of candidate indices that achieve the per-instance best.
Multiple candidates may tie.
__init__(scores, minimize=False)
Source code in steerability/algorithms/input_control/common/pareto.py
17 18 19 20 21 22 23 24 | |
coverage(candidate)
Number of instances on which candidate is a per-instance winner (ties count).
Source code in steerability/algorithms/input_control/common/pareto.py
63 64 65 66 | |
proposers
Proposers produce candidate items from a seed.
__all__ = ['BaseProposer', 'LLMMetaPromptProposer', 'RetrievalProposer', 'parse_whole', 'parse_fenced_or_whole', 'parse_concise_instruction']
module-attribute
BaseProposer
Bases: ABC
Produce n candidate items from a seed.
Source code in steerability/algorithms/input_control/common/proposers/base.py
8 9 10 11 12 13 14 15 16 17 18 | |
propose(seed, n=1, context=None)
abstractmethod
Source code in steerability/algorithms/input_control/common/proposers/base.py
11 12 13 14 15 16 17 18 | |
LLMMetaPromptProposer
Bases: BaseProposer
Format a meta-prompt with seed (and optional context), sample n responses from an LLM, and
parse each response into one or more candidates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
llm
|
PreTrainedModel
|
A causal language model. |
required |
tokenizer
|
PreTrainedTokenizerBase
|
Tokenizer paired with |
required |
meta_prompt_template
|
str
|
Python format string. Always receives |
required |
parse_fn
|
Callable[[str], list[Any]]
|
Maps a single decoded LLM response to a list of candidates (dropping empties).
Defaults to |
parse_whole
|
gen_kwargs
|
dict | None
|
Forwarded to |
None
|
use_chat_template
|
bool | None
|
Controls whether the rendered meta-prompt is wrapped as a single user turn
via the tokenizer's chat template before sampling. |
None
|
max_attempts
|
int
|
Maximum number of sampling rounds in |
4
|
Source code in steerability/algorithms/input_control/common/proposers/llm_meta_prompt.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 | |
gen_kwargs = gen_kwargs or {'max_new_tokens': 128, 'do_sample': True, 'temperature': 0.9, 'top_p': 0.95}
instance-attribute
llm = llm
instance-attribute
max_attempts = max_attempts
instance-attribute
meta_prompt_template = meta_prompt_template
instance-attribute
parse_fn = parse_fn
instance-attribute
tokenizer = tokenizer
instance-attribute
use_chat_template = use_chat_template
instance-attribute
__init__(llm, tokenizer, meta_prompt_template, parse_fn=parse_whole, gen_kwargs=None, use_chat_template=None, max_attempts=4)
Source code in steerability/algorithms/input_control/common/proposers/llm_meta_prompt.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | |
_chat_mode()
Source code in steerability/algorithms/input_control/common/proposers/llm_meta_prompt.py
64 65 66 67 68 | |
_render_meta_prompt(seed, context)
Source code in steerability/algorithms/input_control/common/proposers/llm_meta_prompt.py
58 59 60 61 62 | |
_sample_responses(rendered, n)
Source code in steerability/algorithms/input_control/common/proposers/llm_meta_prompt.py
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 | |
propose(seed, n=1, context=None)
Source code in steerability/algorithms/input_control/common/proposers/llm_meta_prompt.py
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |
RetrievalProposer
Bases: BaseProposer
Encode the seed (treated as a query) and retrieve top-n items from a corpus index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoder
|
_Encoder
|
Object exposing |
required |
corpus_index
|
_CorpusIndex
|
Object exposing |
required |
k_max
|
int
|
Hard upper bound on |
100
|
Source code in steerability/algorithms/input_control/common/proposers/retrieval.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 | |
corpus_index = corpus_index
instance-attribute
encoder = encoder
instance-attribute
k_max = k_max
instance-attribute
__init__(encoder, corpus_index, k_max=100)
Source code in steerability/algorithms/input_control/common/proposers/retrieval.py
33 34 35 36 | |
propose(seed, n=1, context=None)
Source code in steerability/algorithms/input_control/common/proposers/retrieval.py
38 39 40 41 42 43 44 45 46 47 48 | |
parse_concise_instruction(text)
Short-system-prompt parser (CPO / PRewrite).
Reduce a free-text LLM response to a single short instruction:
- Split into paragraphs; skip leading preamble paragraphs (single-line cue/lead-in/ acknowledgement) as long as a later paragraph exists; keep the first remaining paragraph.
- Strip a leading enumerator/bullet ("1. ", "2) ", "- ") from the kept paragraph.
- Drop a leading label line ("Refined prompt:") inside the kept paragraph.
- If >= 2 sentences and the last lacks terminal punctuation, drop the trailing fragment.
- Balance quotes AFTER fragment-dropping (matching pair, else orphaned edge quote).
- Reject degenerate results: preamble-only, fewer than 2 words, or an unterminated
candidate longer than
_MAX_UNTERMINATED_WORDS(max_new_tokens truncation junk).
Returns [instruction] for accepted content, else [] (so callers drop the candidate).
Source code in steerability/algorithms/input_control/common/proposers/utils/parsing.py
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 | |
parse_fenced_or_whole(text)
Long-instruction parser (GEPA).
- If one or more ``` fenced blocks exist, take the FIRST block's inner content. A fence that opens but never closes is treated as running to end-of-text.
- Else take the whole text, stripping only a single leading meta lead-in line (e.g. "Here is the revised prompt:", "Sure, here is ...:").
- Preserve all internal structure: paragraphs, blank lines, bullet lists, length. Do not collapse to one paragraph, drop trailing sentences, or cap length.
Returns [candidate] if non-empty, else [].
Source code in steerability/algorithms/input_control/common/proposers/utils/parsing.py
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 | |
parse_whole(text)
Default parser. Return the whole stripped response as a single candidate.
Returns [] when the response is empty or whitespace-only.
Source code in steerability/algorithms/input_control/common/proposers/utils/parsing.py
65 66 67 68 69 70 71 | |
base
Produce n candidate items from a seed.
BaseProposer
Bases: ABC
Produce n candidate items from a seed.
Source code in steerability/algorithms/input_control/common/proposers/base.py
8 9 10 11 12 13 14 15 16 17 18 | |
propose(seed, n=1, context=None)
abstractmethod
Source code in steerability/algorithms/input_control/common/proposers/base.py
11 12 13 14 15 16 17 18 | |
llm_meta_prompt
Sample candidates from an LLM via a templated meta-prompt.
LLMMetaPromptProposer
Bases: BaseProposer
Format a meta-prompt with seed (and optional context), sample n responses from an LLM, and
parse each response into one or more candidates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
llm
|
PreTrainedModel
|
A causal language model. |
required |
tokenizer
|
PreTrainedTokenizerBase
|
Tokenizer paired with |
required |
meta_prompt_template
|
str
|
Python format string. Always receives |
required |
parse_fn
|
Callable[[str], list[Any]]
|
Maps a single decoded LLM response to a list of candidates (dropping empties).
Defaults to |
parse_whole
|
gen_kwargs
|
dict | None
|
Forwarded to |
None
|
use_chat_template
|
bool | None
|
Controls whether the rendered meta-prompt is wrapped as a single user turn
via the tokenizer's chat template before sampling. |
None
|
max_attempts
|
int
|
Maximum number of sampling rounds in |
4
|
Source code in steerability/algorithms/input_control/common/proposers/llm_meta_prompt.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 | |
gen_kwargs = gen_kwargs or {'max_new_tokens': 128, 'do_sample': True, 'temperature': 0.9, 'top_p': 0.95}
instance-attribute
llm = llm
instance-attribute
max_attempts = max_attempts
instance-attribute
meta_prompt_template = meta_prompt_template
instance-attribute
parse_fn = parse_fn
instance-attribute
tokenizer = tokenizer
instance-attribute
use_chat_template = use_chat_template
instance-attribute
__init__(llm, tokenizer, meta_prompt_template, parse_fn=parse_whole, gen_kwargs=None, use_chat_template=None, max_attempts=4)
Source code in steerability/algorithms/input_control/common/proposers/llm_meta_prompt.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | |
_chat_mode()
Source code in steerability/algorithms/input_control/common/proposers/llm_meta_prompt.py
64 65 66 67 68 | |
_render_meta_prompt(seed, context)
Source code in steerability/algorithms/input_control/common/proposers/llm_meta_prompt.py
58 59 60 61 62 | |
_sample_responses(rendered, n)
Source code in steerability/algorithms/input_control/common/proposers/llm_meta_prompt.py
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 | |
propose(seed, n=1, context=None)
Source code in steerability/algorithms/input_control/common/proposers/llm_meta_prompt.py
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |
retrieval
Retrieve top-n items from a corpus index given a query.
RetrievalProposer
Bases: BaseProposer
Encode the seed (treated as a query) and retrieve top-n items from a corpus index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoder
|
_Encoder
|
Object exposing |
required |
corpus_index
|
_CorpusIndex
|
Object exposing |
required |
k_max
|
int
|
Hard upper bound on |
100
|
Source code in steerability/algorithms/input_control/common/proposers/retrieval.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 | |
corpus_index = corpus_index
instance-attribute
encoder = encoder
instance-attribute
k_max = k_max
instance-attribute
__init__(encoder, corpus_index, k_max=100)
Source code in steerability/algorithms/input_control/common/proposers/retrieval.py
33 34 35 36 | |
propose(seed, n=1, context=None)
Source code in steerability/algorithms/input_control/common/proposers/retrieval.py
38 39 40 41 42 43 44 45 46 47 48 | |
_CorpusIndex
Bases: Protocol
Minimal duck-typed contract for the corpus index used by RetrievalProposer.
Source code in steerability/algorithms/input_control/common/proposers/retrieval.py
9 10 11 12 13 14 | |
query(query_embedding, top_k)
Source code in steerability/algorithms/input_control/common/proposers/retrieval.py
13 14 | |
_Encoder
Bases: Protocol
Source code in steerability/algorithms/input_control/common/proposers/retrieval.py
17 18 19 20 | |
encode(text)
Source code in steerability/algorithms/input_control/common/proposers/retrieval.py
19 20 | |
utils
Helpers used by proposer implementations (not proposers themselves).
parsing
Parser strategies for LLMMetaPromptProposer.
A parser maps a single decoded LLM response to a list of candidate strings (dropping empties).
Methods opt into a parser explicitly; the proposer default is parse_whole. Three strategies are
provided:
parse_whole: the whole stripped response as a single candidate (default; minimal processing).parse_fenced_or_whole: long-instruction parser (GEPA). Extracts the first fenced block when present, else the whole text minus a single meta lead-in line; preserves all internal structure.parse_concise_instruction: short-system-prompt parser (CPO / PRewrite). Reduces an LLM response to a single short instruction paragraph, stripping preamble/enumerators and balancing quotes.
_ACK_RE = re.compile('^(sure|certainly|of course|okay|absolutely|great)[!.…]?$', re.IGNORECASE)
module-attribute
_ENUMERATOR_RE = re.compile('^\\s*(\\d{1,2}[.)]|[-*•])\\s+')
module-attribute
_FENCE_RE = re.compile('```')
module-attribute
_LABEL_LINE_RE = re.compile('^[A-Za-z][A-Za-z ]{0,40}:$')
module-attribute
_LEADIN_RE = re.compile("^(sure|certainly|of course|okay|absolutely|here('s| is)|below is|the following is|i('d| would) be happy)\\b", re.IGNORECASE)
module-attribute
_MAX_UNTERMINATED_WORDS = 25
module-attribute
_METAWORD_RE = re.compile('\\b(prompt|version|refin\\w*|rewrit\\w*|revis\\w*|improv\\w*|attempt\\w*)\\b', re.IGNORECASE)
module-attribute
_QUOTE_CLOSERS = {c: o for o, c in _QUOTE_PAIRS}
module-attribute
_QUOTE_OPENERS = {o: c for o, c in _QUOTE_PAIRS}
module-attribute
_QUOTE_PAIRS = {('"', '"'), ("'", "'"), ('“', '”'), ('`', '`')}
module-attribute
_SENTENCE_SPLIT_RE = re.compile('(?<=[.!?])\\s+')
module-attribute
_TERMINAL_RE = re.compile('[.!?:]$')
module-attribute
_is_preamble(paragraph)
Single-line meta-discourse: a cue line, a chatty lead-in about the prompt, or a bare acknowledgement. Multi-line paragraphs are never preamble.
Source code in steerability/algorithms/input_control/common/proposers/utils/parsing.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 | |
_strip_quotes(para)
Strip a matching surrounding pair; otherwise strip an unmatched edge quote whose counterpart does not appear anywhere else in the text (contraction-safe).
Source code in steerability/algorithms/input_control/common/proposers/utils/parsing.py
37 38 39 40 41 42 43 44 45 46 | |
parse_concise_instruction(text)
Short-system-prompt parser (CPO / PRewrite).
Reduce a free-text LLM response to a single short instruction:
- Split into paragraphs; skip leading preamble paragraphs (single-line cue/lead-in/ acknowledgement) as long as a later paragraph exists; keep the first remaining paragraph.
- Strip a leading enumerator/bullet ("1. ", "2) ", "- ") from the kept paragraph.
- Drop a leading label line ("Refined prompt:") inside the kept paragraph.
- If >= 2 sentences and the last lacks terminal punctuation, drop the trailing fragment.
- Balance quotes AFTER fragment-dropping (matching pair, else orphaned edge quote).
- Reject degenerate results: preamble-only, fewer than 2 words, or an unterminated
candidate longer than
_MAX_UNTERMINATED_WORDS(max_new_tokens truncation junk).
Returns [instruction] for accepted content, else [] (so callers drop the candidate).
Source code in steerability/algorithms/input_control/common/proposers/utils/parsing.py
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 | |
parse_fenced_or_whole(text)
Long-instruction parser (GEPA).
- If one or more ``` fenced blocks exist, take the FIRST block's inner content. A fence that opens but never closes is treated as running to end-of-text.
- Else take the whole text, stripping only a single leading meta lead-in line (e.g. "Here is the revised prompt:", "Sure, here is ...:").
- Preserve all internal structure: paragraphs, blank lines, bullet lists, length. Do not collapse to one paragraph, drop trailing sentences, or cap length.
Returns [candidate] if non-empty, else [].
Source code in steerability/algorithms/input_control/common/proposers/utils/parsing.py
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 | |
parse_whole(text)
Default parser. Return the whole stripped response as a single candidate.
Returns [] when the response is empty or whitespace-only.
Source code in steerability/algorithms/input_control/common/proposers/utils/parsing.py
65 66 67 68 69 70 71 | |
scorers
Scorers assign a scalar score to one or more candidate prompts.
__all__ = ['BaseScorer', 'TaskEvaluationScorer']
module-attribute
BaseScorer
Bases: ABC
Score one or more prompts, optionally conditioned on a parallel sequence of queries.
Returns a list[float] of length len(prompts). Query-independent scorers accept queries=None.
Concrete subclasses define what is scored (task evaluation, judge model, reward function). Selecting
from those scores belongs in a BaseSelector.
Source code in steerability/algorithms/input_control/common/scorers/base.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
score(prompts, queries=None)
abstractmethod
Source code in steerability/algorithms/input_control/common/scorers/base.py
16 17 18 19 20 21 22 | |
TaskEvaluationScorer
Bases: BaseScorer
For each candidate prompt, run the task LM over a dev set and aggregate per-row scores into a single scalar.
Each candidate prompt is applied as the system prompt, one response is generated per dev row,
and the candidate's score is the mean of row_scorer(response, row) over the dev rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_lm
|
PreTrainedModel
|
Causal language model used to generate responses on the dev set. |
required |
tokenizer
|
PreTrainedTokenizerBase
|
Tokenizer paired with |
required |
dev_set
|
Sequence[dict]
|
Dataset rows; each row must contain at least the keys consumed by |
required |
row_scorer
|
SampleScorer
|
|
required |
gen_kwargs
|
dict | None
|
Forwarded to |
None
|
max_dev_size
|
int | None
|
Optional cap on the number of dev rows used per scoring call. |
None
|
format_query
|
Callable[[dict], str] | None
|
Callable that turns a dev row into the user-facing query text. Defaults to
|
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in steerability/algorithms/input_control/common/scorers/task_evaluation.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 | |
dev_set = list(dev_set)
instance-attribute
format_query = format_query or (lambda row: row['input'])
instance-attribute
gen_kwargs = gen_kwargs or {'max_new_tokens': 32, 'do_sample': False}
instance-attribute
max_dev_size = max_dev_size
instance-attribute
row_scorer = row_scorer
instance-attribute
task_lm = task_lm
instance-attribute
tokenizer = tokenizer
instance-attribute
__init__(task_lm, tokenizer, dev_set, row_scorer, gen_kwargs=None, max_dev_size=None, format_query=None)
Source code in steerability/algorithms/input_control/common/scorers/task_evaluation.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | |
_generate_responses(prompt, dev_rows)
Generate responses for all dev rows under a single candidate prompt.
Source code in steerability/algorithms/input_control/common/scorers/task_evaluation.py
64 65 66 67 68 69 | |
_resolve_dev()
Source code in steerability/algorithms/input_control/common/scorers/task_evaluation.py
59 60 61 62 | |
score(prompts, queries=None)
Source code in steerability/algorithms/input_control/common/scorers/task_evaluation.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | |
base
Score one or more prompts, optionally per-query.
BaseScorer
Bases: ABC
Score one or more prompts, optionally conditioned on a parallel sequence of queries.
Returns a list[float] of length len(prompts). Query-independent scorers accept queries=None.
Concrete subclasses define what is scored (task evaluation, judge model, reward function). Selecting
from those scores belongs in a BaseSelector.
Source code in steerability/algorithms/input_control/common/scorers/base.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
score(prompts, queries=None)
abstractmethod
Source code in steerability/algorithms/input_control/common/scorers/base.py
16 17 18 19 20 21 22 | |
task_evaluation
Run the task LM on a dev set under each prompt and aggregate via a per-row scorer.
logger = logging.getLogger(__name__)
module-attribute
TaskEvaluationScorer
Bases: BaseScorer
For each candidate prompt, run the task LM over a dev set and aggregate per-row scores into a single scalar.
Each candidate prompt is applied as the system prompt, one response is generated per dev row,
and the candidate's score is the mean of row_scorer(response, row) over the dev rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_lm
|
PreTrainedModel
|
Causal language model used to generate responses on the dev set. |
required |
tokenizer
|
PreTrainedTokenizerBase
|
Tokenizer paired with |
required |
dev_set
|
Sequence[dict]
|
Dataset rows; each row must contain at least the keys consumed by |
required |
row_scorer
|
SampleScorer
|
|
required |
gen_kwargs
|
dict | None
|
Forwarded to |
None
|
max_dev_size
|
int | None
|
Optional cap on the number of dev rows used per scoring call. |
None
|
format_query
|
Callable[[dict], str] | None
|
Callable that turns a dev row into the user-facing query text. Defaults to
|
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in steerability/algorithms/input_control/common/scorers/task_evaluation.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 | |
dev_set = list(dev_set)
instance-attribute
format_query = format_query or (lambda row: row['input'])
instance-attribute
gen_kwargs = gen_kwargs or {'max_new_tokens': 32, 'do_sample': False}
instance-attribute
max_dev_size = max_dev_size
instance-attribute
row_scorer = row_scorer
instance-attribute
task_lm = task_lm
instance-attribute
tokenizer = tokenizer
instance-attribute
__init__(task_lm, tokenizer, dev_set, row_scorer, gen_kwargs=None, max_dev_size=None, format_query=None)
Source code in steerability/algorithms/input_control/common/scorers/task_evaluation.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | |
_generate_responses(prompt, dev_rows)
Generate responses for all dev rows under a single candidate prompt.
Source code in steerability/algorithms/input_control/common/scorers/task_evaluation.py
64 65 66 67 68 69 | |
_resolve_dev()
Source code in steerability/algorithms/input_control/common/scorers/task_evaluation.py
59 60 61 62 | |
score(prompts, queries=None)
Source code in steerability/algorithms/input_control/common/scorers/task_evaluation.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | |
selectors
Selectors pick k items from a pool, optionally query-conditioned.
__all__ = ['BaseSelector', 'DenseRetrievalSelector', 'MMRSelector', 'RandomSelector', 'TopKSelector']
module-attribute
BaseSelector
Bases: ABC, Generic[T]
Pick k items from a pool, optionally query-conditioned.
Source code in steerability/algorithms/input_control/common/selectors/base.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 | |
prepare(model=None, tokenizer=None, data=None, **kwargs)
Optional offline setup (e.g. train an encoder, precompute embeddings).
Default no-op. Parent controls invoke selector.prepare(...) during their own steer() step
when a selector implements it.
Source code in steerability/algorithms/input_control/common/selectors/base.py
23 24 25 26 27 28 29 30 31 32 33 34 | |
select(items, query=None, k=1, context=None)
abstractmethod
Source code in steerability/algorithms/input_control/common/selectors/base.py
13 14 15 16 17 18 19 20 21 | |
DenseRetrievalSelector
Bases: BaseSelector[T]
Encode a query and pick the nearest neighbors from items in embedding space.
By default, items are encoded on the fly via item_to_text. Subclasses (e.g. EPR's selector) can
precompute embeddings during prepare() and store them on the items themselves; pass
embedding_key to look up a precomputed embedding from a dict-like item instead of re-encoding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoder
|
_Encoder
|
Object exposing |
required |
similarity
|
str
|
Either |
'cosine'
|
item_to_text
|
Callable[[T], str] | None
|
Mapping |
None
|
embedding_key
|
str | None
|
If items are dicts, the key under which a precomputed embedding lives. |
None
|
Source code in steerability/algorithms/input_control/common/selectors/dense_retrieval.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 | |
embedding_key = embedding_key
instance-attribute
encoder = encoder
instance-attribute
item_to_text = item_to_text or str
instance-attribute
similarity = similarity
instance-attribute
__init__(encoder, similarity='cosine', item_to_text=None, embedding_key=None)
Source code in steerability/algorithms/input_control/common/selectors/dense_retrieval.py
33 34 35 36 37 38 39 40 41 42 43 44 45 | |
_embed_item(item)
Source code in steerability/algorithms/input_control/common/selectors/dense_retrieval.py
47 48 49 50 | |
_embed_query(query)
Source code in steerability/algorithms/input_control/common/selectors/dense_retrieval.py
52 53 54 55 56 57 58 | |
_score(q, e)
Source code in steerability/algorithms/input_control/common/selectors/dense_retrieval.py
60 61 62 63 64 | |
_top_k_by_similarity(items, query_embedding, k)
Source code in steerability/algorithms/input_control/common/selectors/dense_retrieval.py
66 67 68 69 70 71 72 73 74 75 76 77 | |
prepare(model=None, tokenizer=None, data=None, **kwargs)
Optional offline setup (e.g. train an encoder, precompute embeddings).
Default no-op. Parent controls invoke selector.prepare(...) during their own steer() step
when a selector implements it.
Source code in steerability/algorithms/input_control/common/selectors/base.py
23 24 25 26 27 28 29 30 31 32 33 34 | |
select(items, query=None, k=1, context=None)
Source code in steerability/algorithms/input_control/common/selectors/dense_retrieval.py
79 80 81 82 83 84 85 86 87 88 89 | |
MMRSelector
Bases: BaseSelector[T]
Maximum-marginal-relevance selection.
At each step, picks the item that maximizes λ · sim(item, query) − (1 − λ) · max_j sim(item, picked_j).
Used when callers want a diverse subset of candidates instead of the top-k by raw similarity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoder
|
_Encoder
|
Object exposing |
required |
lambda_param
|
float
|
Trade-off in [0, 1]. 1.0 = pure relevance, 0.0 = pure diversity. Defaults to 0.5. |
0.5
|
item_to_text
|
Callable[[T], str] | None
|
Mapping |
None
|
Source code in steerability/algorithms/input_control/common/selectors/mmr.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 | |
encoder = encoder
instance-attribute
item_to_text = item_to_text or str
instance-attribute
lambda_param = lambda_param
instance-attribute
__init__(encoder, lambda_param=0.5, item_to_text=None)
Source code in steerability/algorithms/input_control/common/selectors/mmr.py
31 32 33 34 35 36 37 38 39 40 41 | |
_cosine(a, b)
staticmethod
Source code in steerability/algorithms/input_control/common/selectors/mmr.py
43 44 45 46 | |
prepare(model=None, tokenizer=None, data=None, **kwargs)
Optional offline setup (e.g. train an encoder, precompute embeddings).
Default no-op. Parent controls invoke selector.prepare(...) during their own steer() step
when a selector implements it.
Source code in steerability/algorithms/input_control/common/selectors/base.py
23 24 25 26 27 28 29 30 31 32 33 34 | |
select(items, query=None, k=1, context=None)
Source code in steerability/algorithms/input_control/common/selectors/mmr.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 | |
RandomSelector
Bases: BaseSelector[T]
Sample k items uniformly without replacement.
If k >= len(items), returns a copy of all items in random order. The selector owns its
RNG, so reseed() gives per-call determinism without disturbing other consumers of the
process-global generator.
Source code in steerability/algorithms/input_control/common/selectors/random.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 | |
_rng = random.Random(seed)
instance-attribute
__init__(seed=None)
Source code in steerability/algorithms/input_control/common/selectors/random.py
20 21 | |
prepare(model=None, tokenizer=None, data=None, **kwargs)
Optional offline setup (e.g. train an encoder, precompute embeddings).
Default no-op. Parent controls invoke selector.prepare(...) during their own steer() step
when a selector implements it.
Source code in steerability/algorithms/input_control/common/selectors/base.py
23 24 25 26 27 28 29 30 31 32 33 34 | |
reseed(seed)
Re-seed the owned RNG for one call's deterministic selection.
Source code in steerability/algorithms/input_control/common/selectors/random.py
23 24 25 | |
select(items, query=None, k=1, context=None)
Source code in steerability/algorithms/input_control/common/selectors/random.py
27 28 29 30 31 32 33 34 35 36 37 38 39 | |
TopKSelector
Bases: BaseSelector[T]
Pick the k items with the highest scores, where scores come from a BaseScorer.
The scorer's score() is called once with the full item list. Items must be str-castable so they
can be passed as prompts to the scorer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scorer
|
BaseScorer
|
A |
required |
item_to_prompt
|
Callable[[T], str] | None
|
Optional mapping |
None
|
Source code in steerability/algorithms/input_control/common/selectors/top_k.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 | |
item_to_prompt = item_to_prompt or str
instance-attribute
scorer = scorer
instance-attribute
__init__(scorer, item_to_prompt=None)
Source code in steerability/algorithms/input_control/common/selectors/top_k.py
24 25 26 | |
prepare(model=None, tokenizer=None, data=None, **kwargs)
Optional offline setup (e.g. train an encoder, precompute embeddings).
Default no-op. Parent controls invoke selector.prepare(...) during their own steer() step
when a selector implements it.
Source code in steerability/algorithms/input_control/common/selectors/base.py
23 24 25 26 27 28 29 30 31 32 33 34 | |
select(items, query=None, k=1, context=None)
Source code in steerability/algorithms/input_control/common/selectors/top_k.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | |
base
Pick k items from a pool, optionally query-conditioned.
T = TypeVar('T')
module-attribute
BaseSelector
Bases: ABC, Generic[T]
Pick k items from a pool, optionally query-conditioned.
Source code in steerability/algorithms/input_control/common/selectors/base.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 | |
prepare(model=None, tokenizer=None, data=None, **kwargs)
Optional offline setup (e.g. train an encoder, precompute embeddings).
Default no-op. Parent controls invoke selector.prepare(...) during their own steer() step
when a selector implements it.
Source code in steerability/algorithms/input_control/common/selectors/base.py
23 24 25 26 27 28 29 30 31 32 33 34 | |
select(items, query=None, k=1, context=None)
abstractmethod
Source code in steerability/algorithms/input_control/common/selectors/base.py
13 14 15 16 17 18 19 20 21 | |
dense_retrieval
Pick nearest neighbors of a query in a dense embedding space.
T = TypeVar('T')
module-attribute
DenseRetrievalSelector
Bases: BaseSelector[T]
Encode a query and pick the nearest neighbors from items in embedding space.
By default, items are encoded on the fly via item_to_text. Subclasses (e.g. EPR's selector) can
precompute embeddings during prepare() and store them on the items themselves; pass
embedding_key to look up a precomputed embedding from a dict-like item instead of re-encoding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoder
|
_Encoder
|
Object exposing |
required |
similarity
|
str
|
Either |
'cosine'
|
item_to_text
|
Callable[[T], str] | None
|
Mapping |
None
|
embedding_key
|
str | None
|
If items are dicts, the key under which a precomputed embedding lives. |
None
|
Source code in steerability/algorithms/input_control/common/selectors/dense_retrieval.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 | |
embedding_key = embedding_key
instance-attribute
encoder = encoder
instance-attribute
item_to_text = item_to_text or str
instance-attribute
similarity = similarity
instance-attribute
__init__(encoder, similarity='cosine', item_to_text=None, embedding_key=None)
Source code in steerability/algorithms/input_control/common/selectors/dense_retrieval.py
33 34 35 36 37 38 39 40 41 42 43 44 45 | |
_embed_item(item)
Source code in steerability/algorithms/input_control/common/selectors/dense_retrieval.py
47 48 49 50 | |
_embed_query(query)
Source code in steerability/algorithms/input_control/common/selectors/dense_retrieval.py
52 53 54 55 56 57 58 | |
_score(q, e)
Source code in steerability/algorithms/input_control/common/selectors/dense_retrieval.py
60 61 62 63 64 | |
_top_k_by_similarity(items, query_embedding, k)
Source code in steerability/algorithms/input_control/common/selectors/dense_retrieval.py
66 67 68 69 70 71 72 73 74 75 76 77 | |
prepare(model=None, tokenizer=None, data=None, **kwargs)
Optional offline setup (e.g. train an encoder, precompute embeddings).
Default no-op. Parent controls invoke selector.prepare(...) during their own steer() step
when a selector implements it.
Source code in steerability/algorithms/input_control/common/selectors/base.py
23 24 25 26 27 28 29 30 31 32 33 34 | |
select(items, query=None, k=1, context=None)
Source code in steerability/algorithms/input_control/common/selectors/dense_retrieval.py
79 80 81 82 83 84 85 86 87 88 89 | |
_Encoder
Bases: Protocol
Source code in steerability/algorithms/input_control/common/selectors/dense_retrieval.py
13 14 15 16 | |
encode(text)
Source code in steerability/algorithms/input_control/common/selectors/dense_retrieval.py
15 16 | |
mmr
Maximum marginal relevance for diversity.
T = TypeVar('T')
module-attribute
MMRSelector
Bases: BaseSelector[T]
Maximum-marginal-relevance selection.
At each step, picks the item that maximizes λ · sim(item, query) − (1 − λ) · max_j sim(item, picked_j).
Used when callers want a diverse subset of candidates instead of the top-k by raw similarity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoder
|
_Encoder
|
Object exposing |
required |
lambda_param
|
float
|
Trade-off in [0, 1]. 1.0 = pure relevance, 0.0 = pure diversity. Defaults to 0.5. |
0.5
|
item_to_text
|
Callable[[T], str] | None
|
Mapping |
None
|
Source code in steerability/algorithms/input_control/common/selectors/mmr.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 | |
encoder = encoder
instance-attribute
item_to_text = item_to_text or str
instance-attribute
lambda_param = lambda_param
instance-attribute
__init__(encoder, lambda_param=0.5, item_to_text=None)
Source code in steerability/algorithms/input_control/common/selectors/mmr.py
31 32 33 34 35 36 37 38 39 40 41 | |
_cosine(a, b)
staticmethod
Source code in steerability/algorithms/input_control/common/selectors/mmr.py
43 44 45 46 | |
prepare(model=None, tokenizer=None, data=None, **kwargs)
Optional offline setup (e.g. train an encoder, precompute embeddings).
Default no-op. Parent controls invoke selector.prepare(...) during their own steer() step
when a selector implements it.
Source code in steerability/algorithms/input_control/common/selectors/base.py
23 24 25 26 27 28 29 30 31 32 33 34 | |
select(items, query=None, k=1, context=None)
Source code in steerability/algorithms/input_control/common/selectors/mmr.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 | |
_Encoder
Bases: Protocol
Source code in steerability/algorithms/input_control/common/selectors/mmr.py
13 14 15 16 | |
encode(text)
Source code in steerability/algorithms/input_control/common/selectors/mmr.py
15 16 | |
random
Sample k items uniformly without replacement.
T = TypeVar('T')
module-attribute
RandomSelector
Bases: BaseSelector[T]
Sample k items uniformly without replacement.
If k >= len(items), returns a copy of all items in random order. The selector owns its
RNG, so reseed() gives per-call determinism without disturbing other consumers of the
process-global generator.
Source code in steerability/algorithms/input_control/common/selectors/random.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 | |
_rng = random.Random(seed)
instance-attribute
__init__(seed=None)
Source code in steerability/algorithms/input_control/common/selectors/random.py
20 21 | |
prepare(model=None, tokenizer=None, data=None, **kwargs)
Optional offline setup (e.g. train an encoder, precompute embeddings).
Default no-op. Parent controls invoke selector.prepare(...) during their own steer() step
when a selector implements it.
Source code in steerability/algorithms/input_control/common/selectors/base.py
23 24 25 26 27 28 29 30 31 32 33 34 | |
reseed(seed)
Re-seed the owned RNG for one call's deterministic selection.
Source code in steerability/algorithms/input_control/common/selectors/random.py
23 24 25 | |
select(items, query=None, k=1, context=None)
Source code in steerability/algorithms/input_control/common/selectors/random.py
27 28 29 30 31 32 33 34 35 36 37 38 39 | |
top_k
Score items via a BaseScorer and return the top-k.
T = TypeVar('T')
module-attribute
TopKSelector
Bases: BaseSelector[T]
Pick the k items with the highest scores, where scores come from a BaseScorer.
The scorer's score() is called once with the full item list. Items must be str-castable so they
can be passed as prompts to the scorer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scorer
|
BaseScorer
|
A |
required |
item_to_prompt
|
Callable[[T], str] | None
|
Optional mapping |
None
|
Source code in steerability/algorithms/input_control/common/selectors/top_k.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 | |
item_to_prompt = item_to_prompt or str
instance-attribute
scorer = scorer
instance-attribute
__init__(scorer, item_to_prompt=None)
Source code in steerability/algorithms/input_control/common/selectors/top_k.py
24 25 26 | |
prepare(model=None, tokenizer=None, data=None, **kwargs)
Optional offline setup (e.g. train an encoder, precompute embeddings).
Default no-op. Parent controls invoke selector.prepare(...) during their own steer() step
when a selector implements it.
Source code in steerability/algorithms/input_control/common/selectors/base.py
23 24 25 26 27 28 29 30 31 32 33 34 | |
select(items, query=None, k=1, context=None)
Source code in steerability/algorithms/input_control/common/selectors/top_k.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | |