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, tokenizer and ds each can take the HuggingFace Hub slug, or be loaded from local disk.

  • cls keys are class names, resolved at runtime from transformers and this package — a new backbone or head needs no code.
    cls can also name your own class, once decorated with @micm_plugin — see your own classes.

  • args keys pass any extra keyword arguments verbatim to the cls constructor.

python -m micm_nlp run \
    --config        configs/units/tune.lm.aya.ds.bebe.yml \
    --root-path     /path/to/your/workspace
  • --root-path is only needed when PROJECT_ROOT_PATH is 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.json holds what the config cannot: started / finished, every SLURM* variable, host, Python, CUDA_VISIBLE_DEVICES, the package versions, wandb id / url / dir, the resolved seed and metric_for_best_model, paths.best_checkpoint.

  • Metric rows are the compute_metrics dict verbatim, plus metric_group, step, time_id, uuid4 and output.columns.

  • Predictions are saved after the same preprocessing the metric used, so any metric can be recomputed from the file; the sample column is the example’s position in the test split.

  • <stage> is before_train or after_train; a run that never trains has no suffix: test.csv, predictions.csv.

  • Each evaluate() or predict() call is an event and writes its file once.

  • The same rows are in memory as output.results and output.predictions, keyed by event name.

Config

Section

Purpose

mode

preprocess, train, finetune, evaluate, test — selects the pipeline path

task

Task identity, metric groups, prediction post-processing rules

peft

PEFT method and its hyperparameters

model

Architecture tag, pretrained source, adapter, or from-scratch init

tokenizer

Tokenizer source and behaviour

ds

Dataset location, input/label keys, preprocessing and tokenization rules

eval

When to evaluate (before/during/after training), per-task grouping

test

Whether to run the test split, and zero-shot behaviour

trainer

Which HuggingFace Trainer subclass to instantiate

training_args

Which HuggingFace TrainingArguments dataclass, plus its kwargs

data_collator

Which collator to instantiate, plus its kwargs

custom_training_args

Behaviour this package adds on top of HuggingFace

cuda

empty_cache_steps

env

Environment variables set at config-load time

output

Where the run writes and what every result row carries — see output

generation_config

Kwargs for the HuggingFace GenerationConfig, for generative evaluation

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 cls key: trainer, data_collator, training_args, model.pretrained, model.init, model.init.config.

  • args reach 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 .py file in your workspace that decorates something with @micm_plugin is 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_plugin is not autoloaded from artefacts/, tests/, test/, __pycache__/, node_modules/, build/, dist/, dot-folders and virtualenvs, nor from test_*.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

Flatten predictions and labels before metric computation

filter_padded

Drop padded positions

label_id_to_name / label_name_to_id

Convert between label ids and names

label_name_strip_lower

Normalise label names before comparison

verify_labels_match

Assert predictions and labels line up

calc_confusion_matrix

Produce a confusion matrix

prediction_axis

Axis for the argmax (default -1)

label_restricted_likelihood

Restrict the answer-slot argmax to the candidate tokens in ds.label.names

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.

encoder_ratio

Variant

Behaviour

0

SPT

Plain soft prompt tuning, no reparameterization

1

XPE

All virtual tokens pass through the encoder head

0 < r < 1

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

early_stopping_after

float

Fraction of training before stopping may trigger

early_stopping_patience

int

Evaluations without improvement before stopping

early_stopping_threshold

float

Minimum improvement that counts

early_stopping_metric

str

Metric to monitor — see below

eval_max_tokens_per_batch

int | 'auto' | null

Token-budget batching for evaluation

test_max_tokens_per_batch

int | 'auto' | null

Token-budget batching for the test split

train/eval/test_force_sequential

bool

Force a sequential sampler for that stage

save_final_model

bool

Save the final model after training

keep_only_final_model

bool

Discard intermediate checkpoints

usable_columns

list[str]

Extra dataset columns to keep past _remove_unused_columns

optimizer_grouped_parameters

list

Per-parameter-group learning rate and weight decay

random_task_exclusion

bool

Batch sampler that holds out a random task

generation_whitelist

list[str]

Restrict generation to these strings

early_stopping_metric

Early stopping is decoupled from best-checkpoint selection.

Value

Effect

'metric_for_best_model'

Delegate to training_args — same metric and direction used to pick the best checkpoint

any literal key, e.g. 'eval_loss'

Monitor that key directly; direction inferred (a name containing loss means lower is better)

unset

Defaults to 'eval_loss'

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

null

Fixed per_device_*_batch_size (the default)

'auto'

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 *_force_sequential

Token budgets need length-sorted batches; a sequential sampler overrides that

Booleans rejected, integers must be positive

—

training_args.train_sampling_strategy is ignored, not rejected

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

param_name_parts

A trainable parameter joins the group if its name contains any of these substrings

lr

The group’s learning rate

weight_decay

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