Post-Training API
Post-training methods for improving and aligning generative models after
initial pretraining: preference optimization (DPO/SPO), reinforcement learning
(DDPO/GRPO/GARDO), distillation (reflow, consistency), reward modeling, and
self-play (SPIN, RFT). All trainers accept a shared
PostTrainingConfig and integrate with
accelerate (optionally FSDP) for distributed training.
For a task-oriented walkthrough, see Post-Training Guide.
Configuration
- class medlatents.post_training.PostTrainingConfig(method='dpo', lr=1e-05, batch_size=4, gradient_accumulation_steps=4, max_steps=1000, warmup_steps=100, weight_decay=0.01, grad_clip=1.0, mixed_precision='bf16', seed=42, use_ema=True, ema_decay=0.9999, beta=0.1, loss_type='sigmoid', reference_free=False, label_smoothing=0.0, num_candidates=4, step_preference_model=None, clip_range=0.2, kl_coeff=0.1, num_samples_per_prompt=4, normalize_rewards=True, gae_lambda=0.95, reward_threshold=0.1, distance_penalty=0.01, teacher_path=None, num_distillation_steps=50, huber_c=0.00054, discretization_steps=18, num_reflow_iterations=2, pairs_per_iteration=10000, num_self_play_iterations=3, top_k_samples=4, reward_model_type='ai', reward_model_path=None, reward_model_config=<factory>, log_every=10, eval_every=100, save_every=500, logdir='./post_training_logs', run_name=None, wandb_project=None, wandb_entity=None, use_fsdp=True, fsdp_sharding_strategy='full')[source][source]
Bases:
objectConfiguration for post-training methods.
This config class supports all post-training methods in medlatents: - DPO variants (standard, IPO, KTO, SPO) - RL methods (DDPO, GRPO, GARDO) - Distillation (consistency, reflow) - Self-play (SPIN, RFT)
The config is designed to be serializable for experiment tracking and supports sensible defaults that can be overridden as needed.
Example
>>> config = PostTrainingConfig(method="dpo", beta=0.1, lr=1e-5) >>> config = PostTrainingConfig.from_preset("dpo_small")
- Parameters:
method (
Literal['dpo','spo','ipo','kto','ddpo','grpo','gardo','consistency','reflow','self_play','rft'], default:'dpo')lr (
float, default:1e-05)batch_size (
int, default:4)gradient_accumulation_steps (
int, default:4)max_steps (
int, default:1000)warmup_steps (
int, default:100)weight_decay (
float, default:0.01)grad_clip (
float, default:1.0)mixed_precision (
Literal['no','fp16','bf16'], default:'bf16')use_ema (
bool, default:True)ema_decay (
float, default:0.9999)beta (
float, default:0.1)loss_type (
Literal['sigmoid','hinge','ipo','kto','disco'], default:'sigmoid')reference_free (
bool, default:False)label_smoothing (
float, default:0.0)num_candidates (
int, default:4)clip_range (
float, default:0.2)kl_coeff (
float, default:0.1)num_samples_per_prompt (
int, default:4)normalize_rewards (
bool, default:True)gae_lambda (
float, default:0.95)reward_threshold (
float, default:0.1)distance_penalty (
float, default:0.01)num_distillation_steps (
int, default:50)huber_c (
float, default:0.00054)discretization_steps (
int, default:18)num_reflow_iterations (
int, default:2)pairs_per_iteration (
int, default:10000)num_self_play_iterations (
int, default:3)top_k_samples (
int, default:4)reward_model_type (
Literal['trained','ai','discriminator','external'], default:'ai')log_every (
int, default:10)eval_every (
int, default:100)save_every (
int, default:500)logdir (
str, default:'./post_training_logs')use_fsdp (
bool, default:True)fsdp_sharding_strategy (
Literal['full','shard_grad_op','no_shard'], default:'full')
- method: Literal['dpo', 'spo', 'ipo', 'kto', 'ddpo', 'grpo', 'gardo', 'consistency', 'reflow', 'self_play', 'rft'] = 'dpo'
- mixed_precision: Literal['no', 'fp16', 'bf16'] = 'bf16'
- loss_type: Literal['sigmoid', 'hinge', 'ipo', 'kto', 'disco'] = 'sigmoid'
- reward_model_type: Literal['trained', 'ai', 'discriminator', 'external'] = 'ai'
- fsdp_sharding_strategy: Literal['full', 'shard_grad_op', 'no_shard'] = 'full'
- classmethod from_preset(preset, **overrides)[source][source]
Create config from a named preset.
Available presets: - dpo_small: Quick DPO for testing - dpo_standard: Standard DPO settings - dpo_large: Large-scale DPO - spo_standard: Step-by-step preference optimization - ddpo_standard: DDPO with standard settings - grpo_efficient: Memory-efficient GRPO - consistency_fast: Fast consistency distillation
- Parameters:
preset (
str) – Name of the preset**overrides – Parameters to override
- Return type:
- Returns:
PostTrainingConfig with preset values
- __init__(method='dpo', lr=1e-05, batch_size=4, gradient_accumulation_steps=4, max_steps=1000, warmup_steps=100, weight_decay=0.01, grad_clip=1.0, mixed_precision='bf16', seed=42, use_ema=True, ema_decay=0.9999, beta=0.1, loss_type='sigmoid', reference_free=False, label_smoothing=0.0, num_candidates=4, step_preference_model=None, clip_range=0.2, kl_coeff=0.1, num_samples_per_prompt=4, normalize_rewards=True, gae_lambda=0.95, reward_threshold=0.1, distance_penalty=0.01, teacher_path=None, num_distillation_steps=50, huber_c=0.00054, discretization_steps=18, num_reflow_iterations=2, pairs_per_iteration=10000, num_self_play_iterations=3, top_k_samples=4, reward_model_type='ai', reward_model_path=None, reward_model_config=<factory>, log_every=10, eval_every=100, save_every=500, logdir='./post_training_logs', run_name=None, wandb_project=None, wandb_entity=None, use_fsdp=True, fsdp_sharding_strategy='full')[source]
- Parameters:
method (
Literal['dpo','spo','ipo','kto','ddpo','grpo','gardo','consistency','reflow','self_play','rft'], default:'dpo')lr (
float, default:1e-05)batch_size (
int, default:4)gradient_accumulation_steps (
int, default:4)max_steps (
int, default:1000)warmup_steps (
int, default:100)weight_decay (
float, default:0.01)grad_clip (
float, default:1.0)mixed_precision (
Literal['no','fp16','bf16'], default:'bf16')use_ema (
bool, default:True)ema_decay (
float, default:0.9999)beta (
float, default:0.1)loss_type (
Literal['sigmoid','hinge','ipo','kto','disco'], default:'sigmoid')reference_free (
bool, default:False)label_smoothing (
float, default:0.0)num_candidates (
int, default:4)clip_range (
float, default:0.2)kl_coeff (
float, default:0.1)num_samples_per_prompt (
int, default:4)normalize_rewards (
bool, default:True)gae_lambda (
float, default:0.95)reward_threshold (
float, default:0.1)distance_penalty (
float, default:0.01)num_distillation_steps (
int, default:50)huber_c (
float, default:0.00054)discretization_steps (
int, default:18)num_reflow_iterations (
int, default:2)pairs_per_iteration (
int, default:10000)num_self_play_iterations (
int, default:3)top_k_samples (
int, default:4)reward_model_type (
Literal['trained','ai','discriminator','external'], default:'ai')log_every (
int, default:10)eval_every (
int, default:100)save_every (
int, default:500)logdir (
str, default:'./post_training_logs')use_fsdp (
bool, default:True)fsdp_sharding_strategy (
Literal['full','shard_grad_op','no_shard'], default:'full')
- medlatents.post_training.DPO_SMALL = PostTrainingConfig preset
Configuration for post-training methods.
This config class supports all post-training methods in medlatents: - DPO variants (standard, IPO, KTO, SPO) - RL methods (DDPO, GRPO, GARDO) - Distillation (consistency, reflow) - Self-play (SPIN, RFT)
The config is designed to be serializable for experiment tracking and supports sensible defaults that can be overridden as needed.
Example
>>> config = PostTrainingConfig(method="dpo", beta=0.1, lr=1e-5) >>> config = PostTrainingConfig.from_preset("dpo_small")
- medlatents.post_training.DPO_STANDARD = PostTrainingConfig preset
Configuration for post-training methods.
This config class supports all post-training methods in medlatents: - DPO variants (standard, IPO, KTO, SPO) - RL methods (DDPO, GRPO, GARDO) - Distillation (consistency, reflow) - Self-play (SPIN, RFT)
The config is designed to be serializable for experiment tracking and supports sensible defaults that can be overridden as needed.
Example
>>> config = PostTrainingConfig(method="dpo", beta=0.1, lr=1e-5) >>> config = PostTrainingConfig.from_preset("dpo_small")
- medlatents.post_training.DPO_LARGE = PostTrainingConfig preset
Configuration for post-training methods.
This config class supports all post-training methods in medlatents: - DPO variants (standard, IPO, KTO, SPO) - RL methods (DDPO, GRPO, GARDO) - Distillation (consistency, reflow) - Self-play (SPIN, RFT)
The config is designed to be serializable for experiment tracking and supports sensible defaults that can be overridden as needed.
Example
>>> config = PostTrainingConfig(method="dpo", beta=0.1, lr=1e-5) >>> config = PostTrainingConfig.from_preset("dpo_small")
- medlatents.post_training.SPO_STANDARD = PostTrainingConfig preset
Configuration for post-training methods.
This config class supports all post-training methods in medlatents: - DPO variants (standard, IPO, KTO, SPO) - RL methods (DDPO, GRPO, GARDO) - Distillation (consistency, reflow) - Self-play (SPIN, RFT)
The config is designed to be serializable for experiment tracking and supports sensible defaults that can be overridden as needed.
Example
>>> config = PostTrainingConfig(method="dpo", beta=0.1, lr=1e-5) >>> config = PostTrainingConfig.from_preset("dpo_small")
- medlatents.post_training.DDPO_STANDARD = PostTrainingConfig preset
Configuration for post-training methods.
This config class supports all post-training methods in medlatents: - DPO variants (standard, IPO, KTO, SPO) - RL methods (DDPO, GRPO, GARDO) - Distillation (consistency, reflow) - Self-play (SPIN, RFT)
The config is designed to be serializable for experiment tracking and supports sensible defaults that can be overridden as needed.
Example
>>> config = PostTrainingConfig(method="dpo", beta=0.1, lr=1e-5) >>> config = PostTrainingConfig.from_preset("dpo_small")
- medlatents.post_training.GRPO_EFFICIENT = PostTrainingConfig preset
Configuration for post-training methods.
This config class supports all post-training methods in medlatents: - DPO variants (standard, IPO, KTO, SPO) - RL methods (DDPO, GRPO, GARDO) - Distillation (consistency, reflow) - Self-play (SPIN, RFT)
The config is designed to be serializable for experiment tracking and supports sensible defaults that can be overridden as needed.
Example
>>> config = PostTrainingConfig(method="dpo", beta=0.1, lr=1e-5) >>> config = PostTrainingConfig.from_preset("dpo_small")
Preference Data and Reward Models
- class medlatents.post_training.PreferenceDataset(pairs=None, transform=None)[source][source]
Bases:
torch.utils.data.dataset.DatasetPyTorch Dataset for preference learning.
Supports multiple input formats and provides convenient factory methods for common use cases like synthetic generation and loading annotations.
Example
>>> # From explicit pairs >>> dataset = PreferenceDataset(pairs=[pair1, pair2, pair3]) >>> >>> # From generations with reward model >>> dataset = PreferenceDataset.from_generations( ... generator=model, ... prompts=prompt_dataset, ... reward_fn=reward_model, ... ) >>> >>> # From saved file >>> dataset = PreferenceDataset.load("preferences.pt")
- Parameters:
pairs (
Sequence[PreferencePair] |None, default:None)transform (
Callable[[PreferencePair],PreferencePair] |None, default:None)
- __init__(pairs=None, transform=None)[source][source]
Initialize preference dataset.
- Parameters:
pairs (
Sequence[PreferencePair] |None, default:None) – Sequence of PreferencePair objectstransform (
Callable[[PreferencePair],PreferencePair] |None, default:None) – Optional transform to apply to each pair
- add_pair(pair)[source][source]
Add a single preference pair.
- Parameters:
pair (
PreferencePair)- Return type:
- add_ranked(ranked, strategy='best_worst')[source][source]
Add pairs from ranked samples.
- Parameters:
ranked (
RankedSamples)strategy (
Literal['all','adjacent','best_worst'], default:'best_worst')
- Return type:
- filter(predicate)[source][source]
Return new dataset with filtered pairs.
- Parameters:
predicate (
Callable[[PreferencePair],bool])- Return type:
- shuffle(seed=None)[source][source]
Return new dataset with shuffled pairs.
- Parameters:
- Return type:
- split(train_ratio=0.9, seed=None)[source][source]
Split into train and validation sets.
- Parameters:
- Return type:
- classmethod from_generations(generator, prompts, reward_fn, num_samples_per_prompt=4, pair_strategy='best_worst', generation_kwargs=None, device='cuda', show_progress=True)[source][source]
Create dataset by generating samples and ranking with reward function.
This is the primary method for creating synthetic preference data.
- Parameters:
generator (
Module) – Model with a generate methodprompts (
Sequence[Any]) – Sequence of conditioning prompts/labelsreward_fn (
Callable[[Tensor],Tensor]) – Function that scores samples (higher = better)num_samples_per_prompt (
int, default:4) – Number of samples to generate per promptpair_strategy (
Literal['all','adjacent','best_worst'], default:'best_worst') – How to create pairs from rankingsgeneration_kwargs (
dict[str,Any] |None, default:None) – Extra kwargs for generator.generate()device (
device|str, default:'cuda') – Device for generationshow_progress (
bool, default:True) – Show progress bar
- Return type:
- Returns:
PreferenceDataset with generated pairs
- classmethod from_json(path)[source][source]
Load from JSON file.
Expected format:
[ {"chosen": [...], "rejected": [...], "prompt": "...", "margin": 0.8}, ... ]
- Parameters:
- Return type:
- classmethod __class_getitem__(params)[source]
Parameterizes a generic class.
At least, parameterizing a generic class is the main thing this method does. For example, for some generic class Foo, this is called when we do Foo[int] - there, with cls=Foo and params=int.
However, note that this method is also called when defining generic classes in the first place with class Foo(Generic[T]): ….
- class medlatents.post_training.PreferencePair(chosen, rejected, prompt=None, margin=1.0, metadata=<factory>)[source][source]
Bases:
objectA single preference comparison between two samples.
- Variables:
chosen – The preferred sample (tokens or continuous latents)
rejected – The non-preferred sample
prompt – Optional conditioning information (class label, text, etc.)
margin – Preference strength in [0, 1]. Higher = stronger preference. Default 1.0 for binary preferences, can be soft for uncertain labels.
metadata – Optional dictionary for additional information (source, annotator, etc.)
Example
>>> pair = PreferencePair( ... chosen=torch.tensor([1, 2, 3]), ... rejected=torch.tensor([1, 2, 4]), ... prompt="Generate a brain MRI", ... margin=0.8, # Slight preference ... )
- Parameters:
- chosen: torch.Tensor
- rejected: torch.Tensor
- prompt: Any = None
- class medlatents.post_training.RankedSamples(samples, prompt=None, scores=None, metadata=<factory>)[source][source]
Bases:
objectMultiple samples with a preference ranking.
Useful for generating multiple preference pairs from ranked data. Ranking is from best (index 0) to worst (index -1).
- Variables:
samples – List of samples ordered by preference (best first)
prompt – Optional conditioning information
scores – Optional scalar scores for each sample
metadata – Optional dictionary for additional information
Example
>>> ranked = RankedSamples( ... samples=[best_sample, second_best, worst_sample], ... scores=[0.9, 0.6, 0.2], ... ) >>> pairs = ranked.to_pairs() # Creates 3 preference pairs
- Parameters:
- samples: list[torch.Tensor]
- prompt: Any = None
- to_pairs(strategy='all')[source][source]
Convert ranking to preference pairs.
- Parameters:
strategy (
Literal['all','adjacent','best_worst'], default:'all') –“all”: All pairs where i < j (O(n^2) pairs)
”adjacent”: Only adjacent pairs (O(n) pairs)
”best_worst”: Only best vs worst (1 pair)
- Return type:
- Returns:
List of PreferencePair objects
- class medlatents.post_training.StepwisePreference(step_idx, timestep, chosen_state, rejected_state, chosen_score, rejected_score)[source][source]
Bases:
objectPreference at a specific denoising step for SPO.
Used by Step-by-step Preference Optimization to capture fine-grained preferences at each noise level.
- Variables:
step_idx – Index of the denoising step
timestep – Continuous timestep value in [0, 1]
chosen_state – Preferred intermediate state
rejected_state – Non-preferred intermediate state
chosen_score – Score of chosen state
rejected_score – Score of rejected state
- Parameters:
- chosen_state: torch.Tensor
- rejected_state: torch.Tensor
- medlatents.post_training.collate_preference_pairs(batch)[source][source]
Collate function for DataLoader with PreferenceDataset.
Returns a dictionary with batched tensors.
Example
>>> loader = DataLoader(dataset, collate_fn=collate_preference_pairs) >>> for batch in loader: ... chosen = batch["chosen"] # [batch_size, seq_len] ... rejected = batch["rejected"] ... margins = batch["margin"]
- class medlatents.post_training.RewardModel(vocab_size=None, in_channels=None, seq_length=256, hidden_size=512, depth=6, num_heads=8, mlp_ratio=4.0, timestep_aware=False, pooling='mean', qk_norm=False, rope_theta=10000.0, dropout=0.1)[source][source]
Bases:
torch.nn.modules.module.ModuleTrainable reward model that scores samples.
Uses the same transformer architecture as the generative models, but with a scalar output head. This ensures architectural compatibility and enables transfer learning from pretrained generators.
The model can operate in two modes: 1. Discrete: Input is token indices (for MaskGIT, autoreg, D3PM, discrete flow) 2. Continuous: Input is latent vectors (for continuous diffusion/flow)
It optionally accepts timestep conditioning for step-aware scoring (SPO).
Example
>>> # Create reward model for discrete tokens >>> model = RewardModel( ... vocab_size=1024, ... seq_length=256, ... hidden_size=512, ... depth=6, ... num_heads=8, ... ) >>> >>> # Score samples >>> scores = model(tokens) # [batch, 1] >>> >>> # Train from preferences >>> trainer = RewardModelTrainer(model, dataset) >>> trainer.train(epochs=3)
- Parameters:
seq_length (
int, default:256)hidden_size (
int, default:512)depth (
int, default:6)num_heads (
int, default:8)mlp_ratio (
float, default:4.0)timestep_aware (
bool, default:False)pooling (
Literal['mean','cls','last'], default:'mean')qk_norm (
bool, default:False)rope_theta (
float, default:10000.0)dropout (
float, default:0.1)
- __init__(vocab_size=None, in_channels=None, seq_length=256, hidden_size=512, depth=6, num_heads=8, mlp_ratio=4.0, timestep_aware=False, pooling='mean', qk_norm=False, rope_theta=10000.0, dropout=0.1)[source][source]
Initialize reward model.
- Parameters:
vocab_size (
int|None, default:None) – Vocabulary size for discrete mode (mutually exclusive with in_channels)in_channels (
int|None, default:None) – Input channels for continuous modeseq_length (
int, default:256) – Maximum sequence lengthhidden_size (
int, default:512) – Transformer hidden dimensiondepth (
int, default:6) – Number of transformer layersnum_heads (
int, default:8) – Number of attention headsmlp_ratio (
float, default:4.0) – MLP expansion ratiotimestep_aware (
bool, default:False) – If True, accept timestep conditioningpooling (
Literal['mean','cls','last'], default:'mean') – How to aggregate sequence for scalar outputqk_norm (
bool, default:False) – Use QK LayerNorm for stabilityrope_theta (
float, default:10000.0) – RoPE base frequencydropout (
float, default:0.1) – Dropout rate
- compute_preference_loss(chosen, rejected, margin=None, t=None)[source][source]
Compute Bradley-Terry preference loss.
- Parameters:
- Return type:
- Returns:
Dict with loss and metrics
- T_destination = ~T_destination
- add_module(name, module)[source]
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- apply(fn)[source]
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also torch.nn.init).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) is nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16()[source]
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse=True)[source]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- compile(*args, **kwargs)[source]
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.- Return type:
- cpu()[source]
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device=None)[source]
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double()[source]
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- eval()[source]
Set the module in evaluation mode.
This has an effect only on certain modules. See the documentation of particular modules for details of their behaviors in training/evaluation mode, i.e. whether they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See Locally disabling gradient computation for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr()[source]
Return the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- Return type:
- float()[source]
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- get_buffer(target)[source]
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target (
str) – The fully-qualified string name of the buffer to look for. (Seeget_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state()[source]
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
- get_parameter(target)[source]
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target (
str) – The fully-qualified string name of the Parameter to look for. (Seeget_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target)[source]
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Awhich has a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target (
str) – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)- Returns:
The submodule referenced by
target- Return type:
- Raises:
AttributeError – If at any point along the path resulting from the target string the (sub)path resolves to a non-existent attribute name or an object that is not an instance of
nn.Module.
- half()[source]
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device=None)[source]
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict, strict=True, assign=False)[source]
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dictunlessget_swap_module_params_on_conversion()isTrue.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – When set to
False, the properties of the tensors in the current module are preserved whereas setting it toTruepreserves properties of the Tensors in the state dict. The only exception is therequires_gradfield ofParameterfor which the value from the module is preserved. Default:False
- Returns:
missing_keysis a list of str containing any keys that are expectedby this module but missing from the provided
state_dict.
unexpected_keysis a list of str containing the keys that are notexpected by this module but present in the provided
state_dict.
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules(remove_duplicate=True)[source]
Return an iterator over all modules in the network.
- Parameters:
remove_duplicate (
bool, default:True) – whether to remove the duplicated module instances in the result or not.- Yields:
Module – a module in the network
- Return type:
Note
Duplicate modules are returned only once by default. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- mtia(device=None)[source]
Move all model parameters and buffers to the MTIA.
This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on MTIA while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- named_buffers(prefix='', recurse=True, remove_duplicate=True)[source]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children()[source]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo=None, prefix='', remove_duplicate=True)[source]
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix='', recurse=True, remove_duplicate=True)[source]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse=True)[source]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook)[source]
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.
- register_buffer(name, tensor, persistent=True)[source]
Add a buffer to the module.
This is typically used to register a buffer that should not be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook, *, prepend=False, with_kwargs=False, always_call=False)[source]
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook, *, prepend=False, with_kwargs=False)[source]
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook, prepend=False)[source]
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, and its firing rules are as follows:
Ordinarily, the hook fires when the gradients are computed with respect to the module inputs.
If none of the module inputs require gradients, the hook will fire when the gradients are computed with respect to module outputs.
If none of the module outputs require gradients, then the hooks will not fire.
The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook, prepend=False)[source]
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor, ...], Tensor or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)[source]
Register a post-hook to be run after module’s
load_state_dict()is called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_pre_hook(hook)[source]
Register a pre-hook to be run before module’s
load_state_dict()is called.- It should have the following signature::
hook(module, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) -> None # noqa: B950
- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
- register_module(name, module)[source]
Alias for
add_module().
- register_parameter(name, param)[source]
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- Return type:
- register_state_dict_post_hook(hook)[source]
Register a post-hook for the
state_dict()method.- It should have the following signature::
hook(module, state_dict, prefix, local_metadata) -> None
The registered hooks can modify the
state_dictinplace.
- register_state_dict_pre_hook(hook)[source]
Register a pre-hook for the
state_dict()method.- It should have the following signature::
hook(module, prefix, keep_vars) -> None
The registered hooks can be used to perform pre-processing before the
state_dictcall is made.
- requires_grad_(requires_grad=True)[source]
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See Locally disabling gradient computation for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state)[source]
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.
- set_submodule(target, module, strict=False)[source]
Set the submodule given by
targetif it exists, otherwise throw an error.Note
If
strictis set toFalse(default), the method will replace an existing submodule or create a new submodule if the parent module exists. Ifstrictis set toTrue, the method will only attempt to replace an existing submodule and throw an error if the submodule does not exist.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(3, 3, 3) ) (linear): Linear(3, 3) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To override the
Conv2dwith a new submoduleLinear, you could callset_submodule("net_b.net_c.conv", nn.Linear(1, 1))wherestrictcould beTrueorFalseTo add a new submodule
Conv2dto the existingnet_bmodule, you would callset_submodule("net_b.conv", nn.Conv2d(1, 1, 1)).In the above if you set
strict=Trueand callset_submodule("net_b.conv", nn.Conv2d(1, 1, 1), strict=True), an AttributeError will be raised becausenet_bdoes not have a submodule namedconv.- Parameters:
target (
str) – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)module (
Module) – The module to set the submodule to.strict (
bool, default:False) – IfFalse, the method will replace an existing submodule or create a new submodule if the parent module exists. IfTrue, the method will only attempt to replace an existing submodule and throw an error if the submodule doesn’t already exist.
- Raises:
ValueError – If the
targetstring is empty or ifmoduleis not an instance ofnn.Module.AttributeError – If at any point along the path resulting from the
targetstring the (sub)path resolves to a non-existent attribute name or an object that is not an instance ofnn.Module.
- Return type:
See
torch.Tensor.share_memory_().- Return type:
Self
- state_dict(*args, destination=None, prefix='', keep_vars=False)[source]
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)[source]
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)[source]
- to(dtype, non_blocking=False)[source]
- to(tensor, non_blocking=False)[source]
- to(memory_format=torch.channels_last)[source]
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device, recurse=True)[source]
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode=True)[source]
Set the module in training mode.
This has an effect only on certain modules. See the documentation of particular modules for details of their behaviors in training/evaluation mode, i.e., whether they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- type(dst_type)[source]
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device=None)[source]
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none=True)[source]
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.- Return type:
- class medlatents.post_training.RewardModelTrainer(model, dataset, val_dataset=None, lr=0.0001, batch_size=32, weight_decay=0.01, warmup_ratio=0.1, grad_clip=1.0, device='cuda')[source][source]
Bases:
objectTrainer for reward models from preference data.
Handles the training loop with proper logging, checkpointing, and distributed training support.
Example
>>> trainer = RewardModelTrainer( ... model=reward_model, ... dataset=preference_dataset, ... lr=1e-4, ... ) >>> trainer.train(epochs=3)
- Parameters:
model (
RewardModel)dataset (
PreferenceDataset)val_dataset (
PreferenceDataset|None, default:None)lr (
float, default:0.0001)batch_size (
int, default:32)weight_decay (
float, default:0.01)warmup_ratio (
float, default:0.1)grad_clip (
float, default:1.0)
- __init__(model, dataset, val_dataset=None, lr=0.0001, batch_size=32, weight_decay=0.01, warmup_ratio=0.1, grad_clip=1.0, device='cuda')[source][source]
Initialize trainer.
- Parameters:
model (
RewardModel) – RewardModel to traindataset (
PreferenceDataset) – Training preference dataval_dataset (
PreferenceDataset|None, default:None) – Optional validation datalr (
float, default:0.0001) – Learning ratebatch_size (
int, default:32) – Batch sizeweight_decay (
float, default:0.01) – Weight decay for AdamWwarmup_ratio (
float, default:0.1) – Fraction of steps for warmupgrad_clip (
float, default:1.0) – Gradient clipping norm
- medlatents.post_training.create_reward_model(model_size='small', vocab_size=None, in_channels=None, seq_length=256, timestep_aware=False, **kwargs)[source][source]
Factory function to create reward models with standard configurations.
- Parameters:
model_size (
Literal['nano','small','base','large'], default:'small') – Size preset (nano, small, base, large)in_channels (
int|None, default:None) – For continuous modeseq_length (
int, default:256) – Maximum sequence lengthtimestep_aware (
bool, default:False) – Enable timestep conditioning for SPO**kwargs (
Any) – Additional arguments to RewardModel
- Return type:
- Returns:
Configured RewardModel
AI Feedback
- class medlatents.post_training.preference.AIPreferenceScorer(score_fn, higher_is_better=True)[source][source]
Bases:
objectGeneric AI-based preference scoring.
Wraps various scoring backends (reward model, discriminator, external API) into a unified interface.
Example
>>> # From reward model >>> scorer = AIPreferenceScorer.from_reward_model(rm) >>> >>> # Custom scoring function >>> scorer = AIPreferenceScorer(lambda x: my_score_fn(x)) >>> >>> # Generate preference pairs >>> pairs = scorer.generate_pairs(samples, num_pairs=100)
- classmethod from_reward_model(model)[source][source]
Create scorer from a RewardModel.
- Parameters:
model (
RewardModel)- Return type:
- classmethod from_discriminator(discriminator)[source][source]
Create scorer from a discriminator.
- Parameters:
discriminator (
Module)- Return type:
- create_pairs(samples, prompt=None, strategy='best_worst')[source][source]
Create preference pairs from samples.
- generate_pairs_from_generator(generator, prompts, num_samples_per_prompt=4, strategy='best_worst', generation_kwargs=None, device='cuda')[source][source]
Generate preference pairs by sampling from a generator.
- Parameters:
generator (
Module) – Model with generate() methodnum_samples_per_prompt (
int, default:4) – Samples per promptstrategy (
Literal['best_worst','adjacent','all'], default:'best_worst') – Pairing strategygeneration_kwargs (
dict[str,Any] |None, default:None) – Extra args for generationdevice (
device|str, default:'cuda') – Device for generation
- Return type:
- Returns:
List of PreferencePair objects
- class medlatents.post_training.preference.DiscriminatorScorer(discriminator, score_transform='sigmoid')[source][source]
Bases:
torch.nn.modules.module.ModuleScore samples using a discriminator trained to distinguish real from generated.
This is compatible with your existing TokenCritic and can also wrap any binary classifier.
Example
>>> scorer = DiscriminatorScorer(critic_model) >>> scores = scorer(generated_samples) # Higher = more "real"
- Parameters:
- __init__(discriminator, score_transform='sigmoid')[source][source]
Initialize discriminator scorer.
- create_pairs(samples, prompt=None, strategy='best_worst')[source][source]
Create preference pairs from samples using discriminator scores.
- T_destination = ~T_destination
- add_module(name, module)[source]
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- apply(fn)[source]
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also torch.nn.init).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) is nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16()[source]
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse=True)[source]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- compile(*args, **kwargs)[source]
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.- Return type:
- cpu()[source]
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device=None)[source]
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double()[source]
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- eval()[source]
Set the module in evaluation mode.
This has an effect only on certain modules. See the documentation of particular modules for details of their behaviors in training/evaluation mode, i.e. whether they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See Locally disabling gradient computation for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr()[source]
Return the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- Return type:
- float()[source]
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- get_buffer(target)[source]
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target (
str) – The fully-qualified string name of the buffer to look for. (Seeget_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state()[source]
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
- get_parameter(target)[source]
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target (
str) – The fully-qualified string name of the Parameter to look for. (Seeget_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target)[source]
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Awhich has a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target (
str) – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)- Returns:
The submodule referenced by
target- Return type:
- Raises:
AttributeError – If at any point along the path resulting from the target string the (sub)path resolves to a non-existent attribute name or an object that is not an instance of
nn.Module.
- half()[source]
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device=None)[source]
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict, strict=True, assign=False)[source]
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dictunlessget_swap_module_params_on_conversion()isTrue.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – When set to
False, the properties of the tensors in the current module are preserved whereas setting it toTruepreserves properties of the Tensors in the state dict. The only exception is therequires_gradfield ofParameterfor which the value from the module is preserved. Default:False
- Returns:
missing_keysis a list of str containing any keys that are expectedby this module but missing from the provided
state_dict.
unexpected_keysis a list of str containing the keys that are notexpected by this module but present in the provided
state_dict.
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules(remove_duplicate=True)[source]
Return an iterator over all modules in the network.
- Parameters:
remove_duplicate (
bool, default:True) – whether to remove the duplicated module instances in the result or not.- Yields:
Module – a module in the network
- Return type:
Note
Duplicate modules are returned only once by default. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- mtia(device=None)[source]
Move all model parameters and buffers to the MTIA.
This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on MTIA while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- named_buffers(prefix='', recurse=True, remove_duplicate=True)[source]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children()[source]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo=None, prefix='', remove_duplicate=True)[source]
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix='', recurse=True, remove_duplicate=True)[source]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse=True)[source]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook)[source]
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.
- register_buffer(name, tensor, persistent=True)[source]
Add a buffer to the module.
This is typically used to register a buffer that should not be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook, *, prepend=False, with_kwargs=False, always_call=False)[source]
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook, *, prepend=False, with_kwargs=False)[source]
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook, prepend=False)[source]
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, and its firing rules are as follows:
Ordinarily, the hook fires when the gradients are computed with respect to the module inputs.
If none of the module inputs require gradients, the hook will fire when the gradients are computed with respect to module outputs.
If none of the module outputs require gradients, then the hooks will not fire.
The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook, prepend=False)[source]
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor, ...], Tensor or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)[source]
Register a post-hook to be run after module’s
load_state_dict()is called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_pre_hook(hook)[source]
Register a pre-hook to be run before module’s
load_state_dict()is called.- It should have the following signature::
hook(module, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) -> None # noqa: B950
- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
- register_module(name, module)[source]
Alias for
add_module().
- register_parameter(name, param)[source]
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- Return type:
- register_state_dict_post_hook(hook)[source]
Register a post-hook for the
state_dict()method.- It should have the following signature::
hook(module, state_dict, prefix, local_metadata) -> None
The registered hooks can modify the
state_dictinplace.
- register_state_dict_pre_hook(hook)[source]
Register a pre-hook for the
state_dict()method.- It should have the following signature::
hook(module, prefix, keep_vars) -> None
The registered hooks can be used to perform pre-processing before the
state_dictcall is made.
- requires_grad_(requires_grad=True)[source]
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See Locally disabling gradient computation for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state)[source]
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.
- set_submodule(target, module, strict=False)[source]
Set the submodule given by
targetif it exists, otherwise throw an error.Note
If
strictis set toFalse(default), the method will replace an existing submodule or create a new submodule if the parent module exists. Ifstrictis set toTrue, the method will only attempt to replace an existing submodule and throw an error if the submodule does not exist.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(3, 3, 3) ) (linear): Linear(3, 3) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To override the
Conv2dwith a new submoduleLinear, you could callset_submodule("net_b.net_c.conv", nn.Linear(1, 1))wherestrictcould beTrueorFalseTo add a new submodule
Conv2dto the existingnet_bmodule, you would callset_submodule("net_b.conv", nn.Conv2d(1, 1, 1)).In the above if you set
strict=Trueand callset_submodule("net_b.conv", nn.Conv2d(1, 1, 1), strict=True), an AttributeError will be raised becausenet_bdoes not have a submodule namedconv.- Parameters:
target (
str) – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)module (
Module) – The module to set the submodule to.strict (
bool, default:False) – IfFalse, the method will replace an existing submodule or create a new submodule if the parent module exists. IfTrue, the method will only attempt to replace an existing submodule and throw an error if the submodule doesn’t already exist.
- Raises:
ValueError – If the
targetstring is empty or ifmoduleis not an instance ofnn.Module.AttributeError – If at any point along the path resulting from the
targetstring the (sub)path resolves to a non-existent attribute name or an object that is not an instance ofnn.Module.
- Return type:
See
torch.Tensor.share_memory_().- Return type:
Self
- state_dict(*args, destination=None, prefix='', keep_vars=False)[source]
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)[source]
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)[source]
- to(dtype, non_blocking=False)[source]
- to(tensor, non_blocking=False)[source]
- to(memory_format=torch.channels_last)[source]
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device, recurse=True)[source]
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode=True)[source]
Set the module in training mode.
This has an effect only on certain modules. See the documentation of particular modules for details of their behaviors in training/evaluation mode, i.e., whether they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- type(dst_type)[source]
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device=None)[source]
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none=True)[source]
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.- Return type:
- class medlatents.post_training.preference.StepAwarePreferenceModel(base_model=None, vocab_size=None, in_channels=None, seq_length=256, hidden_size=384, depth=6, num_heads=6)[source][source]
Bases:
torch.nn.modules.module.ModuleTimestep-aware preference model for Step-by-step Preference Optimization (SPO).
This model scores intermediate denoising states, allowing SPO to learn fine-grained preferences at each noise level.
The key insight is that preferences differ at different timesteps: - Early steps (high noise): Layout/composition preferences - Late steps (low noise): Fine detail preferences
Example
>>> step_model = StepAwarePreferenceModel( ... base_model=reward_model, # Must be timestep_aware=True ... ) >>> scores = step_model(noisy_samples, t=timesteps)
- Parameters:
- __init__(base_model=None, vocab_size=None, in_channels=None, seq_length=256, hidden_size=384, depth=6, num_heads=6)[source][source]
Initialize step-aware preference model.
Either provide a base_model (must have timestep_aware=True) or specify architecture parameters to create a new model.
- Parameters:
base_model (
RewardModel|None, default:None) – Pre-existing timestep-aware RewardModelvocab_size (
int|None, default:None) – For creating new model (discrete)in_channels (
int|None, default:None) – For creating new model (continuous)seq_length (
int, default:256) – Sequence lengthhidden_size (
int, default:384) – Hidden dimensiondepth (
int, default:6) – Number of layersnum_heads (
int, default:6) – Attention heads
- select_winner_loser(candidates, t)[source][source]
Select best and worst candidates for SPO training.
- sample_random_candidate(candidates)[source][source]
Randomly select one candidate per batch item (for next SPO step).
- T_destination = ~T_destination
- add_module(name, module)[source]
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- apply(fn)[source]
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also torch.nn.init).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) is nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16()[source]
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse=True)[source]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- compile(*args, **kwargs)[source]
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.- Return type:
- cpu()[source]
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device=None)[source]
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double()[source]
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- eval()[source]
Set the module in evaluation mode.
This has an effect only on certain modules. See the documentation of particular modules for details of their behaviors in training/evaluation mode, i.e. whether they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See Locally disabling gradient computation for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr()[source]
Return the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- Return type:
- float()[source]
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- get_buffer(target)[source]
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target (
str) – The fully-qualified string name of the buffer to look for. (Seeget_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state()[source]
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
- get_parameter(target)[source]
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target (
str) – The fully-qualified string name of the Parameter to look for. (Seeget_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target)[source]
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Awhich has a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target (
str) – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)- Returns:
The submodule referenced by
target- Return type:
- Raises:
AttributeError – If at any point along the path resulting from the target string the (sub)path resolves to a non-existent attribute name or an object that is not an instance of
nn.Module.
- half()[source]
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device=None)[source]
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict, strict=True, assign=False)[source]
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dictunlessget_swap_module_params_on_conversion()isTrue.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – When set to
False, the properties of the tensors in the current module are preserved whereas setting it toTruepreserves properties of the Tensors in the state dict. The only exception is therequires_gradfield ofParameterfor which the value from the module is preserved. Default:False
- Returns:
missing_keysis a list of str containing any keys that are expectedby this module but missing from the provided
state_dict.
unexpected_keysis a list of str containing the keys that are notexpected by this module but present in the provided
state_dict.
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules(remove_duplicate=True)[source]
Return an iterator over all modules in the network.
- Parameters:
remove_duplicate (
bool, default:True) – whether to remove the duplicated module instances in the result or not.- Yields:
Module – a module in the network
- Return type:
Note
Duplicate modules are returned only once by default. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- mtia(device=None)[source]
Move all model parameters and buffers to the MTIA.
This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on MTIA while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- named_buffers(prefix='', recurse=True, remove_duplicate=True)[source]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children()[source]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo=None, prefix='', remove_duplicate=True)[source]
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix='', recurse=True, remove_duplicate=True)[source]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse=True)[source]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook)[source]
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.
- register_buffer(name, tensor, persistent=True)[source]
Add a buffer to the module.
This is typically used to register a buffer that should not be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook, *, prepend=False, with_kwargs=False, always_call=False)[source]
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook, *, prepend=False, with_kwargs=False)[source]
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook, prepend=False)[source]
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, and its firing rules are as follows:
Ordinarily, the hook fires when the gradients are computed with respect to the module inputs.
If none of the module inputs require gradients, the hook will fire when the gradients are computed with respect to module outputs.
If none of the module outputs require gradients, then the hooks will not fire.
The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook, prepend=False)[source]
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor, ...], Tensor or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)[source]
Register a post-hook to be run after module’s
load_state_dict()is called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_pre_hook(hook)[source]
Register a pre-hook to be run before module’s
load_state_dict()is called.- It should have the following signature::
hook(module, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) -> None # noqa: B950
- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
- register_module(name, module)[source]
Alias for
add_module().
- register_parameter(name, param)[source]
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- Return type:
- register_state_dict_post_hook(hook)[source]
Register a post-hook for the
state_dict()method.- It should have the following signature::
hook(module, state_dict, prefix, local_metadata) -> None
The registered hooks can modify the
state_dictinplace.
- register_state_dict_pre_hook(hook)[source]
Register a pre-hook for the
state_dict()method.- It should have the following signature::
hook(module, prefix, keep_vars) -> None
The registered hooks can be used to perform pre-processing before the
state_dictcall is made.
- requires_grad_(requires_grad=True)[source]
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See Locally disabling gradient computation for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state)[source]
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.
- set_submodule(target, module, strict=False)[source]
Set the submodule given by
targetif it exists, otherwise throw an error.Note
If
strictis set toFalse(default), the method will replace an existing submodule or create a new submodule if the parent module exists. Ifstrictis set toTrue, the method will only attempt to replace an existing submodule and throw an error if the submodule does not exist.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(3, 3, 3) ) (linear): Linear(3, 3) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To override the
Conv2dwith a new submoduleLinear, you could callset_submodule("net_b.net_c.conv", nn.Linear(1, 1))wherestrictcould beTrueorFalseTo add a new submodule
Conv2dto the existingnet_bmodule, you would callset_submodule("net_b.conv", nn.Conv2d(1, 1, 1)).In the above if you set
strict=Trueand callset_submodule("net_b.conv", nn.Conv2d(1, 1, 1), strict=True), an AttributeError will be raised becausenet_bdoes not have a submodule namedconv.- Parameters:
target (
str) – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)module (
Module) – The module to set the submodule to.strict (
bool, default:False) – IfFalse, the method will replace an existing submodule or create a new submodule if the parent module exists. IfTrue, the method will only attempt to replace an existing submodule and throw an error if the submodule doesn’t already exist.
- Raises:
ValueError – If the
targetstring is empty or ifmoduleis not an instance ofnn.Module.AttributeError – If at any point along the path resulting from the
targetstring the (sub)path resolves to a non-existent attribute name or an object that is not an instance ofnn.Module.
- Return type:
See
torch.Tensor.share_memory_().- Return type:
Self
- state_dict(*args, destination=None, prefix='', keep_vars=False)[source]
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)[source]
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)[source]
- to(dtype, non_blocking=False)[source]
- to(tensor, non_blocking=False)[source]
- to(memory_format=torch.channels_last)[source]
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device, recurse=True)[source]
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode=True)[source]
Set the module in training mode.
This has an effect only on certain modules. See the documentation of particular modules for details of their behaviors in training/evaluation mode, i.e., whether they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- type(dst_type)[source]
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device=None)[source]
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none=True)[source]
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.- Return type:
Direct Preference Optimization (DPO)
- class medlatents.post_training.BaseDPOTrainer(model, ref_model, config, accelerator=None)[source][source]
Bases:
abc.ABCAbstract base class for DPO trainers.
Provides common infrastructure for all model types: - Accelerator setup with FSDP support - EMA for stable training - Logging and checkpointing - Reference model management
Subclasses must implement: - compute_logprobs: Model-specific log-probability computation - prepare_batch: Model-specific batch preprocessing
Example
>>> class MyDPOTrainer(BaseDPOTrainer): ... def compute_logprobs(self, model, batch): ... # Model-specific implementation ... return log_probs ... >>> trainer = MyDPOTrainer(model, ref_model, config) >>> trainer.train(dataset)
- Parameters:
model (
Module)config (
PostTrainingConfig)accelerator (
Accelerator|None, default:None)
- __init__(model, ref_model, config, accelerator=None)[source][source]
Initialize DPO trainer.
- Parameters:
model (
Module) – Model to trainref_model (
Module|None) – Reference model (frozen). If None, uses reference_free mode.config (
PostTrainingConfig) – Training configurationaccelerator (
Accelerator|None, default:None) – Optional pre-configured accelerator
- abstractmethod compute_logprobs(model, samples, **kwargs)[source][source]
Compute log-probabilities for samples.
This is model-type specific: - Autoregressive: Sum of log P(x_i | x_{<i}) - MaskGIT: Pseudo-likelihood via masked prediction - Diffusion: Negative ELBO (Monte Carlo estimate) - Flow: Trajectory-based likelihood
- train(dataset, val_dataset=None)[source][source]
Run full training loop.
- Parameters:
dataset (
PreferenceDataset) – Training preference datasetval_dataset (
PreferenceDataset|None, default:None) – Optional validation dataset
- Return type:
- Returns:
Dictionary of training history
- validate(val_loader)[source][source]
Run validation.
- Parameters:
val_loader (
DataLoader) – Validation dataloader- Return type:
- Returns:
Validation metrics
- class medlatents.post_training.DPOLoss(beta=0.1, loss_type='sigmoid', label_smoothing=0.0, reference_free=False, kto_desirable_weight=1.0, kto_undesirable_weight=1.0)[source][source]
Bases:
torch.nn.modules.module.ModuleFlexible DPO loss with multiple variants.
Supports: - sigmoid: Standard DPO with sigmoid loss (Rafailov et al.) - hinge: Margin-based loss for more aggressive optimization - ipo: Identity Preference Optimization (no sigmoid) - kto: Kahneman-Tversky Optimization (asymmetric) - disco: Distributionally robust DPO
- The DPO objective is:
L = -log(sigmoid(β * (r_w - r_l)))
- where r_w and r_l are implicit rewards defined as:
r(x) = β * log(π_θ(x) / π_ref(x))
Example
>>> loss_fn = DPOLoss(beta=0.1, loss_type="sigmoid") >>> output = loss_fn( ... chosen_logprobs=chosen_lp, ... rejected_logprobs=rejected_lp, ... ref_chosen_logprobs=ref_chosen_lp, ... ref_rejected_logprobs=ref_rejected_lp, ... ) >>> loss = output.loss
- Parameters:
- __init__(beta=0.1, loss_type='sigmoid', label_smoothing=0.0, reference_free=False, kto_desirable_weight=1.0, kto_undesirable_weight=1.0)[source][source]
Initialize DPO loss.
- Parameters:
beta (
float, default:0.1) – KL penalty coefficient (controls deviation from reference)loss_type (
Literal['sigmoid','hinge','ipo','kto','disco'], default:'sigmoid') – Type of preference loss to uselabel_smoothing (
float, default:0.0) – Soft labels for robustnessreference_free (
bool, default:False) – If True, don’t use reference modelkto_desirable_weight (
float, default:1.0) – Weight for KTO desirable termkto_undesirable_weight (
float, default:1.0) – Weight for KTO undesirable term
- forward(chosen_logprobs, rejected_logprobs, ref_chosen_logprobs=None, ref_rejected_logprobs=None, margin=None)[source][source]
Compute DPO loss.
- Parameters:
chosen_logprobs (
Tensor) – Log probs of policy on chosen [batch]rejected_logprobs (
Tensor) – Log probs of policy on rejected [batch]ref_chosen_logprobs (
Tensor|None, default:None) – Log probs of reference on chosen [batch]ref_rejected_logprobs (
Tensor|None, default:None) – Log probs of reference on rejected [batch]margin (
Tensor|None, default:None) – Optional preference margin [batch]
- Return type:
- Returns:
DPOOutput with loss and metrics
- T_destination = ~T_destination
- add_module(name, module)[source]
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- apply(fn)[source]
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also torch.nn.init).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) is nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16()[source]
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse=True)[source]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- compile(*args, **kwargs)[source]
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.- Return type:
- cpu()[source]
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device=None)[source]
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double()[source]
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- eval()[source]
Set the module in evaluation mode.
This has an effect only on certain modules. See the documentation of particular modules for details of their behaviors in training/evaluation mode, i.e. whether they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See Locally disabling gradient computation for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr()[source]
Return the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- Return type:
- float()[source]
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- get_buffer(target)[source]
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target (
str) – The fully-qualified string name of the buffer to look for. (Seeget_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state()[source]
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
- get_parameter(target)[source]
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target (
str) – The fully-qualified string name of the Parameter to look for. (Seeget_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target)[source]
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Awhich has a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target (
str) – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)- Returns:
The submodule referenced by
target- Return type:
- Raises:
AttributeError – If at any point along the path resulting from the target string the (sub)path resolves to a non-existent attribute name or an object that is not an instance of
nn.Module.
- half()[source]
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device=None)[source]
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict, strict=True, assign=False)[source]
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dictunlessget_swap_module_params_on_conversion()isTrue.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – When set to
False, the properties of the tensors in the current module are preserved whereas setting it toTruepreserves properties of the Tensors in the state dict. The only exception is therequires_gradfield ofParameterfor which the value from the module is preserved. Default:False
- Returns:
missing_keysis a list of str containing any keys that are expectedby this module but missing from the provided
state_dict.
unexpected_keysis a list of str containing the keys that are notexpected by this module but present in the provided
state_dict.
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules(remove_duplicate=True)[source]
Return an iterator over all modules in the network.
- Parameters:
remove_duplicate (
bool, default:True) – whether to remove the duplicated module instances in the result or not.- Yields:
Module – a module in the network
- Return type:
Note
Duplicate modules are returned only once by default. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- mtia(device=None)[source]
Move all model parameters and buffers to the MTIA.
This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on MTIA while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- named_buffers(prefix='', recurse=True, remove_duplicate=True)[source]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children()[source]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo=None, prefix='', remove_duplicate=True)[source]
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix='', recurse=True, remove_duplicate=True)[source]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse=True)[source]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook)[source]
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.
- register_buffer(name, tensor, persistent=True)[source]
Add a buffer to the module.
This is typically used to register a buffer that should not be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook, *, prepend=False, with_kwargs=False, always_call=False)[source]
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook, *, prepend=False, with_kwargs=False)[source]
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook, prepend=False)[source]
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, and its firing rules are as follows:
Ordinarily, the hook fires when the gradients are computed with respect to the module inputs.
If none of the module inputs require gradients, the hook will fire when the gradients are computed with respect to module outputs.
If none of the module outputs require gradients, then the hooks will not fire.
The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook, prepend=False)[source]
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor, ...], Tensor or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)[source]
Register a post-hook to be run after module’s
load_state_dict()is called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_pre_hook(hook)[source]
Register a pre-hook to be run before module’s
load_state_dict()is called.- It should have the following signature::
hook(module, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) -> None # noqa: B950
- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
- register_module(name, module)[source]
Alias for
add_module().
- register_parameter(name, param)[source]
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- Return type:
- register_state_dict_post_hook(hook)[source]
Register a post-hook for the
state_dict()method.- It should have the following signature::
hook(module, state_dict, prefix, local_metadata) -> None
The registered hooks can modify the
state_dictinplace.
- register_state_dict_pre_hook(hook)[source]
Register a pre-hook for the
state_dict()method.- It should have the following signature::
hook(module, prefix, keep_vars) -> None
The registered hooks can be used to perform pre-processing before the
state_dictcall is made.
- requires_grad_(requires_grad=True)[source]
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See Locally disabling gradient computation for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state)[source]
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.
- set_submodule(target, module, strict=False)[source]
Set the submodule given by
targetif it exists, otherwise throw an error.Note
If
strictis set toFalse(default), the method will replace an existing submodule or create a new submodule if the parent module exists. Ifstrictis set toTrue, the method will only attempt to replace an existing submodule and throw an error if the submodule does not exist.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(3, 3, 3) ) (linear): Linear(3, 3) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To override the
Conv2dwith a new submoduleLinear, you could callset_submodule("net_b.net_c.conv", nn.Linear(1, 1))wherestrictcould beTrueorFalseTo add a new submodule
Conv2dto the existingnet_bmodule, you would callset_submodule("net_b.conv", nn.Conv2d(1, 1, 1)).In the above if you set
strict=Trueand callset_submodule("net_b.conv", nn.Conv2d(1, 1, 1), strict=True), an AttributeError will be raised becausenet_bdoes not have a submodule namedconv.- Parameters:
target (
str) – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)module (
Module) – The module to set the submodule to.strict (
bool, default:False) – IfFalse, the method will replace an existing submodule or create a new submodule if the parent module exists. IfTrue, the method will only attempt to replace an existing submodule and throw an error if the submodule doesn’t already exist.
- Raises:
ValueError – If the
targetstring is empty or ifmoduleis not an instance ofnn.Module.AttributeError – If at any point along the path resulting from the
targetstring the (sub)path resolves to a non-existent attribute name or an object that is not an instance ofnn.Module.
- Return type:
See
torch.Tensor.share_memory_().- Return type:
Self
- state_dict(*args, destination=None, prefix='', keep_vars=False)[source]
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)[source]
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)[source]
- to(dtype, non_blocking=False)[source]
- to(tensor, non_blocking=False)[source]
- to(memory_format=torch.channels_last)[source]
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device, recurse=True)[source]
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode=True)[source]
Set the module in training mode.
This has an effect only on certain modules. See the documentation of particular modules for details of their behaviors in training/evaluation mode, i.e., whether they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- type(dst_type)[source]
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device=None)[source]
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none=True)[source]
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.- Return type:
- class medlatents.post_training.DPOOutput(loss, chosen_rewards, rejected_rewards, accuracy, reward_margin)[source][source]
Bases:
objectOutput from DPO loss computation.
- Variables:
loss – The total DPO loss
chosen_rewards – Implicit rewards for chosen samples (log-prob ratio)
rejected_rewards – Implicit rewards for rejected samples
accuracy – Fraction where chosen_reward > rejected_reward
reward_margin – Mean (chosen_reward - rejected_reward)
- Parameters:
- loss: torch.Tensor
- chosen_rewards: torch.Tensor
- rejected_rewards: torch.Tensor
- accuracy: torch.Tensor
- reward_margin: torch.Tensor
Discrete models (autoregressive, MaskGIT):
- class medlatents.post_training.AutoregressiveDPOTrainer(model, ref_model, config, accelerator=None, vocab_size=None)[source][source]
Bases:
medlatents.post_training.dpo.base.BaseDPOTrainerDPO trainer for autoregressive discrete models.
- For autoregressive models, the log-probability is computed as:
log p(x) = sum_{i=1}^L log p(x_i | x_{<i})
This is the standard approach used in language model DPO.
Example
>>> from medlatents.autoregressive import AutoregressiveTransformer >>> model = AutoregressiveTransformer(vocab_size=1024, ...) >>> ref_model = copy.deepcopy(model) >>> trainer = AutoregressiveDPOTrainer(model, ref_model, config) >>> trainer.train(preference_dataset)
- Parameters:
- __init__(model, ref_model, config, accelerator=None, vocab_size=None)[source][source]
Initialize autoregressive DPO trainer.
- Parameters:
model (
Module) – Autoregressive model to trainconfig (
PostTrainingConfig) – Training configurationaccelerator (
Accelerator|None, default:None) – Optional pre-configured acceleratorvocab_size (
int|None, default:None) – Vocabulary size (inferred from model if not provided)
- compute_logprobs(model, samples, **kwargs)[source][source]
Compute autoregressive log-probabilities.
- For a sequence x = [x_1, x_2, …, x_L], computes:
log p(x) = sum_{i=1}^{L-1} log p(x_{i+1} | x_1, …, x_i)
- train(dataset, val_dataset=None)[source]
Run full training loop.
- Parameters:
dataset (
PreferenceDataset) – Training preference datasetval_dataset (
PreferenceDataset|None, default:None) – Optional validation dataset
- Return type:
- Returns:
Dictionary of training history
- class medlatents.post_training.MaskGITDPOTrainer(model, ref_model, config, accelerator=None, vocab_size=None, likelihood_strategy='parallel', num_mask_samples=16)[source][source]
Bases:
medlatents.post_training.dpo.base.BaseDPOTrainerDPO trainer for MaskGIT bidirectional models.
- For bidirectional models, we use pseudo-likelihood:
log p(x) ≈ sum_{i=1}^L log p(x_i | x_{i})
where x_{i} denotes all tokens except position i.
This is computed efficiently by masking each position and predicting it from the context. We can use different strategies:
“full”: Mask each position independently (L forward passes, expensive)
“random”: Random subset of positions (cheaper approximation)
“parallel”: Single forward with random masking (training-style)
Example
>>> from medlatents.maskgit import MaskGIT >>> model = MaskGIT(vocab_size=1024, ...) >>> ref_model = copy.deepcopy(model) >>> trainer = MaskGITDPOTrainer(model, ref_model, config) >>> trainer.train(preference_dataset)
- Parameters:
- __init__(model, ref_model, config, accelerator=None, vocab_size=None, likelihood_strategy='parallel', num_mask_samples=16)[source][source]
Initialize MaskGIT DPO trainer.
- Parameters:
model (
Module) – MaskGIT model to trainconfig (
PostTrainingConfig) – Training configurationaccelerator (
Accelerator|None, default:None) – Optional pre-configured acceleratorvocab_size (
int|None, default:None) – Vocabulary size (inferred from model if not provided)likelihood_strategy (
Literal['full','random','parallel'], default:'parallel') – How to compute pseudo-likelihoodnum_mask_samples (
int, default:16) – Number of positions to sample for “random” strategy
- compute_logprobs(model, samples, **kwargs)[source][source]
Compute pseudo-likelihood for MaskGIT.
Uses the specified strategy to estimate log p(x).
- train(dataset, val_dataset=None)[source]
Run full training loop.
- Parameters:
dataset (
PreferenceDataset) – Training preference datasetval_dataset (
PreferenceDataset|None, default:None) – Optional validation dataset
- Return type:
- Returns:
Dictionary of training history
- class medlatents.post_training.DiscreteDPOTrainer(model, ref_model, config, accelerator=None, model_type=None, vocab_size=None, **kwargs)[source][source]
Bases:
medlatents.post_training.dpo.base.BaseDPOTrainerUnified DPO trainer that auto-detects discrete model type.
This is a convenience class that automatically selects the appropriate training strategy based on the model type.
Example
>>> # Works with any discrete model >>> trainer = DiscreteDPOTrainer(model, ref_model, config) >>> trainer.train(dataset)
- Parameters:
- __init__(model, ref_model, config, accelerator=None, model_type=None, vocab_size=None, **kwargs)[source][source]
Initialize discrete DPO trainer.
- Parameters:
model (
Module) – Discrete model to trainconfig (
PostTrainingConfig) – Training configurationaccelerator (
Accelerator|None, default:None) – Optional pre-configured acceleratormodel_type (
Optional[Literal['autoreg','maskgit']], default:None) – Model type (“autoreg” or “maskgit”). Auto-detected if None.**kwargs (
Any) – Additional arguments passed to specific trainer
Diffusion models (D3PM):
- class medlatents.post_training.D3PMDPOTrainer(model, ref_model, config, d3pm, accelerator=None, num_timestep_samples=10, elbo_mode='monte_carlo')[source][source]
Bases:
medlatents.post_training.dpo.base.BaseDPOTrainerDPO trainer for D3PM discrete diffusion models.
- For D3PM models, we compute log-probability using the ELBO:
log p(x_0) ≥ -ELBO = -E_t[KL(q(x_{t-1}|x_t,x_0) || p(x_{t-1}|x_t))]
The ELBO provides a lower bound on the log-likelihood, which we can use for DPO optimization.
We support two modes: 1. Monte Carlo ELBO: Sample timesteps and average 2. Full ELBO: Compute over all timesteps (expensive but exact)
Example
>>> from medlatents.diffusion import D3PM >>> d3pm = D3PM(num_classes=1024, num_timesteps=1000) >>> model = DiscreteDiT(vocab_size=1024, ...) >>> ref_model = copy.deepcopy(model) >>> trainer = D3PMDPOTrainer(model, ref_model, config, d3pm=d3pm) >>> trainer.train(preference_dataset)
- Parameters:
- __init__(model, ref_model, config, d3pm, accelerator=None, num_timestep_samples=10, elbo_mode='monte_carlo')[source][source]
Initialize D3PM DPO trainer.
- Parameters:
model (
Module) – D3PM backbone model to trainconfig (
PostTrainingConfig) – Training configurationd3pm (
D3PM) – D3PM diffusion processaccelerator (
Accelerator|None, default:None) – Optional pre-configured acceleratornum_timestep_samples (
int, default:10) – Number of timesteps to sample for Monte Carlo ELBOelbo_mode (
Literal['monte_carlo','full'], default:'monte_carlo') – How to compute ELBO (“monte_carlo” or “full”)
- compute_logprobs(model, samples, **kwargs)[source][source]
Compute ELBO-based log-probability for D3PM.
- The ELBO is computed as:
ELBO = E_t[KL(q(x_{t-1}|x_t,x_0) || p_θ(x_{t-1}|x_t))]
We return -ELBO as a surrogate for log p(x).
- train(dataset, val_dataset=None)[source]
Run full training loop.
- Parameters:
dataset (
PreferenceDataset) – Training preference datasetval_dataset (
PreferenceDataset|None, default:None) – Optional validation dataset
- Return type:
- Returns:
Dictionary of training history
- class medlatents.post_training.DiffusionDPOTrainer(model, ref_model, config, diffusion, accelerator=None, num_timestep_samples=10, elbo_mode='monte_carlo')[source][source]
Bases:
medlatents.post_training.dpo.base.BaseDPOTrainerUnified DPO trainer for diffusion models.
This is a convenience class that handles both D3PM discrete diffusion and could be extended for continuous diffusion.
For now, it primarily wraps D3PM but provides a cleaner interface.
Example
>>> trainer = DiffusionDPOTrainer( ... model=backbone_model, ... ref_model=ref_backbone, ... config=config, ... diffusion=d3pm, ... ) >>> trainer.train(preference_dataset)
- Parameters:
- __init__(model, ref_model, config, diffusion, accelerator=None, num_timestep_samples=10, elbo_mode='monte_carlo')[source][source]
Initialize diffusion DPO trainer.
- Parameters:
model (
Module) – Diffusion backbone model to trainconfig (
PostTrainingConfig) – Training configurationdiffusion (
D3PM) – D3PM diffusion processaccelerator (
Accelerator|None, default:None) – Optional pre-configured acceleratornum_timestep_samples (
int, default:10) – Number of timesteps for Monte Carloelbo_mode (
Literal['monte_carlo','full'], default:'monte_carlo') – ELBO computation mode
Flow-matching models:
- class medlatents.post_training.DiscreteFlowDPOTrainer(model, ref_model, config, path, source_distribution=None, accelerator=None, vocab_size=None, num_timestep_samples=10, likelihood_strategy='trajectory', time_eps=0.001)[source][source]
Bases:
medlatents.post_training.dpo.base.BaseDPOTrainerDPO trainer for discrete flow matching models.
- For discrete flow matching with mixture paths, we compute likelihood as:
log p(x_1) ≈ -E_t[L_flow(x_1, t)]
where L_flow is the flow matching loss at timestep t. This provides a tractable surrogate for the true likelihood.
We support different estimation strategies: 1. “trajectory”: Sample timesteps and average flow loss 2. “endpoint”: Use only t=1 prediction (fast but less accurate) 3. “importance”: Importance-weighted sampling of timesteps
Example
>>> from medlatents.flow_matching import MixtureDiscreteProbPath >>> path = MixtureDiscreteProbPath(PolynomialConvexScheduler(n=1.0)) >>> model = DiscreteDiT(vocab_size=1024, ...) >>> ref_model = copy.deepcopy(model) >>> trainer = DiscreteFlowDPOTrainer(model, ref_model, config, path=path) >>> trainer.train(preference_dataset)
- Parameters:
model (
Module)config (
PostTrainingConfig)path (
MixtureDiscreteProbPath)accelerator (
Accelerator|None, default:None)num_timestep_samples (
int, default:10)likelihood_strategy (
Literal['trajectory','endpoint','importance'], default:'trajectory')time_eps (
float, default:0.001)
- __init__(model, ref_model, config, path, source_distribution=None, accelerator=None, vocab_size=None, num_timestep_samples=10, likelihood_strategy='trajectory', time_eps=0.001)[source][source]
Initialize discrete flow DPO trainer.
- Parameters:
model (
Module) – Flow matching model to trainconfig (
PostTrainingConfig) – Training configurationpath (
MixtureDiscreteProbPath) – Discrete probability path (e.g., MixtureDiscreteProbPath)source_distribution (
Any|None, default:None) – Source distribution for flow (mask/uniform)accelerator (
Accelerator|None, default:None) – Optional pre-configured acceleratornum_timestep_samples (
int, default:10) – Number of timesteps for trajectory estimationlikelihood_strategy (
Literal['trajectory','endpoint','importance'], default:'trajectory') – How to estimate likelihoodtime_eps (
float, default:0.001) – Small epsilon to avoid t=0 or t=1 exactly
- compute_logprobs(model, samples, **kwargs)[source][source]
Compute flow-based log-probability.
Uses the specified strategy to estimate log p(x_1).
- train(dataset, val_dataset=None)[source]
Run full training loop.
- Parameters:
dataset (
PreferenceDataset) – Training preference datasetval_dataset (
PreferenceDataset|None, default:None) – Optional validation dataset
- Return type:
- Returns:
Dictionary of training history
- class medlatents.post_training.FlowDPOTrainer(model, ref_model, config, path=None, source_distribution=None, accelerator=None, vocab_size=None, num_timestep_samples=10, likelihood_strategy='trajectory', **kwargs)[source][source]
Bases:
medlatents.post_training.dpo.base.BaseDPOTrainerUnified DPO trainer for flow matching models.
This is a convenience class that handles discrete flow matching and can be extended for continuous flow matching (rectified flows).
Example
>>> trainer = FlowDPOTrainer( ... model=flow_model, ... ref_model=ref_flow, ... config=config, ... path=mixture_path, ... ) >>> trainer.train(preference_dataset)
- Parameters:
model (
Module)config (
PostTrainingConfig)path (
MixtureDiscreteProbPath|None, default:None)accelerator (
Accelerator|None, default:None)num_timestep_samples (
int, default:10)likelihood_strategy (
Literal['trajectory','endpoint','importance'], default:'trajectory')kwargs (
Any)
- __init__(model, ref_model, config, path=None, source_distribution=None, accelerator=None, vocab_size=None, num_timestep_samples=10, likelihood_strategy='trajectory', **kwargs)[source][source]
Initialize flow DPO trainer.
- Parameters:
model (
Module) – Flow matching model to trainconfig (
PostTrainingConfig) – Training configurationpath (
MixtureDiscreteProbPath|None, default:None) – Discrete probability path (creates default if None)source_distribution (
Any|None, default:None) – Source distributionaccelerator (
Accelerator|None, default:None) – Optional pre-configured acceleratornum_timestep_samples (
int, default:10) – Number of timesteps for estimationlikelihood_strategy (
Literal['trajectory','endpoint','importance'], default:'trajectory') – Likelihood estimation strategy**kwargs (
Any) – Additional arguments
Step-by-step Preference Optimization (SPO):
- class medlatents.post_training.SPOTrainer(model, config, diffusion=None, flow_path=None, step_scorer=None, accelerator=None, vocab_size=None, num_candidates=4, num_steps=50)[source][source]
Bases:
objectStep-by-step Preference Optimization trainer.
SPO operates by: 1. At each denoising step, generate K candidate states 2. Score candidates with a step-aware preference model 3. Apply DPO loss using best vs worst candidates 4. Randomly select one candidate to continue generation
This provides fine-grained supervision throughout the generation process, leading to better alignment than end-to-end DPO.
Example
>>> # For D3PM diffusion >>> trainer = SPOTrainer( ... model=backbone_model, ... config=config, ... diffusion=d3pm, ... step_scorer=step_preference_model, ... ) >>> trainer.train(prompt_dataset)
- Parameters:
model (
Module)config (
PostTrainingConfig)accelerator (
Accelerator|None, default:None)num_candidates (
int, default:4)num_steps (
int, default:50)
- __init__(model, config, diffusion=None, flow_path=None, step_scorer=None, accelerator=None, vocab_size=None, num_candidates=4, num_steps=50)[source][source]
Initialize SPO trainer.
- Parameters:
model (
Module) – Generative model to trainconfig (
PostTrainingConfig) – Training configurationdiffusion (
Any|None, default:None) – D3PM diffusion process (for diffusion models)flow_path (
Any|None, default:None) – Flow matching path (for flow models)step_scorer (
Module|None, default:None) – Model to score intermediate statesaccelerator (
Accelerator|None, default:None) – Optional pre-configured acceleratornum_candidates (
int, default:4) – Number of candidates per step (K)num_steps (
int, default:50) – Number of generation steps to optimize
- train_step(seq_length)[source][source]
Execute one SPO training step.
Generates a full trajectory with step-wise DPO optimization.
- class medlatents.post_training.StepPreferenceModel(hidden_size=512, depth=4, num_heads=8, vocab_size=None, seq_length=256)[source][source]
Bases:
torch.nn.modules.module.ModuleTimestep-aware preference model for SPO.
This model scores intermediate states at each denoising step, allowing the model to learn step-specific preferences.
The architecture adds timestep conditioning to score states appropriately at different noise levels.
- Parameters:
- __init__(hidden_size=512, depth=4, num_heads=8, vocab_size=None, seq_length=256)[source][source]
Initialize step preference model.
- Parameters:
- T_destination = ~T_destination
- add_module(name, module)[source]
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- apply(fn)[source]
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also torch.nn.init).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) is nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16()[source]
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse=True)[source]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- compile(*args, **kwargs)[source]
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.- Return type:
- cpu()[source]
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device=None)[source]
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double()[source]
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- eval()[source]
Set the module in evaluation mode.
This has an effect only on certain modules. See the documentation of particular modules for details of their behaviors in training/evaluation mode, i.e. whether they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See Locally disabling gradient computation for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr()[source]
Return the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- Return type:
- float()[source]
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- get_buffer(target)[source]
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target (
str) – The fully-qualified string name of the buffer to look for. (Seeget_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state()[source]
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
- get_parameter(target)[source]
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target (
str) – The fully-qualified string name of the Parameter to look for. (Seeget_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target)[source]
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Awhich has a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target (
str) – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)- Returns:
The submodule referenced by
target- Return type:
- Raises:
AttributeError – If at any point along the path resulting from the target string the (sub)path resolves to a non-existent attribute name or an object that is not an instance of
nn.Module.
- half()[source]
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device=None)[source]
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict, strict=True, assign=False)[source]
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dictunlessget_swap_module_params_on_conversion()isTrue.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – When set to
False, the properties of the tensors in the current module are preserved whereas setting it toTruepreserves properties of the Tensors in the state dict. The only exception is therequires_gradfield ofParameterfor which the value from the module is preserved. Default:False
- Returns:
missing_keysis a list of str containing any keys that are expectedby this module but missing from the provided
state_dict.
unexpected_keysis a list of str containing the keys that are notexpected by this module but present in the provided
state_dict.
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules(remove_duplicate=True)[source]
Return an iterator over all modules in the network.
- Parameters:
remove_duplicate (
bool, default:True) – whether to remove the duplicated module instances in the result or not.- Yields:
Module – a module in the network
- Return type:
Note
Duplicate modules are returned only once by default. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- mtia(device=None)[source]
Move all model parameters and buffers to the MTIA.
This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on MTIA while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- named_buffers(prefix='', recurse=True, remove_duplicate=True)[source]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children()[source]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo=None, prefix='', remove_duplicate=True)[source]
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix='', recurse=True, remove_duplicate=True)[source]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse=True)[source]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook)[source]
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.
- register_buffer(name, tensor, persistent=True)[source]
Add a buffer to the module.
This is typically used to register a buffer that should not be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook, *, prepend=False, with_kwargs=False, always_call=False)[source]
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook, *, prepend=False, with_kwargs=False)[source]
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook, prepend=False)[source]
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, and its firing rules are as follows:
Ordinarily, the hook fires when the gradients are computed with respect to the module inputs.
If none of the module inputs require gradients, the hook will fire when the gradients are computed with respect to module outputs.
If none of the module outputs require gradients, then the hooks will not fire.
The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook, prepend=False)[source]
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor, ...], Tensor or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)[source]
Register a post-hook to be run after module’s
load_state_dict()is called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_pre_hook(hook)[source]
Register a pre-hook to be run before module’s
load_state_dict()is called.- It should have the following signature::
hook(module, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) -> None # noqa: B950
- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
- register_module(name, module)[source]
Alias for
add_module().
- register_parameter(name, param)[source]
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- Return type:
- register_state_dict_post_hook(hook)[source]
Register a post-hook for the
state_dict()method.- It should have the following signature::
hook(module, state_dict, prefix, local_metadata) -> None
The registered hooks can modify the
state_dictinplace.
- register_state_dict_pre_hook(hook)[source]
Register a pre-hook for the
state_dict()method.- It should have the following signature::
hook(module, prefix, keep_vars) -> None
The registered hooks can be used to perform pre-processing before the
state_dictcall is made.
- requires_grad_(requires_grad=True)[source]
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See Locally disabling gradient computation for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state)[source]
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.
- set_submodule(target, module, strict=False)[source]
Set the submodule given by
targetif it exists, otherwise throw an error.Note
If
strictis set toFalse(default), the method will replace an existing submodule or create a new submodule if the parent module exists. Ifstrictis set toTrue, the method will only attempt to replace an existing submodule and throw an error if the submodule does not exist.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(3, 3, 3) ) (linear): Linear(3, 3) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To override the
Conv2dwith a new submoduleLinear, you could callset_submodule("net_b.net_c.conv", nn.Linear(1, 1))wherestrictcould beTrueorFalseTo add a new submodule
Conv2dto the existingnet_bmodule, you would callset_submodule("net_b.conv", nn.Conv2d(1, 1, 1)).In the above if you set
strict=Trueand callset_submodule("net_b.conv", nn.Conv2d(1, 1, 1), strict=True), an AttributeError will be raised becausenet_bdoes not have a submodule namedconv.- Parameters:
target (
str) – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)module (
Module) – The module to set the submodule to.strict (
bool, default:False) – IfFalse, the method will replace an existing submodule or create a new submodule if the parent module exists. IfTrue, the method will only attempt to replace an existing submodule and throw an error if the submodule doesn’t already exist.
- Raises:
ValueError – If the
targetstring is empty or ifmoduleis not an instance ofnn.Module.AttributeError – If at any point along the path resulting from the
targetstring the (sub)path resolves to a non-existent attribute name or an object that is not an instance ofnn.Module.
- Return type:
See
torch.Tensor.share_memory_().- Return type:
Self
- state_dict(*args, destination=None, prefix='', keep_vars=False)[source]
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)[source]
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)[source]
- to(dtype, non_blocking=False)[source]
- to(tensor, non_blocking=False)[source]
- to(memory_format=torch.channels_last)[source]
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device, recurse=True)[source]
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode=True)[source]
Set the module in training mode.
This has an effect only on certain modules. See the documentation of particular modules for details of their behaviors in training/evaluation mode, i.e., whether they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- type(dst_type)[source]
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device=None)[source]
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none=True)[source]
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.- Return type:
- class medlatents.post_training.SPOStepOutput(step_idx, timestep, loss, chosen_state, accuracy)[source][source]
Bases:
objectOutput from a single SPO step.
- Variables:
step_idx – Index of the denoising step
timestep – Continuous timestep value
loss – DPO loss at this step
chosen_state – Selected state to continue from
accuracy – Whether chosen had higher reward
- Parameters:
- loss: torch.Tensor
- chosen_state: torch.Tensor
Reinforcement Learning
- class medlatents.post_training.rl.BaseRLTrainer(model, reward_fn, config, ref_model=None, value_model=None, accelerator=None)[source][source]
Bases:
abc.ABCAbstract base class for RL post-training methods.
Provides common infrastructure for: - Trajectory generation and storage - Reward computation - Policy gradient estimation - Training loop with logging
Subclasses must implement: - generate_trajectories: Model-specific generation - compute_policy_loss: Method-specific loss computation
- Parameters:
- __init__(model, reward_fn, config, ref_model=None, value_model=None, accelerator=None)[source][source]
Initialize RL trainer.
- Parameters:
model (
Module) – Policy model to trainreward_fn (
Callable[[Tensor],Tensor]) – Function that computes rewards for samplesconfig (
PostTrainingConfig) – Training configurationref_model (
Module|None, default:None) – Optional reference model for KL penaltyvalue_model (
Module|None, default:None) – Optional value function for advantage estimationaccelerator (
Accelerator|None, default:None) – Optional pre-configured accelerator
- abstractmethod generate_trajectories(batch_size, seq_length, **kwargs)[source][source]
Generate trajectories by sampling from the model.
- Parameters:
- Return type:
- Returns:
List of Trajectory objects
- train_step(seq_length)[source][source]
Execute one training step.
Generate trajectories
Compute rewards
Compute advantages
Update policy
- class medlatents.post_training.rl.DDPOTrainer(model, reward_fn, config, diffusion, ref_model=None, value_model=None, accelerator=None, num_inference_steps=50, clip_range=None, kl_coeff=None)[source][source]
Bases:
medlatents.post_training.rl.base.BaseRLTrainerDDPO trainer for diffusion models.
Implements PPO-style policy gradient optimization for diffusion models. The key idea is to: 1. Sample full denoising trajectories 2. Compute rewards for final samples 3. Estimate advantages using GAE 4. Update policy with clipped surrogate objective
Example
>>> from medlatents.diffusion import D3PM >>> d3pm = D3PM(num_classes=1024, num_timesteps=1000) >>> trainer = DDPOTrainer( ... model=backbone, ... reward_fn=reward_model, ... config=config, ... diffusion=d3pm, ... ) >>> trainer.train(seq_length=256)
- Parameters:
model (
Module)config (
PostTrainingConfig)diffusion (
D3PM)accelerator (
Accelerator|None, default:None)num_inference_steps (
int, default:50)
- __init__(model, reward_fn, config, diffusion, ref_model=None, value_model=None, accelerator=None, num_inference_steps=50, clip_range=None, kl_coeff=None)[source][source]
Initialize DDPO trainer.
- Parameters:
model (
Module) – Diffusion backbone modelreward_fn (
Callable[[Tensor],Tensor]) – Reward function for samplesconfig (
PostTrainingConfig) – Training configurationdiffusion (
D3PM) – D3PM diffusion processref_model (
Module|None, default:None) – Reference model for KL penaltyvalue_model (
Module|None, default:None) – Value function for advantage estimationaccelerator (
Accelerator|None, default:None) – Optional acceleratornum_inference_steps (
int, default:50) – Number of denoising stepsclip_range (
float|None, default:None) – PPO clipping range (uses config if None)kl_coeff (
float|None, default:None) – KL penalty coefficient (uses config if None)
- generate_trajectories(batch_size, seq_length, **kwargs)[source][source]
Generate denoising trajectories.
Samples full denoising paths while recording states, actions, and log probabilities at each step.
- Parameters:
- Return type:
- Returns:
List of Trajectory objects
- compute_policy_loss(trajectories)[source][source]
Compute PPO-style clipped surrogate loss.
- The PPO objective is:
L = -min(r*A, clip(r, 1-ε, 1+ε)*A)
where r = π(a|s) / π_old(a|s) is the probability ratio.
- class medlatents.post_training.rl.DDPODiscreteFlowTrainer(model, reward_fn, config, path, source_distribution=None, ref_model=None, accelerator=None, vocab_size=None, num_inference_steps=50)[source][source]
Bases:
medlatents.post_training.rl.base.BaseRLTrainerDDPO trainer for discrete flow matching models.
Adapts DDPO for discrete flow matching where the model predicts token distributions at each timestep along the flow.
- Parameters:
model (
Module)config (
PostTrainingConfig)path (
Any)accelerator (
Accelerator|None, default:None)num_inference_steps (
int, default:50)
- __init__(model, reward_fn, config, path, source_distribution=None, ref_model=None, accelerator=None, vocab_size=None, num_inference_steps=50)[source][source]
Initialize discrete flow DDPO trainer.
- Parameters:
model (
Module)config (
PostTrainingConfig)path (
Any)accelerator (
Accelerator|None, default:None)num_inference_steps (
int, default:50)
- generate_trajectories(batch_size, seq_length, **kwargs)[source][source]
Generate flow trajectories.
- Parameters:
- Return type:
- class medlatents.post_training.rl.GRPOTrainer(model, reward_fn, config, ref_model=None, accelerator=None, num_samples_per_prompt=None, vocab_size=None, num_inference_steps=50, model_type='diffusion', diffusion=None, flow_path=None)[source][source]
Bases:
medlatents.post_training.rl.base.BaseRLTrainerGroup Relative Policy Optimization trainer.
GRPO samples multiple outputs for each input and computes advantages relative to the group mean. This eliminates the need for a learned value function while providing low-variance gradients.
- The GRPO objective is:
L = -E[A(x) * log π(x)] + β * KL(π || π_ref)
where A(x) = (r(x) - mean(r)) / std(r) is the group-relative advantage.
Example
>>> trainer = GRPOTrainer( ... model=model, ... reward_fn=reward_model, ... config=config, ... num_samples_per_prompt=8, ... ) >>> trainer.train(seq_length=256)
- Parameters:
model (
Module)config (
PostTrainingConfig)accelerator (
Accelerator|None, default:None)num_inference_steps (
int, default:50)model_type (
str, default:'diffusion')
- __init__(model, reward_fn, config, ref_model=None, accelerator=None, num_samples_per_prompt=None, vocab_size=None, num_inference_steps=50, model_type='diffusion', diffusion=None, flow_path=None)[source][source]
Initialize GRPO trainer.
- Parameters:
model (
Module) – Model to trainconfig (
PostTrainingConfig) – Training configurationref_model (
Module|None, default:None) – Reference model for KL penaltyaccelerator (
Accelerator|None, default:None) – Optional acceleratornum_samples_per_prompt (
int|None, default:None) – Samples per group (uses config if None)num_inference_steps (
int, default:50) – Number of generation stepsmodel_type (
str, default:'diffusion') – “diffusion”, “flow”, or “maskgit”diffusion (
Any|None, default:None) – D3PM for diffusion modelsflow_path (
Any|None, default:None) – Path for flow models
- generate_trajectories(batch_size, seq_length, **kwargs)[source][source]
Generate trajectories for GRPO.
Generates multiple samples per “prompt” for group-relative advantages.
- Parameters:
- Return type:
- compute_policy_loss(trajectories)[source][source]
Compute GRPO loss with group-relative advantages.
Groups trajectories by prompt and computes advantages relative to the group mean reward.
- class medlatents.post_training.rl.GARDOTrainer(model, reward_fn, config, ref_model=None, accelerator=None, reward_threshold=None, distance_penalty=None, vocab_size=None, num_inference_steps=50, model_type='diffusion', diffusion=None, adaptive_kl=True, kl_target=0.1)[source][source]
Bases:
medlatents.post_training.rl.base.BaseRLTrainerGradient-Aware Reward Distance Optimization trainer.
GARDO improves upon standard reward fine-tuning by: 1. Monitoring gradient alignment between reward and KL terms 2. Adaptively scaling the KL coefficient 3. Filtering updates based on reward threshold
- The objective is:
L = -r(x) + α(grad) * KL(π || π_ref)
where α(grad) is dynamically adjusted based on gradient cosine similarity.
Example
>>> trainer = GARDOTrainer( ... model=model, ... reward_fn=reward_model, ... config=config, ... reward_threshold=0.1, ... ) >>> trainer.train(seq_length=256)
- Parameters:
- __init__(model, reward_fn, config, ref_model=None, accelerator=None, reward_threshold=None, distance_penalty=None, vocab_size=None, num_inference_steps=50, model_type='diffusion', diffusion=None, adaptive_kl=True, kl_target=0.1)[source][source]
Initialize GARDO trainer.
- Parameters:
model (
Module) – Model to trainconfig (
PostTrainingConfig) – Training configurationref_model (
Module|None, default:None) – Reference model for KL computationaccelerator (
Accelerator|None, default:None) – Optional acceleratorreward_threshold (
float|None, default:None) – Minimum reward improvement to updatedistance_penalty (
float|None, default:None) – Base KL penalty coefficientnum_inference_steps (
int, default:50) – Generation stepsmodel_type (
str, default:'diffusion') – “diffusion”, “flow”, or “maskgit”diffusion (
Any|None, default:None) – D3PM for diffusion modelsadaptive_kl (
bool, default:True) – Whether to adapt KL coefficientkl_target (
float, default:0.1) – Target KL divergence for adaptive scaling
- generate_trajectories(batch_size, seq_length, **kwargs)[source][source]
Generate trajectories.
- Parameters:
- Return type:
- compute_policy_loss(trajectories)[source][source]
Compute GARDO loss with adaptive KL penalty.
The GARDO loss combines: 1. Negative reward (to maximize reward) 2. KL penalty (to stay close to reference) 3. Reward thresholding (to focus on improvements)
- class medlatents.post_training.rl.Trajectory(states, actions, timesteps, log_probs, rewards, final_sample, prompt=None, advantages=None, returns=None)[source][source]
Bases:
objectA single generation trajectory with rewards.
For diffusion/flow models, this represents the full denoising path. For autoregressive models, this is the sequence of token generations.
- Variables:
states – Intermediate states [num_steps, seq_len] or [num_steps, seq_len, dim]
actions – Actions taken (tokens generated) [num_steps, seq_len]
timesteps – Timestep at each step [num_steps]
log_probs – Log probabilities of actions [num_steps]
rewards – Rewards at each step [num_steps] (often only final is non-zero)
final_sample – The final generated sample
prompt – Optional conditioning information
- Parameters:
- states: torch.Tensor
- actions: torch.Tensor
- timesteps: torch.Tensor
- log_probs: torch.Tensor
- rewards: torch.Tensor
- final_sample: torch.Tensor
- prompt: Any = None
- advantages: torch.Tensor | None = None
- returns: torch.Tensor | None = None
- class medlatents.post_training.rl.TrajectoryBuffer(max_size=10000, device=device(type='cpu'))[source][source]
Bases:
objectBuffer for storing and sampling trajectories.
Implements experience replay for RL training with support for priority sampling and trajectory filtering.
- add(trajectory, priority=1.0)[source][source]
Add a trajectory to the buffer.
- Parameters:
trajectory (
Trajectory)priority (
float, default:1.0)
- Return type:
Distillation
- class medlatents.post_training.distillation.ReflowTrainer(model, config, path, vocab_size, accelerator=None, num_inference_steps=50)[source][source]
Bases:
objectIterative reflow training for flow matching models.
Implements the reflow procedure: 1. Generate pairs from current model 2. Train on pairs to get straighter trajectories 3. Repeat
Each iteration produces more linear trajectories, enabling faster sampling with fewer steps.
Example
>>> trainer = ReflowTrainer( ... model=flow_model, ... config=config, ... path=flow_path, ... vocab_size=1024, ... ) >>> # Run one reflow iteration >>> trainer.reflow_iteration(data_loader) >>> >>> # Run multiple iterations >>> for i in range(3): ... trainer.reflow_iteration(data_loader)
- Parameters:
- __init__(model, config, path, vocab_size, accelerator=None, num_inference_steps=50)[source][source]
Initialize reflow trainer.
- Parameters:
model (
Module) – Flow model to trainconfig (
PostTrainingConfig) – Training configurationpath (
Any) – Flow probability pathvocab_size (
int) – Vocabulary sizeaccelerator (
Accelerator|None, default:None) – Optional acceleratornum_inference_steps (
int, default:50) – Inference steps for pair generation
- train_on_pairs(noise_samples, data_samples, num_steps=None)[source][source]
Train on generated (noise, data) pairs.
- reflow_iteration(data_loader, max_pairs=None, num_train_steps=None)[source][source]
Run one complete reflow iteration.
Collect data samples
Generate (noise, data) pairs
Train on pairs
- train(data_loader, num_iterations=None)[source][source]
Run full reflow training with multiple iterations.
- class medlatents.post_training.distillation.ReflowPairGenerator(model, path, vocab_size, device, num_inference_steps=50)[source][source]
Bases:
objectGenerate (noise, data) pairs for reflow training.
Uses the current flow model to generate aligned pairs that represent straight-line trajectories in probability space.
- Parameters:
- __init__(model, path, vocab_size, device, num_inference_steps=50)[source][source]
Initialize pair generator.
- generate_pairs(data_samples, batch_size=32)[source][source]
Generate (noise, data) pairs from real data.
For each data sample x_1: 1. Sample noise x_0 from source distribution 2. Generate trajectory: x_0 -> x_1’ (using model) 3. Store pair (x_0, x_1)
The key insight is that we use the REAL x_1 as target, not the model’s generated x_1’, creating straighter paths.
- class medlatents.post_training.distillation.ConsistencyTrainer(student, config, teacher=None, diffusion=None, accelerator=None, mode='distillation', sigma_min=0.002, sigma_max=80.0, sigma_data=0.5, s0=10, s1=1280, huber_c=None)[source][source]
Bases:
objectConsistency training/distillation for diffusion models.
Supports two modes: 1. Consistency Training (CT): Train from scratch with self-consistency 2. Consistency Distillation (CD): Distill from a pretrained teacher
Example
>>> # Consistency Distillation >>> trainer = ConsistencyTrainer( ... student=student_model, ... teacher=teacher_model, ... config=config, ... mode="distillation", ... ) >>> trainer.train(train_loader) >>> >>> # Consistency Training >>> trainer = ConsistencyTrainer( ... student=model, ... config=config, ... mode="training", ... ) >>> trainer.train(train_loader)
- Parameters:
student (
Module)config (
PostTrainingConfig)accelerator (
Accelerator|None, default:None)mode (
Literal['training','distillation'], default:'distillation')sigma_min (
float, default:0.002)sigma_max (
float, default:80.0)sigma_data (
float, default:0.5)s0 (
int, default:10)s1 (
int, default:1280)
- __init__(student, config, teacher=None, diffusion=None, accelerator=None, mode='distillation', sigma_min=0.002, sigma_max=80.0, sigma_data=0.5, s0=10, s1=1280, huber_c=None)[source][source]
Initialize consistency trainer.
- Parameters:
student (
Module) – Model to trainconfig (
PostTrainingConfig) – Training configurationteacher (
Module|None, default:None) – Teacher model for distillation (required if mode=”distillation”)diffusion (
Any|None, default:None) – D3PM for discrete modelsaccelerator (
Accelerator|None, default:None) – Optional acceleratormode (
Literal['training','distillation'], default:'distillation') – “training” or “distillation”sigma_min (
float, default:0.002) – Minimum noise levelsigma_max (
float, default:80.0) – Maximum noise levelsigma_data (
float, default:0.5) – Data standard deviations0 (
int, default:10) – Initial discretization stepss1 (
int, default:1280) – Final discretization stepshuber_c (
float|None, default:None) – Pseudo-Huber constant
- train_step_distillation(batch)[source][source]
One step of consistency distillation.
Uses teacher to generate targets for student.
- train_step_training(batch)[source][source]
One step of consistency training (no teacher).
Uses self-consistency constraint.
Self-Play
- class medlatents.post_training.self_play.SPINTrainer(model, config, accelerator=None, vocab_size=None, generate_fn=None, num_generation_steps=50, model_type='maskgit')[source][source]
Bases:
objectSelf-Play Iterative Training (SPIN) for generative models.
SPIN improves a model by creating a curriculum of increasingly difficult discrimination tasks:
Iteration 1: Distinguish ground truth from weak model outputs Iteration 2: Distinguish ground truth from stronger model outputs …
This is implemented as iterative DPO where: - Chosen = ground truth data - Rejected = model’s own generations
Example
>>> trainer = SPINTrainer( ... model=model, ... config=config, ... vocab_size=1024, ... ) >>> trainer.train(data_loader, num_iterations=3)
- Parameters:
- __init__(model, config, accelerator=None, vocab_size=None, generate_fn=None, num_generation_steps=50, model_type='maskgit')[source][source]
Initialize SPIN trainer.
- Parameters:
model (
Module) – Model to trainconfig (
PostTrainingConfig) – Training configurationaccelerator (
Accelerator|None, default:None) – Optional acceleratorgenerate_fn (
Callable[[Module,int,int],Tensor] |None, default:None) – Custom generation function (model, batch_size, seq_len) -> samplesnum_generation_steps (
int, default:50) – Steps for generationmodel_type (
str, default:'maskgit') – Model type for default generation
- train(data_loader, num_iterations=None)[source][source]
Run full SPIN training with multiple iterations.
- class medlatents.post_training.self_play.RFTTrainer(model, reward_fn, config, accelerator=None, vocab_size=None, num_samples_per_prompt=8, top_k=None, generate_fn=None, num_generation_steps=50, model_type='maskgit')[source][source]
Bases:
objectRejection Fine-Tuning trainer.
RFT is a simple but effective method that: 1. Generates multiple samples from the model 2. Selects the best ones using a reward function 3. Fine-tunes on the selected samples
This provides quality improvement without the complexity of RL.
Example
>>> trainer = RFTTrainer( ... model=model, ... reward_fn=reward_model, ... config=config, ... num_samples_per_prompt=8, ... top_k=2, ... ) >>> trainer.train(prompt_loader)
- Parameters:
- __init__(model, reward_fn, config, accelerator=None, vocab_size=None, num_samples_per_prompt=8, top_k=None, generate_fn=None, num_generation_steps=50, model_type='maskgit')[source][source]
Initialize RFT trainer.
- Parameters:
model (
Module) – Model to trainreward_fn (
Callable[[Tensor],Tensor]) – Function that scores samples (higher = better)config (
PostTrainingConfig) – Training configurationaccelerator (
Accelerator|None, default:None) – Optional acceleratornum_samples_per_prompt (
int, default:8) – Number of samples to generate per prompttop_k (
int|None, default:None) – Number of top samples to keep (default: num_samples // 2)generate_fn (
Callable[[Module,int,int],Tensor] |None, default:None) – Custom generation functionnum_generation_steps (
int, default:50) – Steps for generationmodel_type (
str, default:'maskgit') – Model type for generation
- train_step(seq_length, num_prompts)[source][source]
One RFT training step.
Generate samples
Select top-k by reward
Fine-tune on selected