Pipeline Unification¶
unit config → unit run
How do I describe a whole run in one place, and make it reproducible?
Intro¶
One YAML unit config describes a whole pipeline that is executed as a unit run and lands in dedicated output dir.
mode: finetune # preprocess | train | finetune | evaluate | test
task: {category, name, metric_groups, preproc_rules}
tokenizer: {source, name, args, ...}
ds: {category, dirs, name, type, splits, preproc_rules, ...}
model: {architecture, pretrained: {cls, args, ...}}
peft: {peft_type, task_type, ...}
trainer: {cls}
training_args: {cls, args}
custom_training_args: {...}
data_collator: {cls, args}
eval: {before_training, after_training, ...}
test: {run, zero_shot, ...}
generation_config: {...}
cuda: {...}
env: {...}
model,tokenizeranddseach can take the HuggingFace Hub slug, or be loaded from local disk.clskeys are class names, resolved at runtime fromtransformersand this package — a new backbone or head needs no code.
clscan also name your own class, once decorated with@micm_plugin— see your own classes.argskeys pass any extra keyword arguments verbatim to theclsconstructor.
python -m micm_nlp run \
--config configs/units/tune.lm.aya.ds.bebe.yml \
--root-path /path/to/your/workspace
--root-pathis only needed whenPROJECT_ROOT_PATHis not set.
Output Dir¶
Everything the run writes is reachable from one directory:
artefacts/runs/units/{model.name}/
├── config.yml # the config as resolved
├── info.json # environment, versions, resolved seed and metric, wandb, paths
├── eval_validation_before_train.csv # one row per metric group
├── eval_validation_after_train.csv # same, from the best checkpoint
├── test_after_train.csv # same, on the test split
├── predictions_after_train.csv # one row per sample, always written
├── model -> … # symlink to the checkpoint
└── wandb -> … # symlink to the wandb run
Console output is kept only by an online wandb run, in wandb/files/output.log; an offline run writes no such file.
The trainer is the only writer of the run directory.
info.jsonholds what the config cannot:started/finished, everySLURM*variable, host, Python,CUDA_VISIBLE_DEVICES, the package versions, wandb id / url / dir, the resolved seed andmetric_for_best_model,paths.best_checkpoint.Metric rows are the
compute_metricsdict verbatim, plusmetric_group,step,time_id,uuid4andoutput.columns.Predictions are saved after the same preprocessing the metric used, so any metric can be recomputed from the file; the
samplecolumn is the example’s position in the test split.<stage>isbefore_trainorafter_train; a run that never trains has no suffix:test.csv,predictions.csv.Each
evaluate()orpredict()call is an event and writes its file once.The same rows are in memory as
output.resultsandoutput.predictions, keyed by event name.
Config¶
Section |
Purpose |
|---|---|
|
|
|
Task identity, metric groups, prediction post-processing rules |
|
PEFT method and its hyperparameters |
|
Architecture tag, pretrained source, adapter, or from-scratch init |
|
Tokenizer source and behaviour |
|
Dataset location, input/label keys, preprocessing and tokenization rules |
|
When to evaluate (before/during/after training), per-task grouping |
|
Whether to run the test split, and zero-shot behaviour |
|
Which HuggingFace |
|
Which HuggingFace |
|
Which collator to instantiate, plus its kwargs |
|
Behaviour this package adds on top of HuggingFace |
|
|
|
Environment variables set at config-load time |
|
Where the run writes and what every result row carries — see |
|
Kwargs for the HuggingFace |
Each section is a pydantic model in micm_nlp.config — the full schema.
Every section accepts extra keys.
Note
PyYAML follows YAML 1.1, where 5e-5 (no decimal point) is a string.
micm_nlp.config extends its float resolver at import, so learning_rate: 5e-5 is a float everywhere.
Your own classes¶
Decorate a class anywhere in your workspace with @micm_plugin, and name it in cls.
from micm_nlp import micm_plugin
from dataclasses import dataclass
from transformers import DataCollatorWithPadding
@micm_plugin
@dataclass
class MyCollator(DataCollatorWithPadding):
alpha: float = 0.5
data_collator: {
cls: MyCollator,
args: {
alpha: 0.7, # for MyCollator
pad_to_multiple_of: 8 # for DataCollatorWithPadding
}
}
Works for every
clskey:trainer,data_collator,training_args,model.pretrained,model.init,model.init.config.argsreach the constructor as keyword arguments, so the class has to declare them.Names resolve from your plugins first, then micm-nlp, then
transformers— a plugin named like a built-in replaces it, with a notice.Every
.pyfile in your workspace that decorates something with@micm_pluginis imported automatically — nothing to install, nothing to import.
Warning
A plugin file’s top-level code runs on that import — keep a script’s work under
if __name__ == '__main__':.@micm_pluginis not autoloaded fromartefacts/,tests/,test/,__pycache__/,node_modules/,build/,dist/, dot-folders and virtualenvs, nor fromtest_*.py,*_test.py,conftest.py.
Your own trainer¶
A trainer takes no args of its own — HuggingFace gives a trainer its settings in TrainingArguments, so yours go in a subclass of it and reach the trainer as self.args.alpha.
from micm_nlp import micm_plugin
from dataclasses import dataclass
from transformers import Trainer, TrainingArguments
@micm_plugin
class MyTrainer(Trainer): ...
@micm_plugin
@dataclass
class MyTrainingArguments(TrainingArguments):
alpha: float = 0.5
trainer: {cls: MyTrainer}
training_args: {
cls: MyTrainingArguments,
args: {
alpha: 0.5, # for MyTrainingArguments
learning_rate: 5e-5 # for TrainingArguments
}
}
task.preproc_rules¶
Post-processing applied to predictions before metrics.
Key |
Meaning |
|---|---|
|
Flatten predictions and labels before metric computation |
|
Drop padded positions |
|
Convert between label ids and names |
|
Normalise label names before comparison |
|
Assert predictions and labels line up |
|
Produce a confusion matrix |
|
Axis for the argmax (default |
|
Restrict the answer-slot argmax to the candidate tokens in |
label_restricted_likelihood is lm-eval-harness multiple_choice scoring for mcqa_ftp: only the label tokens compete at the answer position, not the full vocabulary. Off by default.
peft¶
All Cross-Prompt Encoder variants use peft_type: XPE and differ only in encoder_ratio, the fraction of virtual tokens that are cross-prompt encoded.
|
Variant |
Behaviour |
|---|---|---|
|
SPT |
Plain soft prompt tuning, no reparameterization |
|
XPE |
All virtual tokens pass through the encoder head |
|
DUAL |
Concatenation of both; the ratio is a free hyperparameter |
peft:
peft_type: XPE
task_type: CAUSAL_LM
num_virtual_tokens: 20
encoder_reparameterization_type: MLP
encoder_hidden_size: 256
encoder_num_layers: 2
encoder_dropout: 0.1
encoder_ratio: 1
Any other peft_type goes to stock PEFT.
custom_training_args¶
The knobs this package adds beyond HuggingFace’s TrainingArguments.
Key |
Type |
Meaning |
|---|---|---|
|
float |
Fraction of training before stopping may trigger |
|
int |
Evaluations without improvement before stopping |
|
float |
Minimum improvement that counts |
|
str |
Metric to monitor — see below |
|
int | |
Token-budget batching for evaluation |
|
int | |
Token-budget batching for the test split |
|
bool |
Force a sequential sampler for that stage |
|
bool |
Save the final model after training |
|
bool |
Discard intermediate checkpoints |
|
list[str] |
Extra dataset columns to keep past |
|
list |
Per-parameter-group learning rate and weight decay |
|
bool |
Batch sampler that holds out a random task |
|
list[str] |
Restrict generation to these strings |
early_stopping_metric¶
Early stopping is decoupled from best-checkpoint selection.
Value |
Effect |
|---|---|
|
Delegate to |
any literal key, e.g. |
Monitor that key directly; direction inferred (a name containing |
unset |
Defaults to |
Use it to select on accuracy while the evaluation loss is too unstable to stop on.
eval/test_max_tokens_per_batch¶
Token-budget batching: batches are built to a token count, keeping memory steady across languages whose tokenizations differ in length by an order of magnitude.
Value |
Behaviour |
|---|---|
|
Fixed |
|
Probe the GPU at runtime for the largest budget that does not run out of memory |
an integer |
Skip the probe and use this budget |
A budget counts the tokens in the forward pass: each row’s padded length plus, for a prompt learner (SPT, XPE, DUAL), its virtual tokens, which the length column does not include.
Rule, checked at config load |
Why |
|---|---|
Excludes the matching |
Token budgets need length-sorted batches; a sequential sampler overrides that |
Booleans rejected, integers must be positive |
— |
|
The token-budget sampler length-sorts anyway |
Warning
Samples come out length-sorted, not in dataset order.
Zip predictions against a split through the sampler’s order permutation — the package already does, for per-task grouping and saved predictions.
optimizer_grouped_parameters¶
Gives parameters their own learning rate and weight decay — the mechanism behind a separate schedule for prompt embeddings.
Key |
Meaning |
|---|---|
|
A trainable parameter joins the group if its name contains any of these substrings |
|
The group’s learning rate |
|
The group’s weight decay |
custom_training_args:
optimizer_grouped_parameters:
- param_name_parts:
- dedicated_embeddings
lr: 5.0e-5
weight_decay: 0.01
Parameters that match no group use learning_rate and weight_decay from training_args.
output¶
output is optional; the group runner fills it for you.
Set it by hand only to change dir, add columns, or set a prefix in a custom runner.
Config Example¶
xsc_finetune.yml (from micm-nlp init-examples) preprocesses and fine-tunes BLOOM-560M with the Cross-Prompt
Encoder on the Arabic split of FTP-reframed XStoryCloze:
mode: finetune
task:
id: null
category: text_generation
name: mcqa_ftp
metric_groups:
- metrics:
- accuracy
preproc_rules:
flatten: true
filter_padded: true
label_id_to_name: false
filter_by_prefixes: false
decode: false
label_name_strip_lower: false
label_name_to_float: false
label_name_to_id: false
verify_labels_match: true
calc_confusion_matrix: false
prediction_axis: -1
peft:
peft_type: XPE
task_type: CAUSAL_LM
num_virtual_tokens: 20
encoder_reparameterization_type: MLP
encoder_hidden_size: 256
encoder_num_layers: 2
encoder_dropout: 0.1
encoder_ratio: 1
encoder_input_size: null
encoder_init_state_dict_path: null
encoder_freeze: false
encoder_embedding_freeze: false
encoder_embedding_init_type: hf_default
encoder_embedding_normalize: null
encoder_embedding_normalize_max_norm: null
model:
architecture: bloom
pretrained:
cls: AutoModelForCausalLM
args:
dtype: float32 # transformers 5 would otherwise load the checkpoint's own (fp16)
name: bigscience/bloom-560m
source: huggingface
checkpoint: null
adapter: null
tokenizer:
source: huggingface
name: bigscience/bloom-560m
type: null
algorithm: null
adapt_to_lm: false
args:
padding_side: right
ds:
descriptive_name: null
category: benchmarks
dirs: mikaberidze/xstory-cloze-ftp
name: ar
type: huggingface
splits:
train: eval
test: false
validation: train
input:
key: text
standardize_key: true
label:
key: answer_label
standardize_key: true
task_id: null
preproc_rules:
subset:
run: false
use: 0.01
save_as: false
tokenize:
run: true
pre_rules:
label_name_to_id: false
split_sentences: false
append_eos_token: false
keep_target_texts_for_save: true
text_to_text_rules: false
rules:
max_length: 1024
padding: false
truncation: false
add_special_tokens: true
return_special_tokens_mask: false
return_token_type_ids: false
return_length: true
return_tensors: np
is_split_into_words: false
post_rules:
end_truncation_with_eos: false
concat_samples: false
sort_by_len: true
save_as: false
eval:
before_training: true
before_training_on_test: false
during_training: null
after_training: true
after_training_on_test: false
per_task: null
downstream_tasks: false
test:
run: false
zero_shot: true
zero_shot_only: true
report_to_wandb: true
trainer:
cls: Trainer
data_collator:
cls: DataCollatorForSeq2Seq
args:
max_length: 1024
padding: 'longest'
pad_to_multiple_of: 4
return_tensors: pt
custom_training_args:
train_force_sequential: false
eval_force_sequential: true
test_force_sequential: true
early_stopping_after: 0.5
early_stopping_patience: 30
early_stopping_threshold: 0.0
save_final_model: true
keep_only_final_model: true
random_task_exclusion: false
usable_columns:
- task_ids
optimizer_grouped_parameters:
- param_name_parts:
- dedicated_embeddings
lr: 5.0e-5
weight_decay: 0.01
training_args:
cls: TrainingArguments
args:
num_train_epochs: 10
per_device_train_batch_size: 16
gradient_accumulation_steps: 1
per_device_eval_batch_size: 32
eval_accumulation_steps: 1
logging_strategy: steps
logging_first_step: false
logging_steps: 50
report_to: wandb
eval_strategy: epoch
eval_steps: null
save_strategy: epoch
save_steps: null
save_total_limit: 1
push_to_hub: false
load_best_model_at_end: true
metric_for_best_model: accuracy
greater_is_better: true
learning_rate: 5.0e-5
lr_scheduler_type: cosine_with_restarts
lr_scheduler_kwargs:
num_cycles: 2
warmup_steps: 0.05 # < 1 is a ratio of total steps
weight_decay: 0.01
max_grad_norm: 1.0
train_sampling_strategy: group_by_length
length_column_name: length
full_determinism: false
bf16: true
fp16: false
cuda:
empty_cache_steps: null
env:
PYTORCH_CUDA_ALLOC_CONF: null
TOKENIZERS_PARALLELISM: 'true'
# Logs to artefacts/wandb/ on disk instead of the service, so the example runs
# with no account. Set to 'online' once you have run `wandb login`.
WANDB_MODE: offline