Compare commits
13 Commits
v0.16.1
...
diffusion-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
64f349b7bb | ||
|
|
260ebe4c93 | ||
|
|
63d2280999 | ||
|
|
b210db2d15 | ||
|
|
556a69118f | ||
|
|
8569675b26 | ||
|
|
077b5a4358 | ||
|
|
234b7b3126 | ||
|
|
e19be0c2d9 | ||
|
|
479a454ae3 | ||
|
|
0a9341acde | ||
|
|
d8b63804bc | ||
|
|
3156c605d4 |
57
examples/llama-3/diffusion-3.2-1b-pretrain.yaml
Normal file
57
examples/llama-3/diffusion-3.2-1b-pretrain.yaml
Normal file
@@ -0,0 +1,57 @@
|
||||
base_model: meta-llama/Llama-3.2-1B
|
||||
# Automatically upload checkpoint and final model to HF
|
||||
# hub_model_id: username/custom_model_name
|
||||
|
||||
pretraining_dataset:
|
||||
- path: wikitext
|
||||
name: wikitext-103-raw-v1
|
||||
type: completion
|
||||
field: text
|
||||
|
||||
plugins:
|
||||
- diffusion.DiffusionPlugin
|
||||
noise_schedule: cosine
|
||||
min_mask_ratio: 0.15
|
||||
max_mask_ratio: 0.85
|
||||
eps: 5e-4
|
||||
importance_weighting: true
|
||||
mask_token_id: 128002
|
||||
generate_samples: true
|
||||
generation_interval: 10
|
||||
|
||||
output_dir: ./outputs/model-out
|
||||
|
||||
sequence_len: 512
|
||||
sample_packing: true
|
||||
|
||||
gradient_accumulation_steps: 8
|
||||
micro_batch_size: 4
|
||||
max_steps: 10000
|
||||
|
||||
optimizer: adamw_8bit
|
||||
lr_scheduler: cosine
|
||||
learning_rate: 3e-4
|
||||
|
||||
bf16: auto
|
||||
tf32: true
|
||||
|
||||
gradient_checkpointing: true
|
||||
resume_from_checkpoint:
|
||||
logging_steps: 1
|
||||
sdp_attention: true
|
||||
|
||||
warmup_steps: 1000
|
||||
|
||||
save_strategy: steps
|
||||
save_steps: 1000
|
||||
|
||||
special_tokens:
|
||||
pad_token: "<|end_of_text|>"
|
||||
|
||||
wandb_project:
|
||||
wandb_entity:
|
||||
wandb_watch:
|
||||
wandb_name:
|
||||
wandb_log_model:
|
||||
|
||||
# save_first_step: true # uncomment this to validate checkpoint saving works with your config
|
||||
58
examples/llama-3/diffusion-3.2-1b-sft.yaml
Normal file
58
examples/llama-3/diffusion-3.2-1b-sft.yaml
Normal file
@@ -0,0 +1,58 @@
|
||||
base_model: meta-llama/Llama-3.2-1B
|
||||
# Automatically upload checkpoint and final model to HF
|
||||
# hub_model_id: username/custom_model_name
|
||||
|
||||
datasets:
|
||||
- path: teknium/GPT4-LLM-Cleaned
|
||||
type: alpaca
|
||||
val_set_size: 0.05
|
||||
|
||||
plugins:
|
||||
- diffusion.DiffusionPlugin
|
||||
noise_schedule: cosine
|
||||
min_mask_ratio: 0.1
|
||||
max_mask_ratio: 0.9
|
||||
num_diffusion_steps: 128
|
||||
eps: 1e-3
|
||||
importance_weighting: true
|
||||
mask_token_id: 128002
|
||||
|
||||
output_dir: ./outputs/model-out
|
||||
|
||||
sequence_len: 512
|
||||
sample_packing: true
|
||||
eval_sample_packing: true
|
||||
|
||||
gradient_accumulation_steps: 4
|
||||
micro_batch_size: 4
|
||||
num_epochs: 1
|
||||
|
||||
optimizer: adamw_8bit
|
||||
lr_scheduler: cosine
|
||||
learning_rate: 1e-5
|
||||
|
||||
bf16: auto
|
||||
tf32: true
|
||||
|
||||
gradient_checkpointing: true
|
||||
resume_from_checkpoint:
|
||||
logging_steps: 1
|
||||
sdp_attention: true
|
||||
|
||||
warmup_steps: 1000
|
||||
|
||||
save_strategy: steps
|
||||
eval_strategy: steps
|
||||
save_steps: 500
|
||||
eval_steps: 500
|
||||
|
||||
special_tokens:
|
||||
pad_token: "<|end_of_text|>"
|
||||
|
||||
wandb_project:
|
||||
wandb_entity:
|
||||
wandb_watch:
|
||||
wandb_name:
|
||||
wandb_log_model:
|
||||
|
||||
# save_first_step: true # uncomment this to validate checkpoint saving works with your config
|
||||
@@ -10,6 +10,7 @@ import transformers
|
||||
from transformers import (
|
||||
DataCollatorWithFlattening,
|
||||
EarlyStoppingCallback,
|
||||
Trainer,
|
||||
)
|
||||
from trl.trainer.utils import RewardDataCollatorWithPadding
|
||||
|
||||
@@ -385,10 +386,11 @@ class HFCausalTrainerBuilder(TrainerBuilderBase):
|
||||
**data_collator_kwargs,
|
||||
)
|
||||
sig = inspect.signature(trainer_cls)
|
||||
if "processing_class" in sig.parameters:
|
||||
if "processing_class" in sig.parameters or issubclass(trainer_cls, Trainer):
|
||||
trainer_kwargs["processing_class"] = self.tokenizer
|
||||
elif "tokenizer" in sig.parameters:
|
||||
trainer_kwargs["tokenizer"] = self.tokenizer
|
||||
|
||||
if (
|
||||
trainer_cls not in [AxolotlRewardTrainer, AxolotlPRMTrainer]
|
||||
and self.cfg.datasets is not None
|
||||
|
||||
@@ -82,7 +82,9 @@ class AxolotlTrainer(
|
||||
super().__init__(*_args, **kwargs)
|
||||
|
||||
self.train_data_collator = self.data_collator
|
||||
self._stored_metrics = defaultdict(lambda: defaultdict(list))
|
||||
self._stored_metrics = defaultdict(
|
||||
lambda: defaultdict(lambda: {"values": [], "reduction": "mean"})
|
||||
)
|
||||
if self.args.orpo_alpha:
|
||||
self.loss_fct = torch.nn.CrossEntropyLoss(reduction="none")
|
||||
|
||||
@@ -573,9 +575,26 @@ class AxolotlTrainer(
|
||||
"""
|
||||
# logs either has 'loss' or 'eval_loss'
|
||||
train_eval = "train" if "loss" in logs else "eval"
|
||||
# Add averaged stored metrics to logs
|
||||
for key, metrics in self._stored_metrics[train_eval].items():
|
||||
logs[key] = torch.tensor(metrics).mean().item()
|
||||
|
||||
# Add reduced stored metrics to logs
|
||||
for key, metric_data in self._stored_metrics[train_eval].items():
|
||||
values = torch.tensor(metric_data["values"])
|
||||
reduction_type = metric_data["reduction"]
|
||||
|
||||
if reduction_type == "mean":
|
||||
logs[key] = values.mean().item()
|
||||
elif reduction_type == "min":
|
||||
logs[key] = values.min().item()
|
||||
elif reduction_type == "max":
|
||||
logs[key] = values.max().item()
|
||||
elif reduction_type == "sum":
|
||||
logs[key] = values.sum().item()
|
||||
else:
|
||||
raise NotImplementedError(
|
||||
"Metric reduction must be one of [mean, min, max, sum]"
|
||||
)
|
||||
|
||||
logs[key] = round(logs[key], 4)
|
||||
|
||||
if is_main_process():
|
||||
# Add memory usage
|
||||
@@ -592,10 +611,27 @@ class AxolotlTrainer(
|
||||
return super().log(logs, start_time)
|
||||
|
||||
def store_metrics(
|
||||
self, metrics: dict[str, float], train_eval: Literal["train", "eval"] = "train"
|
||||
self,
|
||||
metrics: dict[str, float] | dict[str, tuple[int | float, str]],
|
||||
train_eval: Literal["train", "eval"] = "train",
|
||||
reduction: Literal["mean", "min", "max", "sum"] = "mean",
|
||||
) -> None:
|
||||
"""
|
||||
Store metrics with specified reduction type.
|
||||
|
||||
Args:
|
||||
metrics: Dictionary of metric names to values, or metric names to (value,
|
||||
reduction_type) tuples.
|
||||
train_eval: Whether this is for training or evaluation.
|
||||
"""
|
||||
for key, value in metrics.items():
|
||||
self._stored_metrics[train_eval][key].append(value)
|
||||
if isinstance(value, tuple):
|
||||
metric_value, metric_reduction = value
|
||||
else:
|
||||
metric_value, metric_reduction = value, reduction
|
||||
|
||||
self._stored_metrics[train_eval][key]["values"].append(metric_value)
|
||||
self._stored_metrics[train_eval][key]["reduction"] = metric_reduction
|
||||
|
||||
def _save_checkpoint(self, model, trial, **kwargs):
|
||||
# make sure the checkpoint dir exists, since trainer is flakey
|
||||
|
||||
@@ -147,7 +147,7 @@ class BasePlugin:
|
||||
"""
|
||||
|
||||
# pylint: disable=unused-argument
|
||||
def get_trainer_cls(self, cfg: DictDefault) -> Trainer | None:
|
||||
def get_trainer_cls(self, cfg: DictDefault) -> type[Trainer] | None:
|
||||
"""Returns a custom class for the trainer.
|
||||
|
||||
Args:
|
||||
|
||||
125
src/axolotl/integrations/diffusion/README.md
Normal file
125
src/axolotl/integrations/diffusion/README.md
Normal file
@@ -0,0 +1,125 @@
|
||||
# Diffusion LM Training Plugin for Axolotl
|
||||
|
||||
This plugin enables diffusion language model training using the LLaDA (Large Language
|
||||
And Diffusion Assistant) approach within the Axolotl framework.
|
||||
|
||||
## Overview
|
||||
|
||||
LLaDA is a diffusion-based approach to language model training that uses:
|
||||
- **Random token masking** during training instead of next-token prediction
|
||||
- **Bidirectional attention** to allow the model to see the full context
|
||||
- **Importance weighting** based on masking probabilities for stable training
|
||||
|
||||
This approach can lead to more robust language models with better understanding of
|
||||
bidirectional context.
|
||||
|
||||
## Installation
|
||||
|
||||
The plugin is included with Axolotl. To use it, simply add the plugin configuration to
|
||||
your training config.
|
||||
|
||||
## Quickstart
|
||||
|
||||
### Basic Configuration
|
||||
|
||||
Add the following to your Axolotl configuration YAML:
|
||||
|
||||
```yaml
|
||||
# Enable diffusion LM training plugin
|
||||
plugins:
|
||||
- axolotl.integrations.diffusion.DiffusionPlugin
|
||||
|
||||
# Diffusion-specific configuration
|
||||
noise_schedule: linear # or "cosine"
|
||||
min_mask_ratio: 0.1
|
||||
max_mask_ratio: 0.9
|
||||
num_diffusion_steps: 128
|
||||
eps: 1e-3
|
||||
importance_weighting: true
|
||||
mask_token_id: 128002
|
||||
|
||||
# Sample generation (optional)
|
||||
generate_samples: true
|
||||
generation_interval: 100
|
||||
num_generation_samples: 3
|
||||
generation_steps: 128
|
||||
generation_temperature: 0.0
|
||||
generation_max_length: 100
|
||||
|
||||
# Model configuration
|
||||
base_model: meta-llama/Llama-3.2-1B
|
||||
model_type: llama
|
||||
|
||||
# Standard Axolotl configuration
|
||||
datasets:
|
||||
- path: your_dataset
|
||||
...
|
||||
|
||||
# Other config
|
||||
sequence_len: 1024
|
||||
micro_batch_size: 8
|
||||
gradient_accumulation_steps: 4
|
||||
learning_rate: 3e-4
|
||||
```
|
||||
|
||||
## Supported Models
|
||||
|
||||
Any models that support 4D attention masks should work out of the box. If not, please
|
||||
create an [issue](https://github.com/axolotl-ai-cloud/axolotl/issues)!
|
||||
|
||||
## How It Works
|
||||
|
||||
### Random Masking
|
||||
During training, tokens are randomly masked based on a sampled timestep:
|
||||
- Sample timestep `t` uniformly from [0, 1]
|
||||
- Calculate masking probability: `p = (1 - eps) * t + eps`
|
||||
- Randomly mask tokens with probability `p`
|
||||
|
||||
### Bidirectional Attention
|
||||
The plugin uses native 4D attention masks to:
|
||||
- Enable bidirectional attention without patches
|
||||
- Allow all tokens to attend to all other tokens
|
||||
- Maintain proper padding masks
|
||||
- Work with modern `transformers` models out of the box
|
||||
|
||||
### Diffusion Loss
|
||||
|
||||
Loss is computed only on masked tokens with (optional) importance weighting:
|
||||
|
||||
```python
|
||||
loss = sum(cross_entropy(pred, target) / p_mask) / total_tokens
|
||||
```
|
||||
|
||||
## Sample Generation
|
||||
|
||||
When `generate_samples: true`, the plugin generates samples during training:
|
||||
|
||||
```
|
||||
Sample 1:
|
||||
Original (45 tokens): The quick brown fox jumps over the lazy dog...
|
||||
Masked (18/45 tokens, 40.0%): The [MASK] [MASK] fox [MASK] over [MASK] lazy [MASK]...
|
||||
Generated: The quick brown fox jumps over the lazy dog...
|
||||
```
|
||||
|
||||
Samples are logged to console and wandb (if enabled).
|
||||
|
||||
## Metrics and Monitoring
|
||||
|
||||
The plugin adds several metrics to track diffusion training:
|
||||
|
||||
- `train/loss`: Weighted diffusion loss
|
||||
- `train/accuracy`: Accuracy on masked tokens
|
||||
- `train/mask_ratio`: Average fraction of tokens masked
|
||||
- `train/num_masked_tokens`: Number of tokens masked
|
||||
- `train/avg_p_mask`: Average masking probability
|
||||
- `train/ce_loss`: Unweighted cross-entropy loss
|
||||
- `train/importance_weight_avg`: Average importance weight
|
||||
|
||||
## Limitations
|
||||
|
||||
- No flash attention support
|
||||
|
||||
## References
|
||||
|
||||
- [LLaDA Paper](https://arxiv.org/abs/2404.10406)
|
||||
- [Axolotl Documentation](https://docs.axolotl.ai/)
|
||||
6
src/axolotl/integrations/diffusion/__init__.py
Normal file
6
src/axolotl/integrations/diffusion/__init__.py
Normal file
@@ -0,0 +1,6 @@
|
||||
"""Diffusion LM training plugin init."""
|
||||
|
||||
from .args import DiffusionArgs
|
||||
from .plugin import DiffusionPlugin
|
||||
|
||||
__all__ = ["DiffusionArgs", "DiffusionPlugin"]
|
||||
70
src/axolotl/integrations/diffusion/args.py
Normal file
70
src/axolotl/integrations/diffusion/args.py
Normal file
@@ -0,0 +1,70 @@
|
||||
"""Config args for diffusion LM training."""
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class DiffusionArgs(BaseModel):
|
||||
"""Arguments for diffusion LM training plugin."""
|
||||
|
||||
# Noise schedule config
|
||||
noise_schedule: Literal["linear", "cosine"] = Field(
|
||||
default="linear", description="Type of noise schedule for diffusion training"
|
||||
)
|
||||
min_mask_ratio: float = Field(
|
||||
default=0.1,
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
description="Minimum masking ratio for diffusion noise schedule",
|
||||
)
|
||||
max_mask_ratio: float = Field(
|
||||
default=0.9,
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
description="Maximum masking ratio for diffusion noise schedule",
|
||||
)
|
||||
num_diffusion_steps: int = Field(
|
||||
default=128, ge=1, description="Number of diffusion timesteps"
|
||||
)
|
||||
eps: float = Field(
|
||||
default=1e-3,
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
description="Epsilon value for minimum masking probability in forward process",
|
||||
)
|
||||
|
||||
# Training config
|
||||
importance_weighting: bool = Field(
|
||||
default=True,
|
||||
description="Apply importance weighting to loss based on masking probability",
|
||||
)
|
||||
mask_token_id: int = Field(
|
||||
default=128002,
|
||||
description=(
|
||||
"Token ID to use for masking. Default is 128002 "
|
||||
"(<|reserved_special_token_0|> for Llama 3.2)"
|
||||
),
|
||||
)
|
||||
|
||||
# Sample generation config
|
||||
generate_samples: bool = Field(
|
||||
default=True, description="Enable sample generation during training"
|
||||
)
|
||||
generation_interval: int = Field(
|
||||
default=100, ge=1, description="Generate samples every N steps"
|
||||
)
|
||||
num_generation_samples: int = Field(
|
||||
default=3, ge=1, description="Number of samples to generate each time"
|
||||
)
|
||||
generation_steps: int = Field(
|
||||
default=128, ge=1, description="Number of diffusion steps for generation"
|
||||
)
|
||||
generation_temperature: float = Field(
|
||||
default=0.0,
|
||||
ge=0.0,
|
||||
description="Temperature for generation sampling (0.0 = deterministic)",
|
||||
)
|
||||
generation_max_length: int = Field(
|
||||
default=100, ge=1, description="Maximum sequence length for generation"
|
||||
)
|
||||
113
src/axolotl/integrations/diffusion/callbacks.py
Normal file
113
src/axolotl/integrations/diffusion/callbacks.py
Normal file
@@ -0,0 +1,113 @@
|
||||
"""Callbacks for diffusion training."""
|
||||
|
||||
import wandb
|
||||
from transformers.trainer_callback import TrainerCallback, TrainerControl, TrainerState
|
||||
from transformers.training_args import TrainingArguments
|
||||
|
||||
from axolotl.utils.logging import get_logger
|
||||
|
||||
from .generation import generate_samples
|
||||
|
||||
LOG = get_logger(__name__)
|
||||
|
||||
|
||||
class DiffusionGenerationCallback(TrainerCallback):
|
||||
"""Callback for generating samples during diffusion training."""
|
||||
|
||||
def __init__(self, trainer):
|
||||
self.trainer = trainer
|
||||
|
||||
# pylint: disable=unused-argument
|
||||
def on_step_end(
|
||||
self,
|
||||
args: TrainingArguments,
|
||||
state: TrainerState,
|
||||
control: TrainerControl,
|
||||
**kwargs,
|
||||
):
|
||||
"""Generate samples at specified intervals."""
|
||||
if (
|
||||
state.global_step > 0
|
||||
and state.global_step % self.trainer.config.generation_interval == 0
|
||||
):
|
||||
# Use eval dataloader if available, otherwise use train dataloader
|
||||
if (
|
||||
hasattr(self.trainer, "eval_dataset")
|
||||
and self.trainer.eval_dataset is not None
|
||||
):
|
||||
dataloader = self.trainer.callback_handler.eval_dataloader
|
||||
else:
|
||||
dataloader = self.trainer.callback_handler.train_dataloader
|
||||
|
||||
# Generate samples
|
||||
samples = generate_samples(
|
||||
model=self.trainer.model,
|
||||
tokenizer=self.trainer.tokenizer,
|
||||
dataloader=dataloader,
|
||||
num_generation_samples=self.trainer.config.num_generation_samples,
|
||||
max_length=self.trainer.config.generation_max_length,
|
||||
num_diffusion_steps=self.trainer.config.generation_steps,
|
||||
temperature=self.trainer.config.generation_temperature,
|
||||
mask_token_id=self.trainer.config.mask_token_id,
|
||||
)
|
||||
|
||||
# Log samples
|
||||
self._log_samples(samples, state.global_step)
|
||||
|
||||
def _log_samples(self, samples: list, step: int):
|
||||
"""Log generated samples."""
|
||||
if not samples:
|
||||
return
|
||||
|
||||
LOG.info("=" * 60)
|
||||
LOG.info("GENERATED SAMPLES")
|
||||
LOG.info("=" * 60)
|
||||
|
||||
for i, sample_data in enumerate(samples, 1):
|
||||
original = sample_data["original"]
|
||||
masked = sample_data["masked"]
|
||||
generated = sample_data["generated"]
|
||||
mask_ratio = sample_data["mask_ratio"]
|
||||
masked_tokens = sample_data["masked_tokens"]
|
||||
total_tokens = sample_data["total_tokens"]
|
||||
|
||||
LOG.info(f"\nSample {i}:")
|
||||
LOG.info(f"\tOriginal ({total_tokens} tokens): {original}")
|
||||
LOG.info(
|
||||
f"\tMasked ({masked_tokens}/{total_tokens} tokens, "
|
||||
f"{mask_ratio:.1%}): {masked}"
|
||||
)
|
||||
LOG.info(f"\tGenerated: {generated}")
|
||||
|
||||
LOG.info("=" * 60)
|
||||
|
||||
if self.trainer.config.use_wandb and self.trainer.state.is_world_process_zero:
|
||||
if wandb.run is not None:
|
||||
wandb.log(
|
||||
{
|
||||
"generated_samples": wandb.Table(
|
||||
columns=[
|
||||
"step",
|
||||
"original",
|
||||
"masked",
|
||||
"generated",
|
||||
"mask_ratio",
|
||||
"masked_tokens",
|
||||
"total_tokens",
|
||||
],
|
||||
data=[
|
||||
[
|
||||
step,
|
||||
sample["original"],
|
||||
sample["masked"],
|
||||
sample["generated"],
|
||||
f"{sample['mask_ratio']:.1%}",
|
||||
sample["masked_tokens"],
|
||||
sample["total_tokens"],
|
||||
]
|
||||
for sample in samples
|
||||
],
|
||||
)
|
||||
},
|
||||
step=step,
|
||||
)
|
||||
269
src/axolotl/integrations/diffusion/generation.py
Normal file
269
src/axolotl/integrations/diffusion/generation.py
Normal file
@@ -0,0 +1,269 @@
|
||||
"""Sample generation utilities for diffusion training."""
|
||||
|
||||
import logging
|
||||
from typing import Any, List, Optional
|
||||
|
||||
import torch
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def generate_samples(
|
||||
model: torch.nn.Module,
|
||||
tokenizer: Any,
|
||||
dataloader: Optional[Any] = None,
|
||||
num_generation_samples: int = 3,
|
||||
max_length: int = 100,
|
||||
num_diffusion_steps: int = 128,
|
||||
temperature: float = 0.0,
|
||||
mask_token_id: int = 32000,
|
||||
) -> List[dict]:
|
||||
"""
|
||||
Generate text samples using the diffusion model by randomly masking sequences from
|
||||
the given dataset and running the reverse diffusion process.
|
||||
|
||||
Args:
|
||||
model: The wrapped or unwrapped model
|
||||
tokenizer: Tokenizer for encoding/decoding
|
||||
dataloader: Validation dataloader (for sampling sequences)
|
||||
num_generation_samples: Number of samples to generate
|
||||
max_length: Maximum length of sequences to use
|
||||
num_diffusion_steps: Number of diffusion steps for generation
|
||||
temperature: Temperature for sampling (0.0 = deterministic)
|
||||
mask_token_id: Token ID used for masking
|
||||
|
||||
Returns:
|
||||
List of dictionaries with original text, masked text, and generated text
|
||||
"""
|
||||
if dataloader is None:
|
||||
logger.warning("No validation dataloader provided, cannot generate samples")
|
||||
return []
|
||||
|
||||
# Get the actual model (unwrap if needed)
|
||||
unwrapped_model = model.module if hasattr(model, "module") else model
|
||||
unwrapped_model.eval()
|
||||
generations = []
|
||||
|
||||
# Sample sequences from validation dataset
|
||||
sampled_sequences = _sample_sequences_from_dataloader(
|
||||
dataloader, num_generation_samples, max_length, unwrapped_model.device
|
||||
)
|
||||
logger.info(f"Sampled {len(sampled_sequences)} sequences from validation dataset")
|
||||
|
||||
# Generate samples using reverse diffusion process
|
||||
with torch.no_grad():
|
||||
for original_sequence in sampled_sequences:
|
||||
generation_result = _generate(
|
||||
unwrapped_model,
|
||||
tokenizer,
|
||||
original_sequence,
|
||||
num_diffusion_steps,
|
||||
temperature,
|
||||
mask_token_id,
|
||||
)
|
||||
generations.append(generation_result)
|
||||
|
||||
unwrapped_model.train()
|
||||
return generations
|
||||
|
||||
|
||||
def _sample_sequences_from_dataloader(
|
||||
dataloader: Any, num_samples: int, max_length: int, device: torch.device
|
||||
) -> List[torch.Tensor]:
|
||||
"""Sample sequences from validation dataloader."""
|
||||
sampled_sequences = []
|
||||
sample_count = 0
|
||||
|
||||
# Add randomness by skipping a random number of batches
|
||||
skip_batches = torch.randint(0, 6, (1,)).item()
|
||||
batch_count = 0
|
||||
|
||||
for batch in dataloader:
|
||||
# Skip some batches for variety
|
||||
if batch_count < skip_batches:
|
||||
batch_count += 1
|
||||
continue
|
||||
|
||||
if sample_count >= num_samples:
|
||||
break
|
||||
|
||||
batch_count += 1
|
||||
input_ids = batch["input_ids"]
|
||||
attention_mask = batch.get("attention_mask")
|
||||
|
||||
# Randomly sample from sequences in this batch
|
||||
batch_indices = torch.randperm(input_ids.size(0)).tolist()
|
||||
|
||||
for i in batch_indices:
|
||||
if sample_count >= num_samples:
|
||||
break
|
||||
|
||||
# Get actual sequence length (non-padded)
|
||||
if attention_mask is not None:
|
||||
seq_len = attention_mask[i].sum().item()
|
||||
else:
|
||||
seq_len = input_ids.size(1)
|
||||
|
||||
# Limit sequence length to max_length
|
||||
actual_length = min(seq_len, max_length)
|
||||
if actual_length < 10: # Skip very short sequences
|
||||
continue
|
||||
|
||||
# Extract the sequence
|
||||
sequence = input_ids[i][:actual_length].unsqueeze(0).to(device)
|
||||
sampled_sequences.append(sequence)
|
||||
sample_count += 1
|
||||
|
||||
return sampled_sequences
|
||||
|
||||
|
||||
def _generate(
|
||||
model: torch.nn.Module,
|
||||
tokenizer: Any,
|
||||
original_sequence: torch.Tensor,
|
||||
num_diffusion_steps: int,
|
||||
temperature: float,
|
||||
mask_token_id: int,
|
||||
) -> dict:
|
||||
"""Generate a single sample using reverse diffusion."""
|
||||
# Get original text for comparison
|
||||
original_text = tokenizer.decode(
|
||||
original_sequence[0].cpu(), skip_special_tokens=True
|
||||
)
|
||||
|
||||
# Apply custom masking with random ratio (10% to 70%)
|
||||
total_tokens = original_sequence.size(1)
|
||||
min_ratio, max_ratio = 0.1, 0.7
|
||||
target_mask_ratio = torch.rand(1).item() * (max_ratio - min_ratio) + min_ratio
|
||||
target_masked_tokens = int(total_tokens * target_mask_ratio)
|
||||
|
||||
# Create random mask indices
|
||||
mask_positions = torch.randperm(total_tokens)[:target_masked_tokens]
|
||||
masked_indices = torch.zeros(
|
||||
1, total_tokens, dtype=torch.bool, device=original_sequence.device
|
||||
)
|
||||
masked_indices[0, mask_positions] = True
|
||||
|
||||
# Create masked sequence
|
||||
masked_sequence = original_sequence.clone()
|
||||
masked_sequence[masked_indices] = mask_token_id
|
||||
|
||||
# Calculate actual mask ratio
|
||||
masked_tokens = masked_indices.sum().item()
|
||||
mask_ratio = masked_tokens / total_tokens
|
||||
|
||||
# Get masked text for comparison
|
||||
masked_text = tokenizer.decode(masked_sequence[0].cpu(), skip_special_tokens=False)
|
||||
# Clean up mask token representation
|
||||
masked_text = _clean_masked_text(masked_text, tokenizer, mask_token_id)
|
||||
|
||||
# Run reverse diffusion process
|
||||
sequence = masked_sequence.clone()
|
||||
for step in range(num_diffusion_steps):
|
||||
sequence = _diffusion_step(
|
||||
model, sequence, step, num_diffusion_steps, temperature, mask_token_id
|
||||
)
|
||||
|
||||
# Get final generated text
|
||||
generated_text = tokenizer.decode(sequence[0].cpu(), skip_special_tokens=True)
|
||||
|
||||
return {
|
||||
"original": original_text,
|
||||
"masked": masked_text,
|
||||
"generated": generated_text,
|
||||
"mask_ratio": mask_ratio,
|
||||
"masked_tokens": masked_tokens,
|
||||
"total_tokens": total_tokens,
|
||||
"formatted": (
|
||||
f"Original: '{original_text}' → Masked: '{masked_text}' "
|
||||
f"({mask_ratio:.1%}) → Generated: '{generated_text}'"
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _clean_masked_text(masked_text: str, tokenizer: Any, mask_token_id: int) -> str:
|
||||
"""Clean up masked text for display."""
|
||||
mask_token_repr = tokenizer.decode([mask_token_id], skip_special_tokens=False)
|
||||
cleaned = masked_text.replace(mask_token_repr, "[MASK]")
|
||||
|
||||
if hasattr(tokenizer, "special_tokens_map"):
|
||||
for token_value in tokenizer.special_tokens_map.values():
|
||||
if token_value and isinstance(token_value, str):
|
||||
cleaned = cleaned.replace(token_value, "")
|
||||
|
||||
cleaned = " ".join(cleaned.split()).strip()
|
||||
|
||||
return cleaned
|
||||
|
||||
|
||||
def _diffusion_step(
|
||||
model: torch.nn.Module,
|
||||
sequence: torch.Tensor,
|
||||
step: int,
|
||||
num_diffusion_steps: int,
|
||||
temperature: float,
|
||||
mask_token_id: int,
|
||||
) -> torch.Tensor:
|
||||
"""Perform a single diffusion step with remasking."""
|
||||
# Only process if there are masked tokens remaining
|
||||
current_mask = sequence == mask_token_id
|
||||
if not current_mask.any():
|
||||
return sequence
|
||||
|
||||
# Create bidirectional attention mask for diffusion
|
||||
batch_size, seq_len = sequence.shape
|
||||
attention_mask = torch.ones(
|
||||
batch_size, 1, seq_len, seq_len, dtype=torch.bool, device=sequence.device
|
||||
)
|
||||
|
||||
# Forward pass
|
||||
outputs = model(input_ids=sequence, attention_mask=attention_mask)
|
||||
logits = outputs.logits
|
||||
|
||||
# Only sample at currently masked positions
|
||||
if current_mask.any():
|
||||
masked_logits = logits[current_mask]
|
||||
|
||||
# Apply temperature scaling
|
||||
if temperature > 0:
|
||||
scaled_logits = masked_logits / temperature
|
||||
else:
|
||||
scaled_logits = masked_logits
|
||||
|
||||
# Suppress mask token in outputs
|
||||
scaled_logits[:, mask_token_id] = -float("inf")
|
||||
|
||||
# Sample predictions
|
||||
if temperature > 0:
|
||||
# Add Gumbel noise for sampling
|
||||
gumbel_noise = -torch.log(
|
||||
-torch.log(torch.rand_like(scaled_logits, dtype=torch.float32))
|
||||
)
|
||||
gumbel_logits = scaled_logits + gumbel_noise
|
||||
predicted_tokens = torch.argmax(gumbel_logits, dim=-1)
|
||||
else:
|
||||
# Deterministic sampling when temperature is 0
|
||||
predicted_tokens = torch.argmax(scaled_logits, dim=-1)
|
||||
|
||||
# Calculate probabilities for confidence scoring
|
||||
probs = torch.softmax(scaled_logits, dim=-1)
|
||||
predicted_token_probs = probs[range(len(predicted_tokens)), predicted_tokens]
|
||||
|
||||
# Determine how many tokens to unmask this step
|
||||
remaining_masked = current_mask.sum().item()
|
||||
if step == num_diffusion_steps - 1:
|
||||
num_to_unmask = remaining_masked
|
||||
else:
|
||||
unmask_ratio = 1.0 / (num_diffusion_steps - step)
|
||||
num_to_unmask = max(1, int(remaining_masked * unmask_ratio))
|
||||
|
||||
# Select highest confidence predictions to unmask
|
||||
if num_to_unmask >= remaining_masked:
|
||||
sequence[current_mask] = predicted_tokens
|
||||
else:
|
||||
_, top_indices = predicted_token_probs.topk(num_to_unmask)
|
||||
mask_positions = torch.where(current_mask)[1]
|
||||
positions_to_unmask = mask_positions[top_indices]
|
||||
sequence[0, positions_to_unmask] = predicted_tokens[top_indices]
|
||||
|
||||
return sequence
|
||||
115
src/axolotl/integrations/diffusion/loss.py
Normal file
115
src/axolotl/integrations/diffusion/loss.py
Normal file
@@ -0,0 +1,115 @@
|
||||
"""Diffusion LM loss function for integration with transformers LOSS_MAPPING."""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
|
||||
def ForDiffusionLMLoss(
|
||||
logits: torch.Tensor,
|
||||
labels: torch.Tensor,
|
||||
vocab_size: int,
|
||||
config: Optional[dict] = None,
|
||||
inputs: Optional[dict] = None,
|
||||
model: Optional[torch.nn.Module] = None,
|
||||
**kwargs,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Diffusion Language Modeling loss function.
|
||||
|
||||
This function computes cross-entropy loss only on masked tokens using
|
||||
diffusion info stored by the model patch during forward pass.
|
||||
|
||||
Args:
|
||||
logits: Model predictions [batch_size, seq_len, vocab_size]
|
||||
labels: Ground truth tokens [batch_size, seq_len]
|
||||
vocab_size: Size of vocabulary
|
||||
config: Model configuration (contains diffusion parameters)
|
||||
inputs: Input batch dictionary (contains input_ids, attention_mask)
|
||||
model: The model instance (to access stored diffusion info)
|
||||
**kwargs: Additional arguments
|
||||
|
||||
Returns:
|
||||
loss: Computed diffusion loss
|
||||
"""
|
||||
# Get diffusion info stored by model patch
|
||||
if model is None or not hasattr(model, "_diffusion_info"):
|
||||
# Fallback to regular causal LM loss if no diffusion info
|
||||
shift_logits = logits[..., :-1, :].contiguous()
|
||||
shift_labels = labels[..., 1:].contiguous()
|
||||
loss_fct = torch.nn.CrossEntropyLoss()
|
||||
return loss_fct(
|
||||
shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)
|
||||
)
|
||||
|
||||
diffusion_info = model._diffusion_info
|
||||
original_input_ids = diffusion_info["original_input_ids"]
|
||||
masked_indices = diffusion_info["masked_indices"]
|
||||
p_mask = diffusion_info["p_mask"]
|
||||
|
||||
# Get diffusion config parameters
|
||||
diffusion_config = getattr(config, "diffusion_config", {})
|
||||
importance_weighting = diffusion_config.get("importance_weighting", True)
|
||||
|
||||
# Check if we have any masked tokens
|
||||
if not masked_indices.any():
|
||||
return torch.tensor(0.0, device=logits.device, requires_grad=True)
|
||||
|
||||
# Get predictions and targets for masked positions only
|
||||
masked_logits = logits[masked_indices]
|
||||
masked_targets = original_input_ids[masked_indices] # Original unmasked tokens
|
||||
|
||||
# Compute cross-entropy loss without reduction
|
||||
token_loss = F.cross_entropy(
|
||||
masked_logits.float(), masked_targets, reduction="none"
|
||||
)
|
||||
|
||||
if importance_weighting:
|
||||
# Apply importance weighting: 1 / p_mask
|
||||
masked_p_mask = p_mask.expand_as(masked_indices)[masked_indices]
|
||||
weighted_loss = token_loss / masked_p_mask
|
||||
|
||||
if labels is not None:
|
||||
# For SFT data: normalize by answer length per sample
|
||||
answer_mask = labels != -100
|
||||
answer_lengths = answer_mask.sum(dim=1).float()
|
||||
|
||||
# Group losses by batch sample
|
||||
batch_indices = torch.arange(
|
||||
original_input_ids.shape[0], device=original_input_ids.device
|
||||
)
|
||||
batch_indices = batch_indices.unsqueeze(1).expand_as(masked_indices)
|
||||
masked_batch_indices = batch_indices[masked_indices]
|
||||
|
||||
# Sum losses per sample and normalize by answer length
|
||||
loss_per_sample = torch.zeros(
|
||||
original_input_ids.shape[0], device=original_input_ids.device
|
||||
)
|
||||
for i in range(original_input_ids.shape[0]):
|
||||
sample_mask = masked_batch_indices == i
|
||||
if sample_mask.any():
|
||||
sample_loss = weighted_loss[sample_mask].sum()
|
||||
loss_per_sample[i] = sample_loss / max(answer_lengths[i], 1)
|
||||
|
||||
loss = loss_per_sample.mean()
|
||||
else:
|
||||
# For completion data: simple average
|
||||
loss = weighted_loss.mean()
|
||||
else:
|
||||
# No importance weighting
|
||||
loss = token_loss.mean()
|
||||
|
||||
return loss
|
||||
|
||||
|
||||
def register_diffusion_loss():
|
||||
"""Register the diffusion loss function in transformers LOSS_MAPPING."""
|
||||
try:
|
||||
from transformers.loss.loss_utils import LOSS_MAPPING
|
||||
|
||||
LOSS_MAPPING["ForDiffusionLM"] = ForDiffusionLMLoss
|
||||
return True
|
||||
except ImportError:
|
||||
# Fallback for older transformers versions
|
||||
return False
|
||||
149
src/axolotl/integrations/diffusion/model_patch.py
Normal file
149
src/axolotl/integrations/diffusion/model_patch.py
Normal file
@@ -0,0 +1,149 @@
|
||||
"""Model patches for diffusion training."""
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
def patch_model_for_bidirectional_attention(model):
|
||||
"""
|
||||
Patch model to handle diffusion training with forward process and bidirectional
|
||||
attention.
|
||||
|
||||
This monkey-patches the model's forward method to:
|
||||
- Apply forward diffusion process (masking) during training
|
||||
- Use bidirectional attention masks
|
||||
- Store info for loss computation
|
||||
"""
|
||||
original_forward = model.forward
|
||||
|
||||
def diffusion_forward(
|
||||
self,
|
||||
input_ids: torch.Tensor | None = None,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
labels: torch.Tensor | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
# Check if this is diffusion training
|
||||
if (
|
||||
hasattr(self.config, "loss_type")
|
||||
and self.config.loss_type == "ForDiffusionLM"
|
||||
and self.training
|
||||
):
|
||||
|
||||
# Store original input_ids for loss computation
|
||||
original_input_ids = input_ids.clone()
|
||||
|
||||
# Apply forward diffusion process (masking)
|
||||
diffusion_config = getattr(self.config, "diffusion_config", {})
|
||||
noisy_input_ids, masked_indices, p_mask = _forward_process(
|
||||
input_ids, attention_mask, labels, diffusion_config
|
||||
)
|
||||
|
||||
# Use noisy input for model forward
|
||||
input_ids = noisy_input_ids
|
||||
|
||||
# Convert attention mask to bidirectional
|
||||
if attention_mask is not None:
|
||||
attention_mask = _create_bidirectional_attention_mask(
|
||||
input_ids, attention_mask
|
||||
)
|
||||
|
||||
# Store diffusion info in the model for loss computation
|
||||
self._diffusion_info = {
|
||||
"original_input_ids": original_input_ids,
|
||||
"masked_indices": masked_indices,
|
||||
"p_mask": p_mask,
|
||||
}
|
||||
|
||||
return original_forward(
|
||||
input_ids=input_ids, attention_mask=attention_mask, labels=labels, **kwargs
|
||||
)
|
||||
|
||||
# Replace the forward method
|
||||
model.forward = diffusion_forward.__get__(model, model.__class__)
|
||||
|
||||
|
||||
def _create_bidirectional_attention_mask(
|
||||
input_ids: torch.Tensor, attention_mask: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Create bidirectional attention mask from 2D attention mask.
|
||||
|
||||
Args:
|
||||
input_ids: Input token IDs [batch_size, seq_len]
|
||||
attention_mask: 2D attention mask [batch_size, seq_len]
|
||||
|
||||
Returns:
|
||||
bidirectional_mask: 4D attention mask [batch_size, 1, seq_len, seq_len]
|
||||
"""
|
||||
batch_size, seq_len = input_ids.shape
|
||||
|
||||
# Simple bidirectional mask - all tokens can attend to all valid tokens
|
||||
# Expand 2D mask to 4D: [batch_size, seq_len] -> [batch_size, 1, seq_len, seq_len]
|
||||
bidirectional_mask = attention_mask.unsqueeze(1).unsqueeze(2) # [B, 1, 1, S]
|
||||
bidirectional_mask = bidirectional_mask.expand(batch_size, 1, seq_len, seq_len)
|
||||
|
||||
# Apply row-wise masking (padded tokens can't attend to anything)
|
||||
row_mask = attention_mask.unsqueeze(1).unsqueeze(3) # [B, 1, S, 1]
|
||||
bidirectional_mask = bidirectional_mask & row_mask
|
||||
|
||||
return bidirectional_mask
|
||||
|
||||
|
||||
def _forward_process(
|
||||
input_ids: torch.Tensor,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
labels: torch.Tensor | None = None,
|
||||
diffusion_config: dict | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""
|
||||
Apply forward diffusion process (random masking).
|
||||
|
||||
Args:
|
||||
input_ids: Input token IDs [batch_size, seq_len]
|
||||
attention_mask: Attention mask [batch_size, seq_len]
|
||||
labels: Labels for SFT training [batch_size, seq_len]
|
||||
diffusion_config: Diffusion configuration dict
|
||||
|
||||
Returns:
|
||||
noisy_input_ids: Input with masked tokens
|
||||
masked_indices: Boolean mask of which tokens were masked
|
||||
p_mask: Masking probabilities used
|
||||
"""
|
||||
if diffusion_config is None:
|
||||
diffusion_config = {}
|
||||
|
||||
batch_size, seq_len = input_ids.shape
|
||||
device = input_ids.device
|
||||
|
||||
eps = diffusion_config.get("eps", 1e-3)
|
||||
mask_token_id = diffusion_config.get("mask_token_id", 128002)
|
||||
|
||||
# Sample random timesteps for each sample
|
||||
t = torch.rand(batch_size, device=device)
|
||||
|
||||
# Calculate masking probability with epsilon
|
||||
p_mask = (1 - eps) * t + eps # [batch_size]
|
||||
p_mask = p_mask.unsqueeze(1).expand(-1, seq_len) # [batch_size, seq_len]
|
||||
|
||||
# Don't mask padding tokens
|
||||
if attention_mask is not None:
|
||||
p_mask = p_mask * attention_mask.float()
|
||||
|
||||
# Create random mask based on p_mask
|
||||
random_values = torch.rand_like(p_mask)
|
||||
masked_indices = random_values < p_mask
|
||||
|
||||
# Apply attention mask constraints
|
||||
if attention_mask is not None:
|
||||
masked_indices = masked_indices & attention_mask.bool()
|
||||
|
||||
# For SFT data, only mask answer tokens (where labels != -100)
|
||||
if labels is not None:
|
||||
answer_mask = labels != -100
|
||||
masked_indices = masked_indices & answer_mask
|
||||
|
||||
# Create noisy input by replacing masked tokens
|
||||
noisy_input_ids = input_ids.clone()
|
||||
noisy_input_ids[masked_indices] = mask_token_id
|
||||
|
||||
return noisy_input_ids, masked_indices, p_mask
|
||||
96
src/axolotl/integrations/diffusion/plugin.py
Normal file
96
src/axolotl/integrations/diffusion/plugin.py
Normal file
@@ -0,0 +1,96 @@
|
||||
"""Diffusion LM training plugin for Axolotl."""
|
||||
|
||||
from peft import PeftModel
|
||||
from transformers import PreTrainedModel
|
||||
|
||||
from axolotl.integrations.base import BasePlugin
|
||||
from axolotl.utils.dict import DictDefault
|
||||
from axolotl.utils.logging import get_logger
|
||||
|
||||
from .args import DiffusionArgs
|
||||
from .callbacks import DiffusionGenerationCallback
|
||||
from .loss import register_diffusion_loss
|
||||
from .model_patch import patch_model_for_bidirectional_attention
|
||||
|
||||
LOG = get_logger(__name__)
|
||||
|
||||
|
||||
class DiffusionPlugin(BasePlugin):
|
||||
"""
|
||||
Plugin for diffusion language model training.
|
||||
|
||||
This plugin enables diffusion-based training using the LLaDA approach, which uses
|
||||
random masking and bidirectional attention to train language models.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.cfg = None
|
||||
|
||||
if register_diffusion_loss():
|
||||
LOG.info("Registered ForDiffusionLM loss function")
|
||||
else:
|
||||
LOG.warning(
|
||||
"Failed to register diffusion loss - older transformers version"
|
||||
)
|
||||
|
||||
def get_input_args(self) -> str:
|
||||
"""Returns the pydantic model for LLaDA plugin arguments."""
|
||||
return "axolotl.integrations.diffusion.DiffusionArgs"
|
||||
|
||||
def post_model_load(self, cfg: DictDefault, model: PreTrainedModel | PeftModel):
|
||||
"""Configure model for diffusion training after loading."""
|
||||
self.cfg = cfg
|
||||
|
||||
# Set loss type for diffusion training
|
||||
if hasattr(model, "config"):
|
||||
model.config.loss_type = "ForDiffusionLM"
|
||||
|
||||
# Store diffusion config in model config
|
||||
model.config.diffusion_config = {
|
||||
"eps": getattr(cfg, "eps", 1e-3),
|
||||
"importance_weighting": getattr(cfg, "importance_weighting", True),
|
||||
"mask_token_id": getattr(cfg, "mask_token_id", 128002),
|
||||
}
|
||||
|
||||
LOG.info("Configured model for diffusion training with ForDiffusionLM loss")
|
||||
|
||||
# Patch model for bidirectional attention during training
|
||||
patch_model_for_bidirectional_attention(model)
|
||||
LOG.info("Applied bidirectional attention patch to model")
|
||||
|
||||
return model
|
||||
|
||||
def post_trainer_create(self, cfg: DictDefault, trainer):
|
||||
"""Configure trainer after creation."""
|
||||
# Create diffusion config from cfg
|
||||
diffusion_config = DiffusionArgs(
|
||||
noise_schedule=getattr(cfg, "noise_schedule", "linear"),
|
||||
min_mask_ratio=getattr(cfg, "min_mask_ratio", 0.1),
|
||||
max_mask_ratio=getattr(cfg, "max_mask_ratio", 0.9),
|
||||
num_diffusion_steps=getattr(cfg, "num_diffusion_steps", 128),
|
||||
eps=getattr(cfg, "eps", 1e-3),
|
||||
importance_weighting=getattr(cfg, "importance_weighting", True),
|
||||
mask_token_id=getattr(cfg, "mask_token_id", 128002),
|
||||
generate_samples=getattr(cfg, "generate_samples", True),
|
||||
generation_interval=getattr(cfg, "generation_interval", 100),
|
||||
num_generation_samples=getattr(cfg, "num_generation_samples", 3),
|
||||
generation_steps=getattr(cfg, "generation_steps", 128),
|
||||
generation_temperature=getattr(cfg, "generation_temperature", 0.0),
|
||||
generation_max_length=getattr(cfg, "generation_max_length", 100),
|
||||
)
|
||||
|
||||
# Store diffusion config on trainer for callbacks to access
|
||||
trainer.diffusion_config = diffusion_config
|
||||
LOG.info("Stored diffusion config on trainer")
|
||||
|
||||
def add_callbacks_post_trainer(self, cfg: DictDefault, trainer):
|
||||
"""Add diffusion generation callback if enabled."""
|
||||
if (
|
||||
hasattr(trainer, "diffusion_config")
|
||||
and trainer.diffusion_config.generate_samples
|
||||
):
|
||||
generation_callback = DiffusionGenerationCallback(trainer)
|
||||
LOG.info("Added diffusion generation callback")
|
||||
return [generation_callback]
|
||||
return []
|
||||
@@ -681,6 +681,23 @@ class ModelLoader:
|
||||
|
||||
return hf_ds_cfg
|
||||
|
||||
def _load_model_from_config(self) -> PreTrainedModel:
|
||||
"""Load model with random initialization using from_config."""
|
||||
if self.auto_model_loader in [AutoModelForCausalLM, AutoModelForVision2Seq]:
|
||||
return self.auto_model_loader.from_config(config=self.model_config)
|
||||
return self.auto_model_loader(config=self.model_config)
|
||||
|
||||
def _load_model_from_pretrained(self, model_loader_class=None) -> PreTrainedModel:
|
||||
"""Load model from pretrained weights."""
|
||||
loader = model_loader_class or self.auto_model_loader
|
||||
kwargs = {
|
||||
**self.model_kwargs,
|
||||
"config": self.model_config,
|
||||
"trust_remote_code": self.cfg.trust_remote_code or False,
|
||||
**self.model_kwargs,
|
||||
}
|
||||
return loader.from_pretrained(self.base_model, **kwargs)
|
||||
|
||||
def _build_model(self) -> bool:
|
||||
"""Load model, with load strategy depending on config."""
|
||||
skip_move_to_device = False
|
||||
@@ -695,7 +712,8 @@ class ModelLoader:
|
||||
if self.is_fsdp_enabled:
|
||||
if self.cfg.fsdp_config.cpu_ram_efficient_loading:
|
||||
skip_move_to_device = True
|
||||
# Don't delete device_map for QLoRA + FSDP - it was set correctly in _set_device_map
|
||||
# Don't delete device_map for QLoRA + FSDP - it was set correctly in
|
||||
# _set_device_map
|
||||
if (
|
||||
"device_map" in self.model_kwargs
|
||||
and not self.is_qlora_and_fsdp_enabled
|
||||
@@ -724,6 +742,11 @@ class ModelLoader:
|
||||
or self.cfg.qlora_sharded_model_loading
|
||||
)
|
||||
):
|
||||
if self.cfg.reinit_weights:
|
||||
LOG.warning(
|
||||
"reinit_weights is not supported with sharded quantized loading. "
|
||||
"Loading from pretrained weights instead."
|
||||
)
|
||||
quant_storage = self.cfg.torch_dtype
|
||||
quantization_config = getattr(
|
||||
self.model_config, "quantization_config", None
|
||||
@@ -739,33 +762,12 @@ class ModelLoader:
|
||||
quantization_config=quantization_config,
|
||||
)
|
||||
skip_move_to_device = True
|
||||
elif (
|
||||
self.model_config.model_type in ["llama", "llama4"]
|
||||
and not self.cfg.trust_remote_code
|
||||
and not self.cfg.gptq
|
||||
):
|
||||
# Please don't remove underscore binding without reading the fn docstring.
|
||||
_ = self._configure_zero3_memory_efficient_loading()
|
||||
|
||||
# Load model with random initialization if specified
|
||||
if self.cfg.random_init_weights:
|
||||
# AutoModel classes support the from_config method
|
||||
if self.auto_model_loader in [
|
||||
AutoModelForCausalLM,
|
||||
AutoModelForVision2Seq,
|
||||
]:
|
||||
self.model = self.auto_model_loader.from_config(
|
||||
config=self.model_config,
|
||||
)
|
||||
else:
|
||||
self.model = self.auto_model_loader(config=self.model_config)
|
||||
else:
|
||||
self.model = self.auto_model_loader.from_pretrained(
|
||||
self.base_model,
|
||||
config=self.model_config,
|
||||
**self.model_kwargs,
|
||||
)
|
||||
elif self.model_type == "MambaLMHeadModel":
|
||||
if self.cfg.reinit_weights:
|
||||
LOG.warning(
|
||||
"reinit_weights is not supported with MambaLMHeadModel. "
|
||||
"Loading from pretrained weights instead."
|
||||
)
|
||||
# FIXME this is janky at best and hacked together to make it work
|
||||
MambaLMHeadModel = fix_mamba_attn_for_loss() # pylint: disable=invalid-name
|
||||
|
||||
@@ -778,41 +780,27 @@ class ModelLoader:
|
||||
self.base_model,
|
||||
**self.model_kwargs,
|
||||
)
|
||||
elif (
|
||||
self.model_type
|
||||
and self.model_type != "AutoModelForCausalLM"
|
||||
and not self.cfg.trust_remote_code
|
||||
):
|
||||
if self.cfg.gptq:
|
||||
self.model = self.auto_model_loader.from_pretrained(
|
||||
self.base_model,
|
||||
config=self.model_config,
|
||||
trust_remote_code=self.cfg.trust_remote_code or False,
|
||||
**self.model_kwargs,
|
||||
)
|
||||
else:
|
||||
self.model = getattr(transformers, self.model_type).from_pretrained(
|
||||
self.base_model,
|
||||
config=self.model_config,
|
||||
trust_remote_code=self.cfg.trust_remote_code or False,
|
||||
**self.model_kwargs,
|
||||
)
|
||||
elif self.cfg.gptq:
|
||||
self.model = self.auto_model_loader.from_pretrained(
|
||||
self.base_model,
|
||||
config=self.model_config,
|
||||
trust_remote_code=self.cfg.trust_remote_code or False,
|
||||
**self.model_kwargs,
|
||||
)
|
||||
else:
|
||||
# Please don't remove underscore binding without reading the fn docstring.
|
||||
# Please don't remove underscore binding without reading the fn docstring
|
||||
_ = self._configure_zero3_memory_efficient_loading()
|
||||
self.model = self.auto_model_loader.from_pretrained(
|
||||
self.base_model,
|
||||
config=self.model_config,
|
||||
trust_remote_code=self.cfg.trust_remote_code or False,
|
||||
**self.model_kwargs,
|
||||
)
|
||||
|
||||
if (
|
||||
self.model_type
|
||||
and self.model_type != "AutoModelForCausalLM"
|
||||
and not self.cfg.trust_remote_code
|
||||
and not self.cfg.gptq
|
||||
):
|
||||
# Use model type from transformers
|
||||
model_loader_class = getattr(transformers, self.model_type)
|
||||
else:
|
||||
# Use auto model loader (handles gptq and default cases)
|
||||
model_loader_class = self.auto_model_loader
|
||||
|
||||
if self.cfg.reinit_weights:
|
||||
self.model = self._load_model_from_config()
|
||||
else:
|
||||
self.model = self._load_model_from_pretrained(model_loader_class)
|
||||
|
||||
if is_deepspeed_zero3_enabled():
|
||||
skip_move_to_device = True
|
||||
|
||||
|
||||
@@ -75,7 +75,7 @@ class PromptTokenizingStrategy(abc.ABC):
|
||||
) -> BatchEncoding:
|
||||
empty = BatchEncoding(data={"input_ids": [], "attention_mask": []})
|
||||
if not prompt:
|
||||
LOG.warning("Empty text requested for tokenization.")
|
||||
LOG.warning_once("Empty text requested for tokenization.")
|
||||
return empty
|
||||
|
||||
result = self.tokenizer(
|
||||
|
||||
@@ -109,6 +109,12 @@ class AxolotlInputConfig(
|
||||
"description": "Don't upcast the embeddings to float32 when using PEFT. Useful for low-VRAM GPUs"
|
||||
},
|
||||
)
|
||||
reinit_weights: bool | None = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": "Reinitialize model weights randomly instead of loading pretrained weights"
|
||||
},
|
||||
)
|
||||
|
||||
trainer_cls: str | None = Field(
|
||||
default=None,
|
||||
|
||||
119
tests/e2e/test_diffusion.py
Normal file
119
tests/e2e/test_diffusion.py
Normal file
@@ -0,0 +1,119 @@
|
||||
"""E2E smoke test for diffusion training plugin."""
|
||||
|
||||
from axolotl.common.datasets import load_datasets
|
||||
from axolotl.train import train
|
||||
from axolotl.utils.config import normalize_config, validate_config
|
||||
from axolotl.utils.dict import DictDefault
|
||||
|
||||
from tests.e2e.utils import check_model_output_exists
|
||||
|
||||
|
||||
class TestDiffusion:
|
||||
"""Test case for diffusion training plugin."""
|
||||
|
||||
def test_diffusion_smoke_test(self, temp_dir):
|
||||
"""
|
||||
Smoke test for diffusion training to ensure the plugin loads and trains without
|
||||
error.
|
||||
"""
|
||||
cfg = DictDefault(
|
||||
{
|
||||
"base_model": "HuggingFaceTB/SmolLM2-135M",
|
||||
"tokenizer_type": "AutoTokenizer",
|
||||
"trust_remote_code": True,
|
||||
"sequence_len": 256,
|
||||
"val_set_size": 0.1,
|
||||
"special_tokens": {
|
||||
"pad_token": "<|endoftext|>",
|
||||
},
|
||||
"datasets": [
|
||||
{
|
||||
"path": "mhenrichsen/alpaca_2k_test",
|
||||
"type": "alpaca",
|
||||
},
|
||||
],
|
||||
"num_epochs": 1,
|
||||
"max_steps": 3,
|
||||
"micro_batch_size": 1,
|
||||
"gradient_accumulation_steps": 1,
|
||||
"output_dir": temp_dir,
|
||||
"learning_rate": 0.0001,
|
||||
"optimizer": "adamw_torch",
|
||||
"lr_scheduler": "cosine",
|
||||
"bf16": True,
|
||||
"save_safetensors": True,
|
||||
"save_first_step": False,
|
||||
"logging_steps": 1,
|
||||
"eval_steps": 3,
|
||||
# Diffusion-specific config
|
||||
"plugins": ["axolotl.integrations.diffusion.DiffusionPlugin"],
|
||||
"diffusion_mask_token_id": 16,
|
||||
"diffusion_eps": 1e-3,
|
||||
"diffusion_importance_weighting": False,
|
||||
}
|
||||
)
|
||||
|
||||
cfg = validate_config(cfg)
|
||||
normalize_config(cfg)
|
||||
dataset_meta = load_datasets(cfg=cfg)
|
||||
|
||||
train(cfg=cfg, dataset_meta=dataset_meta)
|
||||
check_model_output_exists(temp_dir, cfg)
|
||||
|
||||
def test_diffusion_sft_labels(self, temp_dir):
|
||||
"""Test that diffusion training properly handles SFT data with labels."""
|
||||
cfg = DictDefault(
|
||||
{
|
||||
"base_model": "HuggingFaceTB/SmolLM2-135M",
|
||||
"tokenizer_type": "AutoTokenizer",
|
||||
"trust_remote_code": True,
|
||||
"sequence_len": 256,
|
||||
"val_set_size": 0.1,
|
||||
"special_tokens": {
|
||||
"pad_token": "<|endoftext|>",
|
||||
},
|
||||
"datasets": [
|
||||
{
|
||||
"path": "mhenrichsen/alpaca_2k_test",
|
||||
"type": "alpaca",
|
||||
},
|
||||
],
|
||||
"num_epochs": 1,
|
||||
"max_steps": 3,
|
||||
"micro_batch_size": 1,
|
||||
"gradient_accumulation_steps": 1,
|
||||
"output_dir": temp_dir,
|
||||
"learning_rate": 0.0001,
|
||||
"optimizer": "adamw_torch",
|
||||
"lr_scheduler": "cosine",
|
||||
"bf16": True,
|
||||
"save_safetensors": True,
|
||||
"save_first_step": False,
|
||||
"logging_steps": 1,
|
||||
"eval_steps": 2,
|
||||
# Diffusion-specific config
|
||||
"plugins": ["axolotl.integrations.diffusion.DiffusionPlugin"],
|
||||
"diffusion_mask_token_id": 16,
|
||||
"diffusion_eps": 1e-3,
|
||||
"diffusion_importance_weighting": True,
|
||||
# Ensure we have proper SFT labels
|
||||
"train_on_inputs": False,
|
||||
}
|
||||
)
|
||||
|
||||
cfg = validate_config(cfg)
|
||||
normalize_config(cfg)
|
||||
dataset_meta = load_datasets(cfg=cfg)
|
||||
|
||||
# Verify that the dataset has labels
|
||||
sample = dataset_meta.train_dataset[0]
|
||||
assert "labels" in sample, "SFT dataset should have labels"
|
||||
|
||||
# Check that some labels are -100 (prompt tokens)
|
||||
labels = sample["labels"]
|
||||
if hasattr(labels, "tolist"):
|
||||
labels = labels.tolist()
|
||||
assert -100 in labels, "SFT dataset should have -100 labels for prompt tokens"
|
||||
|
||||
train(cfg=cfg, dataset_meta=dataset_meta)
|
||||
check_model_output_exists(temp_dir, cfg)
|
||||
335
tests/integrations/test_diffusion.py
Normal file
335
tests/integrations/test_diffusion.py
Normal file
@@ -0,0 +1,335 @@
|
||||
"""Tests for diffusion trainer integration."""
|
||||
|
||||
# pylint: disable=redefined-outer-name,protected-access
|
||||
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from axolotl.integrations.diffusion.args import DiffusionArgs
|
||||
from axolotl.integrations.diffusion.loss import (
|
||||
ForDiffusionLMLoss,
|
||||
register_diffusion_loss,
|
||||
)
|
||||
from axolotl.integrations.diffusion.model_patch import (
|
||||
_create_bidirectional_attention_mask,
|
||||
_forward_process,
|
||||
patch_model_for_bidirectional_attention,
|
||||
)
|
||||
from axolotl.integrations.diffusion.plugin import DiffusionPlugin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def diffusion_config():
|
||||
"""Create a diffusion config."""
|
||||
return DiffusionArgs(
|
||||
eps=1e-3,
|
||||
importance_weighting=False,
|
||||
mask_token_id=32000,
|
||||
generate_samples=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_model():
|
||||
"""Create a mock model."""
|
||||
model = Mock()
|
||||
model.config = Mock()
|
||||
model.config.loss_type = "ForDiffusionLM"
|
||||
model.config.diffusion_config = {
|
||||
"eps": 1e-3,
|
||||
"importance_weighting": False,
|
||||
"mask_token_id": 32000,
|
||||
}
|
||||
model.training = True
|
||||
return model
|
||||
|
||||
|
||||
class TestDiffusionLoss:
|
||||
"""Test the ForDiffusionLMLoss function."""
|
||||
|
||||
def test_loss_with_diffusion_info(self, mock_model):
|
||||
"""Test loss computation with stored diffusion info."""
|
||||
batch_size, seq_len, vocab_size = 1, 5, 1000
|
||||
|
||||
# Mock stored diffusion info
|
||||
original_input_ids = torch.tensor([[1, 10, 20, 30, 2]], dtype=torch.long)
|
||||
masked_indices = torch.tensor(
|
||||
[[False, True, True, False, False]], dtype=torch.bool
|
||||
)
|
||||
p_mask = torch.tensor([[0.5, 0.5, 0.5, 0.5, 0.5]], dtype=torch.float)
|
||||
|
||||
mock_model._diffusion_info = {
|
||||
"original_input_ids": original_input_ids,
|
||||
"masked_indices": masked_indices,
|
||||
"p_mask": p_mask,
|
||||
}
|
||||
|
||||
# Mock logits
|
||||
logits = torch.randn(batch_size, seq_len, vocab_size, requires_grad=True)
|
||||
labels = torch.tensor([[-100, -100, 20, 30, 2]], dtype=torch.long)
|
||||
|
||||
loss = ForDiffusionLMLoss(
|
||||
logits=logits,
|
||||
labels=labels,
|
||||
vocab_size=vocab_size,
|
||||
config=mock_model.config,
|
||||
model=mock_model,
|
||||
)
|
||||
|
||||
assert isinstance(loss, torch.Tensor)
|
||||
assert loss.requires_grad
|
||||
assert loss.item() >= 0
|
||||
|
||||
def test_loss_fallback_without_diffusion_info(self, mock_model):
|
||||
"""Test fallback to causal LM loss when no diffusion info."""
|
||||
batch_size, seq_len, vocab_size = 1, 5, 1000
|
||||
|
||||
# Remove diffusion info to trigger fallback
|
||||
if hasattr(mock_model, "_diffusion_info"):
|
||||
delattr(mock_model, "_diffusion_info")
|
||||
|
||||
logits = torch.randn(batch_size, seq_len, vocab_size, requires_grad=True)
|
||||
labels = torch.tensor([[1, 10, 20, 30, 2]], dtype=torch.long)
|
||||
|
||||
loss = ForDiffusionLMLoss(
|
||||
logits=logits,
|
||||
labels=labels,
|
||||
vocab_size=vocab_size,
|
||||
config=mock_model.config,
|
||||
model=mock_model,
|
||||
)
|
||||
|
||||
assert isinstance(loss, torch.Tensor)
|
||||
assert loss.requires_grad
|
||||
|
||||
def test_loss_no_masked_tokens(self, mock_model):
|
||||
"""Test loss when no tokens are masked."""
|
||||
batch_size, seq_len, vocab_size = 1, 3, 1000
|
||||
|
||||
# No masked tokens
|
||||
original_input_ids = torch.tensor([[1, 10, 2]], dtype=torch.long)
|
||||
masked_indices = torch.tensor([[False, False, False]], dtype=torch.bool)
|
||||
p_mask = torch.tensor([[0.1, 0.1, 0.1]], dtype=torch.float)
|
||||
|
||||
mock_model._diffusion_info = {
|
||||
"original_input_ids": original_input_ids,
|
||||
"masked_indices": masked_indices,
|
||||
"p_mask": p_mask,
|
||||
}
|
||||
|
||||
logits = torch.randn(batch_size, seq_len, vocab_size)
|
||||
labels = torch.tensor([[1, 10, 2]], dtype=torch.long)
|
||||
|
||||
loss = ForDiffusionLMLoss(
|
||||
logits=logits,
|
||||
labels=labels,
|
||||
vocab_size=vocab_size,
|
||||
config=mock_model.config,
|
||||
model=mock_model,
|
||||
)
|
||||
|
||||
assert loss.item() == 0.0
|
||||
|
||||
|
||||
class TestModelPatch:
|
||||
"""Test the model patching functionality."""
|
||||
|
||||
def test_forward_process_basic(self):
|
||||
"""Test basic forward process."""
|
||||
input_ids = torch.tensor([[1, 10, 20, 30, 2]], dtype=torch.long)
|
||||
diffusion_config = {"eps": 0.1, "mask_token_id": 32000}
|
||||
|
||||
noisy_input_ids, masked_indices, p_mask = _forward_process(
|
||||
input_ids, diffusion_config=diffusion_config
|
||||
)
|
||||
|
||||
# Check shapes
|
||||
assert noisy_input_ids.shape == input_ids.shape
|
||||
assert masked_indices.shape == input_ids.shape
|
||||
assert p_mask.shape == input_ids.shape
|
||||
|
||||
# Check that mask token is applied where masked
|
||||
if masked_indices.any():
|
||||
assert (noisy_input_ids[masked_indices] == 32000).all()
|
||||
|
||||
def test_forward_process_with_labels(self):
|
||||
"""Test forward process with SFT labels."""
|
||||
input_ids = torch.tensor([[1, 10, 20, 30, 2]], dtype=torch.long)
|
||||
labels = torch.tensor([[-100, -100, 20, 30, 2]], dtype=torch.long)
|
||||
diffusion_config = {"eps": 0.1, "mask_token_id": 32000}
|
||||
|
||||
_, masked_indices, _ = _forward_process(
|
||||
input_ids, labels=labels, diffusion_config=diffusion_config
|
||||
)
|
||||
|
||||
# Check that only answer tokens can be masked (where labels != -100)
|
||||
non_answer_mask = labels == -100
|
||||
assert not masked_indices[non_answer_mask].any()
|
||||
|
||||
def test_forward_process_with_attention_mask(self):
|
||||
"""Test forward process with attention mask."""
|
||||
input_ids = torch.tensor([[1, 10, 20, 0]], dtype=torch.long)
|
||||
attention_mask = torch.tensor([[1, 1, 1, 0]], dtype=torch.long)
|
||||
diffusion_config = {"eps": 0.1, "mask_token_id": 32000}
|
||||
|
||||
_, masked_indices, p_mask = _forward_process(
|
||||
input_ids, attention_mask=attention_mask, diffusion_config=diffusion_config
|
||||
)
|
||||
|
||||
# Check that padding tokens are not masked
|
||||
padding_positions = attention_mask == 0
|
||||
assert not masked_indices[padding_positions].any()
|
||||
assert (p_mask[padding_positions] == 0).all()
|
||||
|
||||
def test_bidirectional_attention_mask(self):
|
||||
"""Test bidirectional attention mask creation."""
|
||||
input_ids = torch.tensor([[1, 10, 20, 2]], dtype=torch.long)
|
||||
attention_mask = torch.tensor([[1, 1, 1, 1]], dtype=torch.long)
|
||||
|
||||
mask = _create_bidirectional_attention_mask(input_ids, attention_mask)
|
||||
|
||||
# Should be all-to-all attention
|
||||
expected_shape = (1, 1, 4, 4)
|
||||
assert mask.shape == expected_shape
|
||||
assert mask.all()
|
||||
|
||||
def test_bidirectional_attention_mask_with_padding(self):
|
||||
"""Test bidirectional attention mask with padding."""
|
||||
input_ids = torch.tensor([[1, 10, 20, 0]], dtype=torch.long)
|
||||
attention_mask = torch.tensor([[1, 1, 1, 0]], dtype=torch.long)
|
||||
|
||||
mask = _create_bidirectional_attention_mask(input_ids, attention_mask)
|
||||
|
||||
# Padding positions should not attend or be attended to
|
||||
assert not mask[0, 0, 3, :].any() # Padding can't attend to anything
|
||||
assert not mask[0, 0, :, 3].any() # Nothing can attend to padding
|
||||
|
||||
def test_patch_model_for_bidirectional_attention(self):
|
||||
"""Test that model patching works."""
|
||||
mock_model = Mock()
|
||||
mock_model.config = Mock()
|
||||
mock_model.config.loss_type = "ForDiffusionLM"
|
||||
mock_model.config.diffusion_config = {"eps": 1e-3, "mask_token_id": 32000}
|
||||
mock_model.training = True
|
||||
|
||||
original_forward = Mock()
|
||||
mock_model.forward = original_forward
|
||||
|
||||
# Patch the model
|
||||
patch_model_for_bidirectional_attention(mock_model)
|
||||
|
||||
# Check that forward method was replaced
|
||||
assert mock_model.forward != original_forward
|
||||
|
||||
|
||||
class TestDiffusionPlugin:
|
||||
"""Test the DiffusionPlugin."""
|
||||
|
||||
def test_plugin_registers_loss_function(self):
|
||||
"""Test that plugin registers diffusion loss function."""
|
||||
with patch(
|
||||
"axolotl.integrations.diffusion.plugin.register_diffusion_loss",
|
||||
return_value=True,
|
||||
) as mock_register:
|
||||
plugin = DiffusionPlugin()
|
||||
mock_register.assert_called_once()
|
||||
|
||||
def test_post_model_load_configuration(self):
|
||||
"""Test that post_model_load configures model correctly."""
|
||||
plugin = DiffusionPlugin()
|
||||
|
||||
# Mock model and config
|
||||
mock_model = Mock()
|
||||
mock_model.config = Mock()
|
||||
mock_cfg = Mock()
|
||||
mock_cfg.eps = 1e-3
|
||||
mock_cfg.importance_weighting = True
|
||||
mock_cfg.mask_token_id = 32000
|
||||
|
||||
with patch(
|
||||
"axolotl.integrations.diffusion.plugin.patch_model_for_bidirectional_attention"
|
||||
) as mock_patch:
|
||||
result = plugin.post_model_load(mock_cfg, mock_model)
|
||||
|
||||
# Check model configuration
|
||||
assert mock_model.config.loss_type == "ForDiffusionLM"
|
||||
assert mock_model.config.diffusion_config is not None
|
||||
assert mock_model.config.diffusion_config["eps"] == 1e-3
|
||||
|
||||
# Check model was patched
|
||||
mock_patch.assert_called_once_with(mock_model)
|
||||
|
||||
# Should return the model
|
||||
assert result == mock_model
|
||||
|
||||
def test_post_trainer_create_stores_config(self, diffusion_config):
|
||||
"""Test that post_trainer_create stores config on trainer."""
|
||||
plugin = DiffusionPlugin()
|
||||
mock_trainer = Mock()
|
||||
mock_cfg = Mock()
|
||||
|
||||
# Set config attributes
|
||||
for attr, value in diffusion_config.model_dump().items():
|
||||
setattr(mock_cfg, attr, value)
|
||||
|
||||
plugin.post_trainer_create(mock_cfg, mock_trainer)
|
||||
|
||||
# Check that diffusion config was stored on trainer
|
||||
assert hasattr(mock_trainer, "diffusion_config")
|
||||
assert mock_trainer.diffusion_config.eps == diffusion_config.eps
|
||||
|
||||
def test_add_callbacks_post_trainer_with_generation_enabled(self):
|
||||
"""Test callback addition when generation is enabled."""
|
||||
plugin = DiffusionPlugin()
|
||||
mock_trainer = Mock()
|
||||
mock_cfg = Mock()
|
||||
|
||||
# Mock trainer with diffusion config that has generation enabled
|
||||
mock_trainer.diffusion_config = DiffusionArgs(generate_samples=True)
|
||||
|
||||
with patch(
|
||||
"axolotl.integrations.diffusion.plugin.DiffusionGenerationCallback"
|
||||
) as mock_callback_class:
|
||||
callbacks = plugin.add_callbacks_post_trainer(mock_cfg, mock_trainer)
|
||||
|
||||
# Should return one callback
|
||||
assert len(callbacks) == 1
|
||||
mock_callback_class.assert_called_once_with(mock_trainer)
|
||||
|
||||
def test_add_callbacks_post_trainer_with_generation_disabled(self):
|
||||
"""Test callback addition when generation is disabled."""
|
||||
plugin = DiffusionPlugin()
|
||||
mock_trainer = Mock()
|
||||
mock_cfg = Mock()
|
||||
|
||||
# Mock trainer with diffusion config that has generation disabled
|
||||
mock_trainer.diffusion_config = DiffusionArgs(generate_samples=False)
|
||||
|
||||
callbacks = plugin.add_callbacks_post_trainer(mock_cfg, mock_trainer)
|
||||
|
||||
# Should return no callbacks
|
||||
assert len(callbacks) == 0
|
||||
|
||||
|
||||
class TestLossRegistration:
|
||||
"""Test loss function registration."""
|
||||
|
||||
def test_register_diffusion_loss(self):
|
||||
"""Test that loss function can be registered."""
|
||||
with patch("transformers.loss.loss_utils.LOSS_MAPPING", {}) as mock_mapping:
|
||||
result = register_diffusion_loss()
|
||||
assert result is True
|
||||
assert "ForDiffusionLM" in mock_mapping
|
||||
assert mock_mapping["ForDiffusionLM"] == ForDiffusionLMLoss
|
||||
|
||||
def test_register_diffusion_loss_import_error(self):
|
||||
"""Test fallback when LOSS_MAPPING import fails."""
|
||||
# Patch the import to raise ImportError
|
||||
with patch(
|
||||
"builtins.__import__",
|
||||
side_effect=ImportError("transformers.loss.loss_utils not found"),
|
||||
):
|
||||
result = register_diffusion_loss()
|
||||
assert result is False
|
||||
Reference in New Issue
Block a user