TextPredictionTrainer
Bases: Trainer
Trainer for text prediction (MLM/CLM) using DataFrames.
Handles MLM/CLM data from pandas DataFrames with support for:
- Per-class datasets (e.g., one DataFrame for "Asian", one for "White")
- Automatic class pair combination (e.g., Asian<->White)
- Factual/counterfactual creation
- Automatic label mapping
Required DataFrame columns (names configurable via TextPredictionConfig):
- masked: Text with mask tokens
- label: Target token (e.g., "he", "He")
- label_class: Feature class (e.g., "male", "female", "Asian", "White")
- split: train/val/test
Optional:
- correlation_mapping: Dict mapping label_class -> correlation value (default: +1/-1 for binary)
Initialize TextPredictionTrainer (Trainer with model at creation time).
Two usage patterns are supported:
1) Config object: pass a full TextPredictionConfig as config=.
2) Explicit parameters: pass run_id, data, target_classes and any
other config fields as keyword arguments; they are wrapped into an internal
TextPredictionConfig. Omitted arguments use the config dataclass defaults.
The number of different counterfactuals paired with the same factual sentence (when multiple are available) is controlled by max_counterfactuals_per_sentence (default 1). Only applies in per-class single-token mode when the alternative is derived from the other class's DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Union[str, Any]
|
Model identifier (string path) or ModelWithGradiend instance. |
required |
run_id
|
Optional[str]
|
Optional run identifier (subdir and display). |
None
|
data
|
Optional[Union[DataFrame, Dict[str, DataFrame], str, Path]]
|
Training data (DataFrame, dict of DataFrames, or path to .csv/.parquet). |
None
|
correlation_mapping
|
Optional[Dict[str, float]]
|
Optional correlation mapping dict. |
None
|
config
|
Optional[TextPredictionConfig]
|
Optional TextPredictionConfig instance. If given, other config-related kwargs are ignored except target_classes. |
None
|
target_classes
|
Optional[Union[List[str], Tuple[str, ...]]]
|
Target classes for training (e.g. ["3SG", "3PL"]). Pair is inferred when len(target_classes) == 2. |
None
|
args
|
Optional[TrainingArguments]
|
Alias for training_args. Training arguments (batch size, steps, etc.). |
None
|
training_args
|
Optional[TrainingArguments]
|
Training arguments. If both args and training_args are set, training_args takes precedence. |
None
|
evaluator_class
|
Optional[Type]
|
Optional custom Evaluator class. |
None
|
hf_dataset
|
Optional[str]
|
HuggingFace dataset ID when loading from HF instead of data. |
None
|
hf_subset
|
Optional[Union[str, List[str]]]
|
Subset/config name(s) for HF dataset. |
None
|
hf_splits
|
Optional[List[str]]
|
Splits to load (e.g. ["train", "validation"]). |
None
|
dataset_trust_remote_code
|
Optional[bool]
|
Optional trust_remote_code value for HuggingFace datasets.load_dataset. None means do not pass it. |
None
|
all_classes
|
Optional[List[str]]
|
All class names in the dataset; inferred from data if None. |
None
|
masked_col
|
Optional[str]
|
Column name for masked sentences (default "masked"). |
None
|
label_col
|
Optional[str]
|
Column name for factual token (default "label"). |
None
|
label_class_col
|
Optional[str]
|
Column name for factual class (default "label_class"). |
None
|
split_col
|
Optional[str]
|
Column name for split (default "split"). |
_SPLIT_COL_UNSET
|
alternative_col
|
Optional[str]
|
Column name for alternative token in merged format. |
None
|
alternative_class_col
|
Optional[str]
|
Column name for alternative class in merged format. |
None
|
use_class_names_as_columns
|
Optional[bool]
|
Use class name as column for that class's token. |
None
|
max_counterfactuals_per_sentence
|
Optional[int]
|
Max unique counterfactual tokens per base sentence when deriving from other class (default 1). |
None
|
random_state
|
Optional[int]
|
Seed for reproducible counterfactual sampling; None = nondeterministic. |
None
|
n_features
|
Optional[int]
|
Number of features (default 1). |
None
|
decoder_eval_targets
|
Optional[Dict[str, List[str]]]
|
Per-class token lists for decoder evaluation. |
None
|
decoder_eval_restrict_to_target_classes
|
Optional[bool]
|
Restrict decoder eval to target classes. |
None
|
decoder_eval_prob_on_other_class
|
Optional[bool]
|
Evaluate target prob on other class's data. |
None
|
decoder_eval_ignore_tokens
|
Optional[List[str]]
|
Tokens to ignore in LMS evaluation. |
None
|
decoder_eval_lms_max_samples
|
Optional[int]
|
Max samples for LMS in decoder eval. |
None
|
eval_neutral_data
|
Optional[Union[DataFrame, str, Path]]
|
DataFrame or path for neutral evaluation data. |
None
|
eval_neutral_max_rows
|
Optional[int]
|
Max rows to load from neutral HF datasets. |
None
|
img_format
|
Optional[str]
|
Image format for plots (e.g. 'pdf', 'png'). Default 'png'. |
None
|
img_dpi
|
Optional[int]
|
DPI for saved plots (e.g. 600 for publication). None = use visualizer default. |
None
|
class_merge_map
|
Optional[Dict[str, List[str]]]
|
Optional mapping from merged class names to raw classes. |
None
|
class_merge_transition_groups
|
Optional[List[List[str]]]
|
Optional raw-class transition groups to keep before merging. |
None
|
split_group_col
|
Optional[str]
|
Optional column used to group examples for vocabulary-held-out splitting. |
None
|
split_group_key
|
SplitGroupKey
|
Optional callable or callable sequence applied before split grouping. |
None
|
split_ratios
|
Optional[SplitRatiosInput]
|
Optional train/validation/test split ratio specification. |
None
|
split_train_ratio
|
Optional[float]
|
Train split ratio used when split_ratios is omitted. |
None
|
split_val_ratio
|
Optional[float]
|
Validation split ratio used when split_ratios is omitted. |
None
|
split_test_ratio
|
Optional[float]
|
Test split ratio used when split_ratios is omitted. |
None
|
Source code in gradiend/trainer/text/prediction/trainer.py
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 | |
_data_materialized_all_class_transitions
instance-attribute
combined_data
property
Unified training data (lazy-loaded on first access). When class_merge_map is set, already merged at load.
default_model_with_gradiend_cls
property
Default ModelWithGradiend subclass for TextPredictionTrainer.
Returns TextPredictionModelWithGradiend (TextModelWithGradiend).
_adopt_recorded_setting
Make this trainer's training_args carry the value of name a loaded model was trained with.
A warning is logged only when this replaces a value the trainer's arguments had set (not when they left it
at None).
Source code in gradiend/trainer/text/prediction/trainer.py
_analyze_encoder
_analyze_encoder(model_with_gradiend=None, split='test', neutral_data_df=None, max_size=None, use_cache=None, plot=False, include_other_classes=None, use_all_transitions=False, transition_selection=None, text_col=None, masked_col=None, factual_token_col=None, alternative_token_col=None, source_id_col=None, target_id_col=None, **kwargs)
Analyze encoder by encoding gradients from training data and optional neutral data.
This method processes all variants in a single call:
- Training data (always processed)
- Neutral variant 1 (if decoder_eval_targets configured)
- Neutral variant 2 (if neutral_data_df provided)
This method handles caching. If cached data exists and use_cache=True, it is loaded and returned. Otherwise, the analysis is performed and results are cached.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_with_gradiend
|
Optional[Any]
|
ModelWithGradiend instance |
None
|
split
|
EncoderSplit
|
Dataset split to use |
'test'
|
neutral_data_df
|
Optional[DataFrame]
|
Optional DataFrame with neutral examples (variant 2) |
None
|
max_size
|
Optional[int]
|
Maximum number of samples per variant to encode |
None
|
use_cache
|
Optional[bool]
|
If True, use cached encoder analysis when available. |
None
|
plot
|
bool
|
If True, create encoder distribution plot from analyzed data. |
False
|
include_other_classes
|
Optional[bool]
|
If True, include all transitions in the split
(when |
None
|
use_all_transitions
|
bool
|
Deprecated alias for |
False
|
transition_selection
|
Optional[List[Union[TransitionSpec, Tuple[str, str]]]]
|
Optional explicit transition specs added to
the target-pair transitions during encoder analysis. Non-target
probe transitions keep label |
None
|
text_col
|
Optional[str]
|
Column name for text in neutral_data_df (defaults to training_args.masked_col) |
None
|
masked_col
|
Optional[str]
|
Column name for masked text (defaults to training_args.masked_col) |
None
|
factual_token_col
|
Optional[str]
|
Key name for factual token in entries (defaults to "factual_token") |
None
|
alternative_token_col
|
Optional[str]
|
Key name for alternative token in entries (defaults to "alternative_token") |
None
|
source_id_col
|
Optional[str]
|
Key name for source class ID in entries (defaults to "factual_id") |
None
|
target_id_col
|
Optional[str]
|
Key name for target class ID in entries (defaults to "alternative_id") |
None
|
**kwargs
|
Any
|
Additional arguments passed to create_eval_data |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns: text, encoded, label, source_id, target_id, type, ... |
DataFrame
|
The 'type' column indicates the variant: 'training', 'neutral_training_masked', or 'neutral_dataset' |
Source code in gradiend/trainer/text/prediction/trainer.py
3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 | |
_apply_random_row_splits
Source code in gradiend/trainer/text/prediction/trainer.py
_apply_vocabulary_splits
Source code in gradiend/trainer/text/prediction/trainer.py
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 | |
_balanced_split_cycle_args
Source code in gradiend/trainer/text/prediction/trainer.py
_base_model_in_force
The model the CLM audit looks at: the model in force, as the base model it is built on.
The model in force is model, else the trainer's _model_arg. That is a Hugging Face id or directory
before training, but the saved GRADIEND checkpoint after train() (and for every seed while the seeds are
evaluated). A checkpoint directory is not a Hugging Face model directory (no model_type, no tokenizer),
so it stands for the base model its config.json records (see :func:checkpoint_base_model_id). A model
object is returned as it is. The objective, the tokenizer and the memory of the audit (_clm_audit) all
read this one answer, so they cannot disagree about which model is trained.
Source code in gradiend/trainer/text/prediction/trainer.py
_cached_encoder_df_matches_request
_cached_encoder_df_matches_request(df, *, include_other_classes=False, use_all_transitions=False, transition_selection=None)
Source code in gradiend/trainer/text/prediction/trainer.py
_check_and_filter_clm_alignment
Run pre-training CLM divergence audit and drop or fail fast on unalignable rows.
Applies under label_token_protocol="first_differing_token" only; "no_leading_space" never aligns.
The rule audited is the one in force for training: the one recorded with model if it is a saved model
(see :meth:_recorded_label_token_protocol), else the one of training_args.
Decided from cheap facts first (the rule, then the objective from the model config), so a trainer that does
not train a decoder-only model under clm_next_token never loads a tokenizer or touches its data. The model
that decides is the base model of the model in force (:meth:_base_model_in_force), so a trained checkpoint
is audited, or not, exactly as the model it was trained from. The outcome is remembered together with the
data it audited (_clm_audit): reloaded or re-split data is audited again, the same data is not.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
training_args
|
Optional[TrainingArguments]
|
Arguments of the run; default the trainer's own. |
None
|
model
|
Any
|
Model that will be trained (object or id/path); default the trainer's model. |
None
|
Source code in gradiend/trainer/text/prediction/trainer.py
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 | |
_check_data_non_empty
Raise ValueError if any provided training data has length 0.
Source code in gradiend/trainer/text/prediction/trainer.py
_collect_decoder_mlm_required_labels
All factual/alternative token strings that may appear during GRADIEND train/eval.
Source code in gradiend/trainer/text/prediction/trainer.py
_configure_model
Give every model this trainer hands out the label-token and chat settings it was trained with.
A model loaded from a directory knows its own rule (see :meth:_recorded_label_token_protocol); it wins
over this trainer's training_args, which datasets and evaluation then follow, so a model is never
scored under another rule than the one it was trained for. A model without a record (e.g. a fresh
backbone) takes the trainer's rule. Single-row scorers receive only the model, but must label exactly
as this trainer's datasets do; see
:func:gradiend.trainer.text.prediction.clm_alignment.label_token_id.
A model with a chat tokenizer (Instruct) supports only "first_differing_token": the rule in effect is
checked here, before anything is trained or evaluated, so a loaded model whose record says
"no_leading_space" (an Instruct model trained with the old rule) fails at load time.
The chat settings follow the same pattern. instruction_model and chat_template_date decided which
tokenizer the model was loaded with and which date its chat template sees (see
TextModelWithGradiend._load_model); a loaded model's recorded value wins over the trainer's, and the
trainer's training_args adopt it (with a warning only when that replaces a value the trainer had set).
For instruction_model the value adopted is the decision in force, i.e. what the loader made of the
record: its stored value, or for a record without one (a model saved before it was stored) the old name
rule. A record without a date leaves the trainer's date (else the default) in force. The chat frame is rendered
once here, so a chat template that cannot frame a system prompt and a user turn fails now, before training,
and a template that inserts the current date logs the fixed date it gets.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the model's tokenizer chat-formats its input and the rule in effect is another one, or its chat template cannot frame a system prompt and a user turn. |
Source code in gradiend/trainer/text/prediction/trainer.py
_configured_split_ratios
Source code in gradiend/trainer/text/prediction/trainer.py
_decoder_mlm_coverage_dataframe
(masked, label) rows from all splits for supplementing MLM-head training.
Source code in gradiend/trainer/text/prediction/trainer.py
_encode_neutral_dataset_rows
_encode_neutral_dataset_rows(model_with_gradiend, neutral_data_df, encoder_kwargs, masked_col_name, excluded_tokens, max_size, torch_dtype, device)
Source code in gradiend/trainer/text/prediction/trainer.py
3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 | |
_encode_neutral_training_masked_rows
_encode_neutral_training_masked_rows(model_with_gradiend, train_eval_data, excluded_tokens, factual_token_key, alternative_token_key, max_size, torch_dtype, device)
Encode neutral variant from training templates with re-masked non-target tokens.
Uses training templates, replaces [MASK] with factual token, then re-masks a random non-excluded token. Returns rows with type='neutral_training_masked'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_with_gradiend
|
Any
|
Model used to encode gradient rows. |
required |
train_eval_data
|
Any
|
Training-like evaluation dataset. |
required |
excluded_tokens
|
List[str]
|
Tokens that must not be selected as neutral mask targets. |
required |
factual_token_key
|
str
|
Key containing the factual token in each dataset item. |
required |
alternative_token_key
|
str
|
Key containing the alternative token in each dataset item. |
required |
max_size
|
Optional[int]
|
Optional row cap. |
required |
torch_dtype
|
Any
|
Torch dtype used when tensors are created. |
required |
device
|
Any
|
Device used for tensors and model execution. |
required |
Source code in gradiend/trainer/text/prediction/trainer.py
3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 | |
_encode_training_rows
Encode training data via gradients and return rows with type='training'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_with_gradiend
|
Any
|
Model used to encode gradient rows. |
required |
train_eval_data
|
Any
|
Evaluation dataset built from training-like rows. |
required |
source_type
|
str
|
Encoder source type, such as |
required |
max_size
|
Optional[int]
|
Optional row cap for logging/metadata consistency. |
required |
encoder_kwargs
|
Dict[str, Any]
|
Encoder evaluation options, including |
required |
Source code in gradiend/trainer/text/prediction/trainer.py
2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 | |
_encoder_cache_path
Encoder cache path for analysis CSV. Cache under experiment_dir; includes split/max_size in cache key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str
|
Model path or identifier associated with this cache lookup. |
required |
**encoder_kwargs
|
Any
|
Encoder-analysis options that affect cache keys,
currently including |
{}
|
Source code in gradiend/trainer/text/prediction/trainer.py
_ensure_data
Load and normalize data on first use. Idempotent.
Training data can be specified as:
- config.hf_dataset: HuggingFace dataset ID (optional subset/splits).
- config.data: HuggingFace dataset ID (per-class configs), local path (.csv/.parquet),
per-class dict, or DataFrame in memory. A string is treated as HF id unless it is an existing file path.
Source code in gradiend/trainer/text/prediction/trainer.py
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 | |
_ensure_data_for_training
Ensure data is loaded before creating the model for training (so pair is set and from_pretrained can set feature_class_encoding_direction).
Source code in gradiend/trainer/text/prediction/trainer.py
_ensure_decoder_eval_text_columns
Ensure DataFrame has 'masked' and 'text' columns for decoder evaluation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Decoder evaluation DataFrame to normalize. |
required |
tokenizer
|
Any
|
Tokenizer whose mask token is used to reconstruct text. |
required |
Source code in gradiend/trainer/text/prediction/trainer.py
_exclude_generated_incomplete_target_classes
Source code in gradiend/trainer/text/prediction/trainer.py
_get_decoder_eval_dataframe
_get_decoder_eval_dataframe(tokenizer, max_size_training_like=None, max_size_neutral=None, split='test', cached_training_like_df=None, cached_neutral_df=None)
Get DataFrame for decoder evaluation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokenizer
|
Any
|
Tokenizer |
required |
max_size_training_like
|
Optional[int]
|
Maximum number of generated training-like samples |
None
|
max_size_neutral
|
Optional[int]
|
Maximum number of generated neutral samples |
None
|
split
|
Optional[EncoderSplit]
|
Dataset split(s) used for generated training-like samples. |
'test'
|
cached_training_like_df
|
Optional[DataFrame]
|
Optional cached training-like DataFrame to reuse |
None
|
cached_neutral_df
|
Optional[DataFrame]
|
Optional cached neutral DataFrame to reuse |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[DataFrame, DataFrame]
|
Tuple (training_like_df, neutral_df) |
Source code in gradiend/trainer/text/prediction/trainer.py
3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 | |
_get_decoder_eval_targets
Get decoder eval targets (delegates to _infer_decoder_eval_targets). Returns dict only; overlap implies row-wise at eval time.
Source code in gradiend/trainer/text/prediction/trainer.py
_infer_decoder_eval_targets
Infer decoder evaluation targets from unified data and, when needed, from per-class datasets. For each class, collects tokens used as factual (when factual_class=C) and as alternative (when alternative_class=C). Returns (targets, has_overlap). When has_overlap is True, the resolver will use row-wise evaluation instead.
Source code in gradiend/trainer/text/prediction/trainer.py
2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 | |
_label_token_protocol
Label-token convention for decoder-only items (see TrainingArguments.label_token_protocol).
One accessor for every dataset this trainer builds, so training, in-training evaluation, neutral rows and post-training evaluation cannot disagree.
Source code in gradiend/trainer/text/prediction/trainer.py
_load_hf_dataset
staticmethod
Load a HuggingFace dataset and convert it to a pandas DataFrame.
This is a convenience method for loading HF datasets with common patterns:
- Handles multiple subsets (e.g., "white_to_black" and "black_to_white")
- Adds split column to each split
- Concatenates all splits into a single DataFrame
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
str
|
HuggingFace dataset identifier (e.g., "aieng-lab/gradiend_race_data") |
required |
subset
|
Optional[Union[str, List[str]]]
|
Optional subset name(s). If str, loads that subset. If list, loads multiple subsets and concatenates them. If None, loads the default subset. |
None
|
splits
|
Optional[List[str]]
|
Optional list of splits to include (e.g., ['train', 'validation', 'test']). If None, includes all available splits. |
None
|
dataset_trust_remote_code
|
Optional[bool]
|
Optional trust_remote_code value forwarded
to |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Combined pandas DataFrame with all splits, including a 'split' column. |
Example
df = TextPredictionTrainer._load_hf_dataset( ... "aieng-lab/gradiend_race_data", ... subset=["white_to_black", "black_to_white"], ... splits=['train', 'validation', 'test'] ... )
Source code in gradiend/trainer/text/prediction/trainer.py
1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 | |
_model_for_clm_objective
The model (or a config-only stand-in for a hub id) that decides the prediction objective before anything is loaded.
A hub id costs one AutoConfig read, not a tokenizer or the weights. Returns None if the config cannot be
read (a warning names the error).
Source code in gradiend/trainer/text/prediction/trainer.py
_neutral_encoder_gradient_creator
Gradient creator for neutral encoder rows under clm_mlm_head training.
Source code in gradiend/trainer/text/prediction/trainer.py
_neutral_encoder_prediction_objective
staticmethod
Objective for neutral encoder rows.
The auxiliary decoder MLM head only defines gradients for its trained target labels, so neutral encoder analysis falls back to CLM next-token gradients.
Source code in gradiend/trainer/text/prediction/trainer.py
_prediction_objective
_recorded_label_token_protocol
staticmethod
The label-token convention a loaded model was trained with, or None if it carries no record.
The record is the training_args saved in the model's training.json (read from the file for a saved
model given as a path). A record without the key
belongs to a model trained before the key existed; :meth:TrainingArguments.from_dict gives it
"no_leading_space" (and translates the old names), so this is the one place nothing else needs to know.
Source code in gradiend/trainer/text/prediction/trainer.py
_refresh_data_splits_for_seed
Source code in gradiend/trainer/text/prediction/trainer.py
_resolve_decoder_eval_targets
Resolve decoder eval targets from configuration and/or data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
training_like_df
|
Optional[DataFrame]
|
Optional training-like decoder evaluation DataFrame. Present for callers that already resolved eval rows; currently used only as part of the resolution contract. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Dict[str, List[str]]]
|
(targets, use_row_wise). When use_row_wise is True, targets is None and evaluation |
bool
|
uses row-wise P(factual) vs P(alternative) per row. When False, targets is |
Tuple[Optional[Dict[str, List[str]]], bool]
|
{class_name: [tokens]} for static class-based evaluation. |
Supported config.decoder_eval_targets:
-
None: Auto-infer from unified data (factual + alternative per class).
If inferred targets overlap across classes, fall back to row-wise and log an info message.
-
"label": Row-wise evaluation (P(factual) and P(alternative) per row).
- Dict[class_name, List[tokens]]: Class-based static targets (validated against known classes).
Source code in gradiend/trainer/text/prediction/trainer.py
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 | |
_resolve_encoder_neutral_excluded_tokens
Tokens that must not be selected as neutral mask targets.
Matches generate_neutral_data exclusion: the feature tokens of the training data plus
eval_neutral_additional_excluded_words (and optional decoder LMS ignores). decoder_eval_targets is
deliberately not used: it only scores the decoder and may be a large vocabulary subset that would remove
thousands of unrelated words from the neutral data.
Source code in gradiend/trainer/text/prediction/trainer.py
_resolve_split_col_strategy
Validate an explicitly requested vocabulary-held-out split strategy.
Source code in gradiend/trainer/text/prediction/trainer.py
_resplit_seed_for_training
Source code in gradiend/trainer/text/prediction/trainer.py
_set_all_classes
Set the list of all classes in the dataset (including neutral/identity).
_target_pair_transition_mask
Source code in gradiend/trainer/text/prediction/trainer.py
_tokenizer_for_clm_audit
Tokenizer available before training starts: the model object's, or one loaded from a hub id.
A tokenizer loaded from a hub id goes through the training loader (:class:AutoTokenizerForLM) with the
trainer's instruction_model and chat_template_date, so the audit aligns the rows of an Instruct model
in its chat format, as training will. For a saved checkpoint the id is that of its base model (see
:meth:_base_model_in_force).
Source code in gradiend/trainer/text/prediction/trainer.py
_train
Ensure mandatory prediction-objective resources before the base Trainer loads the training model. In particular, clm_mlm_head must have a trained auxiliary head, while probability-shift scoring remains on the original CLM head.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
|
str
|
Directory where the trained model will be written. |
required |
args
|
Any
|
Training arguments used for this run. |
required |
model
|
Any
|
Base model argument passed to the trainer. |
required |
model_with_gradiend_cls
|
Any
|
ModelWithGradiend subclass used for loading. |
required |
callbacks
|
Any
|
Training callbacks forwarded to the base trainer. |
required |
runtime_monitor
|
Any
|
Optional runtime monitor for diagnostics. |
None
|
Source code in gradiend/trainer/text/prediction/trainer.py
_validate_classes_in_data
staticmethod
Raise ValueError if any requested class is absent from per-class data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
class_dfs
|
Dict[str, DataFrame]
|
Per-class DataFrame mapping. |
required |
classes
|
List[str]
|
Classes expected to be present in |
required |
param_name
|
str
|
Name used in the error message for the checked parameter. |
'target_classes'
|
Source code in gradiend/trainer/text/prediction/trainer.py
_validate_dataframe
Validate that the DataFrame has the required columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame to validate |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If required columns are missing |
Source code in gradiend/trainer/text/prediction/trainer.py
_validate_explicit_decoder_eval_targets
Validate and normalize user-provided decoder_eval_targets in class-based mode.
This helper expects a mapping of the form
{class_name: [token1, token2, ...], ...}
and is used after any higher-level mappings (e.g. label-based, (label, class)-based) have been resolved into per-class token lists.
- Ensures keys are strings that correspond to known classes (all_classes/target_classes).
- Normalizes all tokens to strings and drops Nones.
- When warn_overlap is True, emits a warning (but does not error) when different
classes share overlapping tokens. Set warn_overlap=False when overlap is expected (e.g. decoder_eval_targets="label" where the same label can appear in multiple classes).
Source code in gradiend/trainer/text/prediction/trainer.py
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 | |
_validate_explicit_vocabulary_split_or_raise
Source code in gradiend/trainer/text/prediction/trainer.py
_validate_required_splits
Fail early when unified data cannot support the configured workflow.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
combined_data
|
Optional[DataFrame]
|
Unified training/evaluation DataFrame. |
required |
required_splits
|
Optional[List[str]]
|
Optional explicit split names that must be present. |
None
|
Source code in gradiend/trainer/text/prediction/trainer.py
_vocabulary_split_viable_for_targets
Source code in gradiend/trainer/text/prediction/trainer.py
analyze_decoder_for_plotting
analyze_decoder_for_plotting(decoder_results=None, model_with_gradiend=None, class_ids=None, use_cache=None, **kwargs)
Analyze decoder for plotting: extends decoder results with probabilities for all classes evaluated on all datasets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
decoder_results
|
Optional[Dict[str, Any]]
|
Decoder evaluation result (summary at top level, e.g. result['3SG'], plus 'grid'). If None, calls evaluate_decoder() to get base results. |
None
|
model_with_gradiend
|
Optional[Any]
|
ModelWithGradiend instance. If None, uses self.get_model(). |
None
|
class_ids
|
Optional[List[str]]
|
Classes to evaluate probabilities for. If None, uses all_classes if available, else target_classes. |
None
|
use_cache
|
Optional[bool]
|
Whether to use cached results when re-evaluating. |
None
|
**kwargs
|
Any
|
Decoder evaluation options such as |
{}
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict with 'plotting_data' (extended grid with probs_by_dataset) and 'summary' (summary entries from decoder_results). |
Source code in gradiend/trainer/text/prediction/trainer.py
2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 | |
create_gradient_training_dataset
create_gradient_training_dataset(raw_training_data, model_with_gradiend, *, cache_dir=None, use_cached_gradients=False, **kwargs)
Wrap raw training data into TextGradientTrainingDataset for gradient creation (text modality). source and target are resolved from TrainingArguments (override via kwargs if needed).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw_training_data
|
Any
|
Text training dataset produced by
|
required |
model_with_gradiend
|
Any
|
Model used to create gradients. |
required |
cache_dir
|
Optional[str]
|
Optional gradient cache directory. |
None
|
use_cached_gradients
|
bool
|
Whether existing cached gradients may be reused. |
False
|
**kwargs
|
Any
|
Optional gradient dataset settings such as |
{}
|
Source code in gradiend/trainer/text/prediction/trainer.py
create_training_data
create_training_data(model_or_tokenizer, split='train', class_pair=None, batch_size=None, max_size=None, include_other_classes=False, use_all_transitions=False, transition_selection=None, balance_column='feature_class_id', **kwargs)
Create training dataset from unified data. Training uses only rows where transition in {c1→c2, c2→c1} for the configured pair. Accepts model_with_gradiend or tokenizer as first argument.
When max_size is None, uses train_max_size from training_args if set. For text prediction, max_size caps samples per feature_class_id (downsampling). Note: Balancing happens automatically via dataset scheduler cycling; this parameter primarily reduces total dataset size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_or_tokenizer
|
Any
|
Model-with-GRADIEND or tokenizer used to build text inputs. |
required |
split
|
EncoderSplit
|
Split name(s) to load. Supports one split, |
'train'
|
class_pair
|
Optional[Tuple[str, str]]
|
Optional target class pair. Defaults to the trainer pair. |
None
|
batch_size
|
Optional[int]
|
Optional raw text batch size. |
None
|
max_size
|
Optional[int]
|
Optional per-group cap; defaults to
|
None
|
include_other_classes
|
bool
|
If True, include all class transitions in the split instead of
restricting to the active target pair (when |
False
|
use_all_transitions
|
bool
|
Deprecated alias for |
False
|
transition_selection
|
Optional[List[Union[TransitionSpec, Tuple[str, str]]]]
|
Optional explicit transition specs for evaluation-style probing.
When provided, these transitions are included in addition to the
active target pair. Non-target transitions keep label |
None
|
balance_column
|
Optional[str]
|
Column used for balanced dataset scheduling and per-group capping. |
'feature_class_id'
|
**kwargs
|
Any
|
Additional dataset-construction options, including
|
{}
|
Source code in gradiend/trainer/text/prediction/trainer.py
2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 | |
evaluate_base_model
evaluate_base_model(model, tokenizer, use_cache=None, cache_folder='', model_id=None, training_like_df=None, neutral_df=None, max_size_training_like=None, max_size_neutral=None, eval_batch_size=None)
Evaluate a model for decoder evaluation using generic feature score + LMS.
Probabilities are computed from the passed-in model's forward: for causal/decoder models this is next-token (CLM) logits; for encoder MLM, mask-position logits. When using a decoder-only MLM head, the trainer injects the base CLM so this receives the CLM only (never the MLM head).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Any
|
Model used for probability computation (CLM or full MLM) |
required |
tokenizer
|
Any
|
Tokenizer |
required |
use_cache
|
Optional[bool]
|
If True (default), use cached results when available. |
None
|
cache_folder
|
str
|
Cache folder suffix |
''
|
model_id
|
Optional[str]
|
Model identifier |
None
|
training_like_df
|
Optional[DataFrame]
|
Optional cached training-like DataFrame for probability scoring |
None
|
neutral_df
|
Optional[DataFrame]
|
Optional cached neutral DataFrame for LMS scoring |
None
|
max_size_training_like
|
Optional[int]
|
Maximum number of generated training-like rows |
None
|
max_size_neutral
|
Optional[int]
|
Maximum number of generated neutral rows (and LMS text cap) |
None
|
eval_batch_size
|
Optional[int]
|
Common eval batch size used for LMS computation |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict with 'feature_score' and 'lms' keys |
Source code in gradiend/trainer/text/prediction/trainer.py
2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 | |
get_decoder_mlm_training_data
Get (masked, label) DataFrame for training a decoder-only MLM head.
When trainer has per-class data (class_datasets), uses all subsets of the dataset for the given split—including neutral and every class—so the MLM head sees the full HuggingFace dataset. When only combined_data is available (e.g. single HF dataset), uses combined_data for the split. Returned DataFrame has columns 'masked' and 'label'; masked must contain [MASK]. Multi-token label strings are supported: each unique label maps to one classifier output on the auxiliary MLM head.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
split
|
str
|
Data split(s) to use. |
'train'
|
max_size
|
Optional[int]
|
Optional cap on returned rows. |
None
|
Source code in gradiend/trainer/text/prediction/trainer.py
get_target_feature_class_ids
Feature class IDs for target classes (pair transitions only; excludes identity/neutral). In create_training_data the pair transitions are assigned 0 and 1; identity classes follow.
Source code in gradiend/trainer/text/prediction/trainer.py
peek_unified_training_data
classmethod
Load training data into the unified schema without loading a model.
Uses the same normalization path as :meth:_ensure_data (HF per-class,
merged files, in-memory dicts, etc.). Intended for suite introspection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Any
|
Positional constructor arguments. |
()
|
**kwargs
|
Any
|
Keyword constructor arguments. |
{}
|
Source code in gradiend/trainer/text/prediction/trainer.py
plot_encoder_distributions
plot_encoder_distributions(encoder_df=None, *, output=None, output_dir=None, show=True, title=True, target_and_neutral_only=True, split_plot_mode='facet', include_neutral=False, figsize=None, img_format=None, dpi=None, highlight_non_convergence=None, return_fig_ax=False, **kwargs)
Plot text-prediction encoder distributions with config image defaults.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoder_df
|
Optional[DataFrame]
|
Optional encoder-evaluation DataFrame. |
None
|
output
|
Optional[str]
|
Optional explicit output file path. |
None
|
output_dir
|
Optional[str]
|
Optional output directory. |
None
|
show
|
bool
|
Whether to display the figure interactively. |
True
|
title
|
Union[str, bool]
|
Plot title. |
True
|
target_and_neutral_only
|
bool
|
If True, omit identity/auxiliary rows. |
True
|
split_plot_mode
|
str
|
How split-aware data is shown. |
'facet'
|
include_neutral
|
bool
|
If True, include neutral rows when present. |
False
|
figsize
|
Optional[Tuple[float, float]]
|
Optional Matplotlib figure size. |
None
|
img_format
|
Optional[str]
|
Optional output format. Defaults to trainer config. |
None
|
dpi
|
Optional[int]
|
Optional output DPI. Defaults to trainer config when available. |
None
|
highlight_non_convergence
|
Optional[bool]
|
Override non-convergence markers. |
None
|
return_fig_ax
|
bool
|
If True, return Matplotlib |
False
|
**kwargs
|
Any
|
Additional keyword arguments forwarded to the base trainer. |
{}
|
Source code in gradiend/trainer/text/prediction/trainer.py
plot_probability_shifts
plot_probability_shifts(decoder_results=None, class_ids=None, target_class=None, increase_target_probabilities=True, use_cache=None, *, output=None, show=True, figsize=None, img_format=None, dpi=None, highlight_non_convergence=None, return_fig_ax=False, **kwargs)
Plot text-prediction decoder probability shifts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
decoder_results
|
Optional[Dict[str, Any]]
|
Optional result from |
None
|
class_ids
|
Optional[List[str]]
|
Optional class ids to include in the plot. |
None
|
target_class
|
Optional[str]
|
Optional single target class to plot. |
None
|
increase_target_probabilities
|
bool
|
True for strengthen plots, False for weaken plots. |
True
|
use_cache
|
Optional[bool]
|
Whether cached decoder results may be used. |
None
|
output
|
Optional[str]
|
Optional explicit output file path. |
None
|
show
|
bool
|
Whether to display the Matplotlib figure. |
True
|
figsize
|
Optional[Tuple[float, float]]
|
Optional Matplotlib figure size. |
None
|
img_format
|
Optional[str]
|
Optional output image format. Defaults to trainer config. |
None
|
dpi
|
Optional[int]
|
Optional output DPI. Defaults to trainer config when available. |
None
|
highlight_non_convergence
|
Optional[bool]
|
Override non-convergence markers. |
None
|
return_fig_ax
|
bool
|
If True, return Matplotlib |
False
|
**kwargs
|
Any
|
Additional keyword arguments forwarded to the evaluator. |
{}
|
Source code in gradiend/trainer/text/prediction/trainer.py
plot_training_convergence
plot_training_convergence(*, plot_mean_by_class=True, plot_mean_by_feature_class=None, plot_correlation=True, class_spread=None, output=None, show=True, title=True, figsize=None, img_format=None, dpi=None, highlight_non_convergence=None, return_fig_ax=False, **kwargs)
Plot text-prediction training convergence with config image defaults.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plot_mean_by_class
|
bool
|
Plot mean encoder values by label class. |
True
|
plot_mean_by_feature_class
|
Optional[bool]
|
Plot means grouped by feature class. |
None
|
plot_correlation
|
bool
|
Plot correlation over training steps. |
True
|
class_spread
|
Optional[Literal['minmax', 'iqr', 'ci95']]
|
Optional spread band behind class means.
|
None
|
output
|
Optional[str]
|
Optional explicit output file path. |
None
|
show
|
bool
|
Whether to display the figure interactively. |
True
|
title
|
Union[str, bool]
|
Plot title. |
True
|
figsize
|
Optional[Tuple[float, float]]
|
Optional Matplotlib figure size. |
None
|
img_format
|
Optional[str]
|
Optional output format. Defaults to trainer config. |
None
|
dpi
|
Optional[int]
|
Optional output DPI. Defaults to trainer config when available. |
None
|
highlight_non_convergence
|
Optional[bool]
|
Override non-convergence markers. |
None
|
return_fig_ax
|
bool
|
If True, return Matplotlib |
False
|
**kwargs
|
Any
|
Additional keyword arguments forwarded to the base trainer. |
{}
|
Source code in gradiend/trainer/text/prediction/trainer.py
resolve_custom_prediction_head_dir
Return the directory path for a trained decoder-only MLM head if it exists.
Uses resolve_decoder_mlm_head_dir to determine the path. When this path exists, resolve_model_path will automatically use it instead of the base model. DecoderModelWithMLMHead replaces AutoModelForMaskedLM in loading; no special adapter logic.
Source code in gradiend/trainer/text/prediction/trainer.py
train
train(output_dir=None, model=None, model_with_gradiend_cls=None, callbacks=None, **training_args_overrides)
Source code in gradiend/trainer/text/prediction/trainer.py
train_decoder_only_mlm_head
train_decoder_only_mlm_head(model, output=None, *, split='train', batch_size=4, epochs=5, lr=0.0001, pooling_length=3, max_length=128, max_size=None, use_cache=None, model_use_cache=None)
Train a custom MLM head on a decoder-only model. DecoderModelWithMLMHead is a drop-in replacement for AutoModelForMaskedLM: loading (e.g. trainer.train()) automatically uses this path when you pass the base model name (e.g. 'gpt2').
Use when the target token comes after the mask (e.g. German DE: article before noun). The base model (e.g. gpt2) is frozen; only a small classifier head is trained to predict the token at the [MASK] position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Union[str, Any]
|
Base model name or model instance (e.g. 'gpt2', 'meta-llama/Llama-3.2-3B'). |
required |
output
|
Optional[str]
|
Output directory for the saved MLM head. If None, uses experiment_dir/cache/decoder_mlm_head when experiment_dir is set. |
None
|
split
|
str
|
Dataset split for training (e.g. 'train', 'validation'). Default: 'train'. |
'train'
|
batch_size
|
int
|
Batch size for training. Default: 4. |
4
|
epochs
|
int
|
Number of training epochs. Default: 5. |
5
|
lr
|
float
|
Learning rate. Default: 1e-4. |
0.0001
|
pooling_length
|
Union[int, Sequence[int]]
|
Length of pooling window for the MLM head (context around mask
position). Default: 3. Pass a sequence (e.g. |
3
|
max_length
|
int
|
Maximum sequence length for tokenization. Default: 128. |
128
|
max_size
|
Optional[int]
|
If set, limit training data to this many rows (for faster debugging/trials). |
None
|
use_cache
|
Optional[bool]
|
If True, skip training when model already exists at output path. Defaults to training args use_cache (fallback False). |
None
|
model_use_cache
|
Optional[bool]
|
If False, disable KV cache in model forward (recommended for training). Defaults to training args model_use_cache (fallback False). Manual override supported. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Path (str) to the saved MLM-head model. trainer.train() resolves to this path |
str
|
automatically when it exists. |
Source code in gradiend/trainer/text/prediction/trainer.py
3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 | |