Trainer
Bases: TrainerAnnotationMixin, 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 computationcreate_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 evaluationevaluate_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_argsproperty) - Lazy Evaluator initialization (
evaluatorproperty) - Experiment directory resolution (
experiment_dirproperty)
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__
_apply_explicit_eval_device
Source code in gradiend/trainer/trainer.py
_cleanup_pre_prune_cache
Remove ephemeral pre-prune cache under experiment_dir after train() finishes.
Source code in gradiend/trainer/trainer.py
_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
_is_explicit_cpu_device
staticmethod
_maybe_fail_on_non_convergence
staticmethod
_maybe_fail_on_non_convergence(args, *, convergent_count, min_convergent, run_id=None, model=None, pair=None, output_dir=None, seed_report=None, convergence_metric=None, threshold=None)
Source code in gradiend/trainer/trainer.py
_model_primary_device
Source code in gradiend/trainer/trainer.py
_pre_prune_cache_dir
Source code in gradiend/trainer/trainer.py
_prepare_model_for_evaluation
_prepare_model_for_evaluation(model_with_gradiend=None, *, device=None, context='Encoder evaluation')
Source code in gradiend/trainer/trainer.py
_prepare_model_for_pre_prune_if_needed
Ensure the model uses lazy_init when pre_prune_config is set.
get_model() may return a cached eager-init instance (e.g. from an earlier call before pre_prune_config was set). Recreate from the base model path so encoder/ decoder weights are deferred until after pre-prune.
Source code in gradiend/trainer/trainer.py
_resolve_experiment_dir
Join training_args.experiment_dir with run_id unless run_id is already the leaf name.
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
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 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 | |
_warn_if_eval_on_cpu_unexpected
Source code in gradiend/trainer/trainer.py
_warn_if_reloading_after_unload
Source code in gradiend/trainer/trainer.py
_write_cuda_oom_log
Source code in gradiend/trainer/trainer.py
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 and return encoded scalar values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Forwarded to |
{}
|
Source code in gradiend/trainer/trainer.py
evaluate
Run encoder and decoder evaluation and return a combined result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kwargs_encoder
|
dict
|
Optional keyword arguments passed only to
|
None
|
kwargs_decoder
|
dict
|
Optional keyword arguments passed only to
|
None
|
**kwargs
|
Any
|
Additional keyword arguments applied to both evaluator calls. |
{}
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict with |
Source code in gradiend/trainer/trainer.py
evaluate_decoder
evaluate_decoder(lrs=None, feature_factors=None, use_cache=None, split='test', max_size=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, plot_kwargs=None, decoder_lms_mode=None, device=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
|
split
|
EncoderSplit
|
Dataset split used for training-like decoder evaluation rows. A single name
(default |
'test'
|
max_size
|
Optional[int]
|
Shared evaluation-size alias. If set and explicit decoder caps are omitted, caps both training-like decoder rows and neutral/LMS rows. |
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
|
plot_kwargs
|
Optional[Dict[str, Any]]
|
Optional dict of options forwarded to plot_probability_shifts when
plot=True. E.g. plot_kwargs=dict(figsize=(5, 3), show=False). The |
None
|
decoder_lms_mode
|
Optional[str]
|
Optional override for classification decoder LMS. One of "lm", "classification_accuracy", or "both". If None, uses trainer config (e.g. TextClassificationConfig.decoder_lms_mode). Ignored for non-classification trainers. |
None
|
device
|
Optional[Any]
|
Optional device for evaluation (e.g. |
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
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 2477 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 | |
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, include_other_classes=None, use_all_transitions=False, transition_selection=None, device=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
|
EncoderSplit
|
Dataset split(s) for evaluation. A single name (default |
'test'
|
source
|
Optional[str]
|
Source type for gradient creation. If None, uses default from training args or "factual". Options: "factual", "alternative", "diff". |
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
|
include_other_classes
|
Optional[bool]
|
If True, include all class transitions available in the evaluation
split, not only the active target pair (when |
None
|
use_all_transitions
|
bool
|
Deprecated alias for |
False
|
transition_selection
|
Optional[Any]
|
Optional explicit transition specs, e.g.
|
None
|
device
|
Optional[Any]
|
Optional device for encoding / evaluation (e.g. |
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
2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 | |
get_best_seed_run_path
Source code in gradiend/trainer/trainer.py
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 the current trainer model path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
Optional[str]
|
Optional model path. Defaults to |
None
|
**kwargs
|
Any
|
Additional arguments passed to the base implementation. |
{}
|
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_saved_seed_run_paths
Return saved model directories for selected seed runs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
selection
|
str
|
Which seed runs to return: |
'all_convergent'
|
Returns:
| Type | Description |
|---|---|
List[str]
|
Existing seed-run output directories. Falls back to the current |
List[str]
|
|
Source code in gradiend/trainer/trainer.py
get_seed_report
Source code in gradiend/trainer/trainer.py
get_seed_report_path
Source code in gradiend/trainer/trainer.py
get_seed_run_entries
Return (seed, output_dir) pairs for multi-seed analysis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
selection
|
str
|
Which seed runs to include: |
'all_convergent'
|
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
iter_encoder_eval_cache_dirs
Experiment directories to search for encoder eval cache (best dir, then source seed dir).
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
multi_seed
Return a multi-seed view for evaluation and plotting across convergent seed runs.
All eval/plot methods on the view run once per selected seed checkpoint, then
aggregate results. Top-level evaluation metrics are aggregated scalars (default mean);
seed-level detail lives under the seeds key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
selection
|
str
|
Which seed runs to include: |
'all_convergent'
|
aggregate
|
str
|
How to combine scalar metrics: |
'mean'
|
dispersion
|
Optional[str]
|
Dispersion statistic for |
None
|
return_per_seed
|
bool
|
If True, include full per-seed payloads under |
False
|
Source code in gradiend/trainer/trainer.py
plot_encoder_by_target
plot_encoder_by_target(encoder_df=None, *, plot_style='strip', title=None, output=None, show=True, figsize=None, jitter=0.25, dodge=True, point_size=1.5, interactive=False, height=520, legend_loc='upper right', highlight_non_convergence=None, **kwargs)
Plot encoder values grouped by target token within feature class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoder_df
|
Optional[DataFrame]
|
Optional encoder-evaluation DataFrame. |
None
|
plot_style
|
Literal['strip', 'box', 'violin']
|
Plot style: |
'strip'
|
title
|
Optional[str]
|
Optional plot title. |
None
|
output
|
Optional[str]
|
Optional explicit output file path. |
None
|
show
|
bool
|
Whether to display the plot. |
True
|
figsize
|
Optional[Tuple[float, float]]
|
Optional Matplotlib figure size. |
None
|
jitter
|
float
|
Horizontal jitter for strip points. |
0.25
|
dodge
|
bool
|
If True, separate split hues within each target. |
True
|
point_size
|
float
|
Marker size for strip plots. |
1.5
|
interactive
|
bool
|
If True, create the interactive Plotly variant. |
False
|
height
|
int
|
Plotly height in pixels for interactive plots. |
520
|
legend_loc
|
str
|
Static Matplotlib legend location. |
'upper right'
|
highlight_non_convergence
|
Optional[bool]
|
Override non-convergence markers. |
None
|
**kwargs
|
Any
|
Additional keyword arguments forwarded to the evaluator. |
{}
|
Source code in gradiend/trainer/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='png', dpi=None, highlight_non_convergence=None, return_fig_ax=False, **kwargs)
Plot encoder value distributions for target and optional neutral rows.
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 used when |
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 training rows. |
True
|
split_plot_mode
|
str
|
How split-aware data is shown, e.g. |
'facet'
|
include_neutral
|
bool
|
If True, include neutral evaluation rows when present. |
False
|
figsize
|
Optional[Tuple[float, float]]
|
Optional Matplotlib figure size. |
None
|
img_format
|
str
|
File format used for generated output paths. |
'png'
|
dpi
|
Optional[int]
|
Optional figure DPI. |
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/trainer.py
plot_encoder_scatter
plot_encoder_scatter(encoder_df=None, *, color_by='label', x_col=None, label_name_mapping=None, max_points=None, show=True, title=None, height=500, split='test', highlight_non_convergence=None, **kwargs)
Create an interactive Plotly scatter plot for encoder outlier inspection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoder_df
|
Optional[DataFrame]
|
Optional encoder-evaluation DataFrame. |
None
|
color_by
|
str
|
Column used for point color. |
'label'
|
x_col
|
Optional[str]
|
Optional column for the categorical x-axis. |
None
|
label_name_mapping
|
Optional[dict]
|
Optional mapping from labels to display names. |
None
|
max_points
|
Optional[int]
|
Optional cap on plotted rows. |
None
|
show
|
bool
|
Whether to display the Plotly figure. |
True
|
title
|
Optional[str]
|
Optional plot title. |
None
|
height
|
int
|
Plot height in pixels. |
500
|
split
|
str
|
Split to evaluate/load when |
'test'
|
highlight_non_convergence
|
Optional[bool]
|
Override non-convergence markers. |
None
|
**kwargs
|
Any
|
Additional keyword arguments forwarded to the evaluator. |
{}
|
Source code in gradiend/trainer/trainer.py
plot_encoder_strip_by_split
plot_encoder_strip_by_split(encoder_df=None, *, include_neutral=False, title=None, output=None, show=True, figsize=None, jitter=0.08, dodge=True, point_size=5.0, label_points=False, highlight_non_convergence=None, **kwargs)
Plot encoder values as a strip plot grouped by split.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoder_df
|
Optional[DataFrame]
|
Optional encoder-evaluation DataFrame. |
None
|
include_neutral
|
bool
|
If True, include neutral rows when available. |
False
|
title
|
Optional[str]
|
Optional plot title. |
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
|
jitter
|
float
|
Horizontal jitter for points. |
0.08
|
dodge
|
bool
|
If True, separate split hues within each group. |
True
|
point_size
|
float
|
Marker size. |
5.0
|
label_points
|
Union[bool, Literal['outliers', 'outliers+sample', 'sample'], str]
|
Whether and how to label points. |
False
|
highlight_non_convergence
|
Optional[bool]
|
Override non-convergence markers. |
None
|
**kwargs
|
Any
|
Additional keyword arguments forwarded to the evaluator. |
{}
|
Source code in gradiend/trainer/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='png', dpi=None, highlight_non_convergence=None, return_fig_ax=False, **kwargs)
Plot convergence statistics collected during GRADIEND training.
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
|
str
|
File format used for generated output paths. |
'png'
|
dpi
|
Optional[int]
|
Optional figure DPI. |
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/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.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_with_gradiend
|
Trained GRADIEND model instance. |
required | |
**kwargs
|
Additional training context supplied by subclasses. |
{}
|
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.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pre_cfg
|
Optional[Any]
|
Optional pre-prune configuration. Defaults to
|
None
|
inplace
|
bool
|
If True, prune the current model in place and use it for subsequent training/evaluation. |
True
|
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).
learning_rate and feature_factor from decoder results (and probability-shift plots)
are passed through unchanged to :meth:ModelWithGradiend.rewrite_base_model for every
encoder source.
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
2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 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 | |
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 |
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="validation"), 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
- top-level convergence info (metric, threshold, best seed, etc.)
- a per-seed breakdown with training_score, eval_correlation, selection_score,
convergence_metric_value, and convergence flags.
Source code in gradiend/trainer/trainer.py
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 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 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 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 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 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 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 | |
unload_model
Release the in-memory model reference and try to move the model off GPU.
After calling this, call :meth:get_model or :meth:load_model (and optionally
:meth:cuda) yourself before evaluation if you want explicit control over loading
and device placement. Evaluation methods will still reload from disk when needed
but emit a warning.