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
|
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"). |
None
|
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
|
Source code in gradiend/trainer/text/prediction/trainer.py
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 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 | |
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=True, 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: 1. Training data (always processed) 2. Neutral variant 1 (if decoder_eval_targets configured) 3. 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
|
str
|
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 other classes in analysis |
True
|
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
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 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 | |
_check_data_non_empty
Raise ValueError if any provided training data has length 0.
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
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 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 | |
_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'.
Source code in gradiend/trainer/text/prediction/trainer.py
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 | |
_encode_training_rows
Encode training data via gradients and return rows with text, encoded, label, type='training'.
Source code in gradiend/trainer/text/prediction/trainer.py
_encoder_cache_path
Encoder cache path for analysis CSV. Cache under experiment_dir; includes split/max_size in cache key.
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
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 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 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 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 | |
_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).
_ensure_decoder_eval_text_columns
Ensure DataFrame has 'masked' and 'text' columns for decoder evaluation.
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, cached_training_like_df=None, cached_neutral_df=None)
Get DataFrame for decoder evaluation (test split).
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
|
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
1882 1883 1884 1885 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 | |
_get_decoder_eval_targets
Get decoder eval targets (delegates to _infer_decoder_eval_targets).
_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). When combined_data only has the training pair (e.g. single-token-per-class), classes not in the pair get no tokens from combined_data; we then supplement from self.class_datasets when available.
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
|
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
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 | |
_set_all_classes
Set the list of all classes in the dataset (including neutral/identity).
_validate_classes_in_data
staticmethod
Raise ValueError if any class in classes is not present in class_dfs (data).
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
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
|
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
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 | |
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).
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, 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.
Source code in gradiend/trainer/text/prediction/trainer.py
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 | |
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
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 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 | |
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], label must be a single token per row. Target token IDs are derived from unique values in 'label'.
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
plot_encoder_distributions
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, **kwargs)
Plot decoder evaluation probability shifts vs learning rate for a target class. Uses target_class and increase_target_probabilities (default True = strengthen) to choose which summary config to plot.
Source code in gradiend/trainer/text/prediction/trainer.py
plot_training_convergence
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
|
int
|
Length of pooling window for the MLM head (context around mask position). Default: 3. |
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
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 | |