FewShot
steerability.algorithms.input_control.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.
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
- Keys with a leading underscore in example dicts are reserved by the framework (e.g.
_polarity); user fields should not start with_.
Source code in steerability/algorithms/input_control/few_shot/control.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 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 | |
RUNTIME_KWARGS_SCHEMA = [{'name': 'positive_examples', 'type': 'list[dict]', 'scope': 'call', 'help': 'Positive examples for this call, applied to every prompt row; overrides pool-based selection.'}, {'name': 'negative_examples', 'type': 'list[dict]', 'scope': 'call', 'help': 'Negative examples for this call, applied to every prompt row; overrides pool-based selection.'}]
class-attribute
instance-attribute
args = self.Args.validate(*args, **kwargs)
instance-attribute
directive = None
class-attribute
instance-attribute
enabled = True
class-attribute
instance-attribute
formatter = None
class-attribute
instance-attribute
k_negative = None
class-attribute
instance-attribute
k_positive = None
class-attribute
instance-attribute
memory = None
class-attribute
instance-attribute
negative_example_pool = None
class-attribute
instance-attribute
pool = None
class-attribute
instance-attribute
positive_example_pool = None
class-attribute
instance-attribute
selector = None
class-attribute
instance-attribute
supports_batching = True
class-attribute
instance-attribute
tokenizer = None
class-attribute
instance-attribute
adapt(input_ids, runtime_kwargs=None)
Add few-shot examples to the model's prompt and return adapted token ids.
Both the chat-template path and the no-template fallback route through the resolved
BaseFormatter, which renders the example block from the pool.
Assumes input_ids represents the user's prompt before any chat templating. Pre-templated
input will be re-templated and produce malformed output; use adapt_messages for chat input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_ids
|
list[int] | Tensor
|
The user's prompt token IDs. |
required |
runtime_kwargs
|
dict | None
|
May contain |
None
|
Returns:
| Type | Description |
|---|---|
list[int] | Tensor
|
The transformed token IDs. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If tokenizer is not set (requires calling |
Warns:
| Type | Description |
|---|---|
UserWarning
|
Issued when no examples are configured or none remain after selection. |
Source code in steerability/algorithms/input_control/few_shot/control.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 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 | |
adapt_messages(messages, runtime_kwargs=None)
Insert a single system message containing the directive and labeled example blocks.
Runtime examples (positive_examples / negative_examples in runtime_kwargs) take precedence
over pool-based selection. If there are no examples and no directive, returns None (no change).
Source code in steerability/algorithms/input_control/few_shot/control.py
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 | |
cleanup()
Release resources allocated during steer().
Override in subclasses that allocate GPU memory or other resources during steering. Default no-op.
Source code in steerability/algorithms/core/base_control.py
195 196 197 198 199 200 201 | |
clone_for_call(seed=None)
A configuration-preserving shallow clone for one generation call.
The clone shares steer-time artifacts (memories, steering vectors, attached tokenizers)
with the original but has its own attribute namespace, so per-call attribute mutation on
the clone never races another call using the original. When seed is given and the
control defines reseed(seed), the clone's client-side RNG is re-seeded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int | None
|
Optional seed forwarded to the clone's |
None
|
Returns:
| Type | Description |
|---|---|
BaseControl
|
The clone. |
Source code in steerability/algorithms/core/base_control.py
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 | |
export_state()
Steer-time state to persist when freezing, keyed by logical name.
Values are typed artifacts (SteeringVector, Probe, ProbeSet, a Memory
implementation, CheckpointArtifact, LoRAArtifact, torch.Tensor, or a Path to an
on-disk product). Must be called after steer(). The default returns an empty mapping
(nothing to persist).
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Mapping from logical name to artifact value. |
Source code in steerability/algorithms/core/base_control.py
117 118 119 120 121 122 123 124 125 126 127 128 | |
fit_identity()
The object whose canonical form defines this control's fit digest, or None.
The digest detects recipe edits that invalidate frozen artifacts, so the returned object should cover exactly the inputs a re-fit would consume (training data, fit specs) and exclude inert application parameters (strengths, multipliers). The default returns None (no fits).
Returns:
| Type | Description |
|---|---|
Any | None
|
The fit-identity object, or None. |
Source code in steerability/algorithms/core/base_control.py
161 162 163 164 165 166 167 168 169 170 171 172 | |
frozen_form(state)
The (registry method key, constructor kwargs) of this control's frozen form.
state is the output of export_state(); artifact values inside the returned kwargs
are replaced by store references at encode time. When steer_fits() is empty and
state is empty, the recipe is the frozen form and the control's own key and recipe
args are returned unchanged. A control whose freeze expands into several entries may
return a list of (method key, kwargs) pairs instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
dict[str, Any]
|
The output of |
required |
Returns:
| Type | Description |
|---|---|
tuple[str, dict[str, Any]]
|
The frozen method key and its constructor kwargs. |
Raises:
| Type | Description |
|---|---|
NotFreezableError
|
If the control produces fits or state but declares no frozen form. |
Source code in steerability/algorithms/core/base_control.py
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 | |
requirements()
Backend requirements computed from this instance's configuration, per phase.
Input controls transform the prompt client-side, so the generate phase requires nothing
beyond the session contract on any backend. A control whose steer() reads the live
pipeline model (e.g. for rollouts or scoring) overrides this with a steer-phase
Capability.IN_PROCESS_TORCH requirement.
Returns:
| Type | Description |
|---|---|
Requirements
|
The control's phase-keyed requirements. |
Source code in steerability/algorithms/input_control/base.py
124 125 126 127 128 129 130 131 132 133 134 135 | |
steer(model=None, tokenizer=None, **kwargs)
Optional offline preparation. Default is no-op.
session is a SteeringSession on the steering backend, provided by the pipeline.
Source code in steerability/algorithms/input_control/few_shot/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 | |
steer_access()
The model access this instance's steer step requires, on the ModelAccess ladder.
The default is ModelAccess.FACTS (layout and tokenizer only). A control whose steer
step generates or scores through the session declares ROLLOUTS, one that captures
hidden states declares CAPTURE, and one that touches the model as a live
torch.nn.Module declares MODULE. Configuration determines the result. The pipeline
hands steer() a session scoped to the declared rung, and the live model only at
MODULE. A control may retain the pipeline model beyond steer() only if its
generate phase requires Capability.IN_PROCESS_TORCH.
Returns:
| Type | Description |
|---|---|
ModelAccess
|
The declared access rung. |
Source code in steerability/algorithms/core/base_control.py
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | |
steer_fits()
The fit artifacts this instance's steer step will produce, for the steer plan.
Each entry is (artifact, artifact_class), where artifact is the fit source or
recipe class name and artifact_class is "direction" or "calibrated". The default
is an empty tuple (no fits).
Returns:
| Type | Description |
|---|---|
tuple[tuple[str, str], ...]
|
The declared fit artifacts, in declaration order. |
Source code in steerability/algorithms/core/base_control.py
105 106 107 108 109 110 111 112 113 114 115 | |
selectors
Example selectors for few-shot learning prompt adaptation.
Selectors determine which examples are picked from the pool when constructing the few-shot prompt.
Available selectors:
RandomSelector(re-exported fromcommon.selectors): uniform random sampling. Suitable for homogeneous pools where any example is roughly as informative as any other.EPRSelector: learned dense retriever (Rubin et al. 2021). Constructed by the caller (it requires a scoring LM) and passed toFewShotviaselector=.
EPRSelector
Bases: DenseRetrievalSelector
Learned dense retriever for few-shot example selection (EPR).
At runtime, select() encodes the query and returns the nearest items in the example pool by
cosine similarity over precomputed embeddings. Its prepare() runs the EPR training procedure:
- For each training pair
(x, y), use BM25 overyto retrieve a candidate set of sizecandidate_set_size. - Use the scoring LM to label
k_pospositives andk_negnegatives in the candidate set. - Train a single-tower BERT-base encoder via contrastive loss with in-batch and hard negatives.
The trained encoder is then used at inference time to embed the query and rank pool items.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scoring_lm
|
PreTrainedModel
|
Causal LM used to score (anchor, candidate) pairs during offline labeling. |
required |
scoring_tokenizer
|
PreTrainedTokenizerBase
|
Tokenizer paired with |
required |
base_encoder
|
str
|
Hugging Face model id of the encoder backbone. |
'bert-base-uncased'
|
candidate_set_size
|
int
|
Number of BM25-nearest candidates considered per anchor (paper's |
50
|
k_pos
|
int
|
Number of positives extracted per anchor. |
5
|
k_neg
|
int
|
Number of hard negatives extracted per anchor. |
5
|
train_epochs
|
int
|
Epochs of contrastive training over the labeled pairs. |
3
|
batch_size
|
int
|
Mini-batch size during contrastive training. |
8
|
max_anchors
|
int | None
|
Optional cap on anchors used during labeling (useful for fast CI). |
None
|
input_field
|
str
|
Item key holding the input text. |
'input'
|
output_field
|
str
|
Item key holding the output / target text. |
'output'
|
device
|
Any
|
Optional device override for the encoder. |
None
|
Source code in steerability/algorithms/input_control/few_shot/selectors/epr/selector.py
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 | |
base_encoder_name = base_encoder
instance-attribute
batch_size = batch_size
instance-attribute
candidate_set_size = candidate_set_size
instance-attribute
device = device
instance-attribute
embedding_key = '_epr_embedding'
instance-attribute
encoder = None
instance-attribute
input_field = input_field
instance-attribute
item_to_text = self._format_item
instance-attribute
k_neg = k_neg
instance-attribute
k_pos = k_pos
instance-attribute
max_anchors = max_anchors
instance-attribute
output_field = output_field
instance-attribute
scoring_lm = scoring_lm
instance-attribute
scoring_tokenizer = scoring_tokenizer
instance-attribute
similarity = 'cosine'
instance-attribute
train_epochs = train_epochs
instance-attribute
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/few_shot/selectors/epr/selector.py
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 | |
select(items, query=None, k=1, context=None)
Source code in steerability/algorithms/input_control/few_shot/selectors/epr/selector.py
163 164 165 166 167 168 169 170 171 172 173 174 | |
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 | |
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 | |
selector_from_arg(value)
Resolve a selector argument value to a BaseSelector[dict] instance.
Accepts an instance directly, a string name (looked up in the registry), or None (defaults to
RandomSelector).
Source code in steerability/algorithms/input_control/few_shot/selectors/__init__.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | |
epr
EPR, Efficient Prompt Retrieval (Rubin, Herzig, Berant 2021).
Reference:
- "Learning To Retrieve Prompts for In-Context Learning" Ohad Rubin, Jonathan Herzig, Jonathan Berant https://arxiv.org/abs/2112.08633
EPRSelector
Bases: DenseRetrievalSelector
Learned dense retriever for few-shot example selection (EPR).
At runtime, select() encodes the query and returns the nearest items in the example pool by
cosine similarity over precomputed embeddings. Its prepare() runs the EPR training procedure:
- For each training pair
(x, y), use BM25 overyto retrieve a candidate set of sizecandidate_set_size. - Use the scoring LM to label
k_pospositives andk_negnegatives in the candidate set. - Train a single-tower BERT-base encoder via contrastive loss with in-batch and hard negatives.
The trained encoder is then used at inference time to embed the query and rank pool items.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scoring_lm
|
PreTrainedModel
|
Causal LM used to score (anchor, candidate) pairs during offline labeling. |
required |
scoring_tokenizer
|
PreTrainedTokenizerBase
|
Tokenizer paired with |
required |
base_encoder
|
str
|
Hugging Face model id of the encoder backbone. |
'bert-base-uncased'
|
candidate_set_size
|
int
|
Number of BM25-nearest candidates considered per anchor (paper's |
50
|
k_pos
|
int
|
Number of positives extracted per anchor. |
5
|
k_neg
|
int
|
Number of hard negatives extracted per anchor. |
5
|
train_epochs
|
int
|
Epochs of contrastive training over the labeled pairs. |
3
|
batch_size
|
int
|
Mini-batch size during contrastive training. |
8
|
max_anchors
|
int | None
|
Optional cap on anchors used during labeling (useful for fast CI). |
None
|
input_field
|
str
|
Item key holding the input text. |
'input'
|
output_field
|
str
|
Item key holding the output / target text. |
'output'
|
device
|
Any
|
Optional device override for the encoder. |
None
|
Source code in steerability/algorithms/input_control/few_shot/selectors/epr/selector.py
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 | |
base_encoder_name = base_encoder
instance-attribute
batch_size = batch_size
instance-attribute
candidate_set_size = candidate_set_size
instance-attribute
device = device
instance-attribute
embedding_key = '_epr_embedding'
instance-attribute
encoder = None
instance-attribute
input_field = input_field
instance-attribute
item_to_text = self._format_item
instance-attribute
k_neg = k_neg
instance-attribute
k_pos = k_pos
instance-attribute
max_anchors = max_anchors
instance-attribute
output_field = output_field
instance-attribute
scoring_lm = scoring_lm
instance-attribute
scoring_tokenizer = scoring_tokenizer
instance-attribute
similarity = 'cosine'
instance-attribute
train_epochs = train_epochs
instance-attribute
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/few_shot/selectors/epr/selector.py
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 | |
select(items, query=None, k=1, context=None)
Source code in steerability/algorithms/input_control/few_shot/selectors/epr/selector.py
163 164 165 166 167 168 169 170 171 172 173 174 | |
selector
EPRSelector, a learned dense retriever for few-shot example selection.
Reference:
- "Learning To Retrieve Prompts for In-Context Learning" Ohad Rubin, Jonathan Herzig, Jonathan Berant https://arxiv.org/abs/2112.08633
logger = logging.getLogger(__name__)
module-attribute
EPRSelector
Bases: DenseRetrievalSelector
Learned dense retriever for few-shot example selection (EPR).
At runtime, select() encodes the query and returns the nearest items in the example pool by
cosine similarity over precomputed embeddings. Its prepare() runs the EPR training procedure:
- For each training pair
(x, y), use BM25 overyto retrieve a candidate set of sizecandidate_set_size. - Use the scoring LM to label
k_pospositives andk_negnegatives in the candidate set. - Train a single-tower BERT-base encoder via contrastive loss with in-batch and hard negatives.
The trained encoder is then used at inference time to embed the query and rank pool items.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scoring_lm
|
PreTrainedModel
|
Causal LM used to score (anchor, candidate) pairs during offline labeling. |
required |
scoring_tokenizer
|
PreTrainedTokenizerBase
|
Tokenizer paired with |
required |
base_encoder
|
str
|
Hugging Face model id of the encoder backbone. |
'bert-base-uncased'
|
candidate_set_size
|
int
|
Number of BM25-nearest candidates considered per anchor (paper's |
50
|
k_pos
|
int
|
Number of positives extracted per anchor. |
5
|
k_neg
|
int
|
Number of hard negatives extracted per anchor. |
5
|
train_epochs
|
int
|
Epochs of contrastive training over the labeled pairs. |
3
|
batch_size
|
int
|
Mini-batch size during contrastive training. |
8
|
max_anchors
|
int | None
|
Optional cap on anchors used during labeling (useful for fast CI). |
None
|
input_field
|
str
|
Item key holding the input text. |
'input'
|
output_field
|
str
|
Item key holding the output / target text. |
'output'
|
device
|
Any
|
Optional device override for the encoder. |
None
|
Source code in steerability/algorithms/input_control/few_shot/selectors/epr/selector.py
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 | |
base_encoder_name = base_encoder
instance-attribute
batch_size = batch_size
instance-attribute
candidate_set_size = candidate_set_size
instance-attribute
device = device
instance-attribute
embedding_key = '_epr_embedding'
instance-attribute
encoder = None
instance-attribute
input_field = input_field
instance-attribute
item_to_text = self._format_item
instance-attribute
k_neg = k_neg
instance-attribute
k_pos = k_pos
instance-attribute
max_anchors = max_anchors
instance-attribute
output_field = output_field
instance-attribute
scoring_lm = scoring_lm
instance-attribute
scoring_tokenizer = scoring_tokenizer
instance-attribute
similarity = 'cosine'
instance-attribute
train_epochs = train_epochs
instance-attribute
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/few_shot/selectors/epr/selector.py
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 | |
select(items, query=None, k=1, context=None)
Source code in steerability/algorithms/input_control/few_shot/selectors/epr/selector.py
163 164 165 166 167 168 169 170 171 172 173 174 | |
utils
bm25_index
BM25 candidate retrieval for EPR labeling.
Prefers rank_bm25 when installed; falls back to a minimal pure-NumPy implementation otherwise so
smoke tests can run on the [epr] extra-free baseline.
build_and_query(items, query_field='output', candidate_set_size=50)
For each item, return BM25-nearest candidate indices in the same pool (excluding self).
Used during EPR's offline labeling: for each training pair (x, y), retrieve a candidate set Ē of
size L=candidate_set_size from the rest of the pool, ranking by BM25 over the target sequence y
(the query_field).
Source code in steerability/algorithms/input_control/few_shot/selectors/epr/utils/bm25_index.py
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | |
build_index(corpus)
Return an opaque index object exposing get_scores(query_tokens) -> list[float].
Source code in steerability/algorithms/input_control/few_shot/selectors/epr/utils/bm25_index.py
55 56 57 58 59 60 61 62 | |
query(index, query_text, top_k)
Return the indices of the top-k most BM25-relevant docs in the indexed corpus.
Source code in steerability/algorithms/input_control/few_shot/selectors/epr/utils/bm25_index.py
65 66 67 68 69 70 | |
lm_labeling
LM-based labeling of (anchor, candidate) pairs for EPR.
For each training row (x_i, y_i), compute, for each candidate row (x_j, y_j) from the BM25 set, the
log-probability log p_LM(y_i | (x_j, y_j), x_i). The top-k_pos highest-scoring candidates become
positives, the bottom-k_neg become hard negatives.
logger = logging.getLogger(__name__)
module-attribute
LabeledPair
dataclass
One labeled training pair: an anchor row + a list of (candidate_index, polarity) labels.
Source code in steerability/algorithms/input_control/few_shot/selectors/epr/utils/lm_labeling.py
18 19 20 21 22 23 | |
anchor_index
instance-attribute
negatives
instance-attribute
positives
instance-attribute
label_pairs(items, candidate_sets, scoring_lm, scoring_tokenizer, k_pos=5, k_neg=5, input_field='input', output_field='output', max_anchors=None)
Label each anchor with its k_pos best and k_neg worst candidates by LM scoring.
max_anchors caps the number of anchors processed (useful for fast CI); when None, scores every
anchor in candidate_sets.
Source code in steerability/algorithms/input_control/few_shot/selectors/epr/utils/lm_labeling.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 | |
train_encoder
Contrastive (DPR-style) training of the EPR dual encoder.
The encoder is a single transformer (we use the same model for both query and document encodings, sharing weights). Training uses an InfoNCE-style objective with in-batch negatives and the LM-labeled hard negatives.
logger = logging.getLogger(__name__)
module-attribute
EPREncoder
A thin encoder wrapper exposing encode(text) -> np.ndarray.
Uses mean-pooled last_hidden_state with attention masking. Backbone is shared between queries and pool items (a single-tower retriever, like DPR's text-only variant).
Source code in steerability/algorithms/input_control/few_shot/selectors/epr/utils/train_encoder.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 | |
device
property
model = AutoModel.from_pretrained(model_name_or_path)
instance-attribute
tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
instance-attribute
encode(text)
Source code in steerability/algorithms/input_control/few_shot/selectors/epr/utils/train_encoder.py
41 42 43 44 45 46 47 48 | |
train(labeled, items, base_encoder='bert-base-uncased', epochs=3, batch_size=8, **kwargs)
Source code in steerability/algorithms/input_control/few_shot/selectors/epr/utils/train_encoder.py
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | |
train_encoder(items, labeled, base_encoder='bert-base-uncased', epochs=3, batch_size=8, learning_rate=2e-05, input_field='input', output_field='output', device=None)
Train (or fine-tune) a dual encoder for EPR.
Returns:
| Type | Description |
|---|---|
EPREncoder
|
An |
Source code in steerability/algorithms/input_control/few_shot/selectors/epr/utils/train_encoder.py
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 | |