Trainer
Bases: FeatureLearningDefinition
Abstract base trainer for GRADIEND models with HuggingFace-like API.
The Trainer class is an abstract base class that provides the main interface for training,
evaluating, and working with GRADIEND models. It cannot be instantiated directly; you must
use a concrete subclass such as TextPredictionTrainer that implements the required
abstract methods from FeatureLearningDefinition.
Abstract Methods:
Subclasses must implement the following abstract methods from FeatureLearningDefinition:
- create_training_data(): Create training dataset without gradient computation
- create_gradient_training_dataset(): Create training dataset with gradient computation
- _get_decoder_eval_dataframe(): Get DataFrames for decoder evaluation
- _get_decoder_eval_targets(): Get target tokens for decoder evaluation
- evaluate_base_model(): Evaluate a single model for decoder evaluation
- _analyze_encoder(): Analyze encoder by encoding gradients from training data
Class Management:
The trainer uses target_classes to specify which classes are used for training.
The pair property is automatically inferred from target_classes when exactly two
target classes are specified (i.e., pair = (target_classes[0], target_classes[1])).
The all_classes property includes all classes in the dataset (including non-target
classes) and can be inferred from data if not explicitly set.
- target_classes: Classes used for training (required)
- all_classes: All classes in dataset (optional, inferred from data if not set)
- pair: Automatically computed from target_classes when len(target_classes) == 2
Key Features:
- Model Management: Stores model at construction time with lazy loading and caching
- Training: Full training pipeline with support for pre-pruning, training, and post-pruning
- Multi-Seed Training: Automatic multi-seed training with convergence tracking and best seed selection
- Evaluation: Integrated encoder and decoder evaluation with caching
- Visualization: Delegates plotting to Evaluator/Visualizer
- Device Management: Easy model device movement (CPU/CUDA)
Basic Usage:
from gradiend.trainer.text.prediction.trainer import TextPredictionTrainer
from gradiend.trainer.core.arguments import TrainingArguments
import pandas as pd
# Initialize trainer with model and training arguments
# Note: Use TextPredictionTrainer (or another concrete subclass), not the abstract Trainer directly
args = TrainingArguments(
experiment_dir="./results",
train_batch_size=32,
num_epochs=10,
learning_rate=1e-3,
)
trainer = TextPredictionTrainer(
model="gpt2",
args=args,
run_id="runs/experiment_gpt2",
data=your_dataframe, # Modality-specific data (could also be a HF dataset id)
target_classes=["class1", "class2"], # Target classes the GRADIEND -> these gets encoded as +-1
)
# Train the model
trainer.train()
# Evaluate encoder and decoder
enc_results = trainer.evaluate_encoder()
dec_results = trainer.evaluate_decoder()
# Plot results
trainer.plot_encoder_distributions()
trainer.plot_training_convergence()
Multi-Seed Training:
When TrainingArguments.max_seeds > 1, the trainer automatically runs multiple training
runs with different random seeds. It tracks convergence metrics, selects the best seed based
on selection scores, and writes a comprehensive seed report.
args = TrainingArguments(
max_seeds=5,
min_convergent_seeds=2,
convergent_metric="correlation",
convergent_score_threshold=0.5,
)
trainer = Trainer(model="gpt2", args=args)
trainer.train() # Runs 5 seeds, selects best
Pruning:
The trainer supports both pre-pruning (before training) and post-pruning (after training):
from gradiend.trainer.core.pruning import PrePruneConfig, PostPruneConfig
# Pre-prune: gradient-based pruning before training
pre_cfg = PrePruneConfig(n_samples=1000, topk=0.5, source="diff")
args.pre_prune_config = pre_cfg
# Post-prune: weight-based pruning after training
post_cfg = PostPruneConfig(topk=0.3, part="decoder-weight")
args.post_prune_config = post_cfg
trainer.train() # Automatically applies pre-prune and post-prune
Evaluation:
The trainer provides convenient methods for encoder and decoder evaluation:
# Encoder evaluation: analyze gradient encodings
enc_results = trainer.evaluate_encoder(split="test", max_size=1000)
# Returns: correlation, encoded values, mean_by_class, etc.
# Decoder evaluation: grid search over feature_factor and learning_rate
dec_results = trainer.evaluate_decoder(use_cache=True)
# Returns: summary (best configs per metric) and grid (all results)
# Combined evaluation
results = trainer.evaluate()
# Returns: {"encoder": enc_results, "decoder": dec_results}
Model Access:
# Get the trained model (cached after first load)
model = trainer.get_model()
# Load a specific checkpoint
model = trainer.get_model(load_directory="./results/model")
# Move model to device
trainer.cuda(device=0) # or trainer.cpu()
Architecture:
The Trainer subclasses FeatureLearningDefinition and adds:
- Model storage and lazy loading (get_model())
- Training arguments management (training_args property)
- Lazy Evaluator initialization (evaluator property)
- Experiment directory resolution (experiment_dir property)
Training logic lives in _train(); subclasses can override this method to customize behavior.
Args:
model: Model identifier (string path) or ModelWithGradiend instance. If string,
the model is loaded lazily on first access via get_model().
target_classes: Optional list of target class names for training. If None, subclasses
can determine target_classes from data by setting self._target_classes during initialization
or data loading. Default: None
args: Optional TrainingArguments instance. Can also be passed as kwargs to train().
run_id: Optional run identifier. When set, creates subdirectory under experiment_dir.
n_features: Number of latent features (default: 1).
evaluator_class: Optional Evaluator class. Defaults to Evaluator.
**kwargs: Additional attributes to set on the trainer instance.
Attributes: training_args: TrainingArguments instance (if provided). experiment_dir: Resolved experiment directory (experiment_dir/run_id if run_id set). model_path: Current model path (initial model or path after training). evaluator: Lazy-initialized Evaluator instance.
Methods: train(): Train GRADIEND model with optional pre/post-pruning. evaluate_encoder(): Analyze encoder performance (correlation, encodings). evaluate_decoder(): Grid search decoder configurations. evaluate(): Run both encoder and decoder evaluation. get_model(): Get the trainer's ModelWithGradiend instance (cached). load_model(): Load a ModelWithGradiend instance from a specific directory. pre_prune(): Run pre-pruning before training. post_prune(): Run post-pruning after training. plot_encoder_distributions(): Plot encoder distribution visualizations. plot_training_convergence(): Plot training convergence metrics. rewrite_base_model(): Rewrite base model(s) using decoder evaluation results, optionally save to disk.
See Also:
- FeatureLearningDefinition: Abstract base class providing data creation and evaluation protocols
- TextPredictionTrainer: Concrete implementation for text-based models (MLM/CLM)
- TrainingArguments: Configuration for training behavior
- Evaluator: Evaluation and visualization orchestration
- PrePruneConfig, PostPruneConfig: Pruning configuration
Note:
This class is abstract and cannot be instantiated directly. Use a concrete subclass
such as TextPredictionTrainer that implements the required abstract methods.
Source code in gradiend/trainer/trainer.py
_evaluator_class
instance-attribute
base_model_path
property
Original model passed at construction (base model id or path, e.g. 'bert-base-cased').
experiment_dir
property
Experiment directory for this trainer.
If training_args.experiment_dir is set, returns that (with run_id subdir if run_id is set).
model_path
property
Current model path: base model before training, GRADIEND output dir after train().
__str__
_experiment_dir
Root directory for this experiment (experiment_dir, or experiment_dir/run_id when run_id is set).
Source code in gradiend/trainer/trainer.py
_train
Run GRADIEND training (cache check, model creation, data, core loop, save). Override in subclasses to customize behavior. Returns path to saved model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
|
str
|
Directory to save the trained model. |
required |
args
|
Any
|
TrainingArguments instance. |
required |
model
|
Any
|
Model identifier (string path) or ModelWithGradiend instance. |
required |
model_with_gradiend_cls
|
Any
|
ModelWithGradiend subclass to use when creating model from string path. |
required |
callbacks
|
Any
|
Optional list of TrainingCallback instances. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Path to saved model directory. |
Source code in gradiend/trainer/trainer.py
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 | |
cpu
cuda
Move loaded model to CUDA. device: None (default cuda), int (cuda:N), or str/torch.device.
Source code in gradiend/trainer/trainer.py
encode
Encode eval data; return list of encoded values.
Source code in gradiend/trainer/trainer.py
evaluate
Run encoder and decoder evaluation; return combined dict.
Source code in gradiend/trainer/trainer.py
evaluate_decoder
evaluate_decoder(lrs=None, feature_factors=None, use_cache=None, max_size_training_like=None, max_size_neutral=None, eval_batch_size=None, training_like_df=None, neutral_df=None, selector=None, summary_extractor=None, summary_metrics=None, target_class=None, increase_target_probabilities=True, plot=False, show=None)
Run decoder grid evaluation for one direction (strengthen or weaken).
Delegates to evaluator.evaluate_decoder. Only the datasets and feature-factor combinations
required for the chosen direction are computed. When use_cache=True and experiment_dir is set,
cached grid results are reused when available.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lrs
|
Optional[Sequence[float]]
|
Optional sequence of learning rates to evaluate. If None, defaults are taken from
|
None
|
feature_factors
|
Optional[Sequence[float]]
|
Optional sequence of feature factors to evaluate. If None, defaults are taken
from |
None
|
use_cache
|
Optional[bool]
|
If True, reuse cached decoder grid results when available under experiment_dir.
If None, defaults are taken from |
None
|
max_size_training_like
|
Optional[int]
|
Maximum number of samples per variant for training-like decoder
evaluation data. If None, defaults are taken from
|
None
|
max_size_neutral
|
Optional[int]
|
Maximum number of samples per variant for neutral decoder evaluation data
(and LMS text cap). If None, defaults are taken from
|
None
|
eval_batch_size
|
Optional[int]
|
Optional batch size used during decoder evaluation (e.g. for LMS calls). If None, an appropriate default is chosen by the evaluator. |
None
|
training_like_df
|
Optional[DataFrame]
|
Optional pre-computed training-like DataFrame. When provided, this is used instead of creating training-like evaluation data inside the evaluator. |
None
|
neutral_df
|
Optional[DataFrame]
|
Optional pre-computed neutral DataFrame. When provided, this is used instead of creating neutral evaluation data inside the evaluator. |
None
|
selector
|
Optional[Any]
|
Optional selection policy (e.g. |
None
|
summary_extractor
|
Optional[Any]
|
Optional callable that post-processes raw decoder results and attaches derived metrics (e.g. bpi, fpi, mpi) before summarization. |
None
|
summary_metrics
|
Optional[Sequence[str]]
|
Optional sequence of metric names to summarize (e.g. ["bpi", "fpi", "mpi"]). |
None
|
target_class
|
Optional[Union[str, List[str]]]
|
Optional target class id (or list of ids) to evaluate. When set (e.g. "3SG"), restricts evaluation to that class (or classes) for efficiency. When None, all target classes are evaluated. |
None
|
increase_target_probabilities
|
bool
|
If True (default), compute strengthen summaries only (keys like "3SG"). If False, compute weaken summaries only (keys like "3SG_weaken"). |
True
|
plot
|
bool
|
If True, after selection run any missing evaluations needed for plotting, update cache, then create decoder plots. |
False
|
show
|
Optional[bool]
|
Controls whether plots are shown when plot=True. If True, display plots; if False, only save them. When None and plot=True, defaults to True. |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict with flattened decoder summaries. For strengthen, keys like dec["3SG"]; for weaken, |
Dict[str, Any]
|
keys like dec["3SG_weaken"]. Each summary entry includes value, feature_factor, learning_rate, |
Dict[str, Any]
|
id, strengthen, lms, base_lms. The dict always includes "grid", and when plot=True also |
Dict[str, Any]
|
"plot_paths" and/or "plot_path". |
Source code in gradiend/trainer/trainer.py
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 | |
evaluate_encoder
evaluate_encoder(model_with_gradiend=None, encoder_df=None, split='test', source=None, max_size=None, neutral_data_df=None, use_cache=None, return_df=False, plot=False, plot_kwargs=None, is_decoder_only_model=None, pre_load_gradients=None, **kwargs)
Run encoder analysis and return correlation metrics; default model to current trainer model.
When encoder_df is provided (DataFrame or dict with "encoder_df" key), skips encoding and computes metrics from that DataFrame. Otherwise uses _analyze_encoder to produce the DataFrame (training + neutral variants), then delegates to EncoderEvaluator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_with_gradiend
|
Optional[Any]
|
Optional ModelWithGradiend instance to evaluate. If None, uses the trainer's current model (via get_model()). |
None
|
encoder_df
|
Optional[Union[DataFrame, Dict[str, Any]]]
|
Optional DataFrame or dict with "encoder_df" key. If provided, skips encoding and computes metrics from this data. Use evaluate_encoder(return_df=True) to get such a dict, or pass a pre-computed DataFrame directly. |
None
|
split
|
str
|
Dataset split to use for evaluation. Default: "test". |
'test'
|
source
|
Optional[str]
|
Source type for gradient creation. If None, uses default from training args or "factual". Options: "factual", "counterfactual", etc. |
None
|
max_size
|
Optional[int]
|
Maximum number of samples per variant to encode. If None, uses encoder_eval_max_size from training args. |
None
|
neutral_data_df
|
Optional[DataFrame]
|
Optional DataFrame with neutral examples (neutral_dataset variant). If provided, these will be encoded in addition to training data. |
None
|
use_cache
|
Optional[bool]
|
If True, use cached encoder evaluation when available. If None, uses use_cache from training args (default: False). |
None
|
return_df
|
bool
|
If True, include encoder_df (full DataFrame with type column) in result. |
False
|
plot
|
bool
|
If True, create encoder distribution plot from analyzed data. |
False
|
plot_kwargs
|
Optional[Dict[str, Any]]
|
Optional dict of options forwarded to plot_encoder_distributions when plot=True. E.g. plot_kwargs=dict(target_and_neutral_only=True, show=False). Any argument accepted by plot_encoder_distributions can be passed here. |
None
|
is_decoder_only_model
|
Optional[bool]
|
Whether the model is decoder-only (causal LM). If None, inferred from the model. |
None
|
pre_load_gradients
|
Optional[bool]
|
If True, pre-load cached gradients when available. If None, uses use_cached_gradients from training args (default: False). |
None
|
**kwargs
|
Any
|
Additional arguments passed to _analyze_encoder and create_eval_data. |
{}
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict with unified encoder metrics: n_samples, all_data, training_only, |
Dict[str, Any]
|
target_classes_only, correlation, mean_by_class, mean_by_type, boundaries; |
Dict[str, Any]
|
optionally neutral_mean_by_type, mean_by_feature_class, label_value_to_class_name. |
Dict[str, Any]
|
If return_df=True, includes "encoder_df" key. |
Source code in gradiend/trainer/trainer.py
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 | |
get_encoder_metrics
Get unified encoder metrics from encoder_df or from cached results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
Optional[str]
|
Path to the model; defaults to the trainer's current model path. |
None
|
encoder_df
|
Optional[DataFrame]
|
Optional DataFrame with encoded values and labels. If provided, metrics are computed directly from this DataFrame (same format as evaluate_encoder output). Use when you already have encoder outputs, e.g. from evaluate_encoder(return_df=True). |
None
|
**kwargs
|
Any
|
Additional arguments passed to the base implementation (e.g. split, use_cache). When using cache instead of encoder_df, pass the same kwargs you use for evaluate_encoder. |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
Dict with n_samples, correlation, mean_by_class, etc., or None if encoder_df is empty. |
Source code in gradiend/trainer/trainer.py
get_encodings
Get encodings; default model_path to current trainer model path.
Source code in gradiend/trainer/trainer.py
get_model
Get the trainer's ModelWithGradiend instance.
Returns the in-memory model when set (e.g. during training), otherwise loads from load_directory or model_path. The loaded instance is always cached in memory for subsequent calls. After multi-seed training the cache is cleared so the next get_model() loads from the selected best-seed directory and then caches that instance.
To load a model from a different directory, use load_model() or pass load_directory=.
Note: use_cache (e.g. TrainingArguments.use_cache) applies only to disk/output caches (skip when files exist); the in-memory model from get_model() is always cached.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
use_cache
|
Optional[bool]
|
Ignored; kept for API compatibility. Disk cache is controlled elsewhere. |
None
|
load_directory
|
Optional[Any]
|
If provided, load from this path (GRADIEND checkpoint expected). |
None
|
**kwargs
|
Any
|
Passed to model_with_gradiend_cls.from_pretrained. |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
ModelWithGradiend instance. |
Source code in gradiend/trainer/trainer.py
get_training_stats
Load training stats; default model_path to current trainer model path.
Source code in gradiend/trainer/trainer.py
load_model
Load a ModelWithGradiend instance from a specific directory.
This method loads a model from a different checkpoint/directory than the trainer's current model_path. Use this for loading different checkpoints (e.g., for comparison) or loading specific seed runs in multi-seed training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
load_directory
|
str
|
Directory or path to load the model from. |
required |
model_with_gradiend_cls
|
Optional[Type[Any]]
|
Optional ModelWithGradiend subclass. If None, uses self.model_with_gradiend_cls or self.default_model_with_gradiend_cls. |
None
|
**kwargs
|
Any
|
Passed to model_with_gradiend_cls.from_pretrained (e.g. feature_definition=self for text models). |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
ModelWithGradiend instance loaded from the specified directory. |
Source code in gradiend/trainer/trainer.py
plot_encoder_distributions
plot_encoder_scatter
Delegate to evaluator.plot_encoder_scatter (interactive Plotly scatter).
plot_training_convergence
Plot training convergence (means by class/feature_class and correlation). Delegates to Evaluator/Visualizer. If experiment_dir is set, output path is auto-resolved.
Source code in gradiend/trainer/trainer.py
post_prune
Run post-prune (weight-based) on the current model and keep it in memory. Subsequent evaluation (e.g. evaluate_encoder) will use the pruned model. Does not save to disk.
Uses self._training_args.post_prune_config when post_cfg is None.
Source code in gradiend/trainer/trainer.py
post_training
Optional post-training hook.
Subclasses can override this to perform additional evaluation, logging, or analysis after training. The default implementation is a no-op so that definitions are not required to implement it.
Source code in gradiend/trainer/trainer.py
pre_prune
Run pre-prune (gradient-mean then prune) and keep the pruned model in memory. The next train() will use this model. Does not save to disk; save explicitly if needed.
Uses self._training_args.pre_prune_config when pre_cfg is None.
Source code in gradiend/trainer/trainer.py
rewrite_base_model
rewrite_base_model(decoder_results=None, target_class=None, increase_target_probabilities=True, output_dir=None, base_model=None, decoder_stats_metric_name=None, **decoder_stats_kwargs)
Rewrite the base model by applying GRADIEND decoder updates based on decoder evaluation results.
The decoder evaluation selects a feature factor and learning rate per target class and direction (strengthening vs weakening). This method applies the selected config: by default it strengthens the given target class(es); use increase_target_probabilities=False to apply the weakening config instead (evaluate_decoder currently only produces strengthen summaries).
Accepts/loads internally the cached decoder results when experiment_dir is set. Optionally saves the rewritten model(s) to disk if output_dir is provided.
When called on a Trainer, the trained model is used automatically (base_model not needed). When experiment_dir is set, decoder_results can be omitted and will be loaded from cache (requires evaluate_decoder to have been run with use_cache=True so the decoder stats cache exists).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
decoder_results
|
Optional[Dict[str, Any]]
|
Output from evaluate_decoder. Optional when experiment_dir is set (then loaded from cache). |
None
|
target_class
|
Optional[Union[str, List[str]]]
|
Target class(es) to rewrite for. Must be key(s) present in decoder_results
summary (e.g. per-class ids like "3SG", "masc_nom", or "combined_score"). Pass a single
string for one model, or a list of strings for one rewritten model per class. For
strengthening, use the class id (e.g. "masc_nom"); for weakening, the summary key is
" |
None
|
increase_target_probabilities
|
bool
|
If True (default), apply the config that strengthens the target class (higher probability for that class). If False, apply the config that weakens it (uses opposite feature factor; evaluate_decoder currently only produces strengthen summaries). |
True
|
output_dir
|
Optional[str]
|
Optional directory where the rewritten model(s) should be saved. If provided, models are saved to disk. If None, models are returned in memory only. For a single target_class, this is the exact save directory. For multiple target_classes, experiment_dir must be set (output_dir is only used for a single target_class). |
None
|
base_model
|
Optional[Any]
|
ModelWithGradiend to rewrite; if None, uses current trainer model. |
None
|
decoder_stats_metric_name
|
Optional[str]
|
When loading decoder_results from cache, the summary key used to locate the cache file. Defaults to first target_class or "combined_score". |
None
|
**decoder_stats_kwargs
|
Any
|
Used to locate the cache file (feature_factors, lrs, etc.). |
{}
|
Returns:
| Type | Description |
|---|---|
Union[Any, List[Any], str, List[str]]
|
If output_dir is None: Rewritten model when target_class is a single string; list of models when target_class is a list. |
Union[Any, List[Any], str, List[str]]
|
If output_dir is provided: Path to the saved rewritten model directory, or list of paths when target_class is a list. |
Source code in gradiend/trainer/trainer.py
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 | |
to
Move loaded model to the given device (str or torch.device). No-op if model not loaded.
Source code in gradiend/trainer/trainer.py
train
train(output_dir=None, model=None, model_with_gradiend_cls=None, callbacks=None, **training_args_overrides)
Train GRADIEND using stored TrainingArguments (and optional overrides).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
|
Optional[str]
|
Directory to save the trained model. If None, resolved from experiment_dir (from TrainingArguments) or uses a temporary directory. |
None
|
model
|
Optional[Union[str, Any]]
|
Model to train. If None, uses the model passed at Trainer initialization. Can be a string path or ModelWithGradiend instance. |
None
|
model_with_gradiend_cls
|
Optional[Type[Any]]
|
ModelWithGradiend subclass to use when creating model from string path. Required if model is a string. If None, uses self.model_with_gradiend_cls or self.default_model_with_gradiend_cls (set by subclasses like TextPredictionTrainer). Examples: TextModelWithGradiend for text models. |
None
|
callbacks
|
Optional[List[Any]]
|
Optional list of TrainingCallback instances for custom training behavior. If None, default callbacks are used (evaluation, normalization, checkpoint, logging). |
None
|
**training_args_overrides
|
Any
|
Keyword arguments that override TrainingArguments values. These are merged with self.training_args (if set) or used to create new TrainingArguments. Examples: learning_rate=1e-3, num_epochs=10, experiment_dir="./results". |
{}
|
Returns:
| Type | Description |
|---|---|
Union[Trainer, Dict[int, Any]]
|
Trainer instance (for single-seed training) or Dict[int, Any] mapping seed -> model |
Union[Trainer, Dict[int, Any]]
|
(when keep_seed_runs=True in multi-seed training). |
Multi-seed behavior (when TrainingArguments.max_seeds > 1):
- Each seed is trained from the same base model (or checkpoint path) but with a different random seed applied to PyTorch, Python's random, and NumPy.
- For each seed, training statistics are collected (including encoder correlation and best checkpoints). A training-time score ("training_score") is derived from these.
- Optionally, an additional encoder evaluation on the validation split is run via evaluate_encoder(split="val"), capped by seed_selection_eval_max_size (or encoder_eval_max_size when unset). Its correlation becomes "eval_correlation".
- The "selection_score" for each seed is:
- eval_correlation when available,
- otherwise training_score.
- A convergence metric (correlation or loss) and threshold are used to count how many seeds "converged" (see TrainingArguments.convergent_metric and convergent_score_threshold).
After the loop, a seed_report.json is written under
Source code in gradiend/trainer/trainer.py
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 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 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 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 | |