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
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 682 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 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 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 | |
_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).
_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
3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 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 3570 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 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 | |
_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
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 | |
_balanced_split_cycle_args
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_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
_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
2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 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 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 | |
_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
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 2777 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 | |
_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
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 | |
_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
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 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 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 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 | |
_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
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 | |
_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
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 | |
_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
1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 | |
_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
_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
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 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 | |
_resolve_encoder_neutral_excluded_tokens
Tokens that must not be selected as neutral mask targets.
Matches generate_neutral_data exclusion: all feature target tokens plus
eval_neutral_additional_excluded_words (and optional decoder LMS ignores).
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
_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
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 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 | |
_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
2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 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 2561 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 | |
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
|
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
|
Additional dataset-construction options, including
|
{}
|
Source code in gradiend/trainer/text/prediction/trainer.py
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 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 2080 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 | |
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
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 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 | |
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_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
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 3209 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 | |